Github user zuyu commented on a diff in the pull request:

    https://github.com/apache/incubator-quickstep/pull/237#discussion_r112848427
  
    --- Diff: query_optimizer/rules/ReuseAggregateExpressions.cpp ---
    @@ -0,0 +1,349 @@
    +/**
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *   http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + **/
    +
    +#include "query_optimizer/rules/ReuseAggregateExpressions.hpp"
    +
    +#include <cstddef>
    +#include <list>
    +#include <map>
    +#include <memory>
    +#include <unordered_map>
    +#include <vector>
    +
    +#include "expressions/aggregation/AggregateFunction.hpp"
    +#include "expressions/aggregation/AggregateFunctionFactory.hpp"
    +#include "expressions/aggregation/AggregationID.hpp"
    +#include "query_optimizer/OptimizerContext.hpp"
    +#include "query_optimizer/expressions/AggregateFunction.hpp"
    +#include "query_optimizer/expressions/Alias.hpp"
    +#include "query_optimizer/expressions/AttributeReference.hpp"
    +#include "query_optimizer/expressions/BinaryExpression.hpp"
    +#include "query_optimizer/expressions/ExpressionType.hpp"
    +#include "query_optimizer/expressions/ExpressionUtil.hpp"
    +#include "query_optimizer/expressions/NamedExpression.hpp"
    +#include "query_optimizer/expressions/Scalar.hpp"
    +#include "query_optimizer/physical/Aggregate.hpp"
    +#include "query_optimizer/physical/PatternMatcher.hpp"
    +#include "query_optimizer/physical/Physical.hpp"
    +#include "query_optimizer/physical/PhysicalType.hpp"
    +#include "query_optimizer/physical/Selection.hpp"
    +#include "query_optimizer/physical/TopLevelPlan.hpp"
    +#include "types/operations/binary_operations/BinaryOperation.hpp"
    +#include "types/operations/binary_operations/BinaryOperationFactory.hpp"
    +#include "types/operations/binary_operations/BinaryOperationID.hpp"
    +#include "utility/HashError.hpp"
    +
    +#include "gflags/gflags.h"
    +
    +#include "glog/logging.h"
    +
    +namespace quickstep {
    +namespace optimizer {
    +
    +DEFINE_uint64(reuse_aggregate_group_size_threshold, 1000u,
    +              "The threshold on estimated number of groups for an 
aggregation "
    +              "below which the ReuseAggregateExpressions optimization will 
be "
    +              "performed.");
    +
    +DEFINE_double(reuse_aggregate_ratio_threshold, 0.3,
    +              "The threshold on the ratio of (# of eliminable columns) to "
    +              "(# of original columns) for an aggregation above which the "
    +              "ReuseAggregateExpressions optimization will be performed.");
    +
    +namespace E = ::quickstep::optimizer::expressions;
    +namespace P = ::quickstep::optimizer::physical;
    +
    +void ReuseAggregateExpressions::init(const P::PhysicalPtr &input) {
    +  DCHECK(input->getPhysicalType() == P::PhysicalType::kTopLevelPlan);
    +
    +  // Initialize cost model.
    +  const P::TopLevelPlanPtr top_level_plan =
    +     std::static_pointer_cast<const P::TopLevelPlan>(input);
    +  cost_model_.reset(
    +      new 
cost::StarSchemaSimpleCostModel(top_level_plan->shared_subplans()));
    +}
    +
    +P::PhysicalPtr ReuseAggregateExpressions::applyToNode(
    +    const P::PhysicalPtr &input) {
    +  P::AggregatePtr aggregate;
    +  if (!P::SomeAggregate::MatchesWithConditionalCast(input, &aggregate)) {
    +    return input;
    +  }
    +
    +  const std::vector<E::AliasPtr> &agg_exprs = 
aggregate->aggregate_expressions();
    +
    +  // Maps aggregated expressions to AggregationID + positions.
    +  //
    +  // For example,
    +  // --
    +  //   SELECT SUM(x+1), AVG(x+1), SUM(x+1), COUNT(*), SUM(y) FROM s;
    +  // --
    +  // will generate *agg_expr_info* as
    +  // --
    +  // {
    +  //   x+1: { kSum: [0, 2], kAvg: [1] },
    +  //   y: { kSum: [4] },
    +  // }
    +  // --
    +  // and COUNT(*) will be recorded inside *count_star_info*.
    +  std::unordered_map<E::ScalarPtr,
    +                     std::map<AggregationID, std::vector<std::size_t>>,
    +                     ScalarHash, ScalarEqual> agg_expr_info;
    +  std::list<std::size_t> count_star_info;
    +
    +  for (std::size_t i = 0; i < agg_exprs.size(); ++i) {
    +    DCHECK(agg_exprs[i]->expression()->getExpressionType()
    +               == E::ExpressionType::kAggregateFunction);
    +    const E::AggregateFunctionPtr agg_expr =
    +        std::static_pointer_cast<const E::AggregateFunction>(
    +            agg_exprs[i]->expression());
    +
    +    // Skip DISTINCT aggregations.
    +    if (agg_expr->is_distinct()) {
    +      continue;
    +    }
    +
    +    const AggregationID agg_id = 
agg_expr->getAggregate().getAggregationID();
    +    const std::vector<E::ScalarPtr> &arguments = agg_expr->getArguments();
    +
    +    // Currently we only consider aggregate functions with 0 or 1 argument.
    +    if (agg_id == AggregationID::kCount) {
    +      if (arguments.empty()) {
    +        count_star_info.emplace_front(i);
    +        continue;
    +      } else if (!arguments.front()->getValueType().isNullable()) {
    +        // For COUNT(x) where x is not null, we view it as a more general 
COUNT(*).
    +        count_star_info.emplace_back(i);
    +        continue;
    +      }
    +    }
    +    if (arguments.size() == 1) {
    +      try {
    +        agg_expr_info[arguments.front()][agg_id].emplace_back(i);
    +      } catch (const HashNotSupported &e) {
    +        continue;
    +      }
    +    }
    +  }
    +
    +  // Now for each aggregate expression, figure out whether we can avoid the
    +  // computation by reusing other aggregate expression's result.
    +  std::vector<std::unique_ptr<AggregateReference>> 
agg_refs(agg_exprs.size());
    +
    +  constexpr std::size_t kInvalidRef = static_cast<std::size_t>(-1);
    +  std::size_t count_star_ref;
    +
    +  // Check whether COUNT(*) is available.
    +  if (count_star_info.empty()) {
    +    count_star_ref = kInvalidRef;
    +  } else {
    +    auto it = count_star_info.begin();
    +    count_star_ref = *it;
    +
    +    for (++it; it != count_star_info.end(); ++it) {
    +      agg_refs[*it].reset(new AggregateReference(count_star_ref));
    --- End diff --
    
    We should not use `new` operations for smart pointers to avoid memory leaks 
upon system failures.
    
    Instead, we could use `agg_refs[*it] = 
std::make_unique<AggregateReference>(count_star_ref);`.
    
    Ditto for all `new` usages below.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

Reply via email to