OmniSciDB  1dac507f6e
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
ExpressionRewrite.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017 MapD Technologies, 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 "ExpressionRewrite.h"
18 #include "../Analyzer/Analyzer.h"
19 #include "../Parser/ParserNode.h"
20 #include "../Shared/sqldefs.h"
21 #include "DeepCopyVisitor.h"
22 #include "Execute.h"
23 #include "RelAlgTranslator.h"
24 #include "ScalarExprVisitor.h"
25 #include "Shared/Logger.h"
27 
28 #include <boost/locale/conversion.hpp>
29 #include <unordered_set>
30 
31 namespace {
32 
33 class OrToInVisitor : public ScalarExprVisitor<std::shared_ptr<Analyzer::InValues>> {
34  protected:
35  std::shared_ptr<Analyzer::InValues> visitBinOper(
36  const Analyzer::BinOper* bin_oper) const override {
37  switch (bin_oper->get_optype()) {
38  case kEQ: {
39  const auto rhs_owned = bin_oper->get_own_right_operand();
40  auto rhs_no_cast = extract_cast_arg(rhs_owned.get());
41  if (!dynamic_cast<const Analyzer::Constant*>(rhs_no_cast)) {
42  return nullptr;
43  }
44  const auto arg = bin_oper->get_own_left_operand();
45  const auto& arg_ti = arg->get_type_info();
46  auto rhs = rhs_no_cast->deep_copy()->add_cast(arg_ti);
47  return makeExpr<Analyzer::InValues>(
48  arg, std::list<std::shared_ptr<Analyzer::Expr>>{rhs});
49  }
50  case kOR: {
51  return aggregateResult(visit(bin_oper->get_left_operand()),
52  visit(bin_oper->get_right_operand()));
53  }
54  default:
55  break;
56  }
57  return nullptr;
58  }
59 
60  std::shared_ptr<Analyzer::InValues> visitUOper(
61  const Analyzer::UOper* uoper) const override {
62  return nullptr;
63  }
64 
65  std::shared_ptr<Analyzer::InValues> visitInValues(
66  const Analyzer::InValues*) const override {
67  return nullptr;
68  }
69 
70  std::shared_ptr<Analyzer::InValues> visitInIntegerSet(
71  const Analyzer::InIntegerSet*) const override {
72  return nullptr;
73  }
74 
75  std::shared_ptr<Analyzer::InValues> visitCharLength(
76  const Analyzer::CharLengthExpr*) const override {
77  return nullptr;
78  }
79 
80  std::shared_ptr<Analyzer::InValues> visitKeyForString(
81  const Analyzer::KeyForStringExpr*) const override {
82  return nullptr;
83  }
84 
85  std::shared_ptr<Analyzer::InValues> visitCardinality(
86  const Analyzer::CardinalityExpr*) const override {
87  return nullptr;
88  }
89 
90  std::shared_ptr<Analyzer::InValues> visitLikeExpr(
91  const Analyzer::LikeExpr*) const override {
92  return nullptr;
93  }
94 
95  std::shared_ptr<Analyzer::InValues> visitRegexpExpr(
96  const Analyzer::RegexpExpr*) const override {
97  return nullptr;
98  }
99 
100  std::shared_ptr<Analyzer::InValues> visitCaseExpr(
101  const Analyzer::CaseExpr*) const override {
102  return nullptr;
103  }
104 
105  std::shared_ptr<Analyzer::InValues> visitDatetruncExpr(
106  const Analyzer::DatetruncExpr*) const override {
107  return nullptr;
108  }
109 
110  std::shared_ptr<Analyzer::InValues> visitDatediffExpr(
111  const Analyzer::DatediffExpr*) const override {
112  return nullptr;
113  }
114 
115  std::shared_ptr<Analyzer::InValues> visitDateaddExpr(
116  const Analyzer::DateaddExpr*) const override {
117  return nullptr;
118  }
119 
120  std::shared_ptr<Analyzer::InValues> visitExtractExpr(
121  const Analyzer::ExtractExpr*) const override {
122  return nullptr;
123  }
124 
125  std::shared_ptr<Analyzer::InValues> visitLikelihood(
126  const Analyzer::LikelihoodExpr*) const override {
127  return nullptr;
128  }
129 
130  std::shared_ptr<Analyzer::InValues> visitAggExpr(
131  const Analyzer::AggExpr*) const override {
132  return nullptr;
133  }
134 
135  std::shared_ptr<Analyzer::InValues> aggregateResult(
136  const std::shared_ptr<Analyzer::InValues>& lhs,
137  const std::shared_ptr<Analyzer::InValues>& rhs) const override {
138  if (!lhs || !rhs) {
139  return nullptr;
140  }
141  if (!(*lhs->get_arg() == *rhs->get_arg())) {
142  return nullptr;
143  }
144  auto union_values = lhs->get_value_list();
145  const auto& rhs_values = rhs->get_value_list();
146  union_values.insert(union_values.end(), rhs_values.begin(), rhs_values.end());
147  return makeExpr<Analyzer::InValues>(lhs->get_own_arg(), union_values);
148  }
149 };
150 
152  protected:
153  std::shared_ptr<Analyzer::Expr> visitBinOper(
154  const Analyzer::BinOper* bin_oper) const override {
155  OrToInVisitor simple_visitor;
156  if (bin_oper->get_optype() == kOR) {
157  auto rewritten = simple_visitor.visit(bin_oper);
158  if (rewritten) {
159  return rewritten;
160  }
161  }
162  auto lhs = bin_oper->get_own_left_operand();
163  auto rhs = bin_oper->get_own_right_operand();
164  auto rewritten_lhs = visit(lhs.get());
165  auto rewritten_rhs = visit(rhs.get());
166  return makeExpr<Analyzer::BinOper>(bin_oper->get_type_info(),
167  bin_oper->get_contains_agg(),
168  bin_oper->get_optype(),
169  bin_oper->get_qualifier(),
170  rewritten_lhs ? rewritten_lhs : lhs,
171  rewritten_rhs ? rewritten_rhs : rhs);
172  }
173 };
174 
176  protected:
178 
179  RetType visitArrayOper(const Analyzer::ArrayExpr* array_expr) const override {
180  std::vector<std::shared_ptr<Analyzer::Expr>> args_copy;
181  for (size_t i = 0; i < array_expr->getElementCount(); ++i) {
182  auto const element_expr_ptr = visit(array_expr->getElement(i));
183  auto const& element_expr_type_info = element_expr_ptr->get_type_info();
184 
185  if (!element_expr_type_info.is_string() ||
186  element_expr_type_info.get_compression() != kENCODING_NONE) {
187  args_copy.push_back(element_expr_ptr);
188  } else {
189  auto transient_dict_type_info = element_expr_type_info;
190 
191  transient_dict_type_info.set_compression(kENCODING_DICT);
192  transient_dict_type_info.set_comp_param(TRANSIENT_DICT_ID);
193  transient_dict_type_info.set_fixed_size();
194  args_copy.push_back(element_expr_ptr->add_cast(transient_dict_type_info));
195  }
196  }
197 
198  const auto& type_info = array_expr->get_type_info();
199  return makeExpr<Analyzer::ArrayExpr>(
200  type_info, args_copy, array_expr->getExprIndex(), array_expr->isLocalAlloc());
201  }
202 };
203 
205  template <typename T>
206  bool foldComparison(SQLOps optype, T t1, T t2) const {
207  switch (optype) {
208  case kEQ:
209  return t1 == t2;
210  case kNE:
211  return t1 != t2;
212  case kLT:
213  return t1 < t2;
214  case kLE:
215  return t1 <= t2;
216  case kGT:
217  return t1 > t2;
218  case kGE:
219  return t1 >= t2;
220  default:
221  break;
222  }
223  throw std::runtime_error("Unable to fold");
224  return false;
225  }
226 
227  template <typename T>
228  bool foldLogic(SQLOps optype, T t1, T t2) const {
229  switch (optype) {
230  case kAND:
231  return t1 && t2;
232  case kOR:
233  return t1 || t2;
234  case kNOT:
235  return !t1;
236  default:
237  break;
238  }
239  throw std::runtime_error("Unable to fold");
240  return false;
241  }
242 
243  template <typename T>
244  T foldArithmetic(SQLOps optype, T t1, T t2) const {
245  bool t2_is_zero = (t2 == (t2 - t2));
246  bool t2_is_negative = (t2 < (t2 - t2));
247  switch (optype) {
248  case kPLUS:
249  // The MIN limit for float and double is the smallest representable value,
250  // not the lowest negative value! Switching to C++11 lowest.
251  if ((t2_is_negative && t1 < std::numeric_limits<T>::lowest() - t2) ||
252  (!t2_is_negative && t1 > std::numeric_limits<T>::max() - t2)) {
253  num_overflows_++;
254  throw std::runtime_error("Plus overflow");
255  }
256  return t1 + t2;
257  case kMINUS:
258  if ((t2_is_negative && t1 > std::numeric_limits<T>::max() + t2) ||
259  (!t2_is_negative && t1 < std::numeric_limits<T>::lowest() + t2)) {
260  num_overflows_++;
261  throw std::runtime_error("Minus overflow");
262  }
263  return t1 - t2;
264  case kMULTIPLY: {
265  if (t2_is_zero) {
266  return t2;
267  }
268  auto ct1 = t1;
269  auto ct2 = t2;
270  // Need to keep t2's sign on the left
271  if (t2_is_negative) {
272  if (t1 == std::numeric_limits<T>::lowest() ||
273  t2 == std::numeric_limits<T>::lowest()) {
274  // negation could overflow - bail
275  num_overflows_++;
276  throw std::runtime_error("Mul neg overflow");
277  }
278  ct1 = -t1; // ct1 gets t2's negativity
279  ct2 = -t2; // ct2 is now positive
280  }
281  // Don't check overlow if we are folding FP mul by a fraction
282  bool ct2_is_fraction = (ct2 < (ct2 / ct2));
283  if (!ct2_is_fraction) {
284  if (ct1 > std::numeric_limits<T>::max() / ct2 ||
285  ct1 < std::numeric_limits<T>::lowest() / ct2) {
286  num_overflows_++;
287  throw std::runtime_error("Mul overflow");
288  }
289  }
290  return t1 * t2;
291  }
292  case kDIVIDE:
293  if (t2_is_zero) {
294  throw std::runtime_error("Will not fold division by zero");
295  }
296  return t1 / t2;
297  default:
298  break;
299  }
300  throw std::runtime_error("Unable to fold");
301  }
302 
303  bool foldOper(SQLOps optype,
304  SQLTypes type,
305  Datum lhs,
306  Datum rhs,
307  Datum& result,
308  SQLTypes& result_type) const {
309  result_type = type;
310 
311  try {
312  switch (type) {
313  case kBOOLEAN:
314  if (IS_COMPARISON(optype)) {
315  result.boolval = foldComparison<bool>(optype, lhs.boolval, rhs.boolval);
316  result_type = kBOOLEAN;
317  return true;
318  }
319  if (IS_LOGIC(optype)) {
320  result.boolval = foldLogic<bool>(optype, lhs.boolval, rhs.boolval);
321  result_type = kBOOLEAN;
322  return true;
323  }
324  CHECK(!IS_ARITHMETIC(optype));
325  break;
326  case kTINYINT:
327  if (IS_COMPARISON(optype)) {
328  result.boolval =
329  foldComparison<int8_t>(optype, lhs.tinyintval, rhs.tinyintval);
330  result_type = kBOOLEAN;
331  return true;
332  }
333  if (IS_ARITHMETIC(optype)) {
334  result.tinyintval =
335  foldArithmetic<int8_t>(optype, lhs.tinyintval, rhs.tinyintval);
336  result_type = kTINYINT;
337  return true;
338  }
339  CHECK(!IS_LOGIC(optype));
340  break;
341  case kSMALLINT:
342  if (IS_COMPARISON(optype)) {
343  result.boolval =
344  foldComparison<int16_t>(optype, lhs.smallintval, rhs.smallintval);
345  result_type = kBOOLEAN;
346  return true;
347  }
348  if (IS_ARITHMETIC(optype)) {
349  result.smallintval =
350  foldArithmetic<int16_t>(optype, lhs.smallintval, rhs.smallintval);
351  result_type = kSMALLINT;
352  return true;
353  }
354  CHECK(!IS_LOGIC(optype));
355  break;
356  case kINT:
357  if (IS_COMPARISON(optype)) {
358  result.boolval = foldComparison<int32_t>(optype, lhs.intval, rhs.intval);
359  result_type = kBOOLEAN;
360  return true;
361  }
362  if (IS_ARITHMETIC(optype)) {
363  result.intval = foldArithmetic<int32_t>(optype, lhs.intval, rhs.intval);
364  result_type = kINT;
365  return true;
366  }
367  CHECK(!IS_LOGIC(optype));
368  break;
369  case kBIGINT:
370  if (IS_COMPARISON(optype)) {
371  result.boolval =
372  foldComparison<int64_t>(optype, lhs.bigintval, rhs.bigintval);
373  result_type = kBOOLEAN;
374  return true;
375  }
376  if (IS_ARITHMETIC(optype)) {
377  result.bigintval =
378  foldArithmetic<int64_t>(optype, lhs.bigintval, rhs.bigintval);
379  result_type = kBIGINT;
380  return true;
381  }
382  CHECK(!IS_LOGIC(optype));
383  break;
384  case kFLOAT:
385  if (IS_COMPARISON(optype)) {
386  result.boolval = foldComparison<float>(optype, lhs.floatval, rhs.floatval);
387  result_type = kBOOLEAN;
388  return true;
389  }
390  if (IS_ARITHMETIC(optype)) {
391  result.floatval = foldArithmetic<float>(optype, lhs.floatval, rhs.floatval);
392  result_type = kFLOAT;
393  return true;
394  }
395  CHECK(!IS_LOGIC(optype));
396  break;
397  case kDOUBLE:
398  if (IS_COMPARISON(optype)) {
399  result.boolval = foldComparison<double>(optype, lhs.doubleval, rhs.doubleval);
400  result_type = kBOOLEAN;
401  return true;
402  }
403  if (IS_ARITHMETIC(optype)) {
404  result.doubleval =
405  foldArithmetic<double>(optype, lhs.doubleval, rhs.doubleval);
406  result_type = kDOUBLE;
407  return true;
408  }
409  CHECK(!IS_LOGIC(optype));
410  break;
411  default:
412  break;
413  }
414  } catch (...) {
415  return false;
416  }
417  return false;
418  }
419 
420  std::shared_ptr<Analyzer::Expr> visitUOper(
421  const Analyzer::UOper* uoper) const override {
422  const auto unvisited_operand = uoper->get_operand();
423  const auto optype = uoper->get_optype();
424  const auto& ti = uoper->get_type_info();
425  if (optype == kCAST) {
426  // Cache the cast type so it could be used in operand rewriting/folding
427  casts_.insert({unvisited_operand, ti});
428  }
429  const auto operand = visit(unvisited_operand);
430  const auto& operand_ti = operand->get_type_info();
431  const auto operand_type =
432  operand_ti.is_decimal() ? decimal_to_int_type(operand_ti) : operand_ti.get_type();
433  const auto const_operand =
434  std::dynamic_pointer_cast<const Analyzer::Constant>(operand);
435 
436  if (const_operand) {
437  const auto operand_datum = const_operand->get_constval();
438  Datum zero_datum = {};
439  Datum result_datum = {};
440  SQLTypes result_type;
441  switch (optype) {
442  case kNOT: {
443  if (foldOper(kEQ,
444  operand_type,
445  zero_datum,
446  operand_datum,
447  result_datum,
448  result_type)) {
449  CHECK_EQ(result_type, kBOOLEAN);
450  return makeExpr<Analyzer::Constant>(result_type, false, result_datum);
451  }
452  break;
453  }
454  case kUMINUS: {
455  if (foldOper(kMINUS,
456  operand_type,
457  zero_datum,
458  operand_datum,
459  result_datum,
460  result_type)) {
461  if (!operand_ti.is_decimal()) {
462  return makeExpr<Analyzer::Constant>(result_type, false, result_datum);
463  }
464  return makeExpr<Analyzer::Constant>(ti, false, result_datum);
465  }
466  break;
467  }
468  case kCAST: {
469  // Trying to fold number to number casts only
470  if (!ti.is_number() || !operand_ti.is_number()) {
471  break;
472  }
473  // Disallowing folding of FP to DECIMAL casts for now:
474  // allowing them would make this test pass:
475  // update dectest set d=cast( 1234.0 as float );
476  // which is expected to throw in Update.ImplicitCastToNumericTypes
477  // due to cast codegen currently not supporting these casts
478  if (ti.is_decimal() && operand_ti.is_fp()) {
479  break;
480  }
481  auto operand_copy = const_operand->deep_copy();
482  auto cast_operand = operand_copy->add_cast(ti);
483  auto const_cast_operand =
484  std::dynamic_pointer_cast<const Analyzer::Constant>(cast_operand);
485  if (const_cast_operand) {
486  auto const_cast_datum = const_cast_operand->get_constval();
487  return makeExpr<Analyzer::Constant>(ti, false, const_cast_datum);
488  }
489  }
490  default:
491  break;
492  }
493  }
494 
495  return makeExpr<Analyzer::UOper>(
496  uoper->get_type_info(), uoper->get_contains_agg(), optype, operand);
497  }
498 
499  std::shared_ptr<Analyzer::Expr> visitBinOper(
500  const Analyzer::BinOper* bin_oper) const override {
501  const auto optype = bin_oper->get_optype();
502  auto ti = bin_oper->get_type_info();
503  auto left_operand = bin_oper->get_own_left_operand();
504  auto right_operand = bin_oper->get_own_right_operand();
505 
506  // Check if bin_oper result is cast to a larger int or fp type
507  if (casts_.find(bin_oper) != casts_.end()) {
508  const auto cast_ti = casts_[bin_oper];
509  const auto& lhs_ti = bin_oper->get_left_operand()->get_type_info();
510  // Propagate cast down to the operands for folding
511  if ((cast_ti.is_integer() || cast_ti.is_fp()) && lhs_ti.is_integer() &&
512  cast_ti.get_size() > lhs_ti.get_size() &&
513  (optype == kMINUS || optype == kPLUS || optype == kMULTIPLY)) {
514  // Before folding, cast the operands to the bigger type to avoid overflows.
515  // Currently upcasting smaller integer types to larger integers or double.
516  left_operand = left_operand->deep_copy()->add_cast(cast_ti);
517  right_operand = right_operand->deep_copy()->add_cast(cast_ti);
518  ti = cast_ti;
519  }
520  }
521 
522  const auto lhs = visit(left_operand.get());
523  const auto rhs = visit(right_operand.get());
524 
525  auto const_lhs = std::dynamic_pointer_cast<Analyzer::Constant>(lhs);
526  auto const_rhs = std::dynamic_pointer_cast<Analyzer::Constant>(rhs);
527  const auto& lhs_ti = lhs->get_type_info();
528  const auto& rhs_ti = rhs->get_type_info();
529  auto lhs_type = lhs_ti.is_decimal() ? decimal_to_int_type(lhs_ti) : lhs_ti.get_type();
530  auto rhs_type = rhs_ti.is_decimal() ? decimal_to_int_type(rhs_ti) : rhs_ti.get_type();
531 
532  if (const_lhs && const_rhs && lhs_type == rhs_type) {
533  auto lhs_datum = const_lhs->get_constval();
534  auto rhs_datum = const_rhs->get_constval();
535  Datum result_datum = {};
536  SQLTypes result_type;
537  if (foldOper(optype, lhs_type, lhs_datum, rhs_datum, result_datum, result_type)) {
538  // Fold all ops that don't take in decimal operands, and also decimal comparisons
539  if (!lhs_ti.is_decimal() || IS_COMPARISON(optype)) {
540  return makeExpr<Analyzer::Constant>(result_type, false, result_datum);
541  }
542  // Decimal arithmetic has been done as kBIGINT. Selectively fold some decimal ops,
543  // using result_datum and BinOper expr typeinfo which was adjusted for these ops.
544  if (optype == kMINUS || optype == kPLUS || optype == kMULTIPLY) {
545  return makeExpr<Analyzer::Constant>(ti, false, result_datum);
546  }
547  }
548  }
549 
550  if (optype == kAND && lhs_type == rhs_type && lhs_type == kBOOLEAN) {
551  if (const_rhs && !const_rhs->get_is_null()) {
552  auto rhs_datum = const_rhs->get_constval();
553  if (rhs_datum.boolval == false) {
554  Datum d;
555  d.boolval = false;
556  // lhs && false --> false
557  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
558  }
559  // lhs && true --> lhs
560  return lhs;
561  }
562  if (const_lhs && !const_lhs->get_is_null()) {
563  auto lhs_datum = const_lhs->get_constval();
564  if (lhs_datum.boolval == false) {
565  Datum d;
566  d.boolval = false;
567  // false && rhs --> false
568  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
569  }
570  // true && rhs --> rhs
571  return rhs;
572  }
573  }
574  if (optype == kOR && lhs_type == rhs_type && lhs_type == kBOOLEAN) {
575  if (const_rhs && !const_rhs->get_is_null()) {
576  auto rhs_datum = const_rhs->get_constval();
577  if (rhs_datum.boolval == true) {
578  Datum d;
579  d.boolval = true;
580  // lhs || true --> true
581  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
582  }
583  // lhs || false --> lhs
584  return lhs;
585  }
586  if (const_lhs && !const_lhs->get_is_null()) {
587  auto lhs_datum = const_lhs->get_constval();
588  if (lhs_datum.boolval == true) {
589  Datum d;
590  d.boolval = true;
591  // true || rhs --> true
592  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
593  }
594  // false || rhs --> rhs
595  return rhs;
596  }
597  }
598  if (*lhs == *rhs) {
599  // Tautologies: v=v; v<=v; v>=v
600  if (optype == kEQ || optype == kLE || optype == kGE) {
601  Datum d;
602  d.boolval = true;
603  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
604  }
605  // Contradictions: v!=v; v<v; v>v
606  if (optype == kNE || optype == kLT || optype == kGT) {
607  Datum d;
608  d.boolval = false;
609  return makeExpr<Analyzer::Constant>(kBOOLEAN, false, d);
610  }
611  // v-v
612  if (optype == kMINUS) {
613  Datum d = {};
614  return makeExpr<Analyzer::Constant>(lhs_type, false, d);
615  }
616  }
617  // Convert fp division by a constant to multiplication by 1/constant
618  if (optype == kDIVIDE && const_rhs && rhs_ti.is_fp()) {
619  auto rhs_datum = const_rhs->get_constval();
620  std::shared_ptr<Analyzer::Expr> recip_rhs = nullptr;
621  if (rhs_ti.get_type() == kFLOAT) {
622  if (rhs_datum.floatval == 1.0) {
623  return lhs;
624  }
625  auto f = std::fabs(rhs_datum.floatval);
626  if (f > 1.0 || (f != 0.0 && 1.0 < f * std::numeric_limits<float>::max())) {
627  rhs_datum.floatval = 1.0 / rhs_datum.floatval;
628  recip_rhs = makeExpr<Analyzer::Constant>(rhs_type, false, rhs_datum);
629  }
630  } else if (rhs_ti.get_type() == kDOUBLE) {
631  if (rhs_datum.doubleval == 1.0) {
632  return lhs;
633  }
634  auto d = std::fabs(rhs_datum.doubleval);
635  if (d > 1.0 || (d != 0.0 && 1.0 < d * std::numeric_limits<double>::max())) {
636  rhs_datum.doubleval = 1.0 / rhs_datum.doubleval;
637  recip_rhs = makeExpr<Analyzer::Constant>(rhs_type, false, rhs_datum);
638  }
639  }
640  if (recip_rhs) {
641  return makeExpr<Analyzer::BinOper>(ti,
642  bin_oper->get_contains_agg(),
643  kMULTIPLY,
644  bin_oper->get_qualifier(),
645  lhs,
646  recip_rhs);
647  }
648  }
649 
650  return makeExpr<Analyzer::BinOper>(ti,
651  bin_oper->get_contains_agg(),
652  bin_oper->get_optype(),
653  bin_oper->get_qualifier(),
654  lhs,
655  rhs);
656  }
657 
658  std::shared_ptr<Analyzer::Expr> visitLower(
659  const Analyzer::LowerExpr* lower_expr) const override {
660  const auto constant_arg_expr =
661  dynamic_cast<const Analyzer::Constant*>(lower_expr->get_arg());
662  if (constant_arg_expr) {
664  boost::locale::to_lower(*constant_arg_expr->get_constval().stringval));
665  }
666  return makeExpr<Analyzer::LowerExpr>(lower_expr->get_own_arg());
667  }
668 
669  protected:
670  mutable std::unordered_map<const Analyzer::Expr*, const SQLTypeInfo> casts_;
671  mutable int32_t num_overflows_;
672 
673  public:
674  ConstantFoldingVisitor() : num_overflows_(0) {}
675  int32_t get_num_overflows() { return num_overflows_; }
676  void reset_num_overflows() { num_overflows_ = 0; }
677 };
678 
680  const auto with_likelihood = dynamic_cast<const Analyzer::LikelihoodExpr*>(expr);
681  if (!with_likelihood) {
682  return expr;
683  }
684  return with_likelihood->get_arg();
685 }
686 
687 } // namespace
688 
690  return ArrayElementStringLiteralEncodingVisitor().visit(expr);
691 }
692 
694  const auto sum_window = rewrite_sum_window(expr);
695  if (sum_window) {
696  return sum_window;
697  }
698  const auto avg_window = rewrite_avg_window(expr);
699  if (avg_window) {
700  return avg_window;
701  }
702  const auto expr_no_likelihood = strip_likelihood(expr);
703  // The following check is not strictly needed, but seems silly to transform a
704  // simple string comparison to an IN just to codegen the same thing anyway.
705 
706  RecursiveOrToInVisitor visitor;
707  auto rewritten_expr = visitor.visit(expr_no_likelihood);
708  const auto expr_with_likelihood =
709  std::dynamic_pointer_cast<const Analyzer::LikelihoodExpr>(rewritten_expr);
710  if (expr_with_likelihood) {
711  // Add back likelihood
712  return std::make_shared<Analyzer::LikelihoodExpr>(
713  rewritten_expr, expr_with_likelihood->get_likelihood());
714  }
715  return rewritten_expr;
716 }
717 
718 namespace {
719 
720 static const std::unordered_set<std::string> overlaps_supported_functions = {
721  "ST_Contains_MultiPolygon_Point",
722  "ST_Contains_Polygon_Point"};
723 
724 } // namespace
725 
726 boost::optional<OverlapsJoinConjunction> rewrite_overlaps_conjunction(
727  const std::shared_ptr<Analyzer::Expr> expr) {
728  auto func_oper = dynamic_cast<Analyzer::FunctionOper*>(expr.get());
729  if (func_oper) {
730  // TODO(adb): consider converting unordered set to an unordered map, potentially
731  // storing the rewrite function we want to apply in the map
732  if (overlaps_supported_functions.find(func_oper->getName()) !=
734  CHECK_GE(func_oper->getArity(), size_t(3));
735 
736  DeepCopyVisitor deep_copy_visitor;
737  auto lhs = func_oper->getOwnArg(2);
738  auto rewritten_lhs = deep_copy_visitor.visit(lhs.get());
739  CHECK(rewritten_lhs);
740  const auto& lhs_ti = rewritten_lhs->get_type_info();
741  if (!lhs_ti.is_geometry()) {
742  // TODO(adb): If ST_Contains is passed geospatial literals instead of columns, the
743  // function will be expanded during translation rather than during code
744  // generation. While this scenario does not make sense for the overlaps join, we
745  // need to detect and abort the overlaps rewrite. Adding a GeospatialConstant
746  // dervied class to the Analyzer may prove to be a better way to handle geo
747  // literals, but for now we ensure the LHS type is a geospatial type, which would
748  // mean the function has not been expanded to the physical types, yet.
749  LOG(WARNING) << "Failed to rewrite " << func_oper->getName()
750  << " to overlaps conjunction. LHS input type is not a geospatial "
751  "type. Are both inputs geospatial columns?";
752  return boost::none;
753  }
754 
755  // Read the bounds arg from the ST_Contains FuncOper (second argument)instead of the
756  // poly column (first argument)
757  auto rhs = func_oper->getOwnArg(1);
758  auto rewritten_rhs = deep_copy_visitor.visit(rhs.get());
759  CHECK(rewritten_rhs);
760 
761  auto overlaps_oper = makeExpr<Analyzer::BinOper>(
762  kBOOLEAN, kOVERLAPS, kONE, rewritten_lhs, rewritten_rhs);
763 
764  return OverlapsJoinConjunction{{expr}, {overlaps_oper}};
765  }
766  }
767  return boost::none;
768 }
769 
779  public:
781  for (const auto& join_condition : join_quals) {
782  for (const auto& qual : join_condition.quals) {
783  auto qual_bin_oper = dynamic_cast<Analyzer::BinOper*>(qual.get());
784  if (qual_bin_oper) {
785  join_qual_pairs.emplace_back(qual_bin_oper->get_left_operand(),
786  qual_bin_oper->get_right_operand());
787  }
788  }
789  }
790  }
791 
792  bool visitFunctionOper(const Analyzer::FunctionOper* func_oper) const override {
793  if (overlaps_supported_functions.find(func_oper->getName()) !=
795  const auto lhs = func_oper->getArg(2);
796  const auto rhs = func_oper->getArg(1);
797  for (const auto qual_pair : join_qual_pairs) {
798  if (*lhs == *qual_pair.first && *rhs == *qual_pair.second) {
799  return true;
800  }
801  }
802  }
803  return false;
804  }
805 
806  bool defaultResult() const override { return false; }
807 
808  private:
809  std::vector<std::pair<const Analyzer::Expr*, const Analyzer::Expr*>> join_qual_pairs;
810 };
811 
812 std::list<std::shared_ptr<Analyzer::Expr>> strip_join_covered_filter_quals(
813  const std::list<std::shared_ptr<Analyzer::Expr>>& quals,
814  const JoinQualsPerNestingLevel& join_quals) {
816  return quals;
817  }
818 
819  if (join_quals.empty()) {
820  return quals;
821  }
822 
823  std::list<std::shared_ptr<Analyzer::Expr>> quals_to_return;
824 
825  JoinCoveredQualVisitor visitor(join_quals);
826  for (const auto& qual : quals) {
827  if (!visitor.visit(qual.get())) {
828  // Not a covered qual, don't elide it from the filtered count
829  quals_to_return.push_back(qual);
830  }
831  }
832 
833  return quals_to_return;
834 }
835 
836 std::shared_ptr<Analyzer::Expr> fold_expr(const Analyzer::Expr* expr) {
837  if (!expr) {
838  return nullptr;
839  }
840  const auto expr_no_likelihood = strip_likelihood(expr);
841  ConstantFoldingVisitor visitor;
842  auto rewritten_expr = visitor.visit(expr_no_likelihood);
843  if (visitor.get_num_overflows() > 0 && rewritten_expr->get_type_info().is_integer() &&
844  rewritten_expr->get_type_info().get_type() != kBIGINT) {
845  auto rewritten_expr_const =
846  std::dynamic_pointer_cast<const Analyzer::Constant>(rewritten_expr);
847  if (!rewritten_expr_const) {
848  // Integer expression didn't fold completely the first time due to
849  // overflows in smaller type subexpressions, trying again with a cast
850  const auto& ti = SQLTypeInfo(kBIGINT, false);
851  auto bigint_expr_no_likelihood = expr_no_likelihood->deep_copy()->add_cast(ti);
852  auto rewritten_expr_take2 = visitor.visit(bigint_expr_no_likelihood.get());
853  auto rewritten_expr_take2_const =
854  std::dynamic_pointer_cast<Analyzer::Constant>(rewritten_expr_take2);
855  if (rewritten_expr_take2_const) {
856  // Managed to fold, switch to the new constant
857  rewritten_expr = rewritten_expr_take2_const;
858  }
859  }
860  }
861  const auto expr_with_likelihood = dynamic_cast<const Analyzer::LikelihoodExpr*>(expr);
862  if (expr_with_likelihood) {
863  // Add back likelihood
864  return std::make_shared<Analyzer::LikelihoodExpr>(
865  rewritten_expr, expr_with_likelihood->get_likelihood());
866  }
867  return rewritten_expr;
868 }
int8_t tinyintval
Definition: sqltypes.h:126
Analyzer::ExpressionPtr rewrite_array_elements(Analyzer::Expr const *expr)
#define CHECK_EQ(x, y)
Definition: Logger.h:198
#define IS_LOGIC(X)
Definition: sqldefs.h:60
std::shared_ptr< Analyzer::InValues > visitLikeExpr(const Analyzer::LikeExpr *) const override
std::shared_ptr< Analyzer::InValues > visitDateaddExpr(const Analyzer::DateaddExpr *) const override
const std::shared_ptr< Analyzer::Expr > get_own_arg() const
Definition: Analyzer.h:746
SQLTypes
Definition: sqltypes.h:41
std::shared_ptr< Analyzer::WindowFunction > rewrite_avg_window(const Analyzer::Expr *expr)
int32_t getExprIndex() const
Definition: Analyzer.h:1438
bool g_strip_join_covered_quals
Definition: Execute.cpp:90
std::shared_ptr< Analyzer::InValues > visitKeyForString(const Analyzer::KeyForStringExpr *) const override
std::shared_ptr< Analyzer::WindowFunction > rewrite_sum_window(const Analyzer::Expr *expr)
std::shared_ptr< Analyzer::InValues > visitBinOper(const Analyzer::BinOper *bin_oper) const override
#define LOG(tag)
Definition: Logger.h:185
bool boolval
Definition: sqltypes.h:125
const Expr * get_right_operand() const
Definition: Analyzer.h:437
SQLOps
Definition: sqldefs.h:29
Definition: sqldefs.h:35
Definition: sqldefs.h:36
Definition: sqldefs.h:38
#define CHECK_GE(x, y)
Definition: Logger.h:203
bool get_contains_agg() const
Definition: Analyzer.h:80
Definition: sqldefs.h:49
Definition: sqldefs.h:30
std::shared_ptr< Analyzer::Expr > ExpressionPtr
Definition: Analyzer.h:180
const Analyzer::Expr * extract_cast_arg(const Analyzer::Expr *expr)
Definition: Execute.h:152
Definition: sqldefs.h:41
std::vector< JoinCondition > JoinQualsPerNestingLevel
T visit(const Analyzer::Expr *expr) const
Analyzer::ExpressionPtr rewrite_expr(const Analyzer::Expr *expr)
static const std::unordered_set< std::string > overlaps_supported_functions
std::shared_ptr< Analyzer::InValues > aggregateResult(const std::shared_ptr< Analyzer::InValues > &lhs, const std::shared_ptr< Analyzer::InValues > &rhs) const override
std::list< std::shared_ptr< Analyzer::Expr > > strip_join_covered_filter_quals(const std::list< std::shared_ptr< Analyzer::Expr >> &quals, const JoinQualsPerNestingLevel &join_quals)
std::shared_ptr< Analyzer::InValues > visitUOper(const Analyzer::UOper *uoper) const override
std::shared_ptr< Analyzer::Expr > visitBinOper(const Analyzer::BinOper *bin_oper) const override
std::shared_ptr< Analyzer::Expr > RetType
int32_t intval
Definition: sqltypes.h:128
std::shared_ptr< Analyzer::InValues > visitCharLength(const Analyzer::CharLengthExpr *) const override
std::shared_ptr< Analyzer::InValues > visitInIntegerSet(const Analyzer::InIntegerSet *) const override
SQLOps get_optype() const
Definition: Analyzer.h:433
float floatval
Definition: sqltypes.h:130
std::shared_ptr< Analyzer::Expr > visitUOper(const Analyzer::UOper *uoper) const override
CHECK(cgen_state)
std::shared_ptr< Analyzer::InValues > visitRegexpExpr(const Analyzer::RegexpExpr *) const override
int64_t bigintval
Definition: sqltypes.h:129
std::shared_ptr< Analyzer::InValues > visitAggExpr(const Analyzer::AggExpr *) const override
bool visitFunctionOper(const Analyzer::FunctionOper *func_oper) const override
Definition: sqldefs.h:37
bool foldOper(SQLOps optype, SQLTypes type, Datum lhs, Datum rhs, Datum &result, SQLTypes &result_type) const
int16_t smallintval
Definition: sqltypes.h:127
bool defaultResult() const override
static std::shared_ptr< Analyzer::Expr > analyzeValue(const std::string &)
Definition: ParserNode.cpp:97
boost::optional< OverlapsJoinConjunction > rewrite_overlaps_conjunction(const std::shared_ptr< Analyzer::Expr > expr)
RetType visitArrayOper(const Analyzer::ArrayExpr *array_expr) const override
SQLTypeInfoCore< ArrayContextTypeSizer, ExecutorTypePackaging, DateTimeFacilities > SQLTypeInfo
Definition: sqltypes.h:852
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:78
std::shared_ptr< Analyzer::Expr > visitBinOper(const Analyzer::BinOper *bin_oper) const override
size_t getElementCount() const
Definition: Analyzer.h:1437
SQLTypes decimal_to_int_type(const SQLTypeInfo &ti)
Definition: Datum.cpp:268
Definition: sqldefs.h:34
Definition: sqldefs.h:40
std::vector< std::pair< const Analyzer::Expr *, const Analyzer::Expr * > > join_qual_pairs
Definition: sqldefs.h:69
#define TRANSIENT_DICT_ID
Definition: sqltypes.h:189
bool isLocalAlloc() const
Definition: Analyzer.h:1439
const Analyzer::Expr * getArg(const size_t i) const
Definition: Analyzer.h:1311
#define IS_ARITHMETIC(X)
Definition: sqldefs.h:61
const Expr * get_operand() const
Definition: Analyzer.h:365
Datum get_constval() const
Definition: Analyzer.h:329
Definition: sqldefs.h:32
Expression class for the LOWER (lowercase) string function. The &quot;arg&quot; constructor parameter must be a...
Definition: Analyzer.h:740
std::unordered_map< const Analyzer::Expr *, const SQLTypeInfo > casts_
std::shared_ptr< Analyzer::InValues > visitDatediffExpr(const Analyzer::DatediffExpr *) const override
std::shared_ptr< Analyzer::InValues > visitLikelihood(const Analyzer::LikelihoodExpr *) const override
std::shared_ptr< Analyzer::Expr > visitLower(const Analyzer::LowerExpr *lower_expr) const override
std::shared_ptr< Analyzer::InValues > visitInValues(const Analyzer::InValues *) const override
Definition: sqldefs.h:33
const Expr * get_left_operand() const
Definition: Analyzer.h:436
std::shared_ptr< Analyzer::InValues > visitCaseExpr(const Analyzer::CaseExpr *) const override
Definition: sqltypes.h:48
JoinCoveredQualVisitor(const JoinQualsPerNestingLevel &join_quals)
const std::shared_ptr< Analyzer::Expr > get_own_right_operand() const
Definition: Analyzer.h:441
std::string getName() const
Definition: Analyzer.h:1307
bool is_decimal() const
Definition: sqltypes.h:480
std::shared_ptr< Analyzer::InValues > visitDatetruncExpr(const Analyzer::DatetruncExpr *) const override
Definition: sqldefs.h:39
const std::shared_ptr< Analyzer::Expr > get_own_left_operand() const
Definition: Analyzer.h:438
SQLOps get_optype() const
Definition: Analyzer.h:364
const Expr * get_arg() const
Definition: Analyzer.h:744
std::shared_ptr< Analyzer::Expr > fold_expr(const Analyzer::Expr *expr)
#define IS_COMPARISON(X)
Definition: sqldefs.h:57
double doubleval
Definition: sqltypes.h:131
std::shared_ptr< Analyzer::InValues > visitExtractExpr(const Analyzer::ExtractExpr *) const override
const Analyzer::Expr * getElement(const size_t i) const
Definition: Analyzer.h:1441
SQLQualifier get_qualifier() const
Definition: Analyzer.h:435
const Analyzer::Expr * strip_likelihood(const Analyzer::Expr *expr)
std::shared_ptr< Analyzer::InValues > visitCardinality(const Analyzer::CardinalityExpr *) const override