OmniSciDB  c0231cc57d
 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  const ExecutionOptions eo_modified{eo.output_columnar_hint,
162  eo.keep_result,
163  eo.allow_multifrag,
164  eo.just_explain,
165  eo.allow_loop_joins,
166  eo.with_watchdog,
167  eo.jit_debug,
168  eo.just_validate,
171  /*find_push_down_candidates=*/false,
172  /*just_calcite_explain=*/false,
177 
178  // Dispatch the subqueries first
179  for (auto subquery : subqueries) {
180  // Execute the subquery and cache the result.
181  RelAlgExecutor ra_executor(executor_, cat_);
182  const auto subquery_ra = subquery->getRelAlg();
183  CHECK(subquery_ra);
184  RaExecutionSequence subquery_seq(subquery_ra, executor_);
185  auto result =
186  ra_executor.executeRelAlgSeq(subquery_seq, co, eo_modified, nullptr, 0);
187  subquery->setExecutionResult(std::make_shared<ExecutionResult>(result));
188  }
189  return executeRelAlgSeq(seq, co, eo_modified, render_info, queue_time_ms);
190  }
191  // else
192  return executeRelAlgSeq(seq, co, eo, render_info, queue_time_ms);
193 }
200  const std::vector<InputTableInfo>& table_infos) {
201  if (table_infos.size() < 2) {
202  return false;
203  }
204  // we currently do not support filter push down when there is a self-join involved:
205  // TODO(Saman): prevent Calcite from optimizing self-joins to remove this exclusion
206  std::unordered_set<int> table_ids;
207  for (auto ti : table_infos) {
208  if (table_ids.find(ti.table_id) == table_ids.end()) {
209  table_ids.insert(ti.table_id);
210  } else {
211  // a self-join is involved
212  return false;
213  }
214  }
215  // TODO(Saman): add some extra heuristics to avoid preflight count and push down if it
216  // is not going to be helpful.
217  return true;
218 }
219 
226 std::vector<PushedDownFilterInfo> find_push_down_filters(
227  const RelAlgExecutionUnit& ra_exe_unit,
228  const std::vector<size_t>& input_permutation,
229  const std::vector<size_t>& left_deep_join_input_sizes) {
230  std::vector<PushedDownFilterInfo> result;
231  if (left_deep_join_input_sizes.empty()) {
232  return result;
233  }
234  std::vector<size_t> input_size_prefix_sums(left_deep_join_input_sizes.size());
235  std::partial_sum(left_deep_join_input_sizes.begin(),
236  left_deep_join_input_sizes.end(),
237  input_size_prefix_sums.begin());
238  std::vector<int> to_original_rte_idx(ra_exe_unit.input_descs.size(),
239  ra_exe_unit.input_descs.size());
240  if (!input_permutation.empty()) {
241  CHECK_EQ(to_original_rte_idx.size(), input_permutation.size());
242  for (size_t i = 0; i < input_permutation.size(); ++i) {
243  CHECK_LT(input_permutation[i], to_original_rte_idx.size());
244  CHECK_EQ(static_cast<size_t>(to_original_rte_idx[input_permutation[i]]),
245  to_original_rte_idx.size());
246  to_original_rte_idx[input_permutation[i]] = i;
247  }
248  } else {
249  std::iota(to_original_rte_idx.begin(), to_original_rte_idx.end(), 0);
250  }
251  std::unordered_map<int, std::vector<std::shared_ptr<Analyzer::Expr>>>
252  filters_per_nesting_level;
253  for (const auto& level_conditions : ra_exe_unit.join_quals) {
255  for (const auto& cond : level_conditions.quals) {
256  const auto rte_indices = visitor.visit(cond.get());
257  if (rte_indices.size() > 1) {
258  continue;
259  }
260  const int rte_idx = (!rte_indices.empty()) ? *rte_indices.cbegin() : 0;
261  if (!rte_idx) {
262  continue;
263  }
264  CHECK_GE(rte_idx, 0);
265  CHECK_LT(static_cast<size_t>(rte_idx), to_original_rte_idx.size());
266  filters_per_nesting_level[to_original_rte_idx[rte_idx]].push_back(cond);
267  }
268  }
269  for (const auto& kv : filters_per_nesting_level) {
270  CHECK_GE(kv.first, 0);
271  CHECK_LT(static_cast<size_t>(kv.first), input_size_prefix_sums.size());
272  size_t input_prev = (kv.first > 1) ? input_size_prefix_sums[kv.first - 2] : 0;
273  size_t input_start = kv.first ? input_size_prefix_sums[kv.first - 1] : 0;
274  size_t input_next = input_size_prefix_sums[kv.first];
275  result.emplace_back(
276  PushedDownFilterInfo{kv.second, input_prev, input_start, input_next});
277  }
278  return result;
279 }
int get_table_id() const
Definition: Analyzer.h:201
#define CHECK_EQ(x, y)
Definition: Logger.h:230
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:235
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
double running_query_interrupt_freq
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
unsigned pending_query_interrupt_freq
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:82
std::unordered_map< int, std::unordered_map< int, std::shared_ptr< const ColumnarResults >>> ColumnCacheMap
#define CHECK_LT(x, y)
Definition: Logger.h:232
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:77
Catalog_Namespace::Catalog & cat_
std::unordered_set< InputColDescriptor > visitColumnVar(const Analyzer::ColumnVar *col_var) const override
#define CHECK(condition)
Definition: Logger.h:222
std::vector< InputTableInfo > get_table_infos(const std::vector< InputDescriptor > &input_descs, Executor *executor)
double gpu_input_mem_limit_percent
Definition: sqltypes.h:59
unsigned dynamic_watchdog_time_limit
int get_column_id() const
Definition: Analyzer.h:202
Executor * executor_