Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::StatisticsPropagator Class Reference
Collaboration diagram for duckdb::StatisticsPropagator:

Public Member Functions

 StatisticsPropagator (Optimizer &optimizer, LogicalOperator &root)
unique_ptr< NodeStatistics > PropagateStatistics (unique_ptr< LogicalOperator > &node_ptr)
column_binding_map_t< unique_ptr< BaseStatistics > > GetStatisticsMap ()

Static Public Member Functions

static bool CanPropagateCast (const LogicalType &source, const LogicalType &target)
 Whether or not we can propagate a cast between two types.
static unique_ptr< BaseStatistics > TryPropagateCast (const BaseStatistics &stats, const LogicalType &source, const LogicalType &target)

Private Member Functions

unique_ptr< NodeStatistics > PropagateStatistics (LogicalOperator &node, unique_ptr< LogicalOperator > &node_ptr)
 Propagate statistics through an operator.
unique_ptr< NodeStatistics > PropagateStatistics (LogicalFilter &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalGet &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalJoin &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalPositionalJoin &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalProjection &op, unique_ptr< LogicalOperator > &node_ptr)
void PropagateStatistics (LogicalComparisonJoin &op, unique_ptr< LogicalOperator > &node_ptr)
void PropagateStatistics (LogicalAnyJoin &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalSetOperation &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalAggregate &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalCrossProduct &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalLimit &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalOrder &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateStatistics (LogicalWindow &op, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< NodeStatistics > PropagateChildren (LogicalOperator &node, unique_ptr< LogicalOperator > &node_ptr)
unique_ptr< BaseStatistics > StatisticsFromValue (const Value &input)
 Return statistics from a constant value.
FilterPropagateResult PropagateComparison (BaseStatistics &left, BaseStatistics &right, ExpressionType comparison)
 Run a comparison with two sets of statistics, returns if the comparison will always returns true/false or not.
void UpdateFilterStatistics (BaseStatistics &input, ExpressionType comparison_type, const Value &constant)
 Update filter statistics from a filter with a constant.
void UpdateFilterStatistics (BaseStatistics &lstats, BaseStatistics &rstats, ExpressionType comparison_type)
 Update statistics from a filter between two stats.
void UpdateFilterStatistics (Expression &left, Expression &right, ExpressionType comparison_type)
 Update filter statistics from a generic comparison.
void UpdateFilterStatistics (Expression &condition)
 Update filter statistics from an expression.
void SetStatisticsNotNull (ColumnBinding binding)
 Set the statistics of a specific column binding to not contain null values.
FilterPropagateResult HandleFilter (unique_ptr< Expression > &condition)
 Propagate a filter condition.
FilterPropagateResult PropagateTableFilter (ColumnBinding stats_binding, BaseStatistics &stats, TableFilter &filter)
 Run a comparison between the statistics and the table filter; returns the prune result.
void UpdateFilterStatistics (BaseStatistics &input, const TableFilter &filter)
 Update filter statistics from a TableFilter.
void AddCardinalities (unique_ptr< NodeStatistics > &stats, NodeStatistics &new_stats)
 Add cardinalities together (i.e. new max is stats.max + new_stats.max): used for union.
void MultiplyCardinalities (unique_ptr< NodeStatistics > &stats, NodeStatistics &new_stats)
 Multiply the cardinalities together (i.e. new max cardinality is stats.max * new_stats.max): used for joins/cross products.
void CreateFilterFromJoinStats (unique_ptr< LogicalOperator > &child, unique_ptr< Expression > &expr, const BaseStatistics &stats_before, const BaseStatistics &stats_after)
 Creates and pushes down a filter based on join statistics.
unique_ptr< BaseStatistics > PropagateExpression (unique_ptr< Expression > &expr)
unique_ptr< BaseStatistics > PropagateExpression (Expression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundAggregateExpression &expr, unique_ptr< Expression > &expr_ptr)
 Run a comparison between the statistics and the table filter; returns the prune result.
unique_ptr< BaseStatistics > PropagateExpression (BoundBetweenExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundCaseExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundCastExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundConjunctionExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundFunctionExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundComparisonExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundConstantExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundColumnRefExpression &expr, unique_ptr< Expression > &expr_ptr)
unique_ptr< BaseStatistics > PropagateExpression (BoundOperatorExpression &expr, unique_ptr< Expression > &expr_ptr)
void TryExecuteAggregates (LogicalAggregate &op, unique_ptr< LogicalOperator > &node_ptr)
 Try to execute aggregates using only the statistics if possible.
void ReplaceWithEmptyResult (unique_ptr< LogicalOperator > &node)
bool ExpressionIsConstant (Expression &expr, const Value &val)
bool ExpressionIsConstantOrNull (Expression &expr, const Value &val)
unique_ptr< NodeStatistics > PropagateUnion (LogicalSetOperation &setop, unique_ptr< LogicalOperator > &node_ptr)

Private Attributes

Optimizer & optimizer
ClientContext & context
optional_ptr< LogicalOperator > root
 The root of the query plan.
column_binding_map_t< unique_ptr< BaseStatistics > > statistics_map
 The map of ColumnBinding -> statistics for the various nodes.
unique_ptr< NodeStatistics > node_stats
 Node stats for the current node.

Constructor & Destructor Documentation

◆ StatisticsPropagator()

duckdb::StatisticsPropagator::StatisticsPropagator ( Optimizer & optimizer,
LogicalOperator & root )
325374 : optimizer(optimizer_p), context(optimizer.context), root(&root_p) {
325375 root->ResolveOperatorTypes();
325376}
optional_ptr< LogicalOperator > root
The root of the query plan.
Definition duckdb.hpp:51462

Member Function Documentation

◆ PropagateStatistics() [1/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( unique_ptr< LogicalOperator > & node_ptr)
325443 {
325444 return PropagateStatistics(*node_ptr, node_ptr);
325445}

◆ GetStatisticsMap()

column_binding_map_t< unique_ptr< BaseStatistics > > duckdb::StatisticsPropagator::GetStatisticsMap ( )
inline
51374 {
51375 return std::move(statistics_map);
51376 }
column_binding_map_t< unique_ptr< BaseStatistics > > statistics_map
The map of ColumnBinding -> statistics for the various nodes.
Definition duckdb.hpp:51464

◆ CanPropagateCast()

bool duckdb::StatisticsPropagator::CanPropagateCast ( const LogicalType & source,
const LogicalType & target )
static

Whether or not we can propagate a cast between two types.

323356 {
323357 if (source == target) {
323358 return true;
323359 }
323360 // we can only propagate numeric -> numeric
323361 switch (source.InternalType()) {
323362 case PhysicalType::INT8:
323363 case PhysicalType::INT16:
323364 case PhysicalType::INT32:
323365 case PhysicalType::INT64:
323366 case PhysicalType::INT128:
323367 case PhysicalType::FLOAT:
323369 break;
323370 default:
323371 return false;
323372 }
323373 switch (target.InternalType()) {
323374 case PhysicalType::INT8:
323375 case PhysicalType::INT16:
323376 case PhysicalType::INT32:
323377 case PhysicalType::INT64:
323378 case PhysicalType::INT128:
323379 case PhysicalType::FLOAT:
323381 break;
323382 default:
323383 return false;
323384 }
323385 // for time/timestamps/dates - there are various limitations on what we can propagate
323386 // Downcasting timestamps to times is not a truncation operation
323387 switch (target.id()) {
323388 case LogicalTypeId::TIME: {
323389 switch (source.id()) {
323390 case LogicalTypeId::TIMESTAMP:
323391 case LogicalTypeId::TIMESTAMP_SEC:
323392 case LogicalTypeId::TIMESTAMP_MS:
323394 case LogicalTypeId::TIMESTAMP_TZ:
323395 return false;
323396 default:
323397 break;
323398 }
323399 break;
323400 }
323401 // FIXME: perform actual stats propagation for these casts
323402 case LogicalTypeId::TIMESTAMP:
323403 case LogicalTypeId::TIMESTAMP_TZ: {
323404 const bool to_timestamp = target.id() == LogicalTypeId::TIMESTAMP;
323405 const bool to_timestamp_tz = target.id() == LogicalTypeId::TIMESTAMP_TZ;
323406 // Casting to timestamp[_tz] (us) from a different unit can not re-use stats
323407 switch (source.id()) {
323409 case LogicalTypeId::TIMESTAMP_MS:
323410 case LogicalTypeId::TIMESTAMP_SEC:
323411 return false;
323412 case LogicalTypeId::TIMESTAMP: {
323413 if (to_timestamp_tz) {
323414 // Both use INT64 physical type, but should not be treated equal
323415 return false;
323416 }
323417 break;
323418 }
323419 case LogicalTypeId::TIMESTAMP_TZ: {
323420 if (to_timestamp) {
323421 // Both use INT64 physical type, but should not be treated equal
323422 return false;
323423 }
323424 break;
323425 }
323426 default:
323427 break;
323428 }
323429 break;
323430 }
323432 // Same as above ^
323433 switch (source.id()) {
323434 case LogicalTypeId::TIMESTAMP:
323435 case LogicalTypeId::TIMESTAMP_TZ:
323436 case LogicalTypeId::TIMESTAMP_MS:
323437 case LogicalTypeId::TIMESTAMP_SEC:
323438 return false;
323439 default:
323440 break;
323441 }
323442 break;
323443 }
323444 case LogicalTypeId::TIMESTAMP_MS: {
323445 // Same as above ^
323446 switch (source.id()) {
323447 case LogicalTypeId::TIMESTAMP:
323448 case LogicalTypeId::TIMESTAMP_TZ:
323450 case LogicalTypeId::TIMESTAMP_SEC:
323451 return false;
323452 default:
323453 break;
323454 }
323455 break;
323456 }
323457 case LogicalTypeId::TIMESTAMP_SEC: {
323458 // Same as above ^
323459 switch (source.id()) {
323460 case LogicalTypeId::TIMESTAMP:
323461 case LogicalTypeId::TIMESTAMP_TZ:
323463 case LogicalTypeId::TIMESTAMP_MS:
323464 return false;
323465 default:
323466 break;
323467 }
323468 break;
323469 }
323470 default:
323471 break;
323472 }
323473 // we can propagate!
323474 return true;
323475}
@ TIMESTAMP_NS
us
Definition duckdb.hpp:2886
@ INT64
Signed 64-bit little-endian integer.
Definition duckdb.hpp:2767
@ INT16
Signed 16-bit little-endian integer.
Definition duckdb.hpp:2755
@ INT32
Signed 32-bit little-endian integer.
Definition duckdb.hpp:2761
@ FLOAT
4-byte floating point value
Definition duckdb.hpp:2773
@ INT8
Signed 8-bit little-endian integer.
Definition duckdb.hpp:2749
@ DOUBLE
8-byte floating point value
Definition duckdb.hpp:2776

◆ TryPropagateCast()

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::TryPropagateCast ( const BaseStatistics & stats,
const LogicalType & source,
const LogicalType & target )
static
323504 {
323505 if (source.id() == LogicalTypeId::VARIANT) {
323506 return StatisticsPropagateVariant(stats, target);
323507 }
323508 if (!CanPropagateCast(source, target)) {
323509 return nullptr;
323510 }
323511 return StatisticsOperationsNumericNumericCast(stats, target);
323512}
static bool CanPropagateCast(const LogicalType &source, const LogicalType &target)
Whether or not we can propagate a cast between two types.
Definition duckdb.cpp:323356

◆ PropagateStatistics() [2/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalOperator & node,
unique_ptr< LogicalOperator > & node_ptr )
private

Propagate statistics through an operator.

325391 {
325392 unique_ptr<NodeStatistics> result;
325393 switch (node.type) {
325394 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
325395 result = PropagateStatistics(node.Cast<LogicalAggregate>(), node_ptr);
325396 break;
325397 case LogicalOperatorType::LOGICAL_CROSS_PRODUCT:
325398 result = PropagateStatistics(node.Cast<LogicalCrossProduct>(), node_ptr);
325399 break;
325400 case LogicalOperatorType::LOGICAL_FILTER:
325401 result = PropagateStatistics(node.Cast<LogicalFilter>(), node_ptr);
325402 break;
325403 case LogicalOperatorType::LOGICAL_GET:
325404 result = PropagateStatistics(node.Cast<LogicalGet>(), node_ptr);
325405 break;
325406 case LogicalOperatorType::LOGICAL_PROJECTION:
325407 result = PropagateStatistics(node.Cast<LogicalProjection>(), node_ptr);
325408 break;
325409 case LogicalOperatorType::LOGICAL_ANY_JOIN:
325410 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
325411 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
325412 case LogicalOperatorType::LOGICAL_JOIN:
325413 case LogicalOperatorType::LOGICAL_DELIM_JOIN:
325414 result = PropagateStatistics(node.Cast<LogicalJoin>(), node_ptr);
325415 break;
325416 case LogicalOperatorType::LOGICAL_POSITIONAL_JOIN:
325417 result = PropagateStatistics(node.Cast<LogicalPositionalJoin>(), node_ptr);
325418 break;
325419 case LogicalOperatorType::LOGICAL_UNION:
325420 case LogicalOperatorType::LOGICAL_EXCEPT:
325421 case LogicalOperatorType::LOGICAL_INTERSECT:
325422 result = PropagateStatistics(node.Cast<LogicalSetOperation>(), node_ptr);
325423 break;
325424 case LogicalOperatorType::LOGICAL_ORDER_BY:
325425 result = PropagateStatistics(node.Cast<LogicalOrder>(), node_ptr);
325426 break;
325427 case LogicalOperatorType::LOGICAL_WINDOW:
325428 result = PropagateStatistics(node.Cast<LogicalWindow>(), node_ptr);
325429 break;
325430 default:
325431 result = PropagateChildren(node, node_ptr);
325432 }
325433
325434 if (!optimizer.OptimizerDisabled(OptimizerType::COMPRESSED_MATERIALIZATION)) {
325435 // compress data based on statistics for materializing operators
325436 CompressedMaterialization compressed_materialization(optimizer, *root, statistics_map);
325437 compressed_materialization.Compress(node_ptr);
325438 }
325439
325440 return result;
325441}

◆ PropagateStatistics() [3/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalFilter & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324506 {
324507 // first propagate to the child
324508 node_stats = PropagateStatistics(filter.children[0]);
324509 if (filter.children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT) {
324510 ReplaceWithEmptyResult(node_ptr);
324511 return make_uniq<NodeStatistics>(0U, 0U);
324512 }
324513
324514 // then propagate to each of the expressions
324515 for (idx_t i = 0; i < filter.expressions.size(); i++) {
324516 auto &condition = filter.expressions[i];
324517 auto prune_result = HandleFilter(condition);
324518 if (prune_result == FilterPropagateResult::FILTER_ALWAYS_TRUE) {
324519 // filter is always true; it is useless to execute it
324520 // erase this condition
324521 filter.expressions.erase_at(i);
324522 i--;
324523 if (filter.expressions.empty()) {
324524 // if there is a projection map, we should keep the filter
324525 // the physical planner will eventually skip the filter, but will keep
324526 // the correct columns.
324527 if (filter.projection_map.empty()) {
324528 node_ptr = std::move(filter.children[0]);
324529 }
324530 break;
324531 }
324532 } else if (prune_result == FilterPropagateResult::FILTER_FALSE_OR_NULL) {
324533 // filter is always false or null; this entire filter should be replaced by an empty result block
324534 ReplaceWithEmptyResult(node_ptr);
324535 return make_uniq<NodeStatistics>(0U, 0U);
324536 }
324537 }
324538 // the max cardinality of a filter is the cardinality of the input (i.e. no tuples get filtered)
324539 return std::move(node_stats);
324540}
unique_ptr< NodeStatistics > node_stats
Node stats for the current node.
Definition duckdb.hpp:51466
FilterPropagateResult HandleFilter(unique_ptr< Expression > &condition)
Propagate a filter condition.
Definition duckdb.cpp:324484
void filter(InputArray image, InputArray kernel, OutputArray output)
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237

◆ PropagateStatistics() [4/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalGet & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324660 {
324661 if (get.function.cardinality) {
324662 node_stats = get.function.cardinality(context, get.bind_data.get());
324663 }
324664 if (!get.function.statistics && !get.function.statistics_extended) {
324665 // no column statistics to get
324666 return std::move(node_stats);
324667 }
324668 auto &column_ids = get.GetColumnIds();
324669 for (idx_t i = 0; i < column_ids.size(); i++) {
324670 unique_ptr<BaseStatistics> stats;
324671 if (get.function.statistics_extended) {
324672 TableFunctionGetStatisticsInput input(get.bind_data.get(), column_ids[i]);
324673 stats = get.function.statistics_extended(context, input);
324674 } else {
324675 stats = get.function.statistics(context, get.bind_data.get(), column_ids[i].GetPrimaryIndex());
324676 }
324677
324678 if (stats) {
324679 ColumnBinding binding(get.table_index, i);
324680 statistics_map.insert(make_pair(binding, std::move(stats)));
324681 }
324682 }
324683 // push table filters into the statistics
324684 vector<idx_t> column_indexes;
324685 column_indexes.reserve(get.table_filters.filters.size());
324686 for (auto &kv : get.table_filters.filters) {
324687 column_indexes.push_back(kv.first);
324688 }
324689
324690 for (auto &table_filter_column : column_indexes) {
324691 idx_t column_index;
324692 for (column_index = 0; column_index < column_ids.size(); column_index++) {
324693 if (column_ids[column_index].GetPrimaryIndex() == table_filter_column) {
324694 break;
324695 }
324696 }
324697 D_ASSERT(column_index < column_ids.size());
324698 D_ASSERT(column_ids[column_index].GetPrimaryIndex() == table_filter_column);
324699
324700 // find the stats
324701 ColumnBinding stats_binding(get.table_index, column_index);
324702 auto entry = statistics_map.find(stats_binding);
324703 if (entry == statistics_map.end()) {
324704 // no stats for this entry
324705 continue;
324706 }
324707 auto &stats = *entry->second;
324708
324709 // fetch the table filter
324710 D_ASSERT(get.table_filters.filters.count(table_filter_column) > 0);
324711 auto &filter = get.table_filters.filters[table_filter_column];
324712 auto propagate_result = PropagateTableFilter(stats_binding, stats, *filter);
324713 switch (propagate_result) {
324714 case FilterPropagateResult::FILTER_ALWAYS_TRUE:
324715 // filter is always true; it is useless to execute it
324716 // erase this condition
324717 get.table_filters.filters.erase(table_filter_column);
324718 break;
324719 case FilterPropagateResult::FILTER_TRUE_OR_NULL: {
324720 if (IsConstantOrNullFilter(*get.table_filters.filters[table_filter_column]) &&
324721 !CanReplaceConstantOrNull(*get.table_filters.filters[table_filter_column])) {
324722 break;
324723 }
324724 // filter is true or null; we can replace this with a not null filter
324725 get.table_filters.filters[table_filter_column] = make_uniq<IsNotNullFilter>();
324726 break;
324727 }
324728 case FilterPropagateResult::FILTER_FALSE_OR_NULL:
324729 case FilterPropagateResult::FILTER_ALWAYS_FALSE:
324730 // filter is always false; this entire filter should be replaced by an empty result block
324731 ReplaceWithEmptyResult(node_ptr);
324732 return make_uniq<NodeStatistics>(0U, 0U);
324733 default:
324734 // general case: filter can be true or false, update this columns' statistics
324735 UpdateFilterStatistics(stats, *filter);
324736 break;
324737 }
324738 }
324739 return std::move(node_stats);
324740}
FilterPropagateResult PropagateTableFilter(ColumnBinding stats_binding, BaseStatistics &stats, TableFilter &filter)
Run a comparison between the statistics and the table filter; returns the prune result.
Definition duckdb.cpp:324571
void UpdateFilterStatistics(BaseStatistics &input, ExpressionType comparison_type, const Value &constant)
Update filter statistics from a filter with a constant.
Definition duckdb.cpp:324306
__host__ cudaTextureObject_t get() const noexcept

◆ PropagateStatistics() [5/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalJoin & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324948 {
324949 // first propagate through the children of the join
324950 node_stats = PropagateStatistics(join.children[0]);
324951 for (idx_t child_idx = 1; child_idx < join.children.size(); child_idx++) {
324952 auto child_stats = PropagateStatistics(join.children[child_idx]);
324953 if (!child_stats) {
324954 node_stats = nullptr;
324955 } else if (node_stats) {
324956 MultiplyCardinalities(node_stats, *child_stats);
324957 }
324958 }
324959
324960 auto join_type = join.join_type;
324961 // depending on the join type, we might need to alter the statistics
324962 // LEFT, FULL, RIGHT OUTER and SINGLE joins can introduce null values
324963 // this requires us to alter the statistics after this point in the query plan
324964 bool adds_null_on_left = IsRightOuterJoin(join_type);
324965 bool adds_null_on_right = IsLeftOuterJoin(join_type) || join_type == JoinType::SINGLE;
324966
324967 vector<ColumnBinding> left_bindings, right_bindings;
324968 if (adds_null_on_left) {
324969 left_bindings = join.children[0]->GetColumnBindings();
324970 }
324971 if (adds_null_on_right) {
324972 right_bindings = join.children[1]->GetColumnBindings();
324973 }
324974
324975 // then propagate into the join conditions
324976 switch (join.type) {
324977 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
324978 case LogicalOperatorType::LOGICAL_DELIM_JOIN:
324979 case LogicalOperatorType::LOGICAL_ASOF_JOIN:
324980 PropagateStatistics(join.Cast<LogicalComparisonJoin>(), node_ptr);
324981 break;
324982 case LogicalOperatorType::LOGICAL_ANY_JOIN:
324983 PropagateStatistics(join.Cast<LogicalAnyJoin>(), node_ptr);
324984 break;
324985 default:
324986 break;
324987 }
324988
324989 if (adds_null_on_right) {
324990 // left or full outer join: set IsNull() to true for all rhs statistics
324991 for (auto &binding : right_bindings) {
324992 auto stats = statistics_map.find(binding);
324993 if (stats != statistics_map.end()) {
324994 stats->second->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
324995 }
324996 }
324997 }
324998 if (adds_null_on_left) {
324999 // right or full outer join: set IsNull() to true for all lhs statistics
325000 for (auto &binding : left_bindings) {
325001 auto stats = statistics_map.find(binding);
325002 if (stats != statistics_map.end()) {
325003 stats->second->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
325004 }
325005 }
325006 }
325007 return std::move(node_stats);
325008}
void MultiplyCardinalities(unique_ptr< NodeStatistics > &stats, NodeStatistics &new_stats)
Multiply the cardinalities together (i.e. new max cardinality is stats.max * new_stats....
Definition duckdb.cpp:324926
cv::String join(const cv::String &base, const cv::String &path)
bool IsRightOuterJoin(JoinType type)
True if join is rght or full outer join.
Definition duckdb.cpp:68423
bool IsLeftOuterJoin(JoinType type)
True if join is left or full outer join.
Definition duckdb.cpp:68419

◆ PropagateStatistics() [6/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalPositionalJoin & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325021 {
325022 D_ASSERT(join.type == LogicalOperatorType::LOGICAL_POSITIONAL_JOIN);
325023
325024 // first propagate through the children of the join
325025 node_stats = PropagateStatistics(join.children[0]);
325026 for (idx_t child_idx = 1; child_idx < join.children.size(); child_idx++) {
325027 auto child_stats = PropagateStatistics(join.children[child_idx]);
325028 if (!child_stats) {
325029 node_stats = nullptr;
325030 } else if (node_stats) {
325031 if (!node_stats->has_estimated_cardinality || !child_stats->has_estimated_cardinality ||
325032 !node_stats->has_max_cardinality || !child_stats->has_max_cardinality) {
325033 node_stats = nullptr;
325034 } else {
325035 MaxCardinalities(node_stats, *child_stats);
325036 }
325037 }
325038 }
325039
325040 // No conditions.
325041
325042 // Positional Joins are always FULL OUTER
325043
325044 // set IsNull() to true for all lhs statistics
325045 auto left_bindings = join.children[0]->GetColumnBindings();
325046 for (auto &binding : left_bindings) {
325047 auto stats = statistics_map.find(binding);
325048 if (stats != statistics_map.end()) {
325049 stats->second->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
325050 }
325051 }
325052
325053 // set IsNull() to true for all rhs statistics
325054 auto right_bindings = join.children[1]->GetColumnBindings();
325055 for (auto &binding : right_bindings) {
325056 auto stats = statistics_map.find(binding);
325057 if (stats != statistics_map.end()) {
325058 stats->second->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
325059 }
325060 }
325061
325062 return std::move(node_stats);
325063}

◆ PropagateStatistics() [7/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalProjection & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325155 {
325156 // first propagate to the child
325157 node_stats = PropagateStatistics(proj.children[0]);
325158 if (proj.children[0]->type == LogicalOperatorType::LOGICAL_EMPTY_RESULT) {
325159 ReplaceWithEmptyResult(node_ptr);
325160 return std::move(node_stats);
325161 }
325162 // then propagate to each of the expressions
325163 for (idx_t i = 0; i < proj.expressions.size(); i++) {
325164 auto stats = PropagateExpression(proj.expressions[i]);
325165 if (stats) {
325166 ColumnBinding binding(proj.table_index, i);
325167 statistics_map.insert(make_pair(binding, std::move(stats)));
325168 }
325169 }
325170 return std::move(node_stats);
325171}

◆ PropagateStatistics() [8/15]

void duckdb::StatisticsPropagator::PropagateStatistics ( LogicalComparisonJoin & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324759 {
324760 for (idx_t i = 0; i < join.conditions.size(); i++) {
324761 auto &condition = join.conditions[i];
324762 const auto stats_left = PropagateExpression(condition.left);
324763 const auto stats_right = PropagateExpression(condition.right);
324764 if (stats_left && stats_right) {
324765 if ((condition.comparison == ExpressionType::COMPARE_DISTINCT_FROM ||
324766 condition.comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM) &&
324767 stats_left->CanHaveNull() && stats_right->CanHaveNull()) {
324768 // null values are equal in this join, and both sides can have null values
324769 // nothing to do here
324770 continue;
324771 }
324772 auto prune_result = PropagateComparison(*stats_left, *stats_right, condition.comparison);
324773 // Add stats to logical_join for perfect hash join
324774 join.join_stats.push_back(stats_left->ToUnique());
324775 join.join_stats.push_back(stats_right->ToUnique());
324776 switch (prune_result) {
324777 case FilterPropagateResult::FILTER_FALSE_OR_NULL:
324778 case FilterPropagateResult::FILTER_ALWAYS_FALSE:
324779 // filter is always false or null, none of the join conditions matter
324780 switch (join.join_type) {
324781 case JoinType::RIGHT_SEMI:
324782 case JoinType::SEMI:
324783 case JoinType::INNER:
324784 // semi or inner join on false; entire node can be pruned
324785 ReplaceWithEmptyResult(node_ptr);
324786 return;
324787 case JoinType::RIGHT_ANTI:
324788 case JoinType::ANTI: {
324789 if (join.join_type == JoinType::RIGHT_ANTI) {
324790 std::swap(join.children[0], join.children[1]);
324791 }
324792 // If the filter is always false or Null, just return the left child.
324793 node_ptr = std::move(join.children[0]);
324794 return;
324795 }
324796 case JoinType::LEFT:
324797 // anti/left outer join: replace right side with empty node
324798 ReplaceWithEmptyResult(join.children[1]);
324799 return;
324800 case JoinType::RIGHT:
324801 // right outer join: replace left side with empty node
324802 ReplaceWithEmptyResult(join.children[0]);
324803 return;
324804 default:
324805 // other join types: can't do much meaningful with this information
324806 // full outer join requires both sides anyway; we can skip the execution of the actual join, but eh
324807 // mark/single join requires knowing if the rhs has null values or not
324808 break;
324809 }
324810 break;
324811 case FilterPropagateResult::FILTER_ALWAYS_TRUE:
324812 // filter is always true
324813 // If this is the inequality for an AsOf join,
324814 // then we must leave it in because it also flags
324815 // the semantics of restricting to a single match
324816 // so we can't replace it with an equi-join on the remaining conditions.
324817 if (join.type == LogicalOperatorType::LOGICAL_ASOF_JOIN) {
324818 switch (condition.comparison) {
324819 case ExpressionType::COMPARE_GREATERTHAN:
324820 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
324821 case ExpressionType::COMPARE_LESSTHAN:
324822 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
324823 continue;
324824 default:
324825 break;
324826 }
324827 }
324828 if (join.conditions.size() > 1) {
324829 // there are multiple conditions: erase this condition
324830 join.conditions.erase_at(i);
324831 // remove the corresponding statistics
324832 join.join_stats.clear();
324833 i--;
324834 continue;
324835 } else {
324836 // this is the only condition and it is always true: all conditions are true
324837 switch (join.join_type) {
324838 case JoinType::RIGHT_SEMI:
324839 case JoinType::SEMI: {
324840 if (join.join_type == JoinType::RIGHT_SEMI) {
324841 std::swap(join.children[0], join.children[1]);
324842 }
324843 // when the right child has no data, return an empty set
324844 // cannot just return the left child because if the right child has no cardinality
324845 // then the whole result should be empty.
324846 // TODO: write better CE logic for limits so that we can just look at
324847 // join.children[1].estimated_cardinality.
324848 auto limit = make_uniq<LogicalLimit>(BoundLimitNode::ConstantValue(1), BoundLimitNode());
324849 limit->SetEstimatedCardinality(1);
324850 limit->AddChild(std::move(join.children[1]));
324851 auto cross_product = LogicalCrossProduct::Create(std::move(join.children[0]), std::move(limit));
324852 node_ptr = std::move(cross_product);
324853 return;
324854 }
324855 case JoinType::INNER: {
324856 // inner, replace with cross product
324857 auto cross_product =
324858 LogicalCrossProduct::Create(std::move(join.children[0]), std::move(join.children[1]));
324859 node_ptr = std::move(cross_product);
324860 return;
324861 }
324862 case JoinType::ANTI:
324863 case JoinType::RIGHT_ANTI: {
324864 ReplaceWithEmptyResult(node_ptr);
324865 return;
324866 }
324867 default:
324868 // we don't handle mark/single join here yet
324869 break;
324870 }
324871 }
324872 break;
324873 default:
324874 break;
324875 }
324876 }
324877 // after we have propagated, we can update the statistics on both sides
324878 // note that it is fine to do this now, even if the same column is used again later
324879 // e.g. if we have i=j AND i=k, and the stats for j and k are disjoint, we know there are no results
324880 // so if we have e.g. i: [0, 100], j: [0, 25], k: [75, 100]
324881 // we can set i: [0, 25] after the first comparison, and statically determine that the second comparison is fals
324882
324883 // note that we can't update statistics the same for all join types
324884 // mark and single joins don't filter any tuples -> so there is no propagation possible
324885 // anti joins have inverse statistics propagation
324886 // (i.e. if we have an anti join on i: [0, 100] and j: [0, 25], the resulting stats are i:[25,100])
324887 // for now we don't handle anti joins
324888 if (condition.comparison == ExpressionType::COMPARE_DISTINCT_FROM ||
324889 condition.comparison == ExpressionType::COMPARE_NOT_DISTINCT_FROM) {
324890 // skip update when null values are equal (for now?)
324891 continue;
324892 }
324893 switch (join.join_type) {
324894 case JoinType::INNER:
324895 case JoinType::SEMI: {
324896 UpdateFilterStatistics(*condition.left, *condition.right, condition.comparison);
324897 auto updated_stats_left = PropagateExpression(condition.left);
324898 auto updated_stats_right = PropagateExpression(condition.right);
324899
324900 // Try to push lhs stats down rhs and vice versa
324901 if (stats_left && stats_right && updated_stats_left && updated_stats_right &&
324902 condition.left->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF &&
324903 condition.right->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
324904 CreateFilterFromJoinStats(join.children[0], condition.left, *stats_left, *updated_stats_left);
324905 CreateFilterFromJoinStats(join.children[1], condition.right, *stats_right, *updated_stats_right);
324906 }
324907
324908 // Update join_stats when is already part of the join
324909 if (join.join_stats.size() == 2) {
324910 join.join_stats[0] = std::move(updated_stats_left);
324911 join.join_stats[1] = std::move(updated_stats_right);
324912 }
324913 break;
324914 }
324915 default:
324916 break;
324917 }
324918 }
324919}
void CreateFilterFromJoinStats(unique_ptr< LogicalOperator > &child, unique_ptr< Expression > &expr, const BaseStatistics &stats_before, const BaseStatistics &stats_after)
Creates and pushes down a filter based on join statistics.
Definition duckdb.cpp:325065
FilterPropagateResult PropagateComparison(BaseStatistics &left, BaseStatistics &right, ExpressionType comparison)
Run a comparison with two sets of statistics, returns if the comparison will always returns true/fals...
Definition duckdb.cpp:323550

◆ PropagateStatistics() [9/15]

void duckdb::StatisticsPropagator::PropagateStatistics ( LogicalAnyJoin & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324921 {
324922 // propagate the expression into the join condition
324923 PropagateExpression(join.condition);
324924}

◆ PropagateStatistics() [10/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalSetOperation & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325251 {
325252 if (setop.type == LogicalOperatorType::LOGICAL_UNION) {
325253 return PropagateUnion(setop, node_ptr);
325254 }
325255 D_ASSERT(setop.children.size() == 2);
325256 // first propagate statistics in the child nodes
325257 auto left_stats = PropagateStatistics(setop.children[0]);
325258 auto right_stats = PropagateStatistics(setop.children[1]);
325259
325260 // now fetch the column bindings on both sides
325261 auto left_bindings = setop.children[0]->GetColumnBindings();
325262 auto right_bindings = setop.children[1]->GetColumnBindings();
325263
325264 D_ASSERT(left_bindings.size() == right_bindings.size());
325265 D_ASSERT(left_bindings.size() == setop.column_count);
325266 for (idx_t i = 0; i < setop.column_count; i++) {
325267 // for each column binding, we fetch the statistics from both the lhs and the rhs
325268 auto left_entry = statistics_map.find(left_bindings[i]);
325269 auto right_entry = statistics_map.find(right_bindings[i]);
325270 if (left_entry == statistics_map.end() || right_entry == statistics_map.end()) {
325271 // no statistics on one of the sides: can't propagate stats
325272 continue;
325273 }
325274 unique_ptr<BaseStatistics> new_stats;
325275 switch (setop.type) {
325276 case LogicalOperatorType::LOGICAL_EXCEPT:
325277 // except: use the stats of the LHS
325278 new_stats = left_entry->second->ToUnique();
325279 break;
325280 case LogicalOperatorType::LOGICAL_INTERSECT:
325281 // intersect: intersect the two stats
325282 // FIXME: for now we just use the stats of the LHS, as this is correct
325283 // however, the stats can be further refined to the minimal subset of the LHS and RHS
325284 new_stats = left_entry->second->ToUnique();
325285 break;
325286 default:
325287 throw InternalException("Unsupported setop type");
325288 }
325289 ColumnBinding binding(setop.table_index, i);
325290 statistics_map[binding] = std::move(new_stats);
325291 }
325292 if (!left_stats || !right_stats) {
325293 return nullptr;
325294 }
325295 return left_stats;
325296}

◆ PropagateStatistics() [11/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalAggregate & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324171 {
324172 // first propagate statistics in the child node
324173 node_stats = PropagateStatistics(aggr.children[0]);
324174
324175 // handle the groups: simply propagate statistics and assign the stats to the group binding
324176 aggr.group_stats.resize(aggr.groups.size());
324177 for (idx_t group_idx = 0; group_idx < aggr.groups.size(); group_idx++) {
324178 auto stats = PropagateExpression(aggr.groups[group_idx]);
324179 aggr.group_stats[group_idx] = stats ? stats->ToUnique() : nullptr;
324180 if (!stats) {
324181 continue;
324182 }
324183 if (aggr.grouping_sets.size() > 1) {
324184 // aggregates with multiple grouping sets can introduce NULL values to certain groups
324185 // FIXME: actually figure out WHICH groups can have null values introduced
324186 stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
324187 continue;
324188 }
324189 ColumnBinding group_binding(aggr.group_index, group_idx);
324190 statistics_map[group_binding] = std::move(stats);
324191 }
324192 // propagate statistics in the aggregates
324193 for (idx_t aggregate_idx = 0; aggregate_idx < aggr.expressions.size(); aggregate_idx++) {
324194 auto stats = PropagateExpression(aggr.expressions[aggregate_idx]);
324195 if (!stats) {
324196 continue;
324197 }
324198 ColumnBinding aggregate_binding(aggr.aggregate_index, aggregate_idx);
324199 statistics_map[aggregate_binding] = std::move(stats);
324200 }
324201
324202 // check whether all inputs to the aggregate functions are valid
324203 TupleDataValidityType distinct_validity = TupleDataValidityType::CANNOT_HAVE_NULL_VALUES;
324204 for (const auto &aggr_ref : aggr.expressions) {
324205 if (distinct_validity == TupleDataValidityType::CAN_HAVE_NULL_VALUES) {
324206 break;
324207 }
324208 if (aggr_ref->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) {
324209 // Bail if it's not a bound aggregate
324210 distinct_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES;
324211 break;
324212 }
324213 auto &aggr_expr = aggr_ref->Cast<BoundAggregateExpression>();
324214 for (const auto &child : aggr_expr.children) {
324215 if (child->GetExpressionClass() != ExpressionClass::BOUND_COLUMN_REF) {
324216 // Bail if bound aggregate child is not a colref
324217 distinct_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES;
324218 break;
324219 }
324220 const auto &col_ref = child->Cast<BoundColumnRefExpression>();
324221 auto it = statistics_map.find(col_ref.binding);
324222 if (it == statistics_map.end() || !it->second || it->second->CanHaveNull()) {
324223 // Bail if no stats or if there can be a NULL
324224 distinct_validity = TupleDataValidityType::CAN_HAVE_NULL_VALUES;
324225 break;
324226 }
324227 }
324228 }
324229 aggr.distinct_validity = distinct_validity;
324230
324231 // after we propagate statistics - try to directly execute aggregates using statistics
324232 TryExecuteAggregates(aggr, node_ptr);
324233
324234 // the max cardinality of an aggregate is the max cardinality of the input (i.e. when every row is a unique
324235 // group)
324236 return std::move(node_stats);
324237}
void TryExecuteAggregates(LogicalAggregate &op, unique_ptr< LogicalOperator > &node_ptr)
Try to execute aggregates using only the statistics if possible.
Definition duckdb.cpp:323971

◆ PropagateStatistics() [12/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalCrossProduct & op,
unique_ptr< LogicalOperator > & node_ptr )
private
324246 {
324247 // first propagate statistics in the child node
324248 auto left_stats = PropagateStatistics(cp.children[0]);
324249 auto right_stats = PropagateStatistics(cp.children[1]);
324250 if (!left_stats || !right_stats) {
324251 return nullptr;
324252 }
324253 MultiplyCardinalities(left_stats, *right_stats);
324254 return left_stats;
324255}

◆ PropagateStatistics() [13/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalLimit & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325118 {
325119 // propagate statistics in the child node
325120 PropagateStatistics(limit.children[0]);
325121 // return the node stats, with as expected cardinality the amount specified in the limit
325122 if (limit.limit_val.Type() == LimitNodeType::CONSTANT_VALUE) {
325123 auto constant_limit = limit.limit_val.GetConstantValue();
325124 return make_uniq<NodeStatistics>(constant_limit, constant_limit);
325125 }
325126 return nullptr;
325127}

◆ PropagateStatistics() [14/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalOrder & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325137 {
325138 // first propagate to the child
325139 node_stats = PropagateStatistics(order.children[0]);
325140
325141 // then propagate to each of the order expressions
325142 for (auto &bound_order : order.orders) {
325143 bound_order.stats = PropagateExpression(bound_order.expression);
325144 }
325145 return std::move(node_stats);
325146}

◆ PropagateStatistics() [15/15]

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateStatistics ( LogicalWindow & op,
unique_ptr< LogicalOperator > & node_ptr )
private
325306 {
325307 // first propagate to the child
325308 node_stats = PropagateStatistics(window.children[0]);
325309
325310 // then propagate to each of the order expressions
325311 for (auto &window_expr : window.expressions) {
325312 auto &over_expr = window_expr->Cast<BoundWindowExpression>();
325313 for (auto &expr : over_expr.partitions) {
325314 over_expr.partitions_stats.push_back(PropagateExpression(expr));
325315 }
325316 for (auto &bound_order : over_expr.orders) {
325317 bound_order.stats = PropagateExpression(bound_order.expression);
325318 }
325319
325320 if (over_expr.start_expr) {
325321 over_expr.expr_stats.push_back(PropagateExpression(over_expr.start_expr));
325322 } else {
325323 over_expr.expr_stats.push_back(nullptr);
325324 }
325325
325326 if (over_expr.end_expr) {
325327 over_expr.expr_stats.push_back(PropagateExpression(over_expr.end_expr));
325328 } else {
325329 over_expr.expr_stats.push_back(nullptr);
325330 }
325331
325332 if (over_expr.offset_expr) {
325333 over_expr.expr_stats.push_back(PropagateExpression(over_expr.offset_expr));
325334 } else {
325335 over_expr.expr_stats.push_back(nullptr);
325336 }
325337
325338 if (over_expr.default_expr) {
325339 over_expr.expr_stats.push_back(PropagateExpression(over_expr.default_expr));
325340 } else {
325341 over_expr.expr_stats.push_back(nullptr);
325342 }
325343 for (auto &bound_order : over_expr.arg_orders) {
325344 bound_order.stats = PropagateExpression(bound_order.expression);
325345 }
325346 }
325347 return std::move(node_stats);
325348}

◆ PropagateChildren()

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateChildren ( LogicalOperator & node,
unique_ptr< LogicalOperator > & node_ptr )
private
325383 {
325384 for (idx_t child_idx = 0; child_idx < node.children.size(); child_idx++) {
325385 PropagateStatistics(node.children[child_idx]);
325386 }
325387 return nullptr;
325388}

◆ StatisticsFromValue()

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::StatisticsFromValue ( const Value & input)
private

Return statistics from a constant value.

323748 {
323749 return BaseStatistics::FromConstant(input).ToUnique();
323750}

◆ PropagateComparison()

FilterPropagateResult duckdb::StatisticsPropagator::PropagateComparison ( BaseStatistics & left,
BaseStatistics & right,
ExpressionType comparison )
private

Run a comparison with two sets of statistics, returns if the comparison will always returns true/false or not.

323551 {
323552 // only handle numerics for now
323553 switch (lstats.GetType().InternalType()) {
323554 case PhysicalType::BOOL:
323555 case PhysicalType::UINT8:
323559 case PhysicalType::UINT128:
323560 case PhysicalType::INT8:
323561 case PhysicalType::INT16:
323562 case PhysicalType::INT32:
323563 case PhysicalType::INT64:
323564 case PhysicalType::INT128:
323565 case PhysicalType::FLOAT:
323567 break;
323568 default:
323569 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323570 }
323571 if (!NumericStats::HasMinMax(lstats) || !NumericStats::HasMinMax(rstats)) {
323572 // no stats available: nothing to prune
323573 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323574 }
323575 // the result of the propagation depend on whether or not either side has null values
323576 // if there are null values present, we cannot say whether or not
323577 bool has_null = lstats.CanHaveNull() || rstats.CanHaveNull();
323578 switch (comparison) {
323579 case ExpressionType::COMPARE_EQUAL:
323580 // l = r, if l.min > r.max or r.min > l.max equality is not possible
323581 if (NumericStats::Min(lstats) > NumericStats::Max(rstats) ||
323582 NumericStats::Min(rstats) > NumericStats::Max(lstats)) {
323583 return has_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE;
323584 } else {
323585 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323586 }
323587 case ExpressionType::COMPARE_GREATERTHAN:
323588 // l > r
323589 if (NumericStats::Min(lstats) > NumericStats::Max(rstats)) {
323590 // if l.min > r.max, it is always true ONLY if neither side contains nulls
323591 return has_null ? FilterPropagateResult::FILTER_TRUE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_TRUE;
323592 }
323593 // if r.min is bigger or equal to l.max, the filter is always false
323594 if (NumericStats::Min(rstats) >= NumericStats::Max(lstats)) {
323595 return has_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE;
323596 }
323597 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323598 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
323599 // l >= r
323600 if (NumericStats::Min(lstats) >= NumericStats::Max(rstats)) {
323601 // if l.min >= r.max, it is always true ONLY if neither side contains nulls
323602 return has_null ? FilterPropagateResult::FILTER_TRUE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_TRUE;
323603 }
323604 // if r.min > l.max, the filter is always false
323605 if (NumericStats::Min(rstats) > NumericStats::Max(lstats)) {
323606 return has_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE;
323607 }
323608 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323609 case ExpressionType::COMPARE_LESSTHAN:
323610 // l < r
323611 if (NumericStats::Max(lstats) < NumericStats::Min(rstats)) {
323612 // if l.max < r.min, it is always true ONLY if neither side contains nulls
323613 return has_null ? FilterPropagateResult::FILTER_TRUE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_TRUE;
323614 }
323615 // if l.min >= rstats.max, the filter is always false
323616 if (NumericStats::Min(lstats) >= NumericStats::Max(rstats)) {
323617 return has_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE;
323618 }
323619 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323620 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
323621 // l <= r
323622 if (NumericStats::Max(lstats) <= NumericStats::Min(rstats)) {
323623 // if l.max <= r.min, it is always true ONLY if neither side contains nulls
323624 return has_null ? FilterPropagateResult::FILTER_TRUE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_TRUE;
323625 }
323626 // if l.min > rstats.max, the filter is always false
323627 if (NumericStats::Min(lstats) > NumericStats::Max(rstats)) {
323628 return has_null ? FilterPropagateResult::FILTER_FALSE_OR_NULL : FilterPropagateResult::FILTER_ALWAYS_FALSE;
323629 }
323630 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323631 default:
323632 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
323633 }
323634}
@ UINT32
Unsigned 32-bit little-endian integer.
Definition duckdb.hpp:2758
@ UINT16
Unsigned 16-bit little-endian integer.
Definition duckdb.hpp:2752
@ UINT64
Unsigned 64-bit little-endian integer.
Definition duckdb.hpp:2764
@ BOOL
Boolean as 8 bit "bool" value.
Definition duckdb.hpp:2743
@ UINT8
Unsigned 8-bit little-endian integer.
Definition duckdb.hpp:2746
static DUCKDB_API Value Min(const BaseStatistics &stats)
Returns the min value - throws an exception if there is no min value.
Definition duckdb.cpp:424256
static DUCKDB_API Value Max(const BaseStatistics &stats)
Returns the max value - throws an exception if there is no max value.
Definition duckdb.cpp:424263
static DUCKDB_API bool HasMinMax(const BaseStatistics &stats)
Returns true if the stats has both a min and max value defined.
Definition duckdb.cpp:424237
Here is the call graph for this function:

◆ UpdateFilterStatistics() [1/5]

void duckdb::StatisticsPropagator::UpdateFilterStatistics ( BaseStatistics & input,
ExpressionType comparison_type,
const Value & constant )
private

Update filter statistics from a filter with a constant.

324307 {
324308 // regular comparisons removes all null values
324309 if (!IsCompareDistinct(comparison_type)) {
324310 stats.Set(StatsInfo::CANNOT_HAVE_NULL_VALUES);
324311 }
324312 if (!stats.GetType().IsNumeric()) {
324313 // don't handle non-numeric columns here (yet)
324314 return;
324315 }
324316 if (!NumericStats::HasMinMax(stats)) {
324317 // no stats available: skip this
324318 return;
324319 }
324320 switch (comparison_type) {
324321 case ExpressionType::COMPARE_LESSTHAN:
324322 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
324323 // X < constant OR X <= constant
324324 // max becomes the constant
324325 NumericStats::SetMax(stats, constant);
324326 break;
324327 case ExpressionType::COMPARE_GREATERTHAN:
324328 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
324329 // X > constant OR X >= constant
324330 // min becomes the constant
324331 NumericStats::SetMin(stats, constant);
324332 break;
324333 case ExpressionType::COMPARE_EQUAL:
324334 // X = constant
324335 // both min and max become the constant
324336 NumericStats::SetMin(stats, constant);
324337 NumericStats::SetMax(stats, constant);
324338 break;
324339 default:
324340 break;
324341 }
324342}
static DUCKDB_API void SetMin(BaseStatistics &stats, const Value &val)
Sets the min value of the statistics.
Definition duckdb.cpp:424188
static DUCKDB_API void SetMax(BaseStatistics &stats, const Value &val)
Sets the max value of the statistics.
Definition duckdb.cpp:424193
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateFilterStatistics() [2/5]

void duckdb::StatisticsPropagator::UpdateFilterStatistics ( BaseStatistics & lstats,
BaseStatistics & rstats,
ExpressionType comparison_type )
private

Update statistics from a filter between two stats.

324345 {
324346 // regular comparisons removes all null values
324347 if (!IsCompareDistinct(comparison_type)) {
324348 lstats.Set(StatsInfo::CANNOT_HAVE_NULL_VALUES);
324349 rstats.Set(StatsInfo::CANNOT_HAVE_NULL_VALUES);
324350 }
324351 D_ASSERT(lstats.GetType() == rstats.GetType());
324352 if (!lstats.GetType().IsNumeric()) {
324353 // don't handle non-numeric columns here (yet)
324354 return;
324355 }
324356 if (!NumericStats::HasMinMax(lstats) || !NumericStats::HasMinMax(rstats)) {
324357 // no stats available: skip this
324358 return;
324359 }
324360 switch (comparison_type) {
324361 case ExpressionType::COMPARE_LESSTHAN:
324362 case ExpressionType::COMPARE_LESSTHANOREQUALTO:
324363 // LEFT < RIGHT OR LEFT <= RIGHT
324364 // we know that every value of left is smaller (or equal to) every value in right
324365 // i.e. if we have left = [-50, 250] and right = [-100, 100]
324366
324367 // we know that left.max is AT MOST equal to right.max
324368 // because any value in left that is BIGGER than right.max will not pass the filter
324369 if (NumericStats::Max(lstats) > NumericStats::Max(rstats)) {
324370 NumericStats::SetMax(lstats, NumericStats::Max(rstats));
324371 }
324372
324373 // we also know that right.min is AT MOST equal to left.min
324374 // because any value in right that is SMALLER than left.min will not pass the filter
324375 if (NumericStats::Min(rstats) < NumericStats::Min(lstats)) {
324376 NumericStats::SetMin(rstats, NumericStats::Min(lstats));
324377 }
324378 // so in our example, the bounds get updated as follows:
324379 // left: [-50, 100], right: [-50, 100]
324380 break;
324381 case ExpressionType::COMPARE_GREATERTHAN:
324382 case ExpressionType::COMPARE_GREATERTHANOREQUALTO:
324383 // LEFT > RIGHT OR LEFT >= RIGHT
324384 // we know that every value of left is bigger (or equal to) every value in right
324385 // this is essentially the inverse of the less than (or equal to) scenario
324386 if (NumericStats::Max(rstats) > NumericStats::Max(lstats)) {
324387 NumericStats::SetMax(rstats, NumericStats::Max(lstats));
324388 }
324389 if (NumericStats::Min(lstats) < NumericStats::Min(rstats)) {
324390 NumericStats::SetMin(lstats, NumericStats::Min(rstats));
324391 }
324392 break;
324393 case ExpressionType::COMPARE_EQUAL:
324394 case ExpressionType::COMPARE_NOT_DISTINCT_FROM:
324395 // LEFT = RIGHT
324396 // only the tightest bounds pass
324397 // so if we have e.g. left = [-50, 250] and right = [-100, 100]
324398 // the tighest bounds are [-50, 100]
324399 // select the highest min
324400 if (NumericStats::Min(lstats) > NumericStats::Min(rstats)) {
324401 NumericStats::SetMin(rstats, NumericStats::Min(lstats));
324402 } else {
324403 NumericStats::SetMin(lstats, NumericStats::Min(rstats));
324404 }
324405 // select the lowest max
324406 if (NumericStats::Max(lstats) < NumericStats::Max(rstats)) {
324407 NumericStats::SetMax(rstats, NumericStats::Max(lstats));
324408 } else {
324409 NumericStats::SetMax(lstats, NumericStats::Max(rstats));
324410 }
324411 break;
324412 default:
324413 break;
324414 }
324415}
Here is the call graph for this function:

◆ UpdateFilterStatistics() [3/5]

void duckdb::StatisticsPropagator::UpdateFilterStatistics ( Expression & left,
Expression & right,
ExpressionType comparison_type )
private

Update filter statistics from a generic comparison.

324417 {
324418 // first check if either side is a bound column ref
324419 // any column ref involved in a comparison will not be null after the comparison
324420 bool compare_distinct = IsCompareDistinct(comparison_type);
324421 if (!compare_distinct && left.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
324422 SetStatisticsNotNull((left.Cast<BoundColumnRefExpression>()).binding);
324423 }
324424 if (!compare_distinct && right.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
324425 SetStatisticsNotNull((right.Cast<BoundColumnRefExpression>()).binding);
324426 }
324427 // check if this is a comparison between a constant and a column ref
324428 optional_ptr<BoundConstantExpression> constant;
324429 optional_ptr<BoundColumnRefExpression> columnref;
324430 if (left.GetExpressionType() == ExpressionType::VALUE_CONSTANT &&
324431 right.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
324432 constant = &left.Cast<BoundConstantExpression>();
324433 columnref = &right.Cast<BoundColumnRefExpression>();
324434 comparison_type = FlipComparisonExpression(comparison_type);
324435 } else if (left.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF &&
324436 right.GetExpressionType() == ExpressionType::VALUE_CONSTANT) {
324437 columnref = &left.Cast<BoundColumnRefExpression>();
324438 constant = &right.Cast<BoundConstantExpression>();
324439 } else if (left.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF &&
324440 right.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
324441 // comparison between two column refs
324442 auto &left_column_ref = left.Cast<BoundColumnRefExpression>();
324443 auto &right_column_ref = right.Cast<BoundColumnRefExpression>();
324444 auto lentry = statistics_map.find(left_column_ref.binding);
324445 auto rentry = statistics_map.find(right_column_ref.binding);
324446 if (lentry == statistics_map.end() || rentry == statistics_map.end()) {
324447 return;
324448 }
324449 UpdateFilterStatistics(*lentry->second, *rentry->second, comparison_type);
324450 } else {
324451 // unsupported filter
324452 return;
324453 }
324454 if (constant && columnref) {
324455 // comparison between columnref
324456 auto entry = statistics_map.find(columnref->binding);
324457 if (entry == statistics_map.end()) {
324458 return;
324459 }
324460 UpdateFilterStatistics(*entry->second, comparison_type, constant->value);
324461 }
324462}
void SetStatisticsNotNull(ColumnBinding binding)
Set the statistics of a specific column binding to not contain null values.
Definition duckdb.cpp:324298
ExpressionType FlipComparisonExpression(ExpressionType type)
Flip a comparison expression, turning e.g. < into >, or = into =.
Definition duckdb.cpp:68052
Here is the call graph for this function:

◆ UpdateFilterStatistics() [4/5]

void duckdb::StatisticsPropagator::UpdateFilterStatistics ( Expression & condition)
private

Update filter statistics from an expression.

324464 {
324465 // in filters, we check for constant comparisons with bound columns
324466 // if we find a comparison in the form of e.g. "i=3", we can update our statistics for that column
324467 switch (condition.GetExpressionClass()) {
324468 case ExpressionClass::BOUND_BETWEEN: {
324469 auto &between = condition.Cast<BoundBetweenExpression>();
324470 UpdateFilterStatistics(*between.input, *between.lower, between.LowerComparisonType());
324471 UpdateFilterStatistics(*between.input, *between.upper, between.UpperComparisonType());
324472 break;
324473 }
324474 case ExpressionClass::BOUND_COMPARISON: {
324475 auto &comparison = condition.Cast<BoundComparisonExpression>();
324476 UpdateFilterStatistics(*comparison.left, *comparison.right, comparison.GetExpressionType());
324477 break;
324478 }
324479 default:
324480 break;
324481 }
324482}
Here is the call graph for this function:

◆ SetStatisticsNotNull()

void duckdb::StatisticsPropagator::SetStatisticsNotNull ( ColumnBinding binding)
private

Set the statistics of a specific column binding to not contain null values.

324298 {
324299 auto entry = statistics_map.find(binding);
324300 if (entry == statistics_map.end()) {
324301 return;
324302 }
324303 entry->second->Set(StatsInfo::CANNOT_HAVE_NULL_VALUES);
324304}
Here is the caller graph for this function:

◆ HandleFilter()

FilterPropagateResult duckdb::StatisticsPropagator::HandleFilter ( unique_ptr< Expression > & condition)
private

Propagate a filter condition.

324484 {
324485 PropagateExpression(condition);
324486
324487 if (ExpressionIsConstant(*condition, Value::BOOLEAN(true))) {
324488 return FilterPropagateResult::FILTER_ALWAYS_TRUE;
324489 }
324490
324491 if (ExpressionIsConstantOrNull(*condition, Value::BOOLEAN(true))) {
324492 return FilterPropagateResult::FILTER_TRUE_OR_NULL;
324493 }
324494
324495 if (ExpressionIsConstant(*condition, Value::BOOLEAN(false)) ||
324496 ExpressionIsConstantOrNull(*condition, Value::BOOLEAN(false))) {
324497 return FilterPropagateResult::FILTER_FALSE_OR_NULL;
324498 }
324499
324500 // cannot prune this filter: propagate statistics from the filter
324501 UpdateFilterStatistics(*condition);
324502 return FilterPropagateResult::NO_PRUNING_POSSIBLE;
324503}
static DUCKDB_API Value BOOLEAN(bool value)
Create a boolean Value from a specified value.
Definition duckdb.cpp:132118
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PropagateTableFilter()

FilterPropagateResult duckdb::StatisticsPropagator::PropagateTableFilter ( ColumnBinding stats_binding,
BaseStatistics & stats,
TableFilter & filter )
private

Run a comparison between the statistics and the table filter; returns the prune result.

324572 {
324573 if (filter.filter_type == TableFilterType::EXPRESSION_FILTER) {
324574 auto &expr_filter = filter.Cast<ExpressionFilter>();
324575
324576 // get physical storage index of the filter
324577 // since it is a table filter, every storage index is the same
324578 idx_t physical_index = DConstants::INVALID_INDEX;
324579 string column_alias;
324580 GetColumnIndex(expr_filter.expr, physical_index, column_alias);
324581 D_ASSERT(physical_index != DConstants::INVALID_INDEX);
324582
324583 auto column_ref = make_uniq<BoundColumnRefExpression>(column_alias, stats.GetType(), stats_binding);
324584 auto filter_expr = expr_filter.ToExpression(*column_ref);
324585 // handle the filter before updating the statistics
324586 // otherwise the filter can be pruned by the updated statistics
324587 auto propagate_result = HandleFilter(filter_expr);
324588 auto colref = make_uniq<BoundReferenceExpression>(column_alias, stats.GetType(), physical_index);
324589 UpdateFilterStatistics(*filter_expr);
324590
324591 // replace BoundColumnRefs with BoundRefs
324592 ExpressionFilter::ReplaceExpressionRecursive(filter_expr, *colref, ExpressionType::BOUND_COLUMN_REF);
324593 expr_filter.expr = std::move(filter_expr);
324594
324595 // If we were able to prune solely based on the expression, return that result
324596 if (propagate_result != FilterPropagateResult::NO_PRUNING_POSSIBLE) {
324597 return propagate_result;
324598 }
324599 // Otherwise, check the statistics
324600 }
324601 return filter.CheckStatistics(stats);
324602}
static constexpr const idx_t INVALID_INDEX
The value used to signify an invalid index entry.
Definition duckdb.hpp:1117
Here is the call graph for this function:

◆ UpdateFilterStatistics() [5/5]

void duckdb::StatisticsPropagator::UpdateFilterStatistics ( BaseStatistics & input,
const TableFilter & filter )
private

Update filter statistics from a TableFilter.

324604 {
324605 // FIXME: update stats...
324606 switch (filter.filter_type) {
324607 case TableFilterType::CONJUNCTION_AND: {
324608 auto &conjunction_and = filter.Cast<ConjunctionAndFilter>();
324609 for (auto &child_filter : conjunction_and.child_filters) {
324610 UpdateFilterStatistics(input, *child_filter);
324611 }
324612 break;
324613 }
324614 case TableFilterType::CONSTANT_COMPARISON: {
324615 auto &constant_filter = filter.Cast<ConstantFilter>();
324616 UpdateFilterStatistics(input, constant_filter.comparison_type, constant_filter.constant);
324617 break;
324618 }
324619 default:
324620 break;
324621 }
324622}
Here is the call graph for this function:

◆ AddCardinalities()

void duckdb::StatisticsPropagator::AddCardinalities ( unique_ptr< NodeStatistics > & stats,
NodeStatistics & new_stats )
private

Add cardinalities together (i.e. new max is stats.max + new_stats.max): used for union.

325179 {
325180 if (!stats) {
325181 return;
325182 }
325183 if (!stats->has_estimated_cardinality || !new_stats.has_estimated_cardinality || !stats->has_max_cardinality ||
325184 !new_stats.has_max_cardinality) {
325185 stats = nullptr;
325186 return;
325187 }
325188 stats->estimated_cardinality += new_stats.estimated_cardinality;
325189 auto new_max =
325190 Hugeint::Add(NumericCast<int64_t>(stats->max_cardinality), NumericCast<int64_t>(new_stats.max_cardinality));
325191 if (new_max < NumericLimits<int64_t>::Maximum()) {
325192 int64_t result;
325193 if (!Hugeint::TryCast<int64_t>(new_max, result)) {
325194 throw InternalException("Overflow in cast in statistics propagation");
325195 }
325196 D_ASSERT(result >= 0);
325197 stats->max_cardinality = idx_t(result);
325198 } else {
325199 stats = nullptr;
325200 }
325201}
::int64_t int64_t

◆ MultiplyCardinalities()

void duckdb::StatisticsPropagator::MultiplyCardinalities ( unique_ptr< NodeStatistics > & stats,
NodeStatistics & new_stats )
private

Multiply the cardinalities together (i.e. new max cardinality is stats.max * new_stats.max): used for joins/cross products.

324926 {
324927 if (!stats->has_estimated_cardinality || !new_stats.has_estimated_cardinality || !stats->has_max_cardinality ||
324928 !new_stats.has_max_cardinality) {
324929 stats = nullptr;
324930 return;
324931 }
324932 stats->estimated_cardinality = MaxValue<idx_t>(stats->estimated_cardinality, new_stats.estimated_cardinality);
324933 auto new_max = Hugeint::Multiply(NumericCast<int64_t>(stats->max_cardinality),
324934 NumericCast<int64_t>(new_stats.max_cardinality));
324935 if (new_max < NumericLimits<int64_t>::Maximum()) {
324936 int64_t result;
324937 if (!Hugeint::TryCast<int64_t>(new_max, result)) {
324938 throw InternalException("Overflow in cast in statistics propagation");
324939 }
324940 D_ASSERT(result >= 0);
324941 stats->max_cardinality = idx_t(result);
324942 } else {
324943 stats = nullptr;
324944 }
324945}

◆ CreateFilterFromJoinStats()

void duckdb::StatisticsPropagator::CreateFilterFromJoinStats ( unique_ptr< LogicalOperator > & child,
unique_ptr< Expression > & expr,
const BaseStatistics & stats_before,
const BaseStatistics & stats_after )
private

Creates and pushes down a filter based on join statistics.

325067 {
325068 // Only do this for integral colref's that have stats
325069 if (expr->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF || !expr->return_type.IsIntegral() ||
325070 !NumericStats::HasMinMax(stats_before) || !NumericStats::HasMinMax(stats_after)) {
325071 return;
325072 }
325073
325074 // Retrieve min/max
325075 auto min_before = NumericStats::Min(stats_before);
325076 auto max_before = NumericStats::Max(stats_before);
325077 auto min_after = NumericStats::Min(stats_after);
325078 auto max_after = NumericStats::Max(stats_after);
325079
325080 vector<unique_ptr<Expression>> filter_exprs;
325081 if (min_after > min_before) {
325082 filter_exprs.emplace_back(
325083 make_uniq<BoundComparisonExpression>(ExpressionType::COMPARE_GREATERTHANOREQUALTO, expr->Copy(),
325084 make_uniq<BoundConstantExpression>(std::move(min_after))));
325085 }
325086 if (max_after < max_before) {
325087 filter_exprs.emplace_back(
325088 make_uniq<BoundComparisonExpression>(ExpressionType::COMPARE_LESSTHANOREQUALTO, expr->Copy(),
325089 make_uniq<BoundConstantExpression>(std::move(max_after))));
325090 }
325091
325092 if (filter_exprs.empty()) {
325093 return;
325094 }
325095
325096 auto filter = make_uniq<LogicalFilter>();
325097 filter->children.emplace_back(std::move(child));
325098 child = std::move(filter);
325099
325100 for (auto &filter_expr : filter_exprs) {
325101 child->expressions.emplace_back(std::move(filter_expr));
325102 }
325103
325104 // not allowed to let filter pushdown change mark joins to semi joins.
325105 // semi joins are potentially slower AND the conversion can ruin column binding information
325106 FilterPushdown filter_pushdown(optimizer, false);
325107 child = filter_pushdown.Rewrite(std::move(child));
325108 PropagateExpression(expr);
325109}
Here is the call graph for this function:

◆ PropagateExpression() [1/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( unique_ptr< Expression > & expr)
private
325477 {
325478 auto stats = PropagateExpression(*expr, expr);
325479 if (ClientConfig::GetConfig(context).query_verification_enabled && stats) {
325480 expr->verification_stats = stats->ToUnique();
325481 }
325482 return stats;
325483}

◆ PropagateExpression() [2/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( Expression & expr,
unique_ptr< Expression > & expr_ptr )
private
325448 {
325449 switch (expr.GetExpressionClass()) {
325450 case ExpressionClass::BOUND_AGGREGATE:
325451 return PropagateExpression(expr.Cast<BoundAggregateExpression>(), expr_ptr);
325452 case ExpressionClass::BOUND_BETWEEN:
325453 return PropagateExpression(expr.Cast<BoundBetweenExpression>(), expr_ptr);
325454 case ExpressionClass::BOUND_CASE:
325455 return PropagateExpression(expr.Cast<BoundCaseExpression>(), expr_ptr);
325456 case ExpressionClass::BOUND_CONJUNCTION:
325457 return PropagateExpression(expr.Cast<BoundConjunctionExpression>(), expr_ptr);
325458 case ExpressionClass::BOUND_FUNCTION:
325459 return PropagateExpression(expr.Cast<BoundFunctionExpression>(), expr_ptr);
325460 case ExpressionClass::BOUND_CAST:
325461 return PropagateExpression(expr.Cast<BoundCastExpression>(), expr_ptr);
325462 case ExpressionClass::BOUND_COMPARISON:
325463 return PropagateExpression(expr.Cast<BoundComparisonExpression>(), expr_ptr);
325464 case ExpressionClass::BOUND_CONSTANT:
325465 return PropagateExpression(expr.Cast<BoundConstantExpression>(), expr_ptr);
325466 case ExpressionClass::BOUND_COLUMN_REF:
325467 return PropagateExpression(expr.Cast<BoundColumnRefExpression>(), expr_ptr);
325468 case ExpressionClass::BOUND_OPERATOR:
325469 return PropagateExpression(expr.Cast<BoundOperatorExpression>(), expr_ptr);
325470 default:
325471 break;
325472 }
325473 ExpressionIterator::EnumerateChildren(expr, [&](unique_ptr<Expression> &child) { PropagateExpression(child); });
325474 return nullptr;
325475}

◆ PropagateExpression() [3/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundAggregateExpression & expr,
unique_ptr< Expression > & expr_ptr )
private

Run a comparison between the statistics and the table filter; returns the prune result.

323221 {
323222 vector<BaseStatistics> stats;
323223 stats.reserve(aggr.children.size());
323224 for (auto &child : aggr.children) {
323225 auto stat = PropagateExpression(child);
323226 if (!stat) {
323227 stats.push_back(BaseStatistics::CreateUnknown(child->return_type));
323228 } else {
323229 stats.push_back(stat->Copy());
323230 }
323231 }
323232 if (!aggr.function.HasStatisticsCallback()) {
323233 return nullptr;
323234 }
323235 AggregateStatisticsInput input(aggr.bind_info.get(), stats, node_stats.get());
323236 return aggr.function.GetStatisticsCallback()(context, aggr, input);
323237}
static BaseStatistics CreateUnknown(LogicalType type)
Definition duckdb.cpp:422865
Here is the call graph for this function:

◆ PropagateExpression() [4/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundBetweenExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323249 {
323250 // propagate in all the children
323251 auto input_stats = PropagateExpression(between.input);
323252 auto lower_stats = PropagateExpression(between.lower);
323253 auto upper_stats = PropagateExpression(between.upper);
323254 if (!input_stats) {
323255 return nullptr;
323256 }
323257 auto lower_comparison = between.LowerComparisonType();
323258 auto upper_comparison = between.UpperComparisonType();
323259 // propagate the comparisons
323260 auto lower_prune = FilterPropagateResult::NO_PRUNING_POSSIBLE;
323261 auto upper_prune = FilterPropagateResult::NO_PRUNING_POSSIBLE;
323262 if (lower_stats) {
323263 lower_prune = PropagateComparison(*input_stats, *lower_stats, lower_comparison);
323264 }
323265 if (upper_stats) {
323266 upper_prune = PropagateComparison(*input_stats, *upper_stats, upper_comparison);
323267 }
323268 if (lower_prune == FilterPropagateResult::FILTER_ALWAYS_TRUE &&
323269 upper_prune == FilterPropagateResult::FILTER_ALWAYS_TRUE) {
323270 // both filters are always true: replace the between expression with a constant true
323271 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(true));
323272 } else if (lower_prune == FilterPropagateResult::FILTER_ALWAYS_FALSE ||
323273 upper_prune == FilterPropagateResult::FILTER_ALWAYS_FALSE) {
323274 // either one of the filters is always false: replace the between expression with a constant false
323275 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(false));
323276 } else if (lower_prune == FilterPropagateResult::FILTER_FALSE_OR_NULL ||
323277 upper_prune == FilterPropagateResult::FILTER_FALSE_OR_NULL) {
323278 // either one of the filters is false or null: replace with a constant or null (false)
323279 vector<unique_ptr<Expression>> children;
323280 children.push_back(std::move(between.input));
323281 children.push_back(std::move(between.lower));
323282 children.push_back(std::move(between.upper));
323283 expr_ptr = ExpressionRewriter::ConstantOrNull(std::move(children), Value::BOOLEAN(false));
323284 } else if (lower_prune == FilterPropagateResult::FILTER_TRUE_OR_NULL &&
323285 upper_prune == FilterPropagateResult::FILTER_TRUE_OR_NULL) {
323286 // both filters are true or null: replace with a true or null
323287 vector<unique_ptr<Expression>> children;
323288 children.push_back(std::move(between.input));
323289 children.push_back(std::move(between.lower));
323290 children.push_back(std::move(between.upper));
323291 expr_ptr = ExpressionRewriter::ConstantOrNull(std::move(children), Value::BOOLEAN(true));
323292 } else if (lower_prune == FilterPropagateResult::FILTER_ALWAYS_TRUE) {
323293 // lower filter is always true: replace with upper comparison
323294 expr_ptr =
323295 make_uniq<BoundComparisonExpression>(upper_comparison, std::move(between.input), std::move(between.upper));
323296 } else if (upper_prune == FilterPropagateResult::FILTER_ALWAYS_TRUE) {
323297 // upper filter is always true: replace with lower comparison
323298 expr_ptr =
323299 make_uniq<BoundComparisonExpression>(lower_comparison, std::move(between.input), std::move(between.lower));
323300 }
323301 return nullptr;
323302}

◆ PropagateExpression() [5/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundCaseExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323311 {
323312 // propagate in all the children
323313 auto result_stats = PropagateExpression(bound_case.else_expr);
323314 for (auto &case_check : bound_case.case_checks) {
323315 PropagateExpression(case_check.when_expr);
323316 auto then_stats = PropagateExpression(case_check.then_expr);
323317 if (!then_stats) {
323318 result_stats.reset();
323319 } else if (result_stats) {
323320 result_stats->Merge(*then_stats);
323321 }
323322 }
323323 return result_stats;
323324}

◆ PropagateExpression() [6/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundCastExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323515 {
323516 auto child_stats = PropagateExpression(cast.child);
323517 if (!child_stats) {
323518 return nullptr;
323519 }
323520 auto result_stats = TryPropagateCast(*child_stats, cast.child->return_type, cast.return_type);
323521 if (cast.try_cast && result_stats) {
323522 result_stats->Set(StatsInfo::CAN_HAVE_NULL_VALUES);
323523 }
323524 return result_stats;
323525}
Widget2D cast() const

◆ PropagateExpression() [7/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundConjunctionExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323683 {
323684 auto is_and = expr.GetExpressionType() == ExpressionType::CONJUNCTION_AND;
323685 for (idx_t expr_idx = 0; expr_idx < expr.children.size(); expr_idx++) {
323686 auto &child = expr.children[expr_idx];
323687 auto stats = PropagateExpression(child);
323688 if (!child->IsFoldable()) {
323689 continue;
323690 }
323691 // we have a constant in a conjunction
323692 // we (1) either prune the child
323693 // or (2) replace the entire conjunction with a constant
323694 auto constant = ExpressionExecutor::EvaluateScalar(context, *child);
323695 if (constant.IsNull()) {
323696 continue;
323697 }
323698 auto b = BooleanValue::Get(constant);
323699 bool prune_child = false;
323700 bool constant_value = true;
323701 if (b) {
323702 // true
323703 if (is_and) {
323704 // true in and: prune child
323705 prune_child = true;
323706 } else {
323707 // true in OR: replace with TRUE
323708 constant_value = true;
323709 }
323710 } else {
323711 // false
323712 if (is_and) {
323713 // false in AND: replace with FALSE
323714 constant_value = false;
323715 } else {
323716 // false in OR: prune child
323717 prune_child = true;
323718 }
323719 }
323720 if (prune_child) {
323721 expr.children.erase_at(expr_idx);
323722 expr_idx--;
323723 continue;
323724 }
323725 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(constant_value));
323726 return PropagateExpression(expr_ptr);
323727 }
323728 if (expr.children.empty()) {
323729 // if there are no children left, replace the conjunction with TRUE (for AND) or FALSE (for OR)
323730 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(is_and));
323731 return PropagateExpression(expr_ptr);
323732 } else if (expr.children.size() == 1) {
323733 // if there is one child left, replace the conjunction with that one child
323734 expr_ptr = std::move(expr.children[0]);
323735 }
323736 return nullptr;
323737}
static DUCKDB_API Value EvaluateScalar(ClientContext &context, const Expression &expr, bool allow_unfoldable=false)
Evaluate a scalar expression and fold it into a single value.
Definition duckdb.cpp:149993

◆ PropagateExpression() [8/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundFunctionExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323764 {
323765 vector<BaseStatistics> stats;
323766 stats.reserve(func.children.size());
323767 for (idx_t i = 0; i < func.children.size(); i++) {
323768 auto stat = PropagateExpression(func.children[i]);
323769 if (!stat) {
323770 stats.push_back(BaseStatistics::CreateUnknown(func.children[i]->return_type));
323771 } else {
323772 stats.push_back(stat->Copy());
323773 }
323774 }
323775 if (!func.function.HasStatisticsCallback()) {
323776 return nullptr;
323777 }
323778 FunctionStatisticsInput input(func, func.bind_info.get(), stats, &expr_ptr);
323779 return func.function.GetStatisticsCallback()(context, input);
323780}

◆ PropagateExpression() [9/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundComparisonExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323637 {
323638 auto left_stats = PropagateExpression(expr.left);
323639 auto right_stats = PropagateExpression(expr.right);
323640 if (!left_stats || !right_stats) {
323641 return nullptr;
323642 }
323643 // propagate the statistics of the comparison operator
323644 auto propagate_result = PropagateComparison(*left_stats, *right_stats, expr.GetExpressionType());
323645 switch (propagate_result) {
323646 case FilterPropagateResult::FILTER_ALWAYS_TRUE:
323647 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(true));
323648 return PropagateExpression(expr_ptr);
323649 case FilterPropagateResult::FILTER_ALWAYS_FALSE:
323650 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(false));
323651 return PropagateExpression(expr_ptr);
323652 case FilterPropagateResult::FILTER_TRUE_OR_NULL: {
323653 vector<unique_ptr<Expression>> children;
323654 children.push_back(std::move(expr.left));
323655 children.push_back(std::move(expr.right));
323656 expr_ptr = ExpressionRewriter::ConstantOrNull(std::move(children), Value::BOOLEAN(true));
323657 return nullptr;
323658 }
323659 case FilterPropagateResult::FILTER_FALSE_OR_NULL: {
323660 vector<unique_ptr<Expression>> children;
323661 children.push_back(std::move(expr.left));
323662 children.push_back(std::move(expr.right));
323663 expr_ptr = ExpressionRewriter::ConstantOrNull(std::move(children), Value::BOOLEAN(false));
323664 return nullptr;
323665 }
323666 default:
323667 // FIXME: we can propagate nulls here, i.e. this expression will have nulls only if left and right has nulls
323668 return nullptr;
323669 }
323670}

◆ PropagateExpression() [10/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundConstantExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323753 {
323754 return StatisticsFromValue(constant.value);
323755}
unique_ptr< BaseStatistics > StatisticsFromValue(const Value &input)
Return statistics from a constant value.
Definition duckdb.cpp:323748

◆ PropagateExpression() [11/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundColumnRefExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323534 {
323535 auto stats = statistics_map.find(colref.binding);
323536 if (stats == statistics_map.end()) {
323537 return nullptr;
323538 }
323539 return stats->second->ToUnique();
323540}

◆ PropagateExpression() [12/12]

unique_ptr< BaseStatistics > duckdb::StatisticsPropagator::PropagateExpression ( BoundOperatorExpression & expr,
unique_ptr< Expression > & expr_ptr )
private
323790 {
323791 bool all_have_stats = true;
323792 vector<unique_ptr<BaseStatistics>> child_stats;
323793 child_stats.reserve(expr.children.size());
323794 for (auto &child : expr.children) {
323795 auto stats = PropagateExpression(child);
323796 if (!stats) {
323797 all_have_stats = false;
323798 }
323799 child_stats.push_back(std::move(stats));
323800 }
323801 if (!all_have_stats) {
323802 return nullptr;
323803 }
323804 switch (expr.GetExpressionType()) {
323805 case ExpressionType::OPERATOR_COALESCE:
323806 // COALESCE, merge stats of all children
323807 for (idx_t i = 0; i < expr.children.size(); i++) {
323808 D_ASSERT(child_stats[i]);
323809 if (!child_stats[i]->CanHaveNoNull()) {
323810 // this child is always NULL, we can remove it from the coalesce
323811 // UNLESS there is only one node remaining
323812 if (expr.children.size() > 1) {
323813 expr.children.erase_at(i);
323814 child_stats.erase_at(i);
323815 i--;
323816 }
323817 } else if (!child_stats[i]->CanHaveNull()) {
323818 // coalesce child cannot have NULL entries
323819 // this is the last coalesce node that influences the result
323820 // we can erase any children after this node
323821 if (i + 1 < expr.children.size()) {
323822 expr.children.erase(expr.children.begin() + NumericCast<int64_t>(i + 1), expr.children.end());
323823 child_stats.erase(child_stats.begin() + NumericCast<int64_t>(i + 1), child_stats.end());
323824 }
323825 break;
323826 }
323827 }
323828 D_ASSERT(!expr.children.empty());
323829 D_ASSERT(expr.children.size() == child_stats.size());
323830 if (expr.children.size() == 1) {
323831 // coalesce of one entry: simply return that entry
323832 expr_ptr = std::move(expr.children[0]);
323833 } else {
323834 // coalesce of multiple entries
323835 // merge the stats
323836 for (idx_t i = 1; i < expr.children.size(); i++) {
323837 child_stats[0]->Merge(*child_stats[i]);
323838 }
323839 }
323840 return std::move(child_stats[0]);
323841 case ExpressionType::OPERATOR_IS_NULL:
323842 if (!child_stats[0]->CanHaveNull()) {
323843 // child has no null values: x IS NULL will always be false
323844 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(false));
323845 return PropagateExpression(expr_ptr);
323846 }
323847 if (!child_stats[0]->CanHaveNoNull()) {
323848 // child has no valid values: x IS NULL will always be true
323849 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(true));
323850 return PropagateExpression(expr_ptr);
323851 }
323852 return nullptr;
323853 case ExpressionType::OPERATOR_IS_NOT_NULL:
323854 if (!child_stats[0]->CanHaveNull()) {
323855 // child has no null values: x IS NOT NULL will always be true
323856 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(true));
323857 return PropagateExpression(expr_ptr);
323858 }
323859 if (!child_stats[0]->CanHaveNoNull()) {
323860 // child has no valid values: x IS NOT NULL will always be false
323861 expr_ptr = make_uniq<BoundConstantExpression>(Value::BOOLEAN(false));
323862 return PropagateExpression(expr_ptr);
323863 }
323864 return nullptr;
323865 default:
323866 return nullptr;
323867 }
323868}

◆ TryExecuteAggregates()

void duckdb::StatisticsPropagator::TryExecuteAggregates ( LogicalAggregate & op,
unique_ptr< LogicalOperator > & node_ptr )
private

Try to execute aggregates using only the statistics if possible.

Can't get a storage index for this column, so it doesn't have stats we can use This happens when we're dealing with a generated column for example

323971 {
323972 if (!aggr.groups.empty()) {
323973 // not possible with groups
323974 return;
323975 }
323976 // check if all aggregates are COUNT(*), MIN or MAX
323977 vector<idx_t> count_star_idxs;
323978 vector<ColumnBinding> min_max_bindings;
323979 vector<unique_ptr<ValueComparator>> comparators;
323980
323981 for (idx_t i = 0; i < aggr.expressions.size(); i++) {
323982 auto &aggr_ref = aggr.expressions[i];
323983 if (aggr_ref->GetExpressionClass() != ExpressionClass::BOUND_AGGREGATE) {
323984 // not an aggregate
323985 return;
323986 }
323987 auto &aggr_expr = aggr_ref->Cast<BoundAggregateExpression>();
323988 if (aggr_expr.filter) {
323989 // aggregate has a filter - bail
323990 return;
323991 }
323992 const string &fun_name = aggr_expr.function.name;
323993 if (fun_name == "min" || fun_name == "max") {
323994 if (aggr_expr.children.size() != 1 || aggr_expr.children[0]->type != ExpressionType::BOUND_COLUMN_REF) {
323995 return;
323996 }
323997 const auto &col_ref = aggr_expr.children[0]->Cast<BoundColumnRefExpression>();
323998 min_max_bindings.push_back(col_ref.binding);
323999 auto comparator = GetComparator(fun_name, col_ref.return_type);
324000 if (!comparator) {
324001 // Type has no min max statistics
324002 return;
324003 }
324004 comparators.push_back(std::move(comparator));
324005 } else if (fun_name == "count_star") {
324006 count_star_idxs.push_back(i);
324007 } else {
324008 // aggregate is not count star, min or max - bail
324009 return;
324010 }
324011 }
324012
324013 // skip any projections
324014 reference<LogicalOperator> child_ref = *aggr.children[0];
324015 while (child_ref.get().type == LogicalOperatorType::LOGICAL_PROJECTION) {
324016 for (auto &binding : min_max_bindings) {
324017 auto &expr = child_ref.get().expressions[binding.column_index];
324018 if (expr->type != ExpressionType::BOUND_COLUMN_REF) {
324019 return;
324020 }
324021 binding = expr->Cast<BoundColumnRefExpression>().binding;
324022 }
324023 child_ref = *child_ref.get().children[0];
324024 }
324025
324026 if (child_ref.get().type != LogicalOperatorType::LOGICAL_GET) {
324027 // child must be a LOGICAL_GET
324028 return;
324029 }
324030 auto &get = child_ref.get().Cast<LogicalGet>();
324031 if (!get.function.get_partition_stats) {
324032 // GET does not support getting the partition stats
324033 return;
324034 }
324035 if (get.extra_info.sample_options) {
324036 // only use row group statistics if we query the whole table
324037 return;
324038 }
324039
324040 // we can do the rewrite! get the stats
324041 GetPartitionStatsInput input(get.function, get.bind_data.get());
324042 auto partition_stats = get.function.get_partition_stats(context, input);
324043 if (partition_stats.empty()) {
324044 // no partition stats found
324045 return;
324046 }
324047
324048 vector<StorageIndex> min_max_storage_indexes(min_max_bindings.size());
324049 for (idx_t i = 0; i < min_max_bindings.size(); i++) {
324050 auto &binding = min_max_bindings[i];
324051 auto &column_index = get.GetColumnIds()[binding.column_index];
324052 if (!get.TryGetStorageIndex(column_index, min_max_storage_indexes[i])) {
324055 return;
324056 }
324057 }
324058
324059 vector<LogicalType> types;
324060 vector<unique_ptr<Expression>> agg_results;
324061 // we can keep execute eager aggregate if all partitions could be either filtered entirely or remained entirely
324062 if (!get.table_filters.filters.empty()) {
324063 map<StorageIndex, reference<unique_ptr<TableFilter>>> filter_storage_index_map;
324064 for (auto &entry : get.table_filters.filters) {
324065 auto col_idx = entry.first;
324066 auto &filter = entry.second;
324067 auto column_index = ColumnIndex(col_idx);
324068 StorageIndex storage_index;
324069 if (!get.TryGetStorageIndex(column_index, storage_index)) {
324070 return;
324071 }
324072 filter_storage_index_map.emplace(storage_index, filter);
324073 }
324074 vector<PartitionStatistics> remaining_partition_stats;
324075 for (auto &stats : partition_stats) {
324076 if (!stats.partition_row_group) {
324077 return;
324078 }
324079 auto filter_result = FilterPropagateResult::FILTER_ALWAYS_TRUE;
324080 for (auto &entry : filter_storage_index_map) {
324081 auto &storage_index = entry.first;
324082 auto &filter = entry.second;
324083 auto prg = stats.partition_row_group;
324084 if (!prg) {
324085 return;
324086 }
324087 auto column_stats = prg->GetColumnStatistics(storage_index);
324088 if (!column_stats) {
324089 return;
324090 }
324091 auto col_filter_result = filter.get()->CheckStatistics(*column_stats);
324092 if (col_filter_result == FilterPropagateResult::FILTER_ALWAYS_FALSE) {
324093 // all data in this partition is filtered out, remove this partition entirely
324094 filter_result = FilterPropagateResult::FILTER_ALWAYS_FALSE;
324095 break;
324096 }
324097 if (col_filter_result != FilterPropagateResult::FILTER_ALWAYS_TRUE) {
324098 filter_result = col_filter_result;
324099 }
324100 }
324101 switch (filter_result) {
324102 case FilterPropagateResult::FILTER_ALWAYS_TRUE:
324103 // all filters passed - this partition should keep execute eager aggregate
324104 remaining_partition_stats.push_back(std::move(stats));
324105 break;
324106 case FilterPropagateResult::FILTER_ALWAYS_FALSE:
324107 break;
324108 default:
324109 // any filter that is not always true/false - bail
324110 return;
324111 }
324112 }
324113 partition_stats = std::move(remaining_partition_stats);
324114 }
324115
324116 if (!min_max_bindings.empty()) {
324117 // Execute min/max aggregates on partition statistics
324118 for (idx_t agg_idx = 0; agg_idx < min_max_storage_indexes.size(); agg_idx++) {
324119 const auto &storage_index = min_max_storage_indexes[agg_idx];
324120 auto &comparator = comparators[agg_idx];
324121
324122 Value agg_result;
324123 if (!TryGetValueFromStats(partition_stats[0], storage_index, *comparator, agg_result)) {
324124 return;
324125 }
324126 for (idx_t partition_idx = 1; partition_idx < partition_stats.size(); partition_idx++) {
324127 Value rhs;
324128 if (!TryGetValueFromStats(partition_stats[partition_idx], storage_index, *comparator, rhs)) {
324129 return;
324130 }
324131 if (!comparator->Compare(agg_result, rhs)) {
324132 agg_result = rhs;
324133 }
324134 }
324135 types.push_back(agg_result.GetTypeMutable());
324136 auto expr = make_uniq<BoundConstantExpression>(agg_result);
324137 agg_results.push_back(std::move(expr));
324138 }
324139 }
324140 if (!count_star_idxs.empty()) {
324141 // Execute count_star aggregates on partition statistics
324142 idx_t count = 0;
324143 for (const auto &stats : partition_stats) {
324144 if (stats.count_type == CountType::COUNT_APPROXIMATE) {
324145 // we cannot get an exact count
324146 return;
324147 }
324148 count += stats.count;
324149 }
324150 for (const auto count_star_idx : count_star_idxs) {
324151 auto count_result = make_uniq<BoundConstantExpression>(Value::BIGINT(NumericCast<int64_t>(count)));
324152 agg_results.emplace(agg_results.begin() + NumericCast<int64_t>(count_star_idx), std::move(count_result));
324153 types.insert(types.begin() + NumericCast<int64_t>(count_star_idx), LogicalType::BIGINT);
324154 }
324155 }
324156
324157 // Set column names
324158 for (idx_t expr_idx = 0; expr_idx < agg_results.size(); expr_idx++) {
324159 agg_results[expr_idx]->SetAlias(aggr.expressions[expr_idx]->GetAlias());
324160 }
324161
324162 vector<vector<unique_ptr<Expression>>> expressions;
324163 expressions.push_back(std::move(agg_results));
324164 auto expression_get =
324165 make_uniq<LogicalExpressionGet>(aggr.aggregate_index, std::move(types), std::move(expressions));
324166 expression_get->children.push_back(make_uniq<LogicalDummyScan>(aggr.group_index));
324167 node_ptr = std::move(expression_get);
324168}
static DUCKDB_API Value BIGINT(int64_t value)
Create a bigint Value from a specified value.
Definition duckdb.cpp:132146
Here is the call graph for this function:

◆ ReplaceWithEmptyResult()

void duckdb::StatisticsPropagator::ReplaceWithEmptyResult ( unique_ptr< LogicalOperator > & node)
private
325378 {
325379 node = make_uniq<LogicalEmptyResult>(std::move(node));
325380}

◆ ExpressionIsConstant()

bool duckdb::StatisticsPropagator::ExpressionIsConstant ( Expression & expr,
const Value & val )
private
324275 {
324276 Value expr_value;
324277 if (expr.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) {
324278 expr_value = expr.Cast<BoundConstantExpression>().value;
324279 } else if (expr.IsFoldable()) {
324280 if (!ExpressionExecutor::TryEvaluateScalar(context, expr, expr_value)) {
324281 return false;
324282 }
324283 } else {
324284 return false;
324285 }
324286 D_ASSERT(expr_value.type() == val.type());
324287 return Value::NotDistinctFrom(expr_value, val);
324288}
static DUCKDB_API bool TryEvaluateScalar(ClientContext &context, const Expression &expr, Value &result)
Try to evaluate a scalar expression and fold it into a single value, returns false if an exception is...
Definition duckdb.cpp:150008
static DUCKDB_API bool NotDistinctFrom(const Value &lvalue, const Value &rvalue)
Returns true if the values are not distinct from each other, following SQL semantics for NOT DISTINCT...
Definition duckdb.cpp:134034

◆ ExpressionIsConstantOrNull()

bool duckdb::StatisticsPropagator::ExpressionIsConstantOrNull ( Expression & expr,
const Value & val )
private
324290 {
324291 if (expr.GetExpressionClass() != ExpressionClass::BOUND_FUNCTION) {
324292 return false;
324293 }
324294 auto &bound_function = expr.Cast<BoundFunctionExpression>();
324295 return ConstantOrNull::IsConstantOrNull(bound_function, val);
324296}

◆ PropagateUnion()

unique_ptr< NodeStatistics > duckdb::StatisticsPropagator::PropagateUnion ( LogicalSetOperation & setop,
unique_ptr< LogicalOperator > & node_ptr )
private
325204 {
325205 // first propagate statistics in the child nodes
325206 vector<unique_ptr<NodeStatistics>> stats;
325207 for (auto &child : setop.children) {
325208 stats.push_back(PropagateStatistics(child));
325209 }
325210
325211 // now fetch the column bindings of the children both sides
325212 vector<vector<ColumnBinding>> child_bindings;
325213 for (auto &child : setop.children) {
325214 child_bindings.push_back(child->GetColumnBindings());
325215 }
325216 for (idx_t i = 0; i < setop.column_count; i++) {
325217 // for each column binding, we fetch the statistics from both the lhs and the rhs
325218 unique_ptr<BaseStatistics> new_stats;
325219 for (idx_t child_idx = 0; child_idx < setop.children.size(); child_idx++) {
325220 auto stats_entry = statistics_map.find(child_bindings[child_idx][i]);
325221 if (stats_entry == statistics_map.end()) {
325222 new_stats.reset();
325223 break;
325224 }
325225 auto &child_stats = stats_entry->second;
325226 if (!new_stats) {
325227 new_stats = child_stats->ToUnique();
325228 } else {
325229 new_stats->Merge(*child_stats);
325230 }
325231 }
325232 if (!new_stats) {
325233 // no statistics on at least one of the sides: can't propagate stats
325234 continue;
325235 }
325236 // propagate the stats for this column
325237 ColumnBinding binding(setop.table_index, i);
325238 statistics_map[binding] = std::move(new_stats);
325239 }
325240 // merge all cardinalities of the child stats together
325241 for (idx_t i = 1; i < stats.size(); i++) {
325242 if (!stats[i]) {
325243 return nullptr;
325244 }
325245 AddCardinalities(stats[0], *stats[i]);
325246 }
325247 return std::move(stats[0]);
325248}
void AddCardinalities(unique_ptr< NodeStatistics > &stats, NodeStatistics &new_stats)
Add cardinalities together (i.e. new max is stats.max + new_stats.max): used for union.
Definition duckdb.cpp:325179

The documentation for this class was generated from the following files: