OmniSciDB  a987f07e93
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
JoinFilterPushDown.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2022 HEAVY.AI, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "JoinFilterPushDown.h"
18 #include "DeepCopyVisitor.h"
19 #include "RelAlgExecutor.h"
20 
21 namespace {
22 
24  std::shared_ptr<Analyzer::Expr> visitColumnVar(
25  const Analyzer::ColumnVar* col_var) const override {
26  return makeExpr<Analyzer::ColumnVar>(
27  col_var->get_type_info(), col_var->get_table_id(), col_var->get_column_id(), 0);
28  }
29 };
30 
32  : public ScalarExprVisitor<std::unordered_set<InputColDescriptor>> {
33  std::unordered_set<InputColDescriptor> visitColumnVar(
34  const Analyzer::ColumnVar* col_var) const override {
35  return {InputColDescriptor(col_var->get_column_id(), col_var->get_table_id(), 0)};
36  }
37 
38  public:
39  std::unordered_set<InputColDescriptor> aggregateResult(
40  const std::unordered_set<InputColDescriptor>& aggregate,
41  const std::unordered_set<InputColDescriptor>& next_result) const override {
42  auto result = aggregate;
43  result.insert(next_result.begin(), next_result.end());
44  return result;
45  }
46 };
47 
48 } // namespace
49 
58  const std::vector<std::shared_ptr<Analyzer::Expr>>& filter_expressions,
59  const CompilationOptions& co,
60  const ExecutionOptions& eo) {
61  CollectInputColumnsVisitor input_columns_visitor;
62  std::list<std::shared_ptr<Analyzer::Expr>> quals;
63  std::unordered_set<InputColDescriptor> input_column_descriptors;
64  BindFilterToOutermostVisitor bind_filter_to_outermost;
65  for (const auto& filter_expr : filter_expressions) {
66  input_column_descriptors = input_columns_visitor.aggregateResult(
67  input_column_descriptors, input_columns_visitor.visit(filter_expr.get()));
68  quals.push_back(bind_filter_to_outermost.visit(filter_expr.get()));
69  }
70  std::vector<InputDescriptor> input_descs;
71  std::list<std::shared_ptr<const InputColDescriptor>> input_col_descs;
72  for (const auto& input_col_desc : input_column_descriptors) {
73  if (input_descs.empty()) {
74  input_descs.push_back(input_col_desc.getScanDesc());
75  } else {
76  CHECK(input_col_desc.getScanDesc() == input_descs.front());
77  }
78  input_col_descs.push_back(std::make_shared<const InputColDescriptor>(input_col_desc));
79  }
80  const auto count_expr =
81  makeExpr<Analyzer::AggExpr>(SQLTypeInfo(g_bigint_count ? kBIGINT : kINT, false),
82  kCOUNT,
83  nullptr,
84  false,
85  nullptr);
86  RelAlgExecutionUnit ra_exe_unit{input_descs,
87  input_col_descs,
88  {},
89  quals,
90  {},
91  {},
92  {count_expr.get()},
93  {},
94  nullptr,
95  {{}, SortAlgorithm::Default, 0, 0, false},
96  0};
97  size_t one{1};
98  ResultSetPtr filtered_result;
99  const auto table_infos = get_table_infos(input_descs, executor_);
100  CHECK_EQ(size_t(1), table_infos.size());
101  const size_t total_rows_upper_bound = table_infos.front().info.getNumTuplesUpperBound();
102  try {
103  ColumnCacheMap column_cache;
104  filtered_result = executor_->executeWorkUnit(
105  one, true, table_infos, ra_exe_unit, co, eo, cat_, nullptr, false, column_cache);
106  } catch (...) {
107  return {false, 1.0, 0};
108  }
109  const auto count_row = filtered_result->getNextRow(false, false);
110  CHECK_EQ(size_t(1), count_row.size());
111  const auto& count_tv = count_row.front();
112  const auto count_scalar_tv = boost::get<ScalarTargetValue>(&count_tv);
113  CHECK(count_scalar_tv);
114  const auto count_ptr = boost::get<int64_t>(count_scalar_tv);
115  CHECK(count_ptr);
116  const auto rows_passing = *count_ptr;
117  const auto rows_total = std::max(total_rows_upper_bound, size_t(1));
118  return {true, static_cast<float>(rows_passing) / rows_total, total_rows_upper_bound};
119 }
120 
125 std::vector<PushedDownFilterInfo> RelAlgExecutor::selectFiltersToBePushedDown(
126  const RelAlgExecutor::WorkUnit& work_unit,
127  const CompilationOptions& co,
128  const ExecutionOptions& eo) {
129  const auto all_push_down_candidates =
131  work_unit.input_permutation,
132  work_unit.left_deep_join_input_sizes);
133  std::vector<PushedDownFilterInfo> selective_push_down_candidates;
134  const auto ti = get_table_infos(work_unit.exe_unit.input_descs, executor_);
136  for (const auto& candidate : all_push_down_candidates) {
137  const auto selectivity = getFilterSelectivity(candidate.filter_expressions, co, eo);
138  if (selectivity.is_valid && selectivity.isFilterSelectiveEnough()) {
139  selective_push_down_candidates.push_back(candidate);
140  }
141  }
142  }
143  return selective_push_down_candidates;
144 }
145 
147  const RaExecutionSequence& seq,
148  const CompilationOptions& co,
149  const ExecutionOptions& eo,
150  RenderInfo* render_info,
151  const int64_t queue_time_ms) {
152  // we currently do not fully support filter push down with
153  // multi-step execution and/or with subqueries
154  // TODO(Saman): add proper caching to enable filter push down for all cases
155  const auto& subqueries = getSubqueries();
156  if (seq.size() > 1 || !subqueries.empty()) {
157  if (eo.just_calcite_explain) {
158  return ExecutionResult(std::vector<PushedDownFilterInfo>{},
160  }
161  auto eo_modified = eo;
162  eo_modified.find_push_down_candidates = false;
163  eo_modified.just_calcite_explain = false;
164 
165  // Dispatch the subqueries first
166  for (auto subquery : subqueries) {
167  // Execute the subquery and cache the result.
168  RelAlgExecutor ra_executor(executor_, cat_);
169  const auto subquery_ra = subquery->getRelAlg();
170  CHECK(subquery_ra);
171  RaExecutionSequence subquery_seq(subquery_ra, executor_);
172  auto result =
173  ra_executor.executeRelAlgSeq(subquery_seq, co, eo_modified, nullptr, 0);
174  subquery->setExecutionResult(std::make_shared<ExecutionResult>(result));
175  }
176  return executeRelAlgSeq(seq, co, eo_modified, render_info, queue_time_ms);
177  }
178  // else
179  return executeRelAlgSeq(seq, co, eo, render_info, queue_time_ms);
180 }
187  const std::vector<InputTableInfo>& table_infos) {
188  if (table_infos.size() < 2) {
189  return false;
190  }
191  // we currently do not support filter push down when there is a self-join involved:
192  // TODO(Saman): prevent Calcite from optimizing self-joins to remove this exclusion
193  std::unordered_set<int> table_ids;
194  for (auto ti : table_infos) {
195  if (table_ids.find(ti.table_id) == table_ids.end()) {
196  table_ids.insert(ti.table_id);
197  } else {
198  // a self-join is involved
199  return false;
200  }
201  }
202  // TODO(Saman): add some extra heuristics to avoid preflight count and push down if it
203  // is not going to be helpful.
204  return true;
205 }
206 
213 std::vector<PushedDownFilterInfo> find_push_down_filters(
214  const RelAlgExecutionUnit& ra_exe_unit,
215  const std::vector<size_t>& input_permutation,
216  const std::vector<size_t>& left_deep_join_input_sizes) {
217  std::vector<PushedDownFilterInfo> result;
218  if (left_deep_join_input_sizes.empty()) {
219  return result;
220  }
221  std::vector<size_t> input_size_prefix_sums(left_deep_join_input_sizes.size());
222  std::partial_sum(left_deep_join_input_sizes.begin(),
223  left_deep_join_input_sizes.end(),
224  input_size_prefix_sums.begin());
225  std::vector<int> to_original_rte_idx(ra_exe_unit.input_descs.size(),
226  ra_exe_unit.input_descs.size());
227  if (!input_permutation.empty()) {
228  CHECK_EQ(to_original_rte_idx.size(), input_permutation.size());
229  for (size_t i = 0; i < input_permutation.size(); ++i) {
230  CHECK_LT(input_permutation[i], to_original_rte_idx.size());
231  CHECK_EQ(static_cast<size_t>(to_original_rte_idx[input_permutation[i]]),
232  to_original_rte_idx.size());
233  to_original_rte_idx[input_permutation[i]] = i;
234  }
235  } else {
236  std::iota(to_original_rte_idx.begin(), to_original_rte_idx.end(), 0);
237  }
238  std::unordered_map<int, std::vector<std::shared_ptr<Analyzer::Expr>>>
239  filters_per_nesting_level;
240  for (const auto& level_conditions : ra_exe_unit.join_quals) {
242  for (const auto& cond : level_conditions.quals) {
243  const auto rte_indices = visitor.visit(cond.get());
244  if (rte_indices.size() > 1) {
245  continue;
246  }
247  const int rte_idx = (!rte_indices.empty()) ? *rte_indices.cbegin() : 0;
248  if (!rte_idx) {
249  continue;
250  }
251  CHECK_GE(rte_idx, 0);
252  CHECK_LT(static_cast<size_t>(rte_idx), to_original_rte_idx.size());
253  filters_per_nesting_level[to_original_rte_idx[rte_idx]].push_back(cond);
254  }
255  }
256  for (const auto& kv : filters_per_nesting_level) {
257  CHECK_GE(kv.first, 0);
258  CHECK_LT(static_cast<size_t>(kv.first), input_size_prefix_sums.size());
259  size_t input_prev = (kv.first > 1) ? input_size_prefix_sums[kv.first - 2] : 0;
260  size_t input_start = kv.first ? input_size_prefix_sums[kv.first - 1] : 0;
261  size_t input_next = input_size_prefix_sums[kv.first];
262  result.emplace_back(
263  PushedDownFilterInfo{kv.second, input_prev, input_start, input_next});
264  }
265  return result;
266 }
int get_table_id() const
Definition: Analyzer.h:202
#define CHECK_EQ(x, y)
Definition: Logger.h:297
const std::vector< size_t > left_deep_join_input_sizes
ExecutionResult executeRelAlgSeq(const RaExecutionSequence &seq, const CompilationOptions &co, const ExecutionOptions &eo, RenderInfo *render_info, const int64_t queue_time_ms, const bool with_existing_temp_tables=false)
RelAlgExecutionUnit exe_unit
ExecutionResult executeRelAlgQueryWithFilterPushDown(const RaExecutionSequence &seq, const CompilationOptions &co, const ExecutionOptions &eo, RenderInfo *render_info, const int64_t queue_time_ms)
FilterSelectivity getFilterSelectivity(const std::vector< std::shared_ptr< Analyzer::Expr >> &filter_expressions, const CompilationOptions &co, const ExecutionOptions &eo)
std::vector< InputDescriptor > input_descs
#define CHECK_GE(x, y)
Definition: Logger.h:302
std::vector< PushedDownFilterInfo > selectFiltersToBePushedDown(const RelAlgExecutor::WorkUnit &work_unit, const CompilationOptions &co, const ExecutionOptions &eo)
std::shared_ptr< ResultSet > ResultSetPtr
T visit(const Analyzer::Expr *expr) const
const std::vector< std::shared_ptr< RexSubQuery > > & getSubqueries() const noexcept
std::unordered_set< InputColDescriptor > aggregateResult(const std::unordered_set< InputColDescriptor > &aggregate, const std::unordered_set< InputColDescriptor > &next_result) const override
bool to_gather_info_for_filter_selectivity(const std::vector< InputTableInfo > &table_infos)
const JoinQualsPerNestingLevel join_quals
A container for relational algebra descriptors defining the execution order for a relational algebra ...
DEVICE void partial_sum(ARGS &&...args)
Definition: gpu_enabled.h:87
std::vector< PushedDownFilterInfo > find_push_down_filters(const RelAlgExecutionUnit &ra_exe_unit, const std::vector< size_t > &input_permutation, const std::vector< size_t > &left_deep_join_input_sizes)
bool g_bigint_count
const std::vector< size_t > input_permutation
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:83
std::unordered_map< int, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
#define CHECK_LT(x, y)
Definition: Logger.h:299
std::shared_ptr< Analyzer::Expr > visitColumnVar(const Analyzer::ColumnVar *col_var) const override
DEVICE void iota(ARGS &&...args)
Definition: gpu_enabled.h:69
Definition: sqldefs.h:78
Catalog_Namespace::Catalog & cat_
std::unordered_set< InputColDescriptor > visitColumnVar(const Analyzer::ColumnVar *col_var) const override
#define CHECK(condition)
Definition: Logger.h:289
std::vector< InputTableInfo > get_table_infos(const std::vector< InputDescriptor > &input_descs, Executor *executor)
Definition: sqltypes.h:60
int get_column_id() const
Definition: Analyzer.h:203
Executor * executor_