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::CompressedMaterialization Class Reference
Collaboration diagram for duckdb::CompressedMaterialization:

Public Member Functions

 CompressedMaterialization (Optimizer &optimizer, LogicalOperator &root, statistics_map_t &statistics_map)
void Compress (unique_ptr< LogicalOperator > &op)

Private Member Functions

void CompressAggregate (unique_ptr< LogicalOperator > &op)
 Compress materializing operators.
void CompressComparisonJoin (unique_ptr< LogicalOperator > &op)
void CompressDistinct (unique_ptr< LogicalOperator > &op)
void CompressOrder (unique_ptr< LogicalOperator > &op)
void UpdateAggregateStats (unique_ptr< LogicalOperator > &op)
 Update statistics after compressing.
void UpdateComparisonJoinStats (unique_ptr< LogicalOperator > &op)
void UpdateOrderStats (unique_ptr< LogicalOperator > &op)
void UpdateBindingInfo (CompressedMaterializationInfo &info, const ColumnBinding &binding, bool needs_decompression)
 Updates CMBindingInfo in the binding_map in info.
void CreateProjections (unique_ptr< LogicalOperator > &op, CompressedMaterializationInfo &info)
 Create (de)compress projections around the operator.
bool TryCompressChild (CompressedMaterializationInfo &info, const CMChildInfo &child_info, vector< unique_ptr< CompressExpression > > &compress_expressions)
void CreateCompressProjection (unique_ptr< LogicalOperator > &child_op, vector< unique_ptr< CompressExpression > > compress_exprs, CompressedMaterializationInfo &info, CMChildInfo &child_info)
void CreateDecompressProjection (unique_ptr< LogicalOperator > &op, CompressedMaterializationInfo &info)
unique_ptr< CompressExpression > GetCompressExpression (const ColumnBinding &binding, const LogicalType &type, const bool &can_compress)
 Create expressions that apply a scalar compression function.
unique_ptr< CompressExpression > GetCompressExpression (unique_ptr< Expression > input, const BaseStatistics &stats)
unique_ptr< CompressExpression > GetIntegralCompress (unique_ptr< Expression > input, const BaseStatistics &stats)
unique_ptr< CompressExpression > GetStringCompress (unique_ptr< Expression > input, const BaseStatistics &stats)
unique_ptr< Expression > GetDecompressExpression (unique_ptr< Expression > input, const LogicalType &result_type, const BaseStatistics &stats)
 Create an expression that applies a scalar decompression function.
unique_ptr< Expression > GetIntegralDecompress (unique_ptr< Expression > input, const LogicalType &result_type, const BaseStatistics &stats)
unique_ptr< Expression > GetStringDecompress (unique_ptr< Expression > input, const LogicalType &result_type, const BaseStatistics &stats)

Static Private Member Functions

static void GetReferencedBindings (const Expression &expression, column_binding_set_t &referenced_bindings)
 Adds bindings referenced in expression to referenced_bindings.

Private Attributes

Optimizer & optimizer
ClientContext & context
optional_ptr< LogicalOperator > root
 The root of the query plan.
statistics_map_t & statistics_map
 The map of ColumnBinding -> statistics for the various nodes.

Static Private Attributes

static constexpr idx_t JOIN_BUILD_CARDINALITY_THRESHOLD = 1048576
static constexpr idx_t JOIN_BUILD_COLUMN_COUNT_THRESHOLD = 20
 If the cardinality > threshold, we always perform compressed materialization if there are this many columns.
static constexpr double JOIN_CARDINALITY_RATIO_THRESHOLD = 8
 If not, we perform compressed materialization if join result cardinality > build cardinality * this threshold.

Detailed Description

The CompressedMaterialization optimizer compressed columns using projections, based on available statistics, but only if the data enters a materializing operator

Constructor & Destructor Documentation

◆ CompressedMaterialization()

duckdb::CompressedMaterialization::CompressedMaterialization ( Optimizer & optimizer,
LogicalOperator & root,
statistics_map_t & statistics_map )
306055 : optimizer(optimizer_p), context(optimizer.context), root(&root_p), statistics_map(statistics_map_p) {
306056}
optional_ptr< LogicalOperator > root
The root of the query plan.
Definition duckdb.cpp:305597
statistics_map_t & statistics_map
The map of ColumnBinding -> statistics for the various nodes.
Definition duckdb.cpp:305599

Member Function Documentation

◆ Compress()

void duckdb::CompressedMaterialization::Compress ( unique_ptr< LogicalOperator > & op)
306080 {
306081 if (TopN::CanOptimize(*op)) { // Let's not mess with the TopN optimizer
306082 return;
306083 }
306084
306085 switch (op->type) {
306086 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
306087 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
306088 case LogicalOperatorType::LOGICAL_DISTINCT:
306089 case LogicalOperatorType::LOGICAL_ORDER_BY:
306090 break;
306091 default:
306092 return;
306093 }
306094
306095 root->ResolveOperatorTypes();
306096
306097 switch (op->type) {
306098 case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
306099 CompressAggregate(op);
306100 break;
306101 case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
306102 CompressComparisonJoin(op);
306103 break;
306104 case LogicalOperatorType::LOGICAL_DISTINCT:
306105 CompressDistinct(op);
306106 break;
306107 case LogicalOperatorType::LOGICAL_ORDER_BY:
306108 CompressOrder(op);
306109 break;
306110 default:
306111 break;
306112 }
306113}
void CompressAggregate(unique_ptr< LogicalOperator > &op)
Compress materializing operators.
Definition duckdb.cpp:305610
static bool CanOptimize(LogicalOperator &op, optional_ptr< ClientContext > context=nullptr)
Whether we can perform the optimization on this operator.
Definition duckdb.cpp:325685

◆ CompressAggregate()

void duckdb::CompressedMaterialization::CompressAggregate ( unique_ptr< LogicalOperator > & op)
private

Compress materializing operators.

305610 {
305611 auto &aggregate = op->Cast<LogicalAggregate>();
305612 if (aggregate.grouping_sets.size() > 1) {
305613 return; // FIXME: we should be able to compress here but for some reason the NULL statistics ain't right
305614 }
305615 auto &groups = aggregate.groups;
305616 column_binding_set_t group_binding_set;
305617 for (const auto &group : groups) {
305618 if (group->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) {
305619 continue;
305620 }
305621 auto &colref = group->Cast<BoundColumnRefExpression>();
305622 if (group_binding_set.find(colref.binding) != group_binding_set.end()) {
305623 return; // Duplicate group - don't compress
305624 }
305625 group_binding_set.insert(colref.binding);
305626 }
305627 auto &group_stats = aggregate.group_stats;
305628
305629 // No need to compress if there are no groups/stats
305630 if (groups.empty() || group_stats.empty()) {
305631 return;
305632 }
305633 D_ASSERT(groups.size() == group_stats.size());
305634
305635 // Find all bindings referenced by non-colref expressions in the groups
305636 // These are excluded from compression by projection
305637 // But we can try to compress the expression directly
305638 column_binding_set_t referenced_bindings;
305639 vector<ColumnBinding> group_bindings(groups.size(), ColumnBinding());
305640 vector<bool> needs_decompression(groups.size(), false);
305641 vector<unique_ptr<BaseStatistics>> stored_group_stats;
305642 stored_group_stats.resize(groups.size());
305643 for (idx_t group_idx = 0; group_idx < groups.size(); group_idx++) {
305644 auto &group_expr = *groups[group_idx];
305645 if (group_expr.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
305646 auto &colref = group_expr.Cast<BoundColumnRefExpression>();
305647 group_bindings[group_idx] = colref.binding;
305648 continue; // Will be compressed generically
305649 }
305650
305651 // Mark the bindings referenced by the non-colref expression so they won't be modified
305652 GetReferencedBindings(group_expr, referenced_bindings);
305653
305654 // The non-colref expression won't be compressed generically, so try to compress it here
305655 if (!group_stats[group_idx]) {
305656 continue; // Can't compress without stats
305657 }
305658
305659 // Try to compress, if successful, replace the expression
305660 auto compress_expr = GetCompressExpression(group_expr.Copy(), *group_stats[group_idx]);
305661 if (compress_expr) {
305662 needs_decompression[group_idx] = true;
305663 stored_group_stats[group_idx] = std::move(group_stats[group_idx]);
305664 groups[group_idx] = std::move(compress_expr->expression);
305665 group_stats[group_idx] = std::move(compress_expr->stats);
305666 }
305667 }
305668
305669 // Anything referenced in the aggregate functions is also excluded
305670 for (idx_t expr_idx = 0; expr_idx < aggregate.expressions.size(); expr_idx++) {
305671 const auto &expr = *aggregate.expressions[expr_idx];
305672 D_ASSERT(expr.GetExpressionType() == ExpressionType::BOUND_AGGREGATE);
305673 const auto &aggr_expr = expr.Cast<BoundAggregateExpression>();
305674 for (const auto &child : aggr_expr.children) {
305675 GetReferencedBindings(*child, referenced_bindings);
305676 }
305677 if (aggr_expr.filter) {
305678 GetReferencedBindings(*aggr_expr.filter, referenced_bindings);
305679 }
305680 if (aggr_expr.order_bys) {
305681 for (const auto &order : aggr_expr.order_bys->orders) {
305682 const auto &order_expr = *order.expression;
305683 if (order_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) {
305684 GetReferencedBindings(order_expr, referenced_bindings);
305685 }
305686 }
305687 }
305688 }
305689
305690 // Create info for compression
305691 CompressedMaterializationInfo info(*op, {0}, referenced_bindings);
305692
305693 // Create binding mapping
305694 const auto bindings_out = aggregate.GetColumnBindings();
305695 const auto &types = aggregate.types;
305696 for (idx_t group_idx = 0; group_idx < groups.size(); group_idx++) {
305697 // Aggregate changes bindings as it has a table idx
305698 CMBindingInfo binding_info(bindings_out[group_idx], types[group_idx]);
305699 binding_info.needs_decompression = needs_decompression[group_idx];
305700 if (needs_decompression[group_idx]) {
305701 // Compressed non-generically
305702 auto entry = info.binding_map.emplace(bindings_out[group_idx], std::move(binding_info));
305703 entry.first->second.stats = std::move(stored_group_stats[group_idx]);
305704 } else if (group_bindings[group_idx] != ColumnBinding()) {
305705 info.binding_map.emplace(group_bindings[group_idx], std::move(binding_info));
305706 }
305707 }
305708
305709 // Now try to compress
305710 CreateProjections(op, info);
305711
305712 // Update aggregate statistics
305714}
void UpdateAggregateStats(unique_ptr< LogicalOperator > &op)
Update statistics after compressing.
Definition duckdb.cpp:305716
unique_ptr< CompressExpression > GetCompressExpression(const ColumnBinding &binding, const LogicalType &type, const bool &can_compress)
Create expressions that apply a scalar compression function.
Definition duckdb.cpp:306306
void CreateProjections(unique_ptr< LogicalOperator > &op, CompressedMaterializationInfo &info)
Create (de)compress projections around the operator.
Definition duckdb.cpp:306115
static void GetReferencedBindings(const Expression &expression, column_binding_set_t &referenced_bindings)
Adds bindings referenced in expression to referenced_bindings.
Definition duckdb.cpp:306058
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Here is the call graph for this function:

◆ CompressComparisonJoin()

void duckdb::CompressedMaterialization::CompressComparisonJoin ( unique_ptr< LogicalOperator > & op)
private
305767 {
305768 auto &join = op->Cast<LogicalComparisonJoin>();
305769 if (join.join_type == JoinType::MARK) {
305770 // Tricky to get bindings right. RHS binding stays the same even though it changes type. Skip for now
305771 return;
305772 }
305773
305774 auto &left_child = *join.children[0];
305775 auto &right_child = *join.children[1];
305776
305777#ifndef DEBUG
305778 // In debug mode, we always apply compressed materialization to joins regardless of cardinalities,
305779 // so that it is well-tested. In release mode, we use the thresholds defined in the header
305780 const auto build_cardinality = right_child.has_estimated_cardinality ? right_child.estimated_cardinality
305781 : right_child.EstimateCardinality(context);
305782 if (build_cardinality < JOIN_BUILD_CARDINALITY_THRESHOLD) {
305783 return;
305784 }
305785
305786 if (right_child.types.size() < JOIN_BUILD_COLUMN_COUNT_THRESHOLD) {
305787 const auto join_cardinality =
305788 join.has_estimated_cardinality ? join.estimated_cardinality : join.EstimateCardinality(context);
305789 const double ratio = static_cast<double>(join_cardinality) / static_cast<double>(build_cardinality);
305790 if (ratio > JOIN_CARDINALITY_RATIO_THRESHOLD) {
305791 return;
305792 }
305793 }
305794#endif
305795
305796 // Find all bindings referenced by non-colref expressions in the conditions
305797 // These are excluded from compression by projection
305798 // But we can try to compress the expression directly
305799 column_binding_set_t probe_compress_bindings;
305800 column_binding_set_t referenced_bindings;
305801 for (const auto &condition : join.conditions) {
305802 if (join.conditions.size() == 1 && join.type != LogicalOperatorType::LOGICAL_DELIM_JOIN) {
305803 // We only try to compress the join condition cols if there's one join condition
305804 // Else it gets messy with the stats if one column shows up in multiple conditions
305805 if (condition.left->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF &&
305806 condition.right->GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
305807 // Both are bound column refs, see if both can be compressed generically to the same type
305808 auto &lhs_colref = condition.left->Cast<BoundColumnRefExpression>();
305809 auto &rhs_colref = condition.right->Cast<BoundColumnRefExpression>();
305810 auto lhs_it = statistics_map.find(lhs_colref.binding);
305811 auto rhs_it = statistics_map.find(rhs_colref.binding);
305812 if (lhs_it != statistics_map.end() && rhs_it != statistics_map.end() && lhs_it->second &&
305813 rhs_it->second) {
305814 // For joins we need to compress both using the same statistics, otherwise comparisons don't work
305815 auto merged_stats = lhs_it->second->Copy();
305816 merged_stats.Merge(*rhs_it->second);
305817
305818 // If one can be compressed, both can (same stats)
305819 auto compress_expr = GetCompressExpression(condition.left->Copy(), merged_stats);
305820 if (compress_expr) {
305821 D_ASSERT(GetCompressExpression(condition.right->Copy(), merged_stats));
305822 // This will be compressed generically, but we have to merge the stats
305823 lhs_it->second->Merge(merged_stats);
305824 rhs_it->second->Merge(merged_stats);
305825 probe_compress_bindings.insert(lhs_colref.binding);
305826 continue;
305827 }
305828 }
305829 }
305830 }
305831 GetReferencedBindings(*condition.left, referenced_bindings);
305832 GetReferencedBindings(*condition.right, referenced_bindings);
305833 }
305834
305835 if (join.type == LogicalOperatorType::LOGICAL_DELIM_JOIN) {
305836 for (auto &dec : join.duplicate_eliminated_columns) {
305837 GetReferencedBindings(*dec, referenced_bindings);
305838 }
305839 }
305840
305841 // We mark the probe-side bindings that do not show up in the join condition as "referenced"
305842 // We don't want to compress these because they are streamed
305843 const auto probe_bindings = left_child.GetColumnBindings();
305844 for (auto &binding : probe_bindings) {
305845 if (probe_compress_bindings.find(binding) == probe_compress_bindings.end()) {
305846 referenced_bindings.insert(binding);
305847 }
305848 }
305849
305850 // Create info for compression
305851 CompressedMaterializationInfo info(*op, {0, 1}, referenced_bindings);
305852
305853 const auto bindings_out = join.GetColumnBindings();
305854 const auto &types = join.types;
305855 PopulateBindingMap(info, bindings_out, types, left_child);
305856 PopulateBindingMap(info, bindings_out, types, right_child);
305857
305858 // Now try to compress
305859 CreateProjections(op, info);
305860
305861 // Update join statistics
305862 UpdateComparisonJoinStats(op);
305863}
static constexpr idx_t JOIN_BUILD_COLUMN_COUNT_THRESHOLD
If the cardinality > threshold, we always perform compressed materialization if there are this many c...
Definition duckdb.cpp:305543
static constexpr double JOIN_CARDINALITY_RATIO_THRESHOLD
If not, we perform compressed materialization if join result cardinality > build cardinality * this t...
Definition duckdb.cpp:305545
static constexpr idx_t JOIN_BUILD_CARDINALITY_THRESHOLD
Definition duckdb.cpp:305541
cv::String join(const cv::String &base, const cv::String &path)

◆ CompressDistinct()

void duckdb::CompressedMaterialization::CompressDistinct ( unique_ptr< LogicalOperator > & op)
private
305908 {
305909 auto &distinct = op->Cast<LogicalDistinct>();
305910 auto &distinct_targets = distinct.distinct_targets;
305911
305912 column_binding_set_t referenced_bindings;
305913 for (auto &target : distinct_targets) {
305914 if (target->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { // LCOV_EXCL_START
305915 GetReferencedBindings(*target, referenced_bindings);
305916 } // LCOV_EXCL_STOP
305917 }
305918
305919 if (distinct.order_by) {
305920 for (auto &order : distinct.order_by->orders) {
305921 if (order.expression->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) { // LCOV_EXCL_START
305922 GetReferencedBindings(*order.expression, referenced_bindings);
305923 } // LCOV_EXCL_STOP
305924 }
305925 }
305926
305927 // Create info for compression
305928 CompressedMaterializationInfo info(*op, {0}, referenced_bindings);
305929
305930 // Create binding mapping
305931 const auto bindings = distinct.GetColumnBindings();
305932 const auto &types = distinct.types;
305933 D_ASSERT(bindings.size() == types.size());
305934 for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) {
305935 // Distinct does not change bindings, input binding is output binding
305936 info.binding_map.emplace(bindings[col_idx], CMBindingInfo(bindings[col_idx], types[col_idx]));
305937 }
305938
305939 // Now try to compress
305940 CreateProjections(op, info);
305941}

◆ CompressOrder()

void duckdb::CompressedMaterialization::CompressOrder ( unique_ptr< LogicalOperator > & op)
private
305950 {
305951 auto &order = op->Cast<LogicalOrder>();
305952
305953 // Find all bindings referenced by non-colref expressions in the order nodes
305954 // These are excluded from compression by projection
305955 // But we can try to compress the expression directly
305956 column_binding_set_t referenced_bindings;
305957 for (idx_t order_node_idx = 0; order_node_idx < order.orders.size(); order_node_idx++) {
305958 auto &bound_order = order.orders[order_node_idx];
305959 auto &order_expression = *bound_order.expression;
305960 if (order_expression.GetExpressionType() == ExpressionType::BOUND_COLUMN_REF) {
305961 continue; // Will be compressed generically
305962 }
305963
305964 // Mark the bindings referenced by the non-colref expression so they won't be modified
305965 GetReferencedBindings(order_expression, referenced_bindings);
305966 }
305967
305968 // Create info for compression
305969 CompressedMaterializationInfo info(*op, {0}, referenced_bindings);
305970
305971 // Create binding mapping
305972 const auto bindings = order.GetColumnBindings();
305973 const auto &types = order.types;
305974 D_ASSERT(bindings.size() == types.size());
305975 for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) {
305976 // Order does not change bindings, input binding is output binding
305977 info.binding_map.emplace(bindings[col_idx], CMBindingInfo(bindings[col_idx], types[col_idx]));
305978 }
305979
305980 // Now try to compress
305981 CreateProjections(op, info);
305982
305983 // Update order statistics
305984 UpdateOrderStats(op);
305985}

◆ UpdateAggregateStats()

void duckdb::CompressedMaterialization::UpdateAggregateStats ( unique_ptr< LogicalOperator > & op)
private

Update statistics after compressing.

305716 {
305717 if (op->type != LogicalOperatorType::LOGICAL_PROJECTION) {
305718 return;
305719 }
305720
305721 // Update aggregate group stats if compressed
305722 auto &compressed_aggregate = op->children[0]->Cast<LogicalAggregate>();
305723 auto &groups = compressed_aggregate.groups;
305724 auto &group_stats = compressed_aggregate.group_stats;
305725
305726 for (idx_t group_idx = 0; group_idx < groups.size(); group_idx++) {
305727 auto &group_expr = *groups[group_idx];
305728 if (group_expr.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) {
305729 continue;
305730 }
305731 auto &colref = group_expr.Cast<BoundColumnRefExpression>();
305732 if (!group_stats[group_idx]) {
305733 continue;
305734 }
305735 if (colref.return_type == group_stats[group_idx]->GetType()) {
305736 continue;
305737 }
305738 auto it = statistics_map.find(colref.binding);
305739 if (it != statistics_map.end() && it->second) {
305740 group_stats[group_idx] = it->second->ToUnique();
305741 }
305742 }
305743}
Here is the caller graph for this function:

◆ UpdateComparisonJoinStats()

void duckdb::CompressedMaterialization::UpdateComparisonJoinStats ( unique_ptr< LogicalOperator > & op)
private
305865 {
305866 if (op->type != LogicalOperatorType::LOGICAL_PROJECTION) {
305867 return;
305868 }
305869
305870 // Update join stats if compressed
305871 auto &compressed_join = op->children[0]->Cast<LogicalComparisonJoin>();
305872 if (compressed_join.join_stats.empty()) {
305873 return; // Nothing to update
305874 }
305875
305876 for (idx_t condition_idx = 0; condition_idx < compressed_join.conditions.size(); condition_idx++) {
305877 auto &condition = compressed_join.conditions[condition_idx];
305878 if (condition.left->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF ||
305879 condition.right->GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) {
305880 continue; // We definitely didn't compress these, nothing changed
305881 }
305882 if (condition_idx * 2 >= compressed_join.join_stats.size()) {
305883 break;
305884 }
305885
305886 auto &lhs_colref = condition.left->Cast<BoundColumnRefExpression>();
305887 auto &rhs_colref = condition.right->Cast<BoundColumnRefExpression>();
305888 auto &lhs_join_stats = compressed_join.join_stats[condition_idx * 2];
305889 auto &rhs_join_stats = compressed_join.join_stats[condition_idx * 2 + 1];
305890 auto lhs_it = statistics_map.find(lhs_colref.binding);
305891 auto rhs_it = statistics_map.find(rhs_colref.binding);
305892 if (lhs_it != statistics_map.end() && lhs_it->second) {
305893 lhs_join_stats = lhs_it->second->ToUnique();
305894 }
305895 if (rhs_it != statistics_map.end() && rhs_it->second) {
305896 rhs_join_stats = rhs_it->second->ToUnique();
305897 }
305898 }
305899}

◆ UpdateOrderStats()

void duckdb::CompressedMaterialization::UpdateOrderStats ( unique_ptr< LogicalOperator > & op)
private
305987 {
305988 if (op->type != LogicalOperatorType::LOGICAL_PROJECTION) {
305989 return;
305990 }
305991
305992 // Update order stats if compressed
305993 auto &compressed_order = op->children[0]->Cast<LogicalOrder>();
305994 for (idx_t order_node_idx = 0; order_node_idx < compressed_order.orders.size(); order_node_idx++) {
305995 auto &bound_order = compressed_order.orders[order_node_idx];
305996 auto &order_expression = *bound_order.expression;
305997 if (order_expression.GetExpressionType() != ExpressionType::BOUND_COLUMN_REF) {
305998 continue;
305999 }
306000 auto &colref = order_expression.Cast<BoundColumnRefExpression>();
306001 auto it = statistics_map.find(colref.binding);
306002 if (it != statistics_map.end() && it->second) {
306003 bound_order.stats = it->second->ToUnique();
306004 }
306005 }
306006}

◆ GetReferencedBindings()

void duckdb::CompressedMaterialization::GetReferencedBindings ( const Expression & expression,
column_binding_set_t & referenced_bindings )
staticprivate

Adds bindings referenced in expression to referenced_bindings.

306059 {
306060 ExpressionIterator::VisitExpression<BoundColumnRefExpression>(
306061 root_expr, [&](const BoundColumnRefExpression &col_ref) { referenced_bindings.insert(col_ref.binding); });
306062}
Here is the caller graph for this function:

◆ UpdateBindingInfo()

void duckdb::CompressedMaterialization::UpdateBindingInfo ( CompressedMaterializationInfo & info,
const ColumnBinding & binding,
bool needs_decompression )
private

Updates CMBindingInfo in the binding_map in info.

306065 {
306066 auto &binding_map = info.binding_map;
306067 auto binding_it = binding_map.find(binding);
306068 if (binding_it == binding_map.end()) {
306069 return;
306070 }
306071
306072 auto &binding_info = binding_it->second;
306073 binding_info.needs_decompression = needs_decompression;
306074 auto stats_it = statistics_map.find(binding);
306075 if (stats_it != statistics_map.end()) {
306076 binding_info.stats = statistics_map[binding]->ToUnique();
306077 }
306078}

◆ CreateProjections()

void duckdb::CompressedMaterialization::CreateProjections ( unique_ptr< LogicalOperator > & op,
CompressedMaterializationInfo & info )
private

Create (de)compress projections around the operator.

306116 {
306117 auto &materializing_op = *op;
306118
306119 bool compressed_anything = false;
306120 for (idx_t i = 0; i < info.child_idxs.size(); i++) {
306121 auto &child_info = info.child_info[i];
306122 vector<unique_ptr<CompressExpression>> compress_exprs;
306123 if (TryCompressChild(info, child_info, compress_exprs)) {
306124 // We can compress: Create a projection on top of the child operator
306125 const auto child_idx = info.child_idxs[i];
306126 CreateCompressProjection(materializing_op.children[child_idx], std::move(compress_exprs), info, child_info);
306127 compressed_anything = true;
306128 }
306129 }
306130
306131 if (compressed_anything) {
306132 CreateDecompressProjection(op, info);
306133 }
306134}
Here is the caller graph for this function:

◆ TryCompressChild()

bool duckdb::CompressedMaterialization::TryCompressChild ( CompressedMaterializationInfo & info,
const CMChildInfo & child_info,
vector< unique_ptr< CompressExpression > > & compress_expressions )
private
306137 {
306138 // Try to compress each of the column bindings of the child
306139 bool compressed_anything = false;
306140 for (idx_t child_i = 0; child_i < child_info.bindings_before.size(); child_i++) {
306141 const auto child_binding = child_info.bindings_before[child_i];
306142 const auto &child_type = child_info.types[child_i];
306143 const auto &can_compress = child_info.can_compress[child_i];
306144 auto compress_expr = GetCompressExpression(child_binding, child_type, can_compress);
306145 bool compressed = false;
306146 if (compress_expr) { // We compressed, mark the outgoing binding in need of decompression
306147 compress_exprs.emplace_back(std::move(compress_expr));
306148 compressed = true;
306149 } else { // We did not compress, just push a colref
306150 auto colref_expr = make_uniq<BoundColumnRefExpression>(child_type, child_binding);
306151 auto it = statistics_map.find(colref_expr->binding);
306152 unique_ptr<BaseStatistics> colref_stats = it != statistics_map.end() ? it->second->ToUnique() : nullptr;
306153 compress_exprs.emplace_back(make_uniq<CompressExpression>(std::move(colref_expr), std::move(colref_stats)));
306154 }
306155 UpdateBindingInfo(info, child_binding, compressed);
306156 compressed_anything = compressed_anything || compressed;
306157 }
306158 if (!compressed_anything) {
306159 // If we compressed anything non-generically, we still need to decompress
306160 for (const auto &entry : info.binding_map) {
306161 compressed_anything = compressed_anything || entry.second.needs_decompression;
306162 }
306163 }
306164 return compressed_anything;
306165}
void UpdateBindingInfo(CompressedMaterializationInfo &info, const ColumnBinding &binding, bool needs_decompression)
Updates CMBindingInfo in the binding_map in info.
Definition duckdb.cpp:306064

◆ CreateCompressProjection()

void duckdb::CompressedMaterialization::CreateCompressProjection ( unique_ptr< LogicalOperator > & child_op,
vector< unique_ptr< CompressExpression > > compress_exprs,
CompressedMaterializationInfo & info,
CMChildInfo & child_info )
private
306169 {
306170 // Replace child op with a projection
306171 vector<unique_ptr<Expression>> projections;
306172 projections.reserve(compress_exprs.size());
306173 for (auto &compress_expr : compress_exprs) {
306174 projections.emplace_back(std::move(compress_expr->expression));
306175 }
306176 const auto table_index = optimizer.binder.GenerateTableIndex();
306177 auto compress_projection = make_uniq<LogicalProjection>(table_index, std::move(projections));
306178 if (child_op->has_estimated_cardinality) {
306179 compress_projection->SetEstimatedCardinality(child_op->estimated_cardinality);
306180 }
306181 compress_projection->ResolveOperatorTypes();
306182
306183 compress_projection->children.emplace_back(std::move(child_op));
306184 child_op = std::move(compress_projection);
306185
306186 // Get the new bindings and types
306187 child_info.bindings_after = child_op->GetColumnBindings();
306188 const auto &new_types = child_op->types;
306189
306190 // Initialize a ColumnBindingReplacer with the new bindings and types
306191 ColumnBindingReplacer replacer;
306192 auto &replacement_bindings = replacer.replacement_bindings;
306193 for (idx_t col_idx = 0; col_idx < child_info.bindings_before.size(); col_idx++) {
306194 const auto &old_binding = child_info.bindings_before[col_idx];
306195 const auto &new_binding = child_info.bindings_after[col_idx];
306196 const auto &new_type = new_types[col_idx];
306197 replacement_bindings.emplace_back(old_binding, new_binding, new_type);
306198
306199 // Remove the old binding from the statistics map
306200 statistics_map.erase(old_binding);
306201 }
306202
306203 // Make sure we stop at the compress operator when replacing bindings
306204 replacer.stop_operator = child_op.get();
306205
306206 // Make the plan consistent again
306207 replacer.VisitOperator(*root);
306208
306209 // Replace in/out exprs in the binding map too
306210 auto &binding_map = info.binding_map;
306211 for (auto &replacement_binding : replacement_bindings) {
306212 auto it = binding_map.find(replacement_binding.old_binding);
306213 if (it == binding_map.end()) {
306214 continue;
306215 }
306216 auto &binding_info = it->second;
306217 if (binding_info.binding == replacement_binding.old_binding) {
306218 binding_info.binding = replacement_binding.new_binding;
306219 }
306220
306221 if (it->first == replacement_binding.old_binding) {
306222 auto binding_info_local = std::move(binding_info);
306223 binding_map.erase(it);
306224 binding_map.emplace(replacement_binding.new_binding, std::move(binding_info_local));
306225 }
306226 }
306227
306228 // Add projection stats to statistics map
306229 for (idx_t col_idx = 0; col_idx < child_info.bindings_after.size(); col_idx++) {
306230 const auto &binding = child_info.bindings_after[col_idx];
306231 auto &stats = compress_exprs[col_idx]->stats;
306232 statistics_map.emplace(binding, std::move(stats));
306233 }
306234}

◆ CreateDecompressProjection()

void duckdb::CompressedMaterialization::CreateDecompressProjection ( unique_ptr< LogicalOperator > & op,
CompressedMaterializationInfo & info )
private
306237 {
306238 const auto bindings = op->GetColumnBindings();
306239 op->ResolveOperatorTypes();
306240 const auto &types = op->types;
306241
306242 // Create decompress expressions for everything we compressed
306243 auto &binding_map = info.binding_map;
306244 vector<unique_ptr<Expression>> decompress_exprs;
306245 vector<optional_ptr<BaseStatistics>> statistics;
306246 for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) {
306247 const auto &binding = bindings[col_idx];
306248 auto decompress_expr = make_uniq_base<Expression, BoundColumnRefExpression>(types[col_idx], binding);
306249 optional_ptr<BaseStatistics> stats;
306250 for (auto &entry : binding_map) {
306251 auto &binding_info = entry.second;
306252 if (binding_info.binding != binding) {
306253 continue;
306254 }
306255 stats = binding_info.stats.get();
306256 if (binding_info.needs_decompression) {
306257 decompress_expr = GetDecompressExpression(std::move(decompress_expr), binding_info.type, *stats);
306258 }
306259 }
306260 statistics.push_back(stats);
306261 decompress_exprs.emplace_back(std::move(decompress_expr));
306262 }
306263
306264 // Replace op with a projection
306265 const auto table_index = optimizer.binder.GenerateTableIndex();
306266 auto decompress_projection = make_uniq<LogicalProjection>(table_index, std::move(decompress_exprs));
306267 if (op->has_estimated_cardinality) {
306268 decompress_projection->SetEstimatedCardinality(op->estimated_cardinality);
306269 }
306270
306271 decompress_projection->children.emplace_back(std::move(op));
306272 op = std::move(decompress_projection);
306273
306274 // Check if we're placing a projection on top of the root
306275 if (RefersToSameObject(*op->children[0], *root)) {
306276 root = op;
306277 return;
306278 }
306279
306280 // Get the new bindings and types
306281 auto new_bindings = op->GetColumnBindings();
306282 op->ResolveOperatorTypes();
306283 auto &new_types = op->types;
306284
306285 // Initialize a ColumnBindingReplacer with the new bindings and types
306286 ColumnBindingReplacer replacer;
306287 auto &replacement_bindings = replacer.replacement_bindings;
306288 for (idx_t col_idx = 0; col_idx < bindings.size(); col_idx++) {
306289 const auto &old_binding = bindings[col_idx];
306290 const auto &new_binding = new_bindings[col_idx];
306291 const auto &new_type = new_types[col_idx];
306292 replacement_bindings.emplace_back(old_binding, new_binding, new_type);
306293
306294 if (statistics[col_idx]) {
306295 statistics_map[new_binding] = statistics[col_idx]->ToUnique();
306296 }
306297 }
306298
306299 // Make sure we skip the decompress operator when replacing bindings
306300 replacer.stop_operator = op.get();
306301
306302 // Make the plan consistent again
306303 replacer.VisitOperator(*root);
306304}
unique_ptr< Expression > GetDecompressExpression(unique_ptr< Expression > input, const LogicalType &result_type, const BaseStatistics &stats)
Create an expression that applies a scalar decompression function.
Definition duckdb.cpp:306477
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191

◆ GetCompressExpression() [1/2]

unique_ptr< CompressExpression > duckdb::CompressedMaterialization::GetCompressExpression ( const ColumnBinding & binding,
const LogicalType & type,
const bool & can_compress )
private

Create expressions that apply a scalar compression function.

306308 {
306309 auto it = statistics_map.find(binding);
306310 if (can_compress && it != statistics_map.end() && it->second) {
306311 auto input = make_uniq<BoundColumnRefExpression>(type, binding);
306312 const auto &stats = *it->second;
306313 return GetCompressExpression(std::move(input), stats);
306314 }
306315 return nullptr;
306316}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetCompressExpression() [2/2]

unique_ptr< CompressExpression > duckdb::CompressedMaterialization::GetCompressExpression ( unique_ptr< Expression > input,
const BaseStatistics & stats )
private
306319 {
306320 const auto &type = input->return_type;
306321 if (type != stats.GetType()) { // LCOV_EXCL_START
306322 return nullptr;
306323 } // LCOV_EXCL_STOP
306324 if (type.IsIntegral()) {
306325 return GetIntegralCompress(std::move(input), stats);
306326 } else if (type.id() == LogicalTypeId::VARCHAR) {
306327 return GetStringCompress(std::move(input), stats);
306328 }
306329 return nullptr;
306330}

◆ GetIntegralCompress()

unique_ptr< CompressExpression > duckdb::CompressedMaterialization::GetIntegralCompress ( unique_ptr< Expression > input,
const BaseStatistics & stats )
private
306354 {
306355 const auto &type = input->return_type;
306356 if (GetTypeIdSize(type.InternalType()) == 1) {
306357 return nullptr;
306358 }
306359
306360 LogicalType cast_type;
306361 Value range_value;
306362 Value min;
306363 if (!stats.CanHaveNoNull()) {
306364 // All NULL
306365 cast_type = LogicalType::UTINYINT;
306366 range_value = Value::UTINYINT(0);
306367 min = Value(input->return_type);
306368 } else if (NumericStats::HasMinMax(stats)) {
306369 // Get range and cast to UBIGINT (might fail for HUGEINT, in which case we just return)
306370 range_value = GetIntegralRangeValue(context, type, stats);
306371 if (!range_value.DefaultTryCastAs(LogicalType::UBIGINT)) {
306372 return nullptr;
306373 }
306374
306375 // Get the smallest type that the range can fit into
306376 const auto range = UBigIntValue::Get(range_value);
306377 if (range <= NumericLimits<uint8_t>().Maximum()) {
306378 cast_type = LogicalType::UTINYINT;
306379 } else if (range <= NumericLimits<uint16_t>().Maximum()) {
306380 cast_type = LogicalType::USMALLINT;
306381 } else if (range <= NumericLimits<uint32_t>().Maximum()) {
306382 cast_type = LogicalType::UINTEGER;
306383 } else {
306384 D_ASSERT(range <= NumericLimits<uint64_t>().Maximum());
306385 cast_type = LogicalType::UBIGINT;
306386 }
306387
306388 min = NumericStats::Min(stats);
306389 } else {
306390 // We don't have enough stats to do anything
306391 return nullptr;
306392 }
306393
306394 // Check if type that fits the range is smaller than the input type
306395 if (GetTypeIdSize(cast_type.InternalType()) == GetTypeIdSize(type.InternalType())) {
306396 return nullptr;
306397 }
306398 D_ASSERT(GetTypeIdSize(cast_type.InternalType()) < GetTypeIdSize(type.InternalType()));
306399
306400 // Compressing will yield a benefit
306401 auto compress_function = CMIntegralCompressFun::GetFunction(type, cast_type);
306402 vector<unique_ptr<Expression>> arguments;
306403 arguments.emplace_back(std::move(input));
306404 arguments.emplace_back(make_uniq<BoundConstantExpression>(min));
306405 auto compress_expr =
306406 make_uniq<BoundFunctionExpression>(cast_type, compress_function, std::move(arguments), nullptr);
306407
306408 auto compress_stats = BaseStatistics::CreateEmpty(cast_type);
306409 compress_stats.CopyBase(stats);
306410 NumericStats::SetMin(compress_stats, Value(0).DefaultCastAs(cast_type));
306411 NumericStats::SetMax(compress_stats, range_value.DefaultCastAs(cast_type));
306412
306413 return make_uniq<CompressExpression>(std::move(compress_expr), compress_stats.ToUnique());
306414}
static BaseStatistics CreateEmpty(LogicalType type)
Definition duckdb.cpp:422871
static DUCKDB_API Value UTINYINT(uint8_t value)
Create an unsigned tinyint Value from a specified value.
Definition duckdb.cpp:132181
static softfloat min()
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 bool HasMinMax(const BaseStatistics &stats)
Returns true if the stats has both a min and max value defined.
Definition duckdb.cpp:424237
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

◆ GetStringCompress()

unique_ptr< CompressExpression > duckdb::CompressedMaterialization::GetStringCompress ( unique_ptr< Expression > input,
const BaseStatistics & stats )
private
306417 {
306418 LogicalType cast_type = LogicalType::INVALID;
306419 uint32_t max_string_length;
306420 if (!stats.CanHaveNoNull()) {
306421 // All NULL
306422 cast_type = LogicalType::UTINYINT;
306423 max_string_length = 0;
306424 } else if (StringStats::HasMaxStringLength(stats)) {
306425 max_string_length = StringStats::MaxStringLength(stats);
306426 for (const auto &compressed_type : CMUtils::StringTypes()) {
306427 if (max_string_length < GetTypeIdSize(compressed_type.InternalType())) {
306428 cast_type = compressed_type;
306429 break;
306430 }
306431 }
306432 if (cast_type == LogicalType::INVALID) {
306433 return nullptr;
306434 }
306435 } else {
306436 // We don't have enough stats to do anything
306437 return nullptr;
306438 }
306439
306440 auto compress_stats = BaseStatistics::CreateEmpty(cast_type);
306441 compress_stats.CopyBase(stats);
306442 if (cast_type.id() == LogicalTypeId::USMALLINT) {
306443 auto min_string = StringStats::Min(stats);
306444 auto max_string = StringStats::Max(stats);
306445
306446 uint8_t min_numeric = 0;
306447 if (max_string_length != 0 && !min_string.empty()) {
306448 min_numeric = *reinterpret_cast<const uint8_t *>(min_string.c_str());
306449 }
306450 uint8_t max_numeric = 0;
306451 if (max_string_length != 0 && !max_string.empty()) {
306452 max_numeric = *reinterpret_cast<const uint8_t *>(max_string.c_str());
306453 }
306454
306455 Value min_val = Value::USMALLINT(min_numeric);
306456 Value max_val = Value::USMALLINT(max_numeric + 1);
306457 if (max_numeric < NumericLimits<uint8_t>::Maximum()) {
306458 cast_type = LogicalType::UTINYINT;
306459 compress_stats = BaseStatistics::CreateEmpty(cast_type);
306460 compress_stats.CopyBase(stats);
306461 min_val = Value::UTINYINT(min_numeric);
306462 max_val = Value::UTINYINT(max_numeric + 1);
306463 }
306464
306465 NumericStats::SetMin(compress_stats, min_val);
306466 NumericStats::SetMax(compress_stats, max_val);
306467 }
306468
306469 auto compress_function = CMStringCompressFun::GetFunction(cast_type);
306470 vector<unique_ptr<Expression>> arguments;
306471 arguments.emplace_back(std::move(input));
306472 auto compress_expr =
306473 make_uniq<BoundFunctionExpression>(cast_type, compress_function, std::move(arguments), nullptr);
306474 return make_uniq<CompressExpression>(std::move(compress_expr), compress_stats.ToUnique());
306475}
static DUCKDB_API Value USMALLINT(uint16_t value)
Create an unsigned smallint Value from a specified value.
Definition duckdb.cpp:132188
::uint32_t uint32_t
::uint8_t uint8_t
static const vector< LogicalType > StringTypes()
The types we compress strings to.
Definition duckdb.cpp:224537
static DUCKDB_API uint32_t MaxStringLength(const BaseStatistics &stats)
Returns the maximum string length, or throws an exception if !HasMaxStringLength().
Definition duckdb.cpp:424560
static DUCKDB_API bool HasMaxStringLength(const BaseStatistics &stats)
Whether or not the statistics have a maximum string length defined.
Definition duckdb.cpp:424553
static DUCKDB_API string Max(const BaseStatistics &stats)
Returns the max value (up to a length of StringStatsData::MAX_STRING_MINMAX_SIZE).
Definition duckdb.cpp:424588
static DUCKDB_API string Min(const BaseStatistics &stats)
Returns the min value (up to a length of StringStatsData::MAX_STRING_MINMAX_SIZE).
Definition duckdb.cpp:424584

◆ GetDecompressExpression()

unique_ptr< Expression > duckdb::CompressedMaterialization::GetDecompressExpression ( unique_ptr< Expression > input,
const LogicalType & result_type,
const BaseStatistics & stats )
private

Create an expression that applies a scalar decompression function.

306479 {
306480 const auto &type = result_type;
306481 if (TypeIsIntegral(type.InternalType())) {
306482 return GetIntegralDecompress(std::move(input), result_type, stats);
306483 } else if (type.id() == LogicalTypeId::VARCHAR) {
306484 return GetStringDecompress(std::move(input), result_type, stats);
306485 } else {
306486 throw InternalException("Type other than integral/string marked for decompression!");
306487 }
306488}

◆ GetIntegralDecompress()

unique_ptr< Expression > duckdb::CompressedMaterialization::GetIntegralDecompress ( unique_ptr< Expression > input,
const LogicalType & result_type,
const BaseStatistics & stats )
private
306492 {
306493 D_ASSERT(!stats.CanHaveNoNull() || NumericStats::HasMinMax(stats));
306494 auto decompress_function = CMIntegralDecompressFun::GetFunction(input->return_type, result_type);
306495 const auto min = !stats.CanHaveNoNull() ? Value(result_type) : NumericStats::Min(stats);
306496
306497 vector<unique_ptr<Expression>> arguments;
306498 arguments.emplace_back(std::move(input));
306499 arguments.emplace_back(make_uniq<BoundConstantExpression>(min));
306500 return make_uniq<BoundFunctionExpression>(result_type, decompress_function, std::move(arguments), nullptr);
306501}

◆ GetStringDecompress()

unique_ptr< Expression > duckdb::CompressedMaterialization::GetStringDecompress ( unique_ptr< Expression > input,
const LogicalType & result_type,
const BaseStatistics & stats )
private
306505 {
306506 D_ASSERT(!stats.CanHaveNoNull() || StringStats::HasMaxStringLength(stats));
306507 auto decompress_function = CMStringDecompressFun::GetFunction(input->return_type);
306508 vector<unique_ptr<Expression>> arguments;
306509 arguments.emplace_back(std::move(input));
306510 return make_uniq<BoundFunctionExpression>(result_type, decompress_function, std::move(arguments), nullptr);
306511}

Member Data Documentation

◆ JOIN_BUILD_CARDINALITY_THRESHOLD

idx_t duckdb::CompressedMaterialization::JOIN_BUILD_CARDINALITY_THRESHOLD = 1048576
staticconstexprprivate

Somewhat defensive constants that try to limit when compressed materialization is triggered for joins We only consider compressed materialization for joins when the build cardinality is greater than this


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