LCOV - code coverage report
Current view: top level - sql/server - rel_optimize_sel.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 2010 2174 92.5 %
Date: 2024-10-03 20:03:20 Functions: 102 102 100.0 %

          Line data    Source code
       1             : /*
       2             :  * SPDX-License-Identifier: MPL-2.0
       3             :  *
       4             :  * This Source Code Form is subject to the terms of the Mozilla Public
       5             :  * License, v. 2.0.  If a copy of the MPL was not distributed with this
       6             :  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
       7             :  *
       8             :  * Copyright 2024 MonetDB Foundation;
       9             :  * Copyright August 2008 - 2023 MonetDB B.V.;
      10             :  * Copyright 1997 - July 2008 CWI.
      11             :  */
      12             : 
      13             : #include "monetdb_config.h"
      14             : #include "rel_optimizer_private.h"
      15             : #include "rel_planner.h"
      16             : #include "rel_exp.h"
      17             : #include "rel_select.h"
      18             : #include "rel_rewriter.h"
      19             : 
      20             : /* Split_select optimizer splits case statements in select expressions. This is a step needed for cse */
      21             : static void select_split_exps(mvc *sql, list *exps, sql_rel *rel);
      22             : 
      23             : static sql_exp *
      24      219872 : select_split_exp(mvc *sql, sql_exp *e, sql_rel *rel)
      25             : {
      26      219872 :         switch(e->type) {
      27             :         case e_column:
      28             :                 return e;
      29        6898 :         case e_convert:
      30        6898 :                 e->l = select_split_exp(sql, e->l, rel);
      31        6898 :                 return e;
      32       24421 :         case e_aggr:
      33             :         case e_func:
      34       24421 :                 if (!is_analytic(e) && !exp_has_sideeffect(e)) {
      35       24416 :                         sql_subfunc *f = e->f;
      36       24416 :                         if (e->type == e_func && !f->func->s && is_caselike_func(f) /*is_ifthenelse_func(f)*/)
      37         280 :                                 return add_exp_too_project(sql, e, rel);
      38             :                 }
      39             :                 return e;
      40       75212 :         case e_cmp:
      41       75212 :                 if (e->flag == cmp_or || e->flag == cmp_filter) {
      42       18805 :                         select_split_exps(sql, e->l, rel);
      43       18805 :                         select_split_exps(sql, e->r, rel);
      44       56407 :                 } else if (e->flag == cmp_in || e->flag == cmp_notin) {
      45        3253 :                         e->l = select_split_exp(sql, e->l, rel);
      46        3253 :                         select_split_exps(sql, e->r, rel);
      47             :                 } else {
      48       53154 :                         e->l = select_split_exp(sql, e->l, rel);
      49       53154 :                         e->r = select_split_exp(sql, e->r, rel);
      50       53154 :                         if (e->f)
      51        3590 :                                 e->f = select_split_exp(sql, e->f, rel);
      52             :                 }
      53             :                 return e;
      54             :         case e_atom:
      55             :         case e_psm:
      56             :                 return e;
      57             :         }
      58             :         return e;
      59             : }
      60             : 
      61             : static void
      62       65658 : select_split_exps(mvc *sql, list *exps, sql_rel *rel)
      63             : {
      64       65658 :         node *n;
      65             : 
      66       65658 :         if (!exps)
      67             :                 return;
      68      165481 :         for(n=exps->h; n; n = n->next){
      69       99823 :                 sql_exp *e = n->data;
      70             : 
      71       99823 :                 e = select_split_exp(sql, e, rel);
      72       99823 :                 n->data = e;
      73             :         }
      74             : }
      75             : 
      76             : static sql_rel *
      77     1658100 : rel_split_select_(visitor *v, sql_rel *rel)
      78             : {
      79     1658100 :         if (!rel || !is_select(rel->op) || list_empty(rel->exps) || !rel->l || mvc_highwater(v->sql))
      80     1437552 :                 return rel;
      81             : 
      82      220548 :         bool funcs = false;
      83             : 
      84             :         /* are there functions */
      85      471629 :         for (node *n = rel->exps->h; n && !funcs; n = n->next)
      86      251081 :                 funcs = exp_has_func(n->data);
      87             : 
      88             :         /* introduce extra project */
      89      220548 :         if (funcs) {
      90       24795 :                 sql_rel *nrel = rel_project(v->sql->sa, rel->l,
      91       24795 :                         rel_projections(v->sql, rel->l, NULL, 1, 1));
      92       24795 :                 if (!nrel || !nrel->exps)
      93             :                         return NULL;
      94       24795 :                 rel->l = nrel;
      95             :                 /* recursively split all functions and add those to the projection list */
      96       24795 :                 select_split_exps(v->sql, rel->exps, nrel);
      97       24795 :                 return rel;
      98             :         }
      99             :         return rel;
     100             : }
     101             : 
     102             : static sql_rel *
     103       55464 : rel_split_select(visitor *v, global_props *gp, sql_rel *rel)
     104             : {
     105       55464 :         (void) gp;
     106       55464 :         return rel_visitor_bottomup(v, rel, &rel_split_select_);
     107             : }
     108             : 
     109             : run_optimizer
     110      622729 : bind_split_select(visitor *v, global_props *gp)
     111             : {
     112      622729 :         int flag = v->sql->sql_optimizer;
     113      547457 :         return gp->opt_cycle == 0 && gp->opt_level == 1 && (flag & split_select)
     114     1170178 :                    && gp->cnt[op_select] ? rel_split_select : NULL;
     115             : }
     116             : 
     117             : 
     118             : /*
     119             :  * Remove a redundant join
     120             :  *
     121             :  * join (L, Distinct Project(join(L,P) [ p.key == l.lkey]) [p.key]) [ p.key == l.lkey]
     122             :  * =>
     123             :  * join(L, P) [p.key==l.lkey]
     124             :  */
     125             : static sql_rel *
     126     1465496 : rel_remove_redundant_join_(visitor *v, sql_rel *rel)
     127             : {
     128     1465496 :         if ((is_join(rel->op) || is_semi(rel->op)) && !list_empty(rel->exps)) {
     129      217945 :                 sql_rel *l = rel->l, *r = rel->r, *b, *p = NULL, *j;
     130             : 
     131      217945 :                 if (is_basetable(l->op) && is_simple_project(r->op) && need_distinct(r)) {
     132           9 :                         b = l;
     133           9 :                         p = r;
     134           9 :                         j = p->l;
     135      217936 :                 } else if (is_basetable(r->op) && is_simple_project(l->op) && need_distinct(l)) {
     136        2333 :                         b = r;
     137        2333 :                         p = l;
     138        2333 :                         j = p->l;
     139             :                 }
     140      217945 :                 if (!p || !j || j->op != rel->op)
     141             :                         return rel;
     142             :                 /* j must have b->l (ie table) */
     143          12 :                 sql_rel *jl = j->l, *jr = j->r;
     144          12 :                 if ((is_basetable(jl->op) && jl->l == b->l) ||
     145           8 :                     (is_basetable(jr->op) && jr->l == b->l)) {
     146          11 :                         int left = 0;
     147          11 :                         if (is_basetable(jl->op) && jl->l == b->l)
     148          11 :                                 left = 1;
     149          11 :                         if (!list_empty(p->exps)) {
     150          19 :                                 for (node *n=p->exps->h; n; n = n->next) { /* all exps of 'p' must be bound to the opposite side */
     151          11 :                                         sql_exp *e = n->data;
     152             : 
     153          18 :                                         if (!rel_rebind_exp(v->sql, left ? jr : jl, e))
     154             :                                                 return rel;
     155             :                                 }
     156             :                         }
     157           8 :                         if (exp_match_list(j->exps, rel->exps)) {
     158           0 :                                 p->l = (left)?rel_dup(jr):rel_dup(jl);
     159           0 :                                 rel_destroy(j);
     160           0 :                                 set_nodistinct(p);
     161           0 :                                 v->changes++;
     162           0 :                                 return rel;
     163             :                         }
     164             :                 }
     165             :         }
     166             :         return rel;
     167             : }
     168             : 
     169             : static sql_rel *
     170       47939 : rel_remove_redundant_join(visitor *v, global_props *gp, sql_rel *rel)
     171             : {
     172       47939 :         (void) gp;
     173       47939 :         return rel_visitor_bottomup(v, rel, &rel_remove_redundant_join_); /* this optimizer has to run before rel_first_level_optimizations */
     174             : }
     175             : 
     176             : run_optimizer
     177      622728 : bind_remove_redundant_join(visitor *v, global_props *gp)
     178             : {
     179      622728 :         int flag = v->sql->sql_optimizer;
     180      547454 :         return gp->opt_cycle == 0 && gp->opt_level == 1 && (gp->cnt[op_left] || gp->cnt[op_right]
     181      529002 :                    || gp->cnt[op_full] || gp->cnt[op_join] || gp->cnt[op_semi] || gp->cnt[op_anti]) &&
     182      670667 :                    (flag & remove_redundant_join) ? rel_remove_redundant_join : NULL;
     183             : }
     184             : 
     185             : 
     186             : static list *
     187     1122407 : exp_merge_range(visitor *v, sql_rel *rel, list *exps)
     188             : {
     189     1122407 :         node *n, *m;
     190     2412335 :         for (n=exps->h; n; n = n->next) {
     191     1291821 :                 sql_exp *e = n->data;
     192     1291821 :                 sql_exp *le = e->l;
     193     1291821 :                 sql_exp *re = e->r;
     194             : 
     195             :                 /* handle the and's in the or lists */
     196     1291821 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e)) {
     197       45194 :                         e->l = exp_merge_range(v, rel, e->l);
     198       45194 :                         e->r = exp_merge_range(v, rel, e->r);
     199             :                 /* only look for gt, gte, lte, lt */
     200     1246627 :                 } else if (n->next &&
     201      165214 :                     e->type == e_cmp && e->flag < cmp_equal && !e->f &&
     202        6818 :                     re->card == CARD_ATOM && !is_anti(e)) {
     203        1268 :                         for (m=n->next; m; m = m->next) {
     204         777 :                                 sql_exp *f = m->data;
     205         777 :                                 sql_exp *lf = f->l;
     206         777 :                                 sql_exp *rf = f->r;
     207         777 :                                 int c_le = is_numeric_upcast(le), c_lf = is_numeric_upcast(lf);
     208             : 
     209         777 :                                 if (f->type == e_cmp && f->flag < cmp_equal && !f->f &&
     210         645 :                                     rf->card == CARD_ATOM && !is_anti(f) &&
     211         322 :                                     exp_match_exp(c_le?le->l:le, c_lf?lf->l:lf)) {
     212         172 :                                         sql_exp *ne;
     213         172 :                                         int swap = 0, lt = 0, gt = 0;
     214         172 :                                         sql_subtype super;
     215             :                                         /* for now only   c1 <[=] x <[=] c2 */
     216             : 
     217         172 :                                         swap = lt = (e->flag == cmp_lt || e->flag == cmp_lte);
     218         172 :                                         gt = !lt;
     219             : 
     220         172 :                                         if (gt &&
     221         150 :                                            (f->flag == cmp_gt ||
     222             :                                             f->flag == cmp_gte))
     223          32 :                                                 continue;
     224          22 :                                         if (lt &&
     225          22 :                                            (f->flag == cmp_lt ||
     226             :                                             f->flag == cmp_lte))
     227           0 :                                                 continue;
     228             : 
     229         140 :                                         cmp_supertype(&super, exp_subtype(le), exp_subtype(lf));
     230         140 :                                         if (!(rf = exp_check_type(v->sql, &super, rel, rf, type_equal)) ||
     231         140 :                                                 !(le = exp_check_type(v->sql, &super, rel, le, type_equal)) ||
     232         140 :                                                 !(re = exp_check_type(v->sql, &super, rel, re, type_equal))) {
     233           0 :                                                         v->sql->session->status = 0;
     234           0 :                                                         v->sql->errstr[0] = 0;
     235           0 :                                                         continue;
     236             :                                                 }
     237         140 :                                         if (!swap)
     238         118 :                                                 ne = exp_compare2(v->sql->sa, le, re, rf, compare2range(e->flag, f->flag), 0);
     239             :                                         else
     240          22 :                                                 ne = exp_compare2(v->sql->sa, le, rf, re, compare2range(f->flag, e->flag), 0);
     241             : 
     242         140 :                                         list_remove_data(exps, NULL, e);
     243         140 :                                         list_remove_data(exps, NULL, f);
     244         140 :                                         list_append(exps, ne);
     245         140 :                                         v->changes++;
     246         140 :                                         return exp_merge_range(v, rel, exps);
     247             :                                 }
     248             :                         }
     249     1245996 :                 } else if (n->next &&
     250      164583 :                            e->type == e_cmp && e->flag < cmp_equal && !e->f &&
     251        6187 :                            re->card > CARD_ATOM && !is_anti(e)) {
     252       11218 :                         for (m=n->next; m; m = m->next) {
     253        6784 :                                 sql_exp *f = m->data;
     254        6784 :                                 sql_exp *lf = f->l;
     255        6784 :                                 sql_exp *rf = f->r;
     256             : 
     257        6784 :                                 if (f->type == e_cmp && f->flag < cmp_equal && !f->f  &&
     258        4979 :                                     rf->card > CARD_ATOM && !is_anti(f)) {
     259        4978 :                                         sql_exp *ne, *t;
     260        4978 :                                         int swap = 0, lt = 0, gt = 0;
     261        4978 :                                         comp_type ef = (comp_type) e->flag, ff = (comp_type) f->flag;
     262        4978 :                                         int c_re = is_numeric_upcast(re), c_rf = is_numeric_upcast(rf);
     263        4978 :                                         int c_le = is_numeric_upcast(le), c_lf = is_numeric_upcast(lf), c;
     264        4978 :                                         sql_subtype super;
     265             : 
     266             :                                         /* both swapped ? */
     267        4978 :                                         if (exp_match_exp(c_re?re->l:re, c_rf?rf->l:rf)) {
     268          19 :                                                 t = re;
     269          19 :                                                 re = le;
     270          19 :                                                 le = t;
     271          19 :                                                 c = c_re; c_re = c_le; c_le = c;
     272          19 :                                                 ef = swap_compare(ef);
     273          19 :                                                 t = rf;
     274          19 :                                                 rf = lf;
     275          19 :                                                 lf = t;
     276          19 :                                                 c = c_rf; c_rf = c_lf; c_lf = c;
     277          19 :                                                 ff = swap_compare(ff);
     278             :                                         }
     279             : 
     280             :                                         /* is left swapped ? */
     281        4978 :                                         if (exp_match_exp(c_re?re->l:re, c_lf?lf->l:lf)) {
     282         104 :                                                 t = re;
     283         104 :                                                 re = le;
     284         104 :                                                 le = t;
     285         104 :                                                 c = c_re; c_re = c_le; c_le = c;
     286         104 :                                                 ef = swap_compare(ef);
     287             :                                         }
     288             : 
     289             :                                         /* is right swapped ? */
     290        4978 :                                         if (exp_match_exp(c_le?le->l:le, c_rf?rf->l:rf)) {
     291         177 :                                                 t = rf;
     292         177 :                                                 rf = lf;
     293         177 :                                                 lf = t;
     294         177 :                                                 c = c_rf; c_rf = c_lf; c_lf = c;
     295         177 :                                                 ff = swap_compare(ff);
     296             :                                         }
     297             : 
     298        4978 :                                         if (!exp_match_exp(c_le?le->l:le, c_lf?lf->l:lf))
     299        3225 :                                                 continue;
     300             : 
     301             :                                         /* for now only   c1 <[=] x <[=] c2 */
     302        1830 :                                         swap = lt = (ef == cmp_lt || ef == cmp_lte);
     303        1830 :                                         gt = !lt;
     304             : 
     305        1830 :                                         if (gt && (ff == cmp_gt || ff == cmp_gte))
     306          73 :                                                 continue;
     307        1757 :                                         if (lt && (ff == cmp_lt || ff == cmp_lte))
     308           4 :                                                 continue;
     309             : 
     310        1753 :                                         cmp_supertype(&super, exp_subtype(le), exp_subtype(lf));
     311        1753 :                                         if (!(rf = exp_check_type(v->sql, &super, rel, rf, type_equal)) ||
     312        1753 :                                                 !(le = exp_check_type(v->sql, &super, rel, le, type_equal)) ||
     313        1753 :                                                 !(re = exp_check_type(v->sql, &super, rel, re, type_equal))) {
     314           0 :                                                         v->sql->session->status = 0;
     315           0 :                                                         v->sql->errstr[0] = 0;
     316           0 :                                                         continue;
     317             :                                                 }
     318        1753 :                                         if (!swap)
     319        1653 :                                                 ne = exp_compare2(v->sql->sa, le, re, rf, compare2range(ef, ff), 0);
     320             :                                         else
     321         100 :                                                 ne = exp_compare2(v->sql->sa, le, rf, re, compare2range(ff, ef), 0);
     322             : 
     323        1753 :                                         list_remove_data(exps, NULL, e);
     324        1753 :                                         list_remove_data(exps, NULL, f);
     325        1753 :                                         list_append(exps, ne);
     326        1753 :                                         v->changes++;
     327        1753 :                                         return exp_merge_range(v, rel, exps);
     328             :                                 }
     329             :                         }
     330             :                 }
     331             :         }
     332             :         return exps;
     333             : }
     334             : 
     335             : static int
     336       41704 : exps_cse( mvc *sql, list *oexps, list *l, list *r )
     337             : {
     338       41704 :         list *nexps;
     339       41704 :         node *n, *m;
     340       41704 :         char *lu, *ru;
     341       41704 :         int lc = 0, rc = 0, match = 0, res = 0;
     342             : 
     343       41704 :         if (list_length(l) == 0 || list_length(r) == 0)
     344           0 :                 return 0;
     345             : 
     346             :         /* first recursive exps_cse */
     347       41704 :         nexps = new_exp_list(sql->sa);
     348       88263 :         for (n = l->h; n; n = n->next) {
     349       46559 :                 sql_exp *e = n->data;
     350             : 
     351       46559 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e)) {
     352       16158 :                         res = exps_cse(sql, nexps, e->l, e->r);
     353             :                 } else {
     354       30401 :                         append(nexps, e);
     355             :                 }
     356             :         }
     357       41704 :         l = nexps;
     358             : 
     359       41704 :         nexps = new_exp_list(sql->sa);
     360       90991 :         for (n = r->h; n; n = n->next) {
     361       49287 :                 sql_exp *e = n->data;
     362             : 
     363       49287 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e)) {
     364        3320 :                         res = exps_cse(sql, nexps, e->l, e->r);
     365             :                 } else {
     366       45967 :                         append(nexps, e);
     367             :                 }
     368             :         }
     369       41704 :         r = nexps;
     370             : 
     371             :         /* simplify  true or .. and .. or true */
     372       41704 :         if (list_length(l) == list_length(r) && list_length(l) == 1) {
     373       36604 :                 sql_exp *le = l->h->data, *re = r->h->data;
     374             : 
     375       36604 :                 if (exp_is_true(le)) {
     376          14 :                         append(oexps, le);
     377          14 :                         return 1;
     378             :                 }
     379       36590 :                 if (exp_is_true(re)) {
     380           5 :                         append(oexps, re);
     381           5 :                         return 1;
     382             :                 }
     383             :         }
     384             : 
     385       41685 :         lu = SA_ZNEW_ARRAY(sql->ta, char, list_length(l));
     386       41685 :         ru = SA_ZNEW_ARRAY(sql->ta, char, list_length(r));
     387       88951 :         for (n = l->h, lc = 0; n; n = n->next, lc++) {
     388       47266 :                 sql_exp *le = n->data;
     389             : 
     390      106336 :                 for ( m = r->h, rc = 0; m; m = m->next, rc++) {
     391       59070 :                         sql_exp *re = m->data;
     392             : 
     393       59070 :                         if (!ru[rc] && exp_match_exp(le,re)) {
     394         796 :                                 lu[lc] = 1;
     395         796 :                                 ru[rc] = 1;
     396         796 :                                 match = 1;
     397             :                         }
     398             :                 }
     399             :         }
     400       41685 :         if (match) {
     401         415 :                 list *nl = new_exp_list(sql->sa);
     402         415 :                 list *nr = new_exp_list(sql->sa);
     403             : 
     404        1625 :                 for (n = l->h, lc = 0; n; n = n->next, lc++)
     405        1210 :                         if (!lu[lc])
     406         418 :                                 append(nl, n->data);
     407        1639 :                 for (n = r->h, rc = 0; n; n = n->next, rc++)
     408        1224 :                         if (!ru[rc])
     409         428 :                                 append(nr, n->data);
     410             : 
     411         415 :                 if (list_length(nl) && list_length(nr))
     412         387 :                         append(oexps, exp_or(sql->sa, nl, nr, 0));
     413             : 
     414        1625 :                 for (n = l->h, lc = 0; n; n = n->next, lc++) {
     415        1210 :                         if (lu[lc])
     416         792 :                                 append(oexps, n->data);
     417             :                 }
     418             :                 res = 1;
     419             :         } else {
     420       41270 :                 append(oexps, exp_or(sql->sa, list_dup(l, (fdup)NULL),
     421             :                                      list_dup(r, (fdup)NULL), 0));
     422             :         }
     423             :         return res;
     424             : }
     425             : 
     426             : static int
     427       93427 : are_equality_exps( list *exps, sql_exp **L)
     428             : {
     429       93427 :         sql_exp *l = *L;
     430             : 
     431       93427 :         if (list_length(exps) == 1) {
     432       89320 :                 sql_exp *e = exps->h->data, *le = e->l, *re = e->r;
     433             : 
     434       89320 :                 if (e->type == e_cmp && e->flag == cmp_equal && le->card != CARD_ATOM && re->card == CARD_ATOM && !is_semantics(e)) {
     435       22376 :                         if (!l) {
     436       10841 :                                 *L = l = le;
     437       10841 :                                 if (!is_column(le->type))
     438             :                                         return 0;
     439             :                         }
     440       22376 :                         return (exp_match(l, le));
     441             :                 }
     442       66944 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e) && !is_semantics(e))
     443       72667 :                         return (are_equality_exps(e->l, L) && are_equality_exps(e->r, L));
     444             :         }
     445             :         return 0;
     446             : }
     447             : 
     448             : static void
     449        4283 : get_exps( list *n, list *l )
     450             : {
     451        5996 :         sql_exp *e = l->h->data, *re = e->r;
     452             : 
     453        5996 :         if (e->type == e_cmp && e->flag == cmp_equal && re->card == CARD_ATOM)
     454        4283 :                 list_append(n, re);
     455        5996 :         if (e->type == e_cmp && e->flag == cmp_or) {
     456        1713 :                 get_exps(n, e->l);
     457        1713 :                 get_exps(n, e->r);
     458             :         }
     459        4283 : }
     460             : 
     461             : static sql_exp *
     462        1285 : equality_exps_2_in( mvc *sql, sql_exp *ce, list *l, list *r)
     463             : {
     464        1285 :         list *nl = new_exp_list(sql->sa);
     465             : 
     466        1285 :         get_exps(nl, l);
     467        1285 :         get_exps(nl, r);
     468             : 
     469        1285 :         return exp_in( sql->sa, ce, nl, cmp_in);
     470             : }
     471             : 
     472             : static list *
     473      604796 : merge_ors(mvc *sql, list *exps, int *changes)
     474             : {
     475      604796 :         list *nexps = NULL;
     476      604796 :         int needed = 0;
     477             : 
     478     1292339 :         for (node *n = exps->h; n && !needed; n = n->next) {
     479      687543 :                 sql_exp *e = n->data;
     480             : 
     481      687543 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e))
     482      687543 :                         needed = 1;
     483             :         }
     484             : 
     485      604796 :         if (needed) {
     486       42109 :                 nexps = new_exp_list(sql->sa);
     487       92606 :                 for (node *n = exps->h; n; n = n->next) {
     488       50497 :                         sql_exp *e = n->data, *l = NULL;
     489             : 
     490       50497 :                         if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e) && are_equality_exps(e->l, &l) && are_equality_exps(e->r, &l) && l) {
     491        1285 :                                 (*changes)++;
     492        1285 :                                 append(nexps, equality_exps_2_in(sql, l, e->l, e->r));
     493             :                         } else {
     494       49212 :                                 append(nexps, e);
     495             :                         }
     496             :                 }
     497             :         } else {
     498             :                 nexps = exps;
     499             :         }
     500             : 
     501     1299672 :         for (node *n = nexps->h; n ; n = n->next) {
     502      694876 :                 sql_exp *e = n->data;
     503             : 
     504      694876 :                 if (e->type == e_cmp && e->flag == cmp_or) {
     505       41936 :                         e->l = merge_ors(sql, e->l, changes);
     506       41936 :                         e->r = merge_ors(sql, e->r, changes);
     507             :                 }
     508             :         }
     509             : 
     510      604796 :         return nexps;
     511             : }
     512             : 
     513             : #define TRIVIAL_NOT_EQUAL_CMP(e) \
     514             :         ((e)->type == e_cmp && (e)->flag == cmp_notequal && !is_anti((e)) && !is_semantics((e)) && ((sql_exp*)(e)->l)->card != CARD_ATOM && ((sql_exp*)(e)->r)->card == CARD_ATOM)
     515             : 
     516             : static list *
     517      604796 : merge_notequal(mvc *sql, list *exps, int *changes)
     518             : {
     519      604796 :         list *inequality_groups = NULL, *nexps = NULL;
     520      604796 :         int needed = 0;
     521             : 
     522     1299672 :         for (node *n = exps->h; n; n = n->next) {
     523      694876 :                 sql_exp *e = n->data;
     524             : 
     525      694876 :                 if (TRIVIAL_NOT_EQUAL_CMP(e)) {
     526       82315 :                         bool appended = false;
     527             : 
     528       82315 :                         if (inequality_groups) {
     529        9091 :                                 for (node *m = inequality_groups->h; m && !appended; m = m->next) {
     530        5210 :                                         list *next = m->data;
     531        5210 :                                         sql_exp *first = (sql_exp*) next->h->data;
     532             : 
     533        5210 :                                         if (exp_match(first->l, e->l)) {
     534        1164 :                                                 list_append(next, e);
     535        1164 :                                                 appended = true;
     536             :                                         }
     537             :                                 }
     538             :                         }
     539        3881 :                         if (!appended) {
     540       81151 :                                 if (!inequality_groups)
     541       78434 :                                         inequality_groups = new_exp_list(sql->sa);
     542       81151 :                                 list_append(inequality_groups, list_append(new_exp_list(sql->sa), e));
     543             :                         }
     544             :                 }
     545             :         }
     546             : 
     547      604796 :         if (inequality_groups) { /* if one list of inequalities has more than one entry, then the re-write is needed */
     548      159585 :                 for (node *n = inequality_groups->h; n; n = n->next) {
     549       81151 :                         list *next = n->data;
     550             : 
     551       81151 :                         if (list_length(next) > 1)
     552        1079 :                                 needed = 1;
     553             :                 }
     554             :         }
     555             : 
     556       78434 :         if (needed) {
     557         997 :                 nexps = new_exp_list(sql->sa);
     558        2610 :                 for (node *n = inequality_groups->h; n; n = n->next) {
     559        1613 :                         list *next = n->data;
     560        1613 :                         sql_exp *first = (sql_exp*) next->h->data;
     561             : 
     562        1613 :                         if (list_length(next) > 1) {
     563        1079 :                                 list *notin = new_exp_list(sql->sa);
     564             : 
     565        3322 :                                 for (node *m = next->h; m; m = m->next) {
     566        2243 :                                         sql_exp *e = m->data;
     567        2243 :                                         list_append(notin, e->r);
     568             :                                 }
     569        1079 :                                 list_append(nexps, exp_in(sql->sa, first->l, notin, cmp_notin));
     570             :                         } else {
     571         534 :                                 list_append(nexps, first);
     572             :                         }
     573             :                 }
     574             : 
     575        4132 :                 for (node *n = exps->h; n; n = n->next) {
     576        3135 :                         sql_exp *e = n->data;
     577             : 
     578        3135 :                         if (!TRIVIAL_NOT_EQUAL_CMP(e))
     579         358 :                                 list_append(nexps, e);
     580             :                 }
     581         997 :                 (*changes)++;
     582             :         } else {
     583             :                 nexps = exps;
     584             :         }
     585             : 
     586     1298508 :         for (node *n = nexps->h; n ; n = n->next) {
     587      693712 :                 sql_exp *e = n->data;
     588             : 
     589      693712 :                 if (e->type == e_cmp && e->flag == cmp_or) {
     590       41936 :                         e->l = merge_notequal(sql, e->l, changes);
     591       41936 :                         e->r = merge_notequal(sql, e->r, changes);
     592             :                 }
     593             :         }
     594             : 
     595      604796 :         return nexps;
     596             : }
     597             : 
     598             : int
     599      174089 : is_numeric_upcast(sql_exp *e)
     600             : {
     601      174089 :         if (is_convert(e->type)) {
     602        4675 :                 sql_subtype *f = exp_fromtype(e);
     603        4675 :                 sql_subtype *t = exp_totype(e);
     604             : 
     605        4675 :                 if (f->type->eclass == t->type->eclass && EC_COMPUTE(f->type->eclass)) {
     606        1640 :                         if (f->type->localtype < t->type->localtype)
     607        1620 :                                 return 1;
     608             :                 }
     609             :         }
     610             :         return 0;
     611             : }
     612             : 
     613             : /* optimize (a = b) or (a is null and b is null) -> a = b with null semantics */
     614             : static sql_exp *
     615       44976 : try_rewrite_equal_or_is_null(mvc *sql, sql_rel *rel, sql_exp *or, list *l1, list *l2)
     616             : {
     617       44976 :         if (list_length(l1) == 1) {
     618       41411 :                 bool valid = true, first_is_null_found = false, second_is_null_found = false;
     619       41411 :                 sql_exp *cmp = l1->h->data;
     620       41411 :                 sql_exp *first = cmp->l, *second = cmp->r;
     621             : 
     622       41411 :                 if (is_compare(cmp->type) && !is_anti(cmp) && !cmp->f && cmp->flag == cmp_equal) {
     623        7126 :                         int fupcast = is_numeric_upcast(first), supcast = is_numeric_upcast(second);
     624       14517 :                         for(node *n = l2->h ; n && valid; n = n->next) {
     625        7391 :                                 sql_exp *e = n->data, *l = e->l, *r = e->r;
     626             : 
     627        7391 :                                 if (is_compare(e->type) && e->flag == cmp_equal && !e->f &&
     628        4511 :                                         !is_anti(e) && is_semantics(e)) {
     629        1789 :                                         int lupcast = is_numeric_upcast(l);
     630        1789 :                                         int rupcast = is_numeric_upcast(r);
     631        1789 :                                         sql_exp *rr = rupcast ? r->l : r;
     632             : 
     633        1789 :                                         if (rr->type == e_atom && rr->l && atom_null(rr->l)) {
     634        1789 :                                                 if (exp_match_exp(fupcast?first->l:first, lupcast?l->l:l))
     635             :                                                         first_is_null_found = true;
     636         353 :                                                 else if (exp_match_exp(supcast?second->l:second, lupcast?l->l:l))
     637             :                                                         second_is_null_found = true;
     638             :                                                 else
     639        5690 :                                                         valid = false;
     640             :                                         } else {
     641             :                                                 valid = false;
     642             :                                         }
     643             :                                 } else {
     644             :                                         valid = false;
     645             :                                 }
     646             :                         }
     647        7126 :                         if (valid && first_is_null_found && second_is_null_found) {
     648         262 :                                 sql_subtype super;
     649             : 
     650         262 :                                 cmp_supertype(&super, exp_subtype(first), exp_subtype(second)); /* first and second must have the same type */
     651         262 :                                 if (!(first = exp_check_type(sql, &super, rel, first, type_equal)) ||
     652         262 :                                         !(second = exp_check_type(sql, &super, rel, second, type_equal))) {
     653           0 :                                                 sql->session->status = 0;
     654           0 :                                                 sql->errstr[0] = 0;
     655           0 :                                                 return or;
     656             :                                         }
     657         262 :                                 sql_exp *res = exp_compare(sql->sa, first, second, cmp->flag);
     658         262 :                                 set_semantics(res);
     659         262 :                                 if (exp_name(or))
     660           0 :                                         exp_prop_alias(sql->sa, res, or);
     661         262 :                                 return res;
     662             :                         }
     663             :                 }
     664             :         }
     665             :         return or;
     666             : }
     667             : 
     668             : static list *
     669     1030126 : merge_cmp_or_null(mvc *sql, sql_rel *rel, list *exps, int *changes)
     670             : {
     671     2215207 :         for (node *n = exps->h; n ; n = n->next) {
     672     1185081 :                 sql_exp *e = n->data;
     673             : 
     674     1185081 :                 if (is_compare(e->type) && e->flag == cmp_or && !is_anti(e)) {
     675       22488 :                         sql_exp *ne = try_rewrite_equal_or_is_null(sql, rel, e, e->l, e->r);
     676       22488 :                         if (ne != e) {
     677         260 :                                 (*changes)++;
     678         260 :                                 n->data = ne;
     679             :                         }
     680       22488 :                         ne = try_rewrite_equal_or_is_null(sql, rel, e, e->r, e->l);
     681       22488 :                         if (ne != e) {
     682           2 :                                 (*changes)++;
     683           2 :                                 n->data = ne;
     684             :                         }
     685             :                 }
     686             :         }
     687     1030126 :         return exps;
     688             : }
     689             : 
     690             : static list *
     691     1030126 : cleanup_equal_exps(mvc *sql, sql_rel *rel, list *exps, int *changes)
     692             : {
     693     1030126 :         if (list_length(exps) <= 1)
     694             :                 return exps;
     695      141361 :         if (is_join(rel->op)) {
     696      213119 :                 for(node *n = exps->h; n; n = n->next) {
     697      143306 :                         sql_exp *e = n->data;
     698      286443 :                         if (e->type == e_cmp && !e->f && e->flag <= cmp_notequal &&
     699      184604 :                                 !rel_find_exp(rel->l, e->l) && !rel_find_exp(rel->r, e->r) &&
     700       41293 :                                 !find_prop(e->p, PROP_HASHCOL) && !find_prop(e->p, PROP_JOINIDX)) {
     701       20566 :                                 exp_swap(e);
     702             :                         }
     703             :                 }
     704             :         }
     705      141361 :         bool needed = false;
     706      438733 :         for(node *n = exps->h; !needed && n; n = n->next) {
     707      588985 :                 for (node *m = n->next; !needed && m; m = m->next) {
     708      291613 :                         if (exp_match_exp_semantics(n->data, m->data, true))
     709          89 :                                 needed = true;
     710             :                 }
     711             :         }
     712      141361 :         if (needed) {
     713          89 :                 list *nexps = sa_list(sql->sa);
     714             : 
     715         293 :                 for(node *n = exps->h; n; n = n->next) {
     716         204 :                         bool done = false;
     717         629 :                         for (node *m = exps->h; m && !done; m = m->next) {
     718         425 :                                 if (n != m && exp_match_exp_semantics(n->data, m->data, false)) {
     719         179 :                                         sql_exp *e1 = n->data, *e2 = m->data;
     720         179 :                                         if ((is_any(e1) || is_semantics(e1)) || (!is_any(e2) && !is_semantics(e2))) {
     721         179 :                                                 append(nexps, e1);
     722         179 :                                                 if ((!is_any(e2) && !is_semantics(e2)) && is_left(rel->op) && list_length(rel->attr) == 1) {
     723             :                                                         /* nil is false */
     724           0 :                                                         sql_exp *m = rel->attr->h->data;
     725           0 :                                                         if (exp_is_atom(m))
     726           0 :                                                                 set_no_nil(m);
     727             :                                                 }
     728             :                                         }
     729             :                                         done = true;
     730             :                                 }
     731             :                         }
     732         204 :                         if (!done)
     733          25 :                                 append(nexps, n->data);
     734             :                 }
     735             :                 return nexps;
     736             :         }
     737             :         (void)changes;
     738             :         return exps;
     739             : }
     740             : 
     741             : static inline sql_rel *
     742     1030126 : rel_select_cse(visitor *v, sql_rel *rel)
     743             : {
     744     1030126 :         if ((is_select(rel->op) || is_join(rel->op) || is_semi(rel->op)) && rel->exps) /* cleanup equal expressions */
     745     1030126 :                 rel->exps = cleanup_equal_exps(v->sql, rel, rel->exps, &v->changes); /* (a = b) and (a += b) */
     746             : 
     747     1030126 :         if (is_select(rel->op) && rel->exps)
     748      520924 :                 rel->exps = merge_ors(v->sql, rel->exps, &v->changes); /* x = 1 or x = 2 => x in (1, 2)*/
     749             : 
     750     1030126 :         if (is_select(rel->op) && rel->exps)
     751      520924 :                 rel->exps = merge_notequal(v->sql, rel->exps, &v->changes); /* x <> 1 and x <> 2 => x not in (1, 2)*/
     752             : 
     753     1030126 :         if ((is_select(rel->op) || is_join(rel->op) || is_semi(rel->op)) && rel->exps)
     754     1030126 :                 rel->exps = merge_cmp_or_null(v->sql, rel, rel->exps, &v->changes); /* (a = b) or (a is null and b is null) -> a = b with null semantics */
     755             : 
     756     1030126 :         if ((is_select(rel->op) || is_join(rel->op) || is_semi(rel->op)) && rel->exps) {
     757     1030126 :                 node *n;
     758     1030126 :                 list *nexps;
     759     1030126 :                 int needed = 0;
     760             : 
     761     2208588 :                 for (n=rel->exps->h; n && !needed; n = n->next) {
     762     1178462 :                         sql_exp *e = n->data;
     763             : 
     764     1178462 :                         if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e))
     765     1178462 :                                 needed = 1;
     766             :                 }
     767     1030126 :                 if (!needed)
     768             :                         return rel;
     769       21417 :                 nexps = new_exp_list(v->sql->sa);
     770       50849 :                 for (n=rel->exps->h; n; n = n->next) {
     771       29432 :                         sql_exp *e = n->data;
     772             : 
     773       29432 :                         if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e)) {
     774             :                                 /* split the common expressions */
     775       22226 :                                 v->changes += exps_cse(v->sql, nexps, e->l, e->r);
     776             :                         } else {
     777        7206 :                                 append(nexps, e);
     778             :                         }
     779             :                 }
     780       21417 :                 rel->exps = nexps;
     781             :         }
     782             :         return rel;
     783             : }
     784             : 
     785             : static list *
     786       14204 : exps_merge_select_rse( mvc *sql, list *l, list *r, bool *merged)
     787             : {
     788       14204 :         node *n, *m, *o;
     789       14204 :         list *nexps = NULL, *lexps, *rexps;
     790       14204 :         bool lmerged = true, rmerged = true;
     791             : 
     792       14204 :         lexps = new_exp_list(sql->sa);
     793       30142 :         for (n = l->h; n; n = n->next) {
     794       15938 :                 sql_exp *e = n->data;
     795             : 
     796       15938 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e) && !is_semantics(e)) {
     797        5478 :                         lmerged = false;
     798        5478 :                         list *nexps = exps_merge_select_rse(sql, e->l, e->r, &lmerged);
     799        5994 :                         for (o = nexps->h; o; o = o->next)
     800         516 :                                 append(lexps, o->data);
     801             :                 } else {
     802       10460 :                         append(lexps, e);
     803             :                 }
     804             :         }
     805       14204 :         if (lmerged)
     806        8785 :                 lmerged = (list_length(lexps) == 1);
     807       14204 :         rexps = new_exp_list(sql->sa);
     808       30755 :         for (n = r->h; n; n = n->next) {
     809       16551 :                 sql_exp *e = n->data;
     810             : 
     811       16551 :                 if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e) && !is_semantics(e)) {
     812        1104 :                         rmerged = false;
     813        1104 :                         list *nexps = exps_merge_select_rse(sql, e->l, e->r, &rmerged);
     814        1127 :                         for (o = nexps->h; o; o = o->next)
     815          23 :                                 append(rexps, o->data);
     816             :                 } else {
     817       15447 :                         append(rexps, e);
     818             :                 }
     819             :         }
     820       14204 :         if (rmerged)
     821       13118 :                 rmerged = (list_length(r) == 1);
     822             : 
     823       14204 :         nexps = new_exp_list(sql->sa);
     824             : 
     825             :         /* merge merged lists first ? */
     826       25180 :         for (n = lexps->h; n; n = n->next) {
     827       10976 :                 sql_exp *le = n->data, *re, *fnd = NULL;
     828             : 
     829       10976 :                 if (le->type != e_cmp || le->flag == cmp_or || is_anti(le) || is_semantics(le) || is_symmetric(le))
     830         598 :                         continue;
     831       21185 :                 for (m = rexps->h; !fnd && m; m = m->next) {
     832       10807 :                         re = m->data;
     833       10807 :                         if (exps_match_col_exps(le, re))
     834        1726 :                                 fnd = re;
     835             :                 }
     836       10378 :                 if (fnd && (is_anti(fnd) || is_semantics(fnd)))
     837          52 :                         continue;
     838             :                 /* cases
     839             :                  * 1) 2 values (cmp_equal)
     840             :                  * 2) 1 value (cmp_equal), and cmp_in
     841             :                  *      (also cmp_in, cmp_equal)
     842             :                  * 3) 2 cmp_in
     843             :                  * 4) ranges
     844             :                  */
     845        1674 :                 if (fnd) {
     846        1674 :                         re = fnd;
     847        1674 :                         fnd = NULL;
     848        1674 :                         if (is_anti(le) || is_anti(re) || is_symmetric(re))
     849           0 :                                 continue;
     850        2228 :                         if (le->flag == cmp_equal && re->flag == cmp_equal) {
     851         554 :                                 list *exps = new_exp_list(sql->sa);
     852             : 
     853         554 :                                 append(exps, le->r);
     854         554 :                                 append(exps, re->r);
     855         554 :                                 fnd = exp_in(sql->sa, le->l, exps, cmp_in);
     856        1291 :                         } else if (le->flag == cmp_equal && re->flag == cmp_in){
     857         171 :                                 list *exps = new_exp_list(sql->sa);
     858             : 
     859         171 :                                 append(exps, le->r);
     860         171 :                                 list_merge(exps, re->r, NULL);
     861         171 :                                 fnd = exp_in(sql->sa, le->l, exps, cmp_in);
     862        1280 :                         } else if (le->flag == cmp_in && re->flag == cmp_equal){
     863         331 :                                 list *exps = new_exp_list(sql->sa);
     864             : 
     865         331 :                                 append(exps, re->r);
     866         331 :                                 list_merge(exps, le->r, NULL);
     867         331 :                                 fnd = exp_in(sql->sa, le->l, exps, cmp_in);
     868         738 :                         } else if (le->flag == cmp_in && re->flag == cmp_in){
     869         120 :                                 list *exps = new_exp_list(sql->sa);
     870             : 
     871         120 :                                 list_merge(exps, le->r, NULL);
     872         120 :                                 list_merge(exps, re->r, NULL);
     873         120 :                                 fnd = exp_in(sql->sa, le->l, exps, cmp_in);
     874         498 :                         } else if (le->f && re->f && /* merge ranges */
     875          20 :                                    le->flag == re->flag && le->flag <= cmp_lt) {
     876          20 :                                 sql_exp *mine = NULL, *maxe = NULL;
     877             : 
     878          20 :                                 if (!(mine = rel_binop_(sql, NULL, exp_copy(sql, le->r), exp_copy(sql, re->r), "sys", "sql_min", card_value, true))) {
     879           0 :                                         sql->session->status = 0;
     880           0 :                                         sql->errstr[0] = '\0';
     881           0 :                                         continue;
     882             :                                 }
     883          20 :                                 if (!(maxe = rel_binop_(sql, NULL, exp_copy(sql, le->f), exp_copy(sql, re->f), "sys", "sql_max", card_value, true))) {
     884           0 :                                         sql->session->status = 0;
     885           0 :                                         sql->errstr[0] = '\0';
     886           0 :                                         continue;
     887             :                                 }
     888          20 :                                 fnd = exp_compare2(sql->sa, exp_copy(sql, le->l), mine, maxe, le->flag, 0);
     889          20 :                                 lmerged = false;
     890             :                         }
     891        1196 :                         if (fnd) {
     892        1196 :                                 append(nexps, fnd);
     893        2229 :                                 *merged = (fnd && lmerged && rmerged);
     894             :                         }
     895             :                 }
     896             :         }
     897       14204 :         return nexps;
     898             : }
     899             : 
     900             : /* merge related sub expressions
     901             :  *
     902             :  * ie   (x = a and y > 1 and y < 5) or
     903             :  *      (x = c and y > 1 and y < 10) or
     904             :  *      (x = e and y > 1 and y < 20)
     905             :  * ->
     906             :  *     ((x = a and y > 1 and y < 5) or
     907             :  *      (x = c and y > 1 and y < 10) or
     908             :  *      (x = e and y > 1 and y < 20)) and
     909             :  *       x in (a,c,e) and
     910             :  *       y > 1 and y < 20
     911             :  *
     912             :  * for single expression or's we can do better
     913             :  *              x in (a, b, c) or x in (d, e, f)
     914             :  *              ->
     915             :  *              x in (a, b, c, d, e, f)
     916             :  * */
     917             : static inline sql_rel *
     918      395707 : rel_merge_select_rse(visitor *v, sql_rel *rel)
     919             : {
     920             :         /* only execute once per select */
     921      395707 :         if ((is_select(rel->op) || is_join(rel->op) || is_semi(rel->op)) && rel->exps && !is_rel_merge_select_rse_used(rel->used)) {
     922      140095 :                 node *n, *o;
     923      140095 :                 list *nexps = new_exp_list(v->sql->sa);
     924             : 
     925      299845 :                 for (n=rel->exps->h; n; n = n->next) {
     926      159750 :                         sql_exp *e = n->data;
     927             : 
     928      167372 :                         if (e->type == e_cmp && e->flag == cmp_or && !is_anti(e) && !is_semantics(e)) {
     929             :                                 /* possibly merge related expressions */
     930        7622 :                                 bool merged = false;
     931             : 
     932        7622 :                                 list *ps = exps_merge_select_rse(v->sql, e->l, e->r, &merged);
     933        8279 :                                 for (o = ps->h; o; o = o->next)
     934         657 :                                         append(nexps, o->data);
     935        7622 :                                 if (merged)
     936          86 :                                         v->changes++;
     937             :                                 else
     938        7536 :                                         append(nexps, e);
     939             :                         } else {
     940      152128 :                                 append(nexps, e);
     941             :                         }
     942             :                 }
     943      140095 :                 rel->exps = nexps;
     944      140095 :                 rel->used |= rel_merge_select_rse_used;
     945             :         }
     946      395707 :         return rel;
     947             : }
     948             : 
     949             : /* pack optimizers into a single function call to avoid iterations in the AST */
     950             : static sql_rel *
     951     3623356 : rel_optimize_select_and_joins_bottomup_(visitor *v, sql_rel *rel)
     952             : {
     953     3623356 :         if (!rel || (!is_join(rel->op) && !is_semi(rel->op) && !is_select(rel->op)) || list_empty(rel->exps))
     954     2593230 :                 return rel;
     955     1030126 :         uint8_t cycle = *(uint8_t*) v->data;
     956             : 
     957     1030126 :         rel->exps = exp_merge_range(v, rel, rel->exps);
     958     1030126 :         rel = rel_select_cse(v, rel);
     959     1030126 :         if (cycle == 1)
     960      395707 :                 rel = rel_merge_select_rse(v, rel);
     961     1030126 :         rel = rewrite_simplify(v, cycle, v->value_based_opt, rel);
     962     1030126 :         return rel;
     963             : }
     964             : 
     965             : static sql_rel *
     966      125747 : rel_optimize_select_and_joins_bottomup(visitor *v, global_props *gp, sql_rel *rel)
     967             : {
     968      125747 :         v->data = &gp->opt_cycle;
     969      125747 :         rel = rel_visitor_bottomup(v, rel, &rel_optimize_select_and_joins_bottomup_);
     970      125747 :         v->data = gp;
     971      125747 :         return rel;
     972             : }
     973             : 
     974             : run_optimizer
     975      622729 : bind_optimize_select_and_joins_bottomup(visitor *v, global_props *gp)
     976             : {
     977      622729 :         int flag = v->sql->sql_optimizer;
     978      622533 :         return gp->opt_level == 1 && (gp->cnt[op_join] || gp->cnt[op_left] || gp->cnt[op_right] ||
     979      538664 :                    gp->cnt[op_full] || gp->cnt[op_semi] || gp->cnt[op_anti] ||
     980     1245262 :                    gp->cnt[op_select]) && (flag & optimize_select_and_joins_bottomup) ? rel_optimize_select_and_joins_bottomup : NULL;
     981             : }
     982             : 
     983             : 
     984             : static inline sql_rel *
     985     3424420 : rel_push_join_exps_down(visitor *v, sql_rel *rel)
     986             : {
     987             :         /* push select exps part of join expressions down */
     988             :         /* TODO CHECK WHY not semi enabled */
     989     3424420 :         if ((is_innerjoin(rel->op) || is_left(rel->op) || is_right(rel->op) /*|| is_semi(rel->op)*/) && !list_empty(rel->exps)) {
     990      482219 :                 int left = is_innerjoin(rel->op) || is_right(rel->op) || rel->op == op_semi;
     991      482219 :                 int right = is_innerjoin(rel->op) || is_left(rel->op) || is_semi(rel->op);
     992      482219 :                 sql_rel *jl = rel->l, *ojl = jl, *jr = rel->r, *ojr = jr;
     993             : 
     994      482219 :                 set_processed(jl);
     995      482219 :                 set_processed(jr);
     996     1038089 :                 for (node *n = rel->exps->h; n;) {
     997      555870 :                         node *next = n->next;
     998      555870 :                         sql_exp *e = n->data;
     999             : 
    1000      555870 :                         if (left && rel_rebind_exp(v->sql, jl, e) && !is_any(e)) { /* select expressions on left */
    1001        1335 :                                 if (!is_select(jl->op) || rel_is_ref(jl))
    1002        1325 :                                         rel->l = jl = rel_select(v->sql->sa, jl, NULL);
    1003        1335 :                                 rel_select_add_exp(v->sql->sa, jl, e);
    1004        1335 :                                 list_remove_node(rel->exps, NULL, n);
    1005        1335 :                                 v->changes++;
    1006      554535 :                         } else if (right && rel_rebind_exp(v->sql, jr, e) && !is_any(e)) { /* select expressions on right */
    1007          42 :                                 if (!is_select(jr->op) || rel_is_ref(jr))
    1008          40 :                                         rel->r = jr = rel_select(v->sql->sa, jr, NULL);
    1009          42 :                                 rel_select_add_exp(v->sql->sa, jr, e);
    1010          42 :                                 list_remove_node(rel->exps, NULL, n);
    1011          42 :                                 v->changes++;
    1012             :                         }
    1013             :                         n = next;
    1014             :                 }
    1015      482219 :                 if (ojl != jl)
    1016        1325 :                         set_processed(jl);
    1017      482219 :                 if (ojr != jr)
    1018          40 :                         set_processed(jr);
    1019             :         }
    1020     3424420 :         return rel;
    1021             : }
    1022             : 
    1023             : static inline bool
    1024     3424420 : is_non_trivial_select_applied_to_outer_join(sql_rel *rel)
    1025             : {
    1026     3424420 :         return is_select(rel->op) && rel->exps && is_outerjoin(((sql_rel*) rel->l)->op);
    1027             : }
    1028             : 
    1029             : extern list *list_append_before(list *l, node *n, void *data);
    1030             : 
    1031             : static void replace_column_references_with_nulls_2(mvc *sql, list* crefs, sql_exp* e);
    1032             : 
    1033             : static void
    1034        5525 : replace_column_references_with_nulls_1(mvc *sql, list* crefs, list* exps) {
    1035        5525 :         if (list_empty(exps))
    1036             :                 return;
    1037       14058 :         for(node* n = exps->h; n; n=n->next) {
    1038        8533 :                 sql_exp* e = n->data;
    1039        8533 :                 replace_column_references_with_nulls_2(sql, crefs, e);
    1040             :         }
    1041             : }
    1042             : 
    1043             : static void
    1044       27472 : replace_column_references_with_nulls_2(mvc *sql, list* crefs, sql_exp* e) {
    1045       35042 :         if (e == NULL) {
    1046             :                 return;
    1047             :         }
    1048             : 
    1049       29040 :         switch (e->type) {
    1050        8699 :         case e_column:
    1051             :                 {
    1052        8699 :                         sql_exp *c = NULL;
    1053        8699 :                         if (e->nid)
    1054        8699 :                                 c = exps_bind_nid(crefs, e->nid);
    1055        8699 :                         if (c) {
    1056        2353 :                                 e->type = e_atom;
    1057        2353 :                                 e->l = atom_general(sql->sa, &e->tpe, NULL, 0);
    1058        2353 :                                 e->r = e->f = NULL;
    1059             :                         }
    1060             :                 }
    1061             :                 break;
    1062        9061 :         case e_cmp:
    1063        9061 :                 switch (e->flag) {
    1064        6428 :                 case cmp_gt:
    1065             :                 case cmp_gte:
    1066             :                 case cmp_lte:
    1067             :                 case cmp_lt:
    1068             :                 case cmp_equal:
    1069             :                 case cmp_notequal:
    1070             :                 {
    1071        6428 :                         sql_exp* l = e->l;
    1072        6428 :                         sql_exp* r = e->r;
    1073        6428 :                         sql_exp* f = e->f;
    1074             : 
    1075        6428 :                         replace_column_references_with_nulls_2(sql, crefs, l);
    1076        6428 :                         replace_column_references_with_nulls_2(sql, crefs, r);
    1077        6428 :                         replace_column_references_with_nulls_2(sql, crefs, f);
    1078        6428 :                         break;
    1079             :                 }
    1080        1896 :                 case cmp_filter:
    1081             :                 case cmp_or:
    1082             :                 {
    1083        1896 :                         list* l = e->l;
    1084        1896 :                         list* r = e->r;
    1085        1896 :                         replace_column_references_with_nulls_1(sql, crefs, l);
    1086        1896 :                         replace_column_references_with_nulls_1(sql, crefs, r);
    1087        1896 :                         break;
    1088             :                 }
    1089         737 :                 case cmp_in:
    1090             :                 case cmp_notin:
    1091             :                 {
    1092         737 :                         sql_exp* l = e->l;
    1093         737 :                         list* r = e->r;
    1094         737 :                         replace_column_references_with_nulls_2(sql, crefs, l);
    1095         737 :                         replace_column_references_with_nulls_1(sql, crefs, r);
    1096         737 :                         break;
    1097             :                 }
    1098             :                 default:
    1099             :                         break;
    1100             :                 }
    1101             :                 break;
    1102         996 :         case e_func:
    1103             :         {
    1104         996 :                 list* l = e->l;
    1105         996 :                 replace_column_references_with_nulls_1(sql, crefs, l);
    1106         996 :                 break;
    1107             :         }
    1108        1142 :         case e_convert:
    1109             :         {
    1110        1142 :                 sql_exp* l = e->l;
    1111        1142 :                 replace_column_references_with_nulls_2(sql, crefs, l);
    1112        1142 :                 break;
    1113             :         }
    1114             :         default:
    1115             :                 break;
    1116             :         }
    1117             : }
    1118             : 
    1119             : static sql_rel *
    1120        4864 : out2inner(visitor *v, sql_rel* sel, sql_rel* join, sql_rel* inner_join_side, operator_type new_type) {
    1121             : 
    1122             :         /* handle inner_join relations with a simple select */
    1123        4864 :         if (is_select(inner_join_side->op) && inner_join_side->l)
    1124        4864 :                 inner_join_side = inner_join_side->l;
    1125        4864 :         if (!is_base(inner_join_side->op) && !is_simple_project(inner_join_side->op)) {
    1126             :                 // Nothing to do here.
    1127             :                 return sel;
    1128             :         }
    1129             : 
    1130        4734 :         list* inner_join_column_references = inner_join_side->exps;
    1131        4734 :         list* select_predicates = exps_copy(v->sql, sel->exps);
    1132             : 
    1133        9997 :         for(node* n = select_predicates->h; n; n=n->next) {
    1134        5346 :                 sql_exp* e = n->data;
    1135        5346 :                 replace_column_references_with_nulls_2(v->sql, inner_join_column_references, e);
    1136             : 
    1137        5346 :                 if (exp_is_false(e)) {
    1138          83 :                         join->op = new_type;
    1139          83 :                         v->changes++;
    1140          83 :                         break;
    1141             :                 }
    1142             :         }
    1143             : 
    1144             :         return sel;
    1145             : }
    1146             : 
    1147             : static inline sql_rel *
    1148     3424420 : rel_out2inner(visitor *v, sql_rel *rel) {
    1149             : 
    1150     3424420 :         if (!is_non_trivial_select_applied_to_outer_join(rel)) {
    1151             :                 // Nothing to do here.
    1152             :                 return rel;
    1153             :         }
    1154             : 
    1155        4841 :         sql_rel* join = (sql_rel*) rel->l;
    1156             : 
    1157        4841 :         if (rel_is_ref(join)) {
    1158             :                 /* Do not alter a multi-referenced join relation.
    1159             :                         * This is problematic (e.g. in the case of the plan of a merge statement)
    1160             :                         * basically because there are no guarantees on the other container relations.
    1161             :                         * In particular there is no guarantee that the other referencing relations are
    1162             :                         * select relations with null-rejacting predicates on the inner join side.
    1163             :                         */
    1164             :                 return rel;
    1165             :         }
    1166             : 
    1167        4841 :         sql_rel* inner_join_side;
    1168        4841 :         if (is_left(join->op)) {
    1169        4792 :                 inner_join_side = join->r;
    1170        4792 :                 return out2inner(v, rel, join, inner_join_side, op_join);
    1171             :         }
    1172          49 :         else if (is_right(join->op)) {
    1173          26 :                 inner_join_side = join->l;
    1174          26 :                 return out2inner(v, rel, join, inner_join_side, op_join);
    1175             :         }
    1176             :         else /*full outer join*/ {
    1177             :                 // First check if left side can degenerate from full outer join to just right outer join.
    1178          23 :                 inner_join_side = join->r;
    1179          23 :                 rel = out2inner(v, rel, join, inner_join_side, op_right);
    1180             :                 /* Now test if the right side can degenerate to
    1181             :                         * a normal inner join or a left outer join
    1182             :                         * depending on the result of previous call to out2inner.
    1183             :                         */
    1184             : 
    1185          23 :                 inner_join_side = join->l;
    1186          38 :                 return out2inner(v, rel, join, inner_join_side, is_right(join->op)? op_join: op_left);
    1187             :         }
    1188             : }
    1189             : 
    1190             : static bool
    1191        4219 : exps_uses_any(list *exps, list *l)
    1192             : {
    1193        4219 :         bool uses_any = false;
    1194             : 
    1195        4219 :         if (list_empty(exps) || list_empty(l))
    1196          14 :                 return false;
    1197        8416 :         for (node *n = l->h; n && !uses_any; n = n->next) {
    1198        4211 :                 sql_exp *e = n->data;
    1199        4211 :                 uses_any |= list_exps_uses_exp(exps, exp_relname(e), exp_name(e)) != NULL;
    1200             :         }
    1201             : 
    1202             :         return uses_any;
    1203             : }
    1204             : 
    1205             : /* TODO At the moment I have to disable the new join2semi because the join order optimizer doesn't take semi-joins into account,
    1206             : so plans get deteriorated if more joins are optimized into semi-joins. Later I will review the join order with semi-joins and hopefully,
    1207             : I will be able to re-enable the new join2semi. */
    1208             : #if 0
    1209             : #define NO_EXP_FOUND 0
    1210             : #define FOUND_WITH_DUPLICATES 1
    1211             : #define MAY_HAVE_DUPLICATE_NULLS 2
    1212             : #define ALL_VALUES_DISTINCT 3
    1213             : 
    1214             : static int
    1215             : find_projection_for_join2semi(sql_rel *rel, sql_exp *jc)
    1216             : {
    1217             :         sql_rel *res = NULL;
    1218             :         sql_exp *e = NULL;
    1219             :         bool underjoin = false;
    1220             : 
    1221             :         if ((e = rel_find_exp_and_corresponding_rel(rel, jc, &res, &underjoin))) {
    1222             :                 if (underjoin || e->type != e_column)
    1223             :                         return FOUND_WITH_DUPLICATES;
    1224             :                 /* if just one groupby column is projected or the relation needs distinct values and one column is projected or is a primary key, it will be distinct */
    1225             :                 if (is_unique(e) ||
    1226             :                         (is_groupby(res->op) && list_length(res->r) == 1 && exps_find_exp(res->r, e)) ||
    1227             :                         ((is_project(res->op) || is_base(res->op)) && ((need_distinct(res) && list_length(res->exps) == 1) || res->card < CARD_AGGR)))
    1228             :                         return has_nil(e) ? MAY_HAVE_DUPLICATE_NULLS : ALL_VALUES_DISTINCT;
    1229             :                 return FOUND_WITH_DUPLICATES;
    1230             :         }
    1231             :         return NO_EXP_FOUND;
    1232             : }
    1233             : 
    1234             : static int
    1235             : subrel_uses_exp_outside_subrel(visitor *v, sql_rel *rel, list *l, sql_rel *j)
    1236             : {
    1237             :         if (rel == j)
    1238             :                 return 0;
    1239             :         if (mvc_highwater(v->sql))
    1240             :                 return 1;
    1241             :         switch(rel->op){
    1242             :         case op_join:
    1243             :         case op_left:
    1244             :         case op_right:
    1245             :         case op_full:
    1246             :                 return exps_uses_any(rel->exps, l) ||
    1247             :                         subrel_uses_exp_outside_subrel(v, rel->l, l, j) || subrel_uses_exp_outside_subrel(v, rel->r, l, j);
    1248             :         case op_semi:
    1249             :         case op_anti:
    1250             :         case op_select:
    1251             :                 return exps_uses_any(rel->exps, l) ||
    1252             :                         subrel_uses_exp_outside_subrel(v, rel->l, l, j);
    1253             :         case op_project:
    1254             :         case op_groupby:
    1255             :                 return exps_uses_any(rel->exps, l) || exps_uses_any(rel->r, l);
    1256             :         case op_basetable:
    1257             :         case op_table:
    1258             :         case op_union:
    1259             :         case op_except:
    1260             :         case op_inter:
    1261             :                 return exps_uses_any(rel->exps, l);
    1262             :         case op_topn:
    1263             :         case op_sample:
    1264             :                 return subrel_uses_exp_outside_subrel(v, rel->l, l, j);
    1265             :         default:
    1266             :                 return 1;
    1267             :         }
    1268             : }
    1269             : 
    1270             : static int
    1271             : projrel_uses_exp_outside_subrel(visitor *v, sql_rel *rel, list *l, sql_rel *j)
    1272             : {
    1273             :         /* test if projecting relation uses any of the join expressions */
    1274             :         assert((is_simple_project(rel->op) || is_groupby(rel->op)) && rel->l);
    1275             :         return exps_uses_any(rel->exps, l) || exps_uses_any(rel->r, l) || subrel_uses_exp_outside_subrel(v, rel->l, l, j);
    1276             : }
    1277             : 
    1278             : static sql_rel *
    1279             : rewrite_joins2semi(visitor *v, sql_rel *proj, sql_rel *rel)
    1280             : {
    1281             :         /* generalize possibility : we need the visitor 'step' here */
    1282             :         if (rel_is_ref(rel) || mvc_highwater(v->sql)) /* if the join has multiple references, it's dangerous to convert it into a semijoin */
    1283             :                 return rel;
    1284             :         if (is_innerjoin(rel->op) && !list_empty(rel->exps)) {
    1285             :                 sql_rel *l = rel->l, *r = rel->r;
    1286             :                 bool left_unique = true, right_unique = true;
    1287             : 
    1288             :                 /* these relations don't project anything, so skip them */
    1289             :                 while (is_topn(l->op) || is_sample(l->op) || is_select(l->op) || is_semi(l->op))
    1290             :                         l = l->l;
    1291             :                 /* joins will expand values, so don't search on those */
    1292             :                 if (!is_base(l->op) && !is_project(l->op))
    1293             :                         left_unique = false;
    1294             :                 while (is_topn(r->op) || is_sample(r->op) || is_select(r->op) || is_semi(r->op))
    1295             :                         r = r->l;
    1296             :                 if (!is_base(r->op) && !is_project(r->op))
    1297             :                         right_unique = false;
    1298             :                 /* if all columns used in equi-joins from one of the sides are unique, the join can be rewritten into a semijoin */
    1299             :                 for (node *n=rel->exps->h; n && (left_unique || right_unique); n = n->next) {
    1300             :                         sql_exp *e = n->data, *el = e->l, *er = e->r;
    1301             : 
    1302             :                         if (!is_compare(e->type) || e->flag != cmp_equal || exp_has_func(el) || exp_has_func(er)) {
    1303             :                                 left_unique = right_unique = false;
    1304             :                         } else {
    1305             :                                 int found = 0;
    1306             : 
    1307             :                                 if (left_unique && (found = find_projection_for_join2semi(l, el)) > NO_EXP_FOUND)
    1308             :                                         left_unique &= (found == ALL_VALUES_DISTINCT || (found == MAY_HAVE_DUPLICATE_NULLS && (!is_semantics(e) || !has_nil(er))));
    1309             :                                 if (left_unique && (found = find_projection_for_join2semi(l, er)) > NO_EXP_FOUND)
    1310             :                                         left_unique &= (found == ALL_VALUES_DISTINCT || (found == MAY_HAVE_DUPLICATE_NULLS && (!is_semantics(e) || !has_nil(el))));
    1311             :                                 if (right_unique && (found = find_projection_for_join2semi(r, el)) > NO_EXP_FOUND)
    1312             :                                         right_unique &= (found == ALL_VALUES_DISTINCT || (found == MAY_HAVE_DUPLICATE_NULLS && (!is_semantics(e) || !has_nil(er))));
    1313             :                                 if (right_unique && (found = find_projection_for_join2semi(r, er)) > NO_EXP_FOUND)
    1314             :                                         right_unique &= (found == ALL_VALUES_DISTINCT || (found == MAY_HAVE_DUPLICATE_NULLS && (!is_semantics(e) || !has_nil(el))));
    1315             :                         }
    1316             :                 }
    1317             : 
    1318             :                 /* now we need to check relation's expressions are not used */
    1319             :                 if (left_unique && !projrel_uses_exp_outside_subrel(v, proj, l->exps, rel)) {
    1320             :                         sql_rel *tmp = rel->r;
    1321             :                         rel->r = rel->l;
    1322             :                         rel->l = tmp;
    1323             :                         rel->op = op_semi;
    1324             :                         v->changes++;
    1325             :                 } else if (right_unique && !projrel_uses_exp_outside_subrel(v, proj, r->exps, rel)) {
    1326             :                         rel->op = op_semi;
    1327             :                         v->changes++;
    1328             :                 }
    1329             :         }
    1330             :         if (is_join(rel->op)) {
    1331             :                 rel->l = rewrite_joins2semi(v, proj, rel->l);
    1332             :                 rel->r = rewrite_joins2semi(v, proj, rel->r);
    1333             :         } else if (is_topn(rel->op) || is_sample(rel->op) || is_select(rel->op) || is_semi(rel->op)) {
    1334             :                 rel->l = rewrite_joins2semi(v, proj, rel->l);
    1335             :         }
    1336             :         return rel;
    1337             : }
    1338             : 
    1339             : static inline sql_rel *
    1340             : rel_join2semijoin(visitor *v, sql_rel *rel)
    1341             : {
    1342             :         if ((is_simple_project(rel->op) || is_groupby(rel->op)) && rel->l)
    1343             :                 rel->l = rewrite_joins2semi(v, rel, rel->l);
    1344             :         return rel;
    1345             : }
    1346             : #endif
    1347             : 
    1348             : #define NO_PROJECTION_FOUND 0
    1349             : #define MAY_HAVE_DUPLICATE_NULLS 1
    1350             : #define ALL_VALUES_DISTINCT 2
    1351             : 
    1352             : static int
    1353      703323 : find_projection_for_join2semi(sql_rel *rel)
    1354             : {
    1355      703323 :         if (is_simple_project(rel->op) || is_groupby(rel->op) || is_inter(rel->op) || is_except(rel->op) || is_base(rel->op) || (is_union(rel->op) && need_distinct(rel))) {
    1356      373194 :                 if (rel->card < CARD_AGGR) /* const or groupby without group by exps */
    1357             :                         return ALL_VALUES_DISTINCT;
    1358      372047 :                 if (list_length(rel->exps) == 1) {
    1359        6627 :                         sql_exp *e = rel->exps->h->data;
    1360             :                         /* a single group by column in the projection list from a group by relation is guaranteed to be unique, but not an aggregate */
    1361        6627 :                         if (e->type == e_column) {
    1362        6597 :                                 sql_rel *res = NULL;
    1363        6597 :                                 sql_exp *found = NULL;
    1364        6597 :                                 bool underjoin = false;
    1365             : 
    1366             :                                 /* if just one groupby column is projected or the relation needs distinct values and one column is projected or is a primary key, it will be distinct */
    1367        6597 :                                 if ((is_groupby(rel->op) && list_length(rel->r) == 1 && exps_find_exp(rel->r, e)) || (need_distinct(rel) && list_length(rel->exps) == 1))
    1368        9528 :                                         return ALL_VALUES_DISTINCT;
    1369        2958 :                                 if (is_unique(e))
    1370        2249 :                                         return has_nil(e) ? MAY_HAVE_DUPLICATE_NULLS : ALL_VALUES_DISTINCT;
    1371             : 
    1372         709 :                                 if ((is_simple_project(rel->op) || is_groupby(rel->op) || is_inter(rel->op) || is_except(rel->op)) &&
    1373         129 :                                         (found = rel_find_exp_and_corresponding_rel(rel->l, e, false, &res, &underjoin)) && !underjoin) { /* grouping column on inner relation */
    1374         113 :                                         if (need_distinct(res) && list_length(res->exps) == 1)
    1375             :                                                 return ALL_VALUES_DISTINCT;
    1376         113 :                                         if (is_unique(found))
    1377           0 :                                                 return has_nil(e) ? MAY_HAVE_DUPLICATE_NULLS : ALL_VALUES_DISTINCT;
    1378         113 :                                         if (found->type == e_column && found->card <= CARD_AGGR) {
    1379           1 :                                                 if (!is_groupby(res->op) && list_length(res->exps) != 1)
    1380             :                                                         return NO_PROJECTION_FOUND;
    1381           0 :                                                 for (node *n = res->exps->h ; n ; n = n->next) { /* must be the single column in the group by expression list */
    1382           0 :                                                         sql_exp *e = n->data;
    1383           0 :                                                         if (e != found && e->type == e_column)
    1384             :                                                                 return NO_PROJECTION_FOUND;
    1385             :                                                 }
    1386             :                                                 return ALL_VALUES_DISTINCT;
    1387             :                                         }
    1388             :                                 }
    1389             :                         }
    1390             :                 }
    1391             :         }
    1392             :         return NO_PROJECTION_FOUND;
    1393             : }
    1394             : 
    1395             : static sql_rel *
    1396     2242606 : find_candidate_join2semi(visitor *v, sql_rel *rel, bool *swap)
    1397             : {
    1398             :         /* generalize possibility : we need the visitor 'step' here */
    1399     2243126 :         if (rel_is_ref(rel)) /* if the join has multiple references, it's dangerous to convert it into a semijoin */
    1400             :                 return NULL;
    1401     2125696 :         if (rel->op == op_join && !list_empty(rel->exps) && list_empty(rel->attr)) {
    1402      353828 :                 sql_rel *l = rel->l, *r = rel->r;
    1403      353828 :                 int foundr = NO_PROJECTION_FOUND, foundl = NO_PROJECTION_FOUND, found = NO_PROJECTION_FOUND;
    1404      353828 :                 bool ok = false;
    1405             : 
    1406      353828 :                 foundr = find_projection_for_join2semi(r);
    1407      353828 :                 if (foundr < ALL_VALUES_DISTINCT)
    1408      349495 :                         foundl = find_projection_for_join2semi(l);
    1409      353828 :                 if (foundr && foundr > foundl) {
    1410        4339 :                         *swap = false;
    1411        4339 :                         found = foundr;
    1412      349489 :                 } else if (foundl) {
    1413        2689 :                         *swap = true;
    1414        2689 :                         found = foundl;
    1415             :                 }
    1416             : 
    1417        7028 :                 if (found > NO_PROJECTION_FOUND) {
    1418             :                         /* if all join expressions can be pushed down or have function calls, then it cannot be rewritten into a semijoin */
    1419       14060 :                         for (node *n=rel->exps->h; n && !ok; n = n->next) {
    1420        7032 :                                 sql_exp *e = n->data;
    1421             : 
    1422       10796 :                                 ok |= e->type == e_cmp && e->flag == cmp_equal && !exp_has_func(e) && !rel_rebind_exp(v->sql, l, e) && !rel_rebind_exp(v->sql, r, e) &&
    1423           7 :                                         (found == ALL_VALUES_DISTINCT || !is_semantics(e) || !has_nil((sql_exp *)e->l) || !has_nil((sql_exp *)e->r));
    1424             :                         }
    1425             :                 }
    1426             : 
    1427      353828 :                 if (ok)
    1428             :                         return rel;
    1429             :         }
    1430     2122421 :         if (is_join(rel->op) || is_semi(rel->op)) {
    1431      533265 :                 sql_rel *c;
    1432             : 
    1433      533265 :                 if ((c=find_candidate_join2semi(v, rel->l, swap)) != NULL ||
    1434      532875 :                     (c=find_candidate_join2semi(v, rel->r, swap)) != NULL)
    1435         412 :                         if (list_empty(c->attr))
    1436             :                                 return c;
    1437             :         }
    1438     2122009 :         if (is_topn(rel->op) || is_sample(rel->op))
    1439         520 :                 return find_candidate_join2semi(v, rel->l, swap);
    1440             :         return NULL;
    1441             : }
    1442             : 
    1443             : static int
    1444        2507 : subrel_uses_exp_outside_subrel(sql_rel *rel, list *l, sql_rel *c)
    1445             : {
    1446        2508 :         if (rel == c)
    1447             :                 return 0;
    1448             :         /* for subrel only expect joins (later possibly selects) */
    1449         825 :         if (is_join(rel->op) || is_semi(rel->op)) {
    1450         418 :                 if (exps_uses_any(rel->exps, l))
    1451             :                         return 1;
    1452         818 :                 if (subrel_uses_exp_outside_subrel(rel->l, l, c) ||
    1453         408 :                     subrel_uses_exp_outside_subrel(rel->r, l, c))
    1454           5 :                         return 1;
    1455             :         }
    1456         812 :         if (is_topn(rel->op) || is_sample(rel->op))
    1457           1 :                 return subrel_uses_exp_outside_subrel(rel->l, l, c);
    1458             :         return 0;
    1459             : }
    1460             : 
    1461             : static int
    1462        3275 : rel_uses_exp_outside_subrel(sql_rel *rel, list *l, sql_rel *c)
    1463             : {
    1464             :         /* for now we only expect sub relations of type project, selects (rel) or join/semi */
    1465        3275 :         if (is_simple_project(rel->op) || is_groupby(rel->op) || is_select(rel->op)) {
    1466        3275 :                 if (!list_empty(rel->exps) && exps_uses_any(rel->exps, l))
    1467             :                         return 1;
    1468        1689 :                 if ((is_simple_project(rel->op) || is_groupby(rel->op)) && !list_empty(rel->r) && exps_uses_any(rel->r, l))
    1469             :                         return 1;
    1470        1689 :                 if (rel->l)
    1471        1689 :                         return subrel_uses_exp_outside_subrel(rel->l, l, c);
    1472             :         }
    1473           0 :         if (is_topn(rel->op) || is_sample(rel->op))
    1474           0 :                 return subrel_uses_exp_outside_subrel(rel->l, l, c);
    1475             :         return 1;
    1476             : }
    1477             : 
    1478             : static inline sql_rel *
    1479     3424420 : rel_join2semijoin(visitor *v, sql_rel *rel)
    1480             : {
    1481     3424420 :         if ((is_simple_project(rel->op) || is_groupby(rel->op)) && rel->l) {
    1482     1176466 :                 bool swap = false;
    1483     1176466 :                 sql_rel *l = rel->l;
    1484     1176466 :                 sql_rel *c = find_candidate_join2semi(v, l, &swap);
    1485             : 
    1486     1176466 :                 if (c) {
    1487             :                         /* 'p' is a project */
    1488        3275 :                         sql_rel *p = swap ? c->l : c->r;
    1489             : 
    1490             :                         /* now we need to check if ce is only used at the level of c */
    1491        3275 :                         if (!rel_uses_exp_outside_subrel(rel, p->exps, c)) {
    1492        1681 :                                 c->op = op_semi;
    1493        1681 :                                 if (swap) {
    1494         518 :                                         sql_rel *tmp = c->r;
    1495         518 :                                         c->r = c->l;
    1496         518 :                                         c->l = tmp;
    1497             :                                 }
    1498        1681 :                                 v->changes++;
    1499             :                         }
    1500             :                 }
    1501             :         }
    1502     3424420 :         return rel;
    1503             : }
    1504             : 
    1505             : static inline sql_rel *
    1506     3424420 : rel_push_join_down_outer(visitor *v, sql_rel *rel)
    1507             : {
    1508     3424420 :         if (is_join(rel->op) && !is_outerjoin(rel->op) && !is_single(rel) && !list_empty(rel->exps) && !rel_is_ref(rel)) {
    1509      364350 :                 sql_rel *l = rel->l, *r = rel->r;
    1510             : 
    1511      364350 :                 if (is_left(r->op) && (is_select(l->op) || (is_join(l->op) && !is_outerjoin(l->op))) && !rel_is_ref(l) &&
    1512         887 :                                 !rel_is_ref(r)) {
    1513         887 :                         sql_rel *rl = r->l;
    1514         887 :                         sql_rel *rr = r->r;
    1515         887 :                         if (rel_is_ref(rl) || rel_is_ref(rr))
    1516             :                                 return rel;
    1517             :                         /* join exps should only include l and r.l */
    1518         887 :                         list *njexps = sa_list(v->sql->sa);
    1519        2023 :                         for(node *n = rel->exps->h; n; n = n->next) {
    1520        1136 :                                 sql_exp *je = n->data;
    1521             : 
    1522        1136 :                                 assert(je->type == e_cmp);
    1523        1136 :                                 if (je->f)
    1524             :                                         return rel;
    1525        1136 :                                 if ((rel_find_exp(l, je->l) && rel_find_exp(rl, je->r)) || (rel_find_exp(l, je->r) && rel_find_exp(rl, je->l))) {
    1526        1136 :                                         list_append(njexps, je);
    1527             :                                 } else {
    1528           0 :                                         return rel;
    1529             :                                 }
    1530             :                         }
    1531         887 :                         sql_rel *nl = rel_crossproduct(v->sql->sa, rel_dup(l), rl, rel->op);
    1532         887 :                         r->l = nl;
    1533         887 :                         nl->exps = njexps;
    1534         887 :                         nl->attr = rel->attr;
    1535         887 :                         rel->attr = NULL;
    1536         887 :                         set_processed(nl);
    1537         887 :                         rel_dup(r);
    1538         887 :                         rel_destroy(rel);
    1539         887 :                         rel = r;
    1540         887 :                         v->changes++;
    1541             :                 }
    1542             :         }
    1543             :         return rel;
    1544             : }
    1545             : 
    1546             : static sql_rel *
    1547     3424420 : rel_optimize_joins_(visitor *v, sql_rel *rel)
    1548             : {
    1549     3424420 :         rel = rel_push_join_exps_down(v, rel);
    1550     3424420 :         rel = rel_out2inner(v, rel);
    1551     3424420 :         rel = rel_join2semijoin(v, rel);
    1552     3424420 :         rel = rel_push_join_down_outer(v, rel);
    1553     3424420 :         return rel;
    1554             : }
    1555             : 
    1556             : static sql_rel *
    1557       89049 : rel_optimize_joins(visitor *v, global_props *gp, sql_rel *rel)
    1558             : {
    1559       89049 :         (void) gp;
    1560       89049 :         return rel_visitor_topdown(v, rel, &rel_optimize_joins_);
    1561             : }
    1562             : 
    1563             : run_optimizer
    1564      622727 : bind_optimize_joins(visitor *v, global_props *gp)
    1565             : {
    1566      622727 :         int flag = v->sql->sql_optimizer;
    1567      622531 :         return gp->opt_level == 1 && (gp->cnt[op_join] || gp->cnt[op_left] || gp->cnt[op_right]
    1568     1245258 :                    || gp->cnt[op_full] || gp->cnt[op_semi] || gp->cnt[op_anti]) && (flag & optimize_joins) ? rel_optimize_joins : NULL;
    1569             : }
    1570             : 
    1571             : 
    1572             : static sql_rel *rel_join_order_(visitor *v, sql_rel *rel);
    1573             : 
    1574             : static void
    1575      698933 : get_relations(visitor *v, sql_rel *rel, list *rels)
    1576             : {
    1577      971998 :         if (list_empty(rel->attr) && !rel_is_ref(rel) && rel->op == op_join && rel->exps == NULL) {
    1578      273065 :                 sql_rel *l = rel->l;
    1579      273065 :                 sql_rel *r = rel->r;
    1580             : 
    1581      273065 :                 get_relations(v, l, rels);
    1582      273065 :                 get_relations(v, r, rels);
    1583      273065 :                 rel->l = NULL;
    1584      273065 :                 rel->r = NULL;
    1585      273065 :                 rel_destroy(rel);
    1586             :         } else {
    1587      425868 :                 rel = rel_join_order_(v, rel);
    1588      425868 :                 append(rels, rel);
    1589             :         }
    1590      698933 : }
    1591             : 
    1592             : static void
    1593      188672 : get_inner_relations(mvc *sql, sql_rel *rel, list *rels)
    1594             : {
    1595      299500 :         if (!rel_is_ref(rel) && is_join(rel->op)) {
    1596      110828 :                 sql_rel *l = rel->l;
    1597      110828 :                 sql_rel *r = rel->r;
    1598             : 
    1599      110828 :                 get_inner_relations(sql, l, rels);
    1600      110828 :                 get_inner_relations(sql, r, rels);
    1601             :         } else {
    1602      188672 :                 append(rels, rel);
    1603             :         }
    1604      188672 : }
    1605             : 
    1606             : static int
    1607     1049381 : exp_count(int *cnt, sql_exp *e)
    1608             : {
    1609     1049381 :         int flag;
    1610     1049381 :         if (!e)
    1611             :                 return 0;
    1612     1049381 :         if (find_prop(e->p, PROP_JOINIDX))
    1613        3541 :                 *cnt += 100;
    1614     1049381 :         if (find_prop(e->p, PROP_HASHCOL))
    1615       34204 :                 *cnt += 100;
    1616     1049381 :         if (find_prop(e->p, PROP_HASHIDX))
    1617           0 :                 *cnt += 100;
    1618     1049381 :         switch(e->type) {
    1619      387589 :         case e_cmp:
    1620      387589 :                 if (!is_complex_exp(e->flag)) {
    1621      329367 :                         exp_count(cnt, e->l);
    1622      329367 :                         exp_count(cnt, e->r);
    1623      329367 :                         if (e->f)
    1624        3052 :                                 exp_count(cnt, e->f);
    1625             :                 }
    1626      387589 :                 flag = e->flag;
    1627      387589 :                 switch (flag) {
    1628      305477 :                 case cmp_equal:
    1629      305477 :                         *cnt += 90;
    1630      305477 :                         return 90;
    1631       17390 :                 case cmp_notequal:
    1632       17390 :                         *cnt += 7;
    1633       17390 :                         return 7;
    1634        6500 :                 case cmp_gt:
    1635             :                 case cmp_gte:
    1636             :                 case cmp_lt:
    1637             :                 case cmp_lte:
    1638        6500 :                         *cnt += 6;
    1639        6500 :                         if (e->l) {
    1640        6500 :                                 sql_exp *l = e->l;
    1641        6500 :                                 sql_subtype *t = exp_subtype(l);
    1642        6500 :                                 if (EC_TEMP(t->type->eclass)) /* give preference to temporal ranges */
    1643         172 :                                         *cnt += 90;
    1644             :                         }
    1645        6500 :                         if (e->f){ /* range */
    1646        3052 :                                 *cnt += 6;
    1647        3052 :                                 return 12;
    1648             :                         }
    1649             :                         return 6;
    1650         688 :                 case cmp_filter:
    1651         688 :                         if (exps_card(e->r) > CARD_AGGR) {
    1652             :                                 /* filters for joins are special */
    1653           5 :                                 *cnt += 1000;
    1654           5 :                                 return 1000;
    1655             :                         }
    1656         683 :                         *cnt += 2;
    1657         683 :                         return 2;
    1658       52830 :                 case cmp_in:
    1659             :                 case cmp_notin: {
    1660       52830 :                         list *l = e->r;
    1661       52830 :                         int c = 9 - 10*list_length(l);
    1662       52830 :                         *cnt += c;
    1663       52830 :                         return c;
    1664             :                 }
    1665        4704 :                 case cmp_or: /* prefer or over functions */
    1666        4704 :                         *cnt += 3;
    1667        4704 :                         return 3;
    1668             :                 default:
    1669             :                         return 0;
    1670             :                 }
    1671      522625 :         case e_column:
    1672      522625 :                 *cnt += 20;
    1673      522625 :                 return 20;
    1674      120747 :         case e_atom:
    1675      120747 :                 *cnt += 10;
    1676      120747 :                 return 10;
    1677        2856 :         case e_func:
    1678             :                 /* functions are more expensive, depending on the number of columns involved. */
    1679        2856 :                 if (e->card == CARD_ATOM)
    1680             :                         return 0;
    1681        2565 :                 *cnt -= 5*list_length(e->l);
    1682        2565 :                 return 5*list_length(e->l);
    1683       15564 :         case e_convert:
    1684             :                 /* functions are more expensive, depending on the number of columns involved. */
    1685       15564 :                 if (e->card == CARD_ATOM)
    1686             :                         return 0;
    1687             :                 /* fall through */
    1688             :         default:
    1689       14906 :                 *cnt -= 5;
    1690       14906 :                 return -5;
    1691             :         }
    1692             : }
    1693             : 
    1694             : int
    1695      263922 : exp_keyvalue(sql_exp *e)
    1696             : {
    1697      263922 :         int cnt = 0;
    1698       58510 :         exp_count(&cnt, e);
    1699      263922 :         return cnt;
    1700             : }
    1701             : 
    1702             : static sql_exp *
    1703      737954 : joinexp_col(sql_exp *e, sql_rel *r)
    1704             : {
    1705      737954 :         if (e->type == e_cmp) {
    1706      737954 :                 if (rel_has_exp(r, e->l, false) >= 0)
    1707      394733 :                         return e->l;
    1708      343221 :                 return e->r;
    1709             :         }
    1710           0 :         assert(0);
    1711             :         return NULL;
    1712             : }
    1713             : 
    1714             : static sql_column *
    1715      487980 : table_colexp(sql_exp *e, sql_rel *r)
    1716             : {
    1717      487980 :         sql_table *t = r->l;
    1718             : 
    1719      487980 :         if (e->type == e_column) {
    1720      474067 :                 const char *name = exp_name(e);
    1721      474067 :                 node *cn;
    1722             : 
    1723      474067 :                 if (r->exps) { /* use alias */
    1724      886838 :                         for (cn = r->exps->h; cn; cn = cn->next) {
    1725      882526 :                                 sql_exp *ce = cn->data;
    1726      882526 :                                 if (strcmp(exp_name(ce), name) == 0) {
    1727      469755 :                                         name = ce->r;
    1728      469755 :                                         break;
    1729             :                                 }
    1730             :                         }
    1731             :                 }
    1732     1039510 :                 for (cn = ol_first_node(t->columns); cn; cn = cn->next) {
    1733     1035198 :                         sql_column *c = cn->data;
    1734     1035198 :                         if (strcmp(c->base.name, name) == 0)
    1735      469755 :                                 return c;
    1736             :                 }
    1737             :         }
    1738             :         return NULL;
    1739             : }
    1740             : 
    1741             : static list *
    1742      354833 : matching_joins(allocator *sa, list *rels, list *exps, sql_exp *je)
    1743             : {
    1744      354833 :         sql_rel *l, *r;
    1745             : 
    1746      354833 :         assert (je->type == e_cmp);
    1747             : 
    1748      354833 :         l = find_rel(rels, je->l);
    1749      354833 :         r = find_rel(rels, je->r);
    1750      354833 :         if (l && r) {
    1751      354689 :                 list *res;
    1752      354689 :                 list *n_rels = sa_list(sa);
    1753             : 
    1754      354689 :                 append(n_rels, l);
    1755      354689 :                 append(n_rels, r);
    1756      354689 :                 res = list_select(exps, n_rels, (fcmp) &exp_joins_rels, (fdup)NULL);
    1757      354689 :                 return res;
    1758             :         }
    1759         144 :         return sa_list(sa);
    1760             : }
    1761             : 
    1762             : static int
    1763        6373 : sql_column_kc_cmp(sql_column *c, sql_kc *kc)
    1764             : {
    1765             :         /* return on equality */
    1766        6373 :         return (c->colnr - kc->c->colnr);
    1767             : }
    1768             : 
    1769             : static sql_idx *
    1770      458689 : find_fk_index(mvc *sql, sql_table *l, list *lcols, sql_table *r, list *rcols)
    1771             : {
    1772      458689 :         sql_trans *tr = sql->session->tr;
    1773             : 
    1774      458689 :         if (l->idxs) {
    1775      458689 :                 node *in;
    1776      545597 :                 for (in = ol_first_node(l->idxs); in; in = in->next){
    1777       87748 :                         sql_idx *li = in->data;
    1778       87748 :                         if (li->type == join_idx) {
    1779        8717 :                                 sql_key *rk = (sql_key*)os_find_id(tr->cat->objects, tr, ((sql_fkey*)li->key)->rkey);
    1780        8717 :                                 fcmp cmp = (fcmp)&sql_column_kc_cmp;
    1781             : 
    1782        9666 :                                 if (rk->t == r &&
    1783        1789 :                                         list_match(lcols, li->columns, cmp) == 0 &&
    1784         840 :                                         list_match(rcols, rk->columns, cmp) == 0) {
    1785         840 :                                         return li;
    1786             :                                 }
    1787             :                         }
    1788             :                 }
    1789             :         }
    1790             :         return NULL;
    1791             : }
    1792             : 
    1793             : static sql_rel *
    1794      709666 : find_basetable( sql_rel *r)
    1795             : {
    1796     1062083 :         if (!r)
    1797             :                 return NULL;
    1798     1054485 :         switch(r->op) {
    1799      570787 :         case op_basetable:
    1800      570787 :                 if (!r->l)
    1801           0 :                         return NULL;
    1802             :                 return r;
    1803      352417 :         case op_semi:
    1804             :         case op_anti:
    1805             :         case op_project:
    1806             :         case op_select:
    1807             :         case op_topn:
    1808             :         case op_sample:
    1809      352417 :                 return find_basetable(r->l);
    1810             :         default:
    1811             :                 return NULL;
    1812             :         }
    1813             : }
    1814             : 
    1815             : static int
    1816       97892 : exps_count(list *exps)
    1817             : {
    1818       97892 :         node *n;
    1819       97892 :         int cnt = 0;
    1820             : 
    1821       97892 :         if (!exps)
    1822             :                 return 0;
    1823      221565 :         for (n = exps->h; n; n=n->next)
    1824      123673 :                 exp_count(&cnt, n->data);
    1825       97892 :         return cnt;
    1826             : }
    1827             : 
    1828             : static list *
    1829      253320 : order_join_expressions(mvc *sql, list *dje, list *rels)
    1830             : {
    1831      253320 :         node *n;
    1832      253320 :         int cnt = list_length(dje);
    1833             : 
    1834      253320 :         if (cnt <= 1)
    1835             :                 return dje;
    1836             : 
    1837       65229 :         list *res = sa_list(sql->sa);
    1838       65229 :         int i, *keys = SA_NEW_ARRAY(sql->ta, int, cnt);
    1839       65229 :         void **data = SA_NEW_ARRAY(sql->ta, void*, cnt);
    1840             : 
    1841      270641 :         for (n = dje->h, i = 0; n; n = n->next, i++) {
    1842      205412 :                 sql_exp *e = n->data;
    1843             : 
    1844      205412 :                 keys[i] = exp_keyvalue(e);
    1845             :                 /* add some weight for the selections */
    1846      205412 :                 if (e->type == e_cmp && !is_complex_exp(e->flag)) {
    1847      205386 :                         sql_rel *l = find_rel(rels, e->l);
    1848      205386 :                         sql_rel *r = find_rel(rels, e->r);
    1849             : 
    1850      205386 :                         if (l && is_select(l->op) && l->exps)
    1851       52498 :                                 keys[i] += list_length(l->exps)*10 + exps_count(l->exps);
    1852      205386 :                         if (r && is_select(r->op) && r->exps)
    1853       45394 :                                 keys[i] += list_length(r->exps)*10 + exps_count(r->exps);
    1854             :                 }
    1855      205412 :                 data[i] = n->data;
    1856             :         }
    1857             :         /* sort descending */
    1858       65229 :         GDKqsort(keys, data, NULL, cnt, sizeof(int), sizeof(void *), TYPE_int, true, true);
    1859      335870 :         for(i=0; i<cnt; i++) {
    1860      205412 :                 list_append(res, data[i]);
    1861             :         }
    1862             :         return res;
    1863             : }
    1864             : 
    1865             : static int
    1866      236885 : find_join_rels(list **L, list **R, list *exps, list *rels)
    1867             : {
    1868      236885 :         node *n;
    1869             : 
    1870      236885 :         *L = sa_list(exps->sa);
    1871      236885 :         *R = sa_list(exps->sa);
    1872      236885 :         if (!exps || list_length(exps) <= 1)
    1873             :                 return -1;
    1874      288697 :         for(n = exps->h; n; n = n->next) {
    1875      217853 :                 sql_exp *e = n->data;
    1876      217853 :                 sql_rel *l = NULL, *r = NULL;
    1877             : 
    1878      217853 :                 if (!is_complex_exp(e->flag)){
    1879      217846 :                         l = find_rel(rels, e->l);
    1880      217846 :                         r = find_rel(rels, e->r);
    1881             :                 }
    1882      217846 :                 if (l<r) {
    1883      140967 :                         list_append(*L, l);
    1884      140967 :                         list_append(*R, r);
    1885             :                 } else {
    1886       76886 :                         list_append(*L, r);
    1887       76886 :                         list_append(*R, l);
    1888             :                 }
    1889             :         }
    1890             :         return 0;
    1891             : }
    1892             : 
    1893             : static list *
    1894       70844 : distinct_join_exps(list *aje, list *lrels, list *rrels)
    1895             : {
    1896       70844 :         node *n, *m, *o, *p;
    1897       70844 :         int len = list_length(aje), i, j;
    1898       70844 :         char *used = SA_ZNEW_ARRAY(aje->sa, char, len);
    1899       70844 :         list *res = sa_list(aje->sa);
    1900             : 
    1901       70844 :         assert(len == list_length(lrels));
    1902      288697 :         for(n = lrels->h, m = rrels->h, j = 0; n && m;
    1903      217853 :             n = n->next, m = m->next, j++) {
    1904      217853 :                 if (n->data && m->data)
    1905      946679 :                 for(o = n->next, p = m->next, i = j+1; o && p;
    1906      728878 :                     o = o->next, p = p->next, i++) {
    1907      728878 :                         if (o->data == n->data && p->data == m->data)
    1908       30277 :                                 used[i] = 1;
    1909             :                 }
    1910             :         }
    1911      288697 :         for (i = 0, n = aje->h; i < len; n = n->next, i++) {
    1912      217853 :                 if (!used[i])
    1913      192667 :                         list_append(res, n->data);
    1914             :         }
    1915       70844 :         return res;
    1916             : }
    1917             : 
    1918             : static list *
    1919      236885 : find_fk( mvc *sql, list *rels, list *exps)
    1920             : {
    1921      236885 :         node *djn;
    1922      236885 :         list *sdje, *aje, *dje;
    1923      236885 :         list *lrels, *rrels;
    1924             : 
    1925             :         /* first find the distinct join expressions */
    1926      236885 :         aje = list_select(exps, rels, (fcmp) &exp_is_join, (fdup)NULL);
    1927             :         /* add left/right relation */
    1928      236885 :         if (find_join_rels(&lrels, &rrels, aje, rels) < 0)
    1929             :                 dje = aje;
    1930             :         else
    1931       70844 :                 dje = distinct_join_exps(aje, lrels, rrels);
    1932      595218 :         for(djn=dje->h; djn; djn = djn->next) {
    1933             :                 /* equal join expressions */
    1934      358426 :                 sql_idx *idx = NULL;
    1935      358426 :                 sql_exp *je = djn->data, *le = je->l, *re = je->r;
    1936             : 
    1937      358426 :                 if (is_complex_exp(je->flag))
    1938             :                         break;
    1939      358333 :                 if (!find_prop(je->p, PROP_JOINIDX)) {
    1940      354833 :                         int swapped = 0;
    1941      354833 :                         list *aaje = matching_joins(sql->sa, rels, aje, je);
    1942      354833 :                         list *eje = list_select(aaje, (void*)1, (fcmp) &exp_is_eqjoin, (fdup)NULL);
    1943      354833 :                         sql_rel *lr = find_rel(rels, le), *olr = lr;
    1944      354833 :                         sql_rel *rr = find_rel(rels, re), *orr = rr;
    1945      354833 :                         sql_rel *bt = NULL;
    1946      354833 :                         char *iname;
    1947             : 
    1948      354833 :                         sql_table *l, *r;
    1949      354833 :                         list *lexps = list_map(eje, lr, (fmap) &joinexp_col);
    1950      354833 :                         list *rexps = list_map(eje, rr, (fmap) &joinexp_col);
    1951      354833 :                         list *lcols, *rcols;
    1952             : 
    1953      354833 :                         lr = find_basetable(lr);
    1954      354833 :                         rr = find_basetable(rr);
    1955      354833 :                         if (!lr || !rr)
    1956      232342 :                                 continue;
    1957      247647 :                         l = lr->l;
    1958      247647 :                         r = rr->l;
    1959      247647 :                         lcols = list_map(lexps, lr, (fmap) &table_colexp);
    1960      247647 :                         rcols = list_map(rexps, rr, (fmap) &table_colexp);
    1961      247647 :                         lcols->destroy = NULL;
    1962      247647 :                         rcols->destroy = NULL;
    1963      247647 :                         if (list_length(lcols) != list_length(rcols))
    1964       17969 :                                 continue;
    1965             : 
    1966      229678 :                         idx = find_fk_index(sql, l, lcols, r, rcols);
    1967      229678 :                         if (!idx) {
    1968      229011 :                                 idx = find_fk_index(sql, r, rcols, l, lcols);
    1969      229011 :                                 swapped = 1;
    1970             :                         }
    1971             : 
    1972      229678 :                         if (idx && (iname = sa_strconcat( sql->sa, "%", idx->base.name)) != NULL &&
    1973         667 :                                    ((!swapped && name_find_column(olr, NULL, iname, -2, &bt) == NULL) ||
    1974         173 :                                     ( swapped && name_find_column(orr, NULL, iname, -2, &bt) == NULL)))
    1975             :                                 idx = NULL;
    1976             : 
    1977             :                         if (idx) {
    1978         751 :                                 prop *p;
    1979         751 :                                 node *n;
    1980         751 :                                 sql_exp *t = NULL, *i = NULL;
    1981             : 
    1982         751 :                                 if (list_length(lcols) > 1 || !mvc_debug_on(sql, 512)) {
    1983             : 
    1984             :                                         /* Add join between idx and TID */
    1985         751 :                                         if (swapped) {
    1986         155 :                                                 sql_exp *s = je->l, *l = je->r;
    1987             : 
    1988         155 :                                                 t = rel_find_column(sql, olr, s->l, TID);
    1989         155 :                                                 i = rel_find_column(sql, orr, l->l, iname);
    1990         155 :                                                 if (!t || !i)
    1991           1 :                                                         continue;
    1992         154 :                                                 t->p = NULL;
    1993         154 :                                                 i->p = NULL;
    1994         154 :                                                 je = exp_compare(sql->sa, i, t, cmp_equal);
    1995             :                                         } else {
    1996         596 :                                                 sql_exp *s = je->r, *l = je->l;
    1997             : 
    1998         596 :                                                 t = rel_find_column(sql, orr, s->l, TID);
    1999         596 :                                                 i = rel_find_column(sql, olr, l->l, iname);
    2000         596 :                                                 if (!t || !i)
    2001           0 :                                                         continue;
    2002         596 :                                                 t->p = NULL;
    2003         596 :                                                 i->p = NULL;
    2004         596 :                                                 je = exp_compare(sql->sa, i, t, cmp_equal);
    2005             :                                         }
    2006             : 
    2007             :                                         /* Remove all join expressions */
    2008        1502 :                                         for (n = eje->h; n; n = n->next)
    2009         752 :                                                 list_remove_data(exps, NULL, n->data);
    2010         750 :                                         append(exps, je);
    2011         750 :                                         djn->data = je;
    2012           0 :                                 } else if (swapped) { /* else keep je for single column expressions */
    2013           0 :                                         je = exp_compare(sql->sa, je->r, je->l, cmp_equal);
    2014             :                                         /* Remove all join expressions */
    2015           0 :                                         for (n = eje->h; n; n = n->next)
    2016           0 :                                                 list_remove_data(exps, NULL, n->data);
    2017           0 :                                         append(exps, je);
    2018           0 :                                         djn->data = je;
    2019             :                                 }
    2020         750 :                                 je->p = p = prop_create(sql->sa, PROP_JOINIDX, je->p);
    2021         750 :                                 p->value.pval = idx;
    2022             :                         }
    2023             :                 }
    2024             :         }
    2025             : 
    2026             :         /* sort expressions on weighted number of reducing operators */
    2027      236885 :         sdje = order_join_expressions(sql, dje, rels);
    2028      236885 :         return sdje;
    2029             : }
    2030             : 
    2031             : static int
    2032      547750 : rels_find_one_rel( sql_rel **rels, int nr, sql_exp *e)
    2033             : {
    2034      547750 :         int fnd = 0;
    2035             : 
    2036     4402330 :         for(int i = 1; i<=nr; i++) {
    2037     3854646 :                 if (rel_has_exp(rels[i], e, false) == 0) {
    2038      547509 :                         if (fnd)
    2039             :                                 return 0;
    2040             :                         fnd = i;
    2041             :                 }
    2042             :         }
    2043             :         return fnd;
    2044             : }
    2045             : 
    2046             : /* TODO move popcount and popcount64 into gdk_*.h, used in gdk_cand, strimps and here */
    2047             : static inline int
    2048             : popcount64(uint64_t x)
    2049             : {
    2050             : #ifdef __has_builtin
    2051             : #if __has_builtin(__builtin_popcountll)
    2052             :         return (uint32_t) __builtin_popcountll(x);
    2053             : #define BUILTIN_USED
    2054             : #endif
    2055             : #endif
    2056             : #ifndef BUILTIN_USED
    2057             : #if defined(_MSC_VER)
    2058             : #if SIZEOF_OID == 4
    2059             :         /* no __popcnt64 on 32 bit Windows */
    2060             :         return (int) (__popcnt((uint32_t) x) + __popcnt((uint32_t) (x >> 32)));
    2061             : #else
    2062             :         return (uint32_t) __popcnt64(x);
    2063             : #endif
    2064             : #else
    2065             :         x = (x & UINT64_C(0x5555555555555555)) + ((x >> 1) & UINT64_C(0x5555555555555555));
    2066             :         x = (x & UINT64_C(0x3333333333333333)) + ((x >> 2) & UINT64_C(0x3333333333333333));
    2067             :         x = (x & UINT64_C(0x0F0F0F0F0F0F0F0F)) + ((x >> 4) & UINT64_C(0x0F0F0F0F0F0F0F0F));
    2068             :         return (x * UINT64_C(0x0101010101010101)) >> 56;
    2069             : #endif
    2070             : #endif
    2071             : #undef BUILTIN_USED
    2072             : }
    2073             : 
    2074             : static sql_rel *
    2075      152803 : order_joins(visitor *v, list *rels, list *exps)
    2076             : {
    2077      152803 :         sql_rel *top = NULL, *l = NULL, *r = NULL;
    2078      152803 :         sql_exp *cje;
    2079      152803 :         node *djn;
    2080      152803 :         list *sdje, *n_rels = NULL;
    2081      152803 :         int fnd = 0;
    2082      152803 :         unsigned int rsingle;
    2083      152803 :         int direct = 1;
    2084             : 
    2085             :         /* find foreign keys and reorder the expressions on reducing quality */
    2086      152803 :         sdje = find_fk(v->sql, rels, exps);
    2087             : 
    2088      426573 :         for(djn = sdje->h; djn; djn = djn->next ) {
    2089      273770 :                 sql_exp *e = djn->data;
    2090      273770 :                 list_remove_data(exps, NULL, e);
    2091             :         }
    2092      152803 :         if (list_length(rels) > 2 && mvc_debug_on(v->sql, 256)) {
    2093           0 :                 top =  rel_planner(v->sql, rels, sdje, exps);
    2094           0 :                 return top;
    2095             :         }
    2096             : 
    2097      152803 :         int nr_exps = list_length(sdje), nr_rels = list_length(rels), ci = 1;
    2098      152803 :         if (nr_rels > 64) {
    2099           1 :                 direct = 0;
    2100           1 :                 n_rels = sa_list(v->sql->ta);
    2101             :         }
    2102      152803 :         sql_rel **rels_a = SA_NEW_ARRAY(v->sql->ta, sql_rel*, nr_rels+1); /* don't use slot 0 */
    2103      152803 :         rels_a[0] = NULL;
    2104      578671 :         for (node *n = rels->h; n; n = n->next, ci++) {
    2105      425868 :                 rels_a[ci] = n->data;
    2106             :         }
    2107      152803 :         ulng *h = SA_NEW_ARRAY(v->sql->ta, ulng, nr_exps), rel_mask = 0;  /* bit field (for > 64 its an imprint) */
    2108      152803 :         uint16_t *r1 = SA_NEW_ARRAY(v->sql->ta, uint16_t, nr_exps);
    2109      152803 :         uint16_t *r2 = SA_NEW_ARRAY(v->sql->ta, uint16_t, nr_exps);
    2110             :         /* change r3 into rest list's */
    2111      152803 :         int *r3 = SA_NEW_ARRAY(v->sql->ta, int, nr_exps);
    2112             : 
    2113      152803 :         ci = 0;
    2114      426573 :         for (node *n = sdje->h; n; n = n->next, ci++) {
    2115      273770 :                 sql_exp *cje = n->data;
    2116             : 
    2117      273770 :                 h[ci] = r1[ci] = r2[ci] = 0;
    2118      273770 :                 r3[ci] = 0;
    2119             :                 /* h[ci] = exp_find_rels(cje, rels) */
    2120      273770 :                 if (cje->type != e_cmp || is_complex_exp(cje->flag) || !find_prop(cje->p, PROP_HASHCOL) ||
    2121          29 :                    (cje->type == e_cmp && cje->f == NULL)) {
    2122      273770 :                         cje->tmp = ci;
    2123      273770 :                         r1[ci] = rels_find_one_rel(rels_a, nr_rels, cje->l);
    2124      273770 :                         r2[ci] = rels_find_one_rel(rels_a, nr_rels, cje->r);
    2125      273770 :                         if (r1[ci])
    2126      273636 :                                 h[ci] |= ((ulng)1)<<((r1[ci]-1)%64);
    2127      273770 :                         if (r2[ci])
    2128      273617 :                                 h[ci] |= ((ulng)1)<<((r2[ci]-1)%64);
    2129      273770 :                         if (cje->f) {
    2130         210 :                                 r3[ci] = rels_find_one_rel(rels_a, nr_rels, cje->f);
    2131         210 :                                 if (r3[ci] == r2[ci])
    2132         190 :                                         r3[ci] = 0;
    2133         210 :                                 if (r3[ci])
    2134          10 :                                         h[ci] |= ((ulng)1)<<((r3[ci]-1)%64);
    2135             :                         }
    2136             :                 }
    2137             :         }
    2138             :         /* open problem, some expressions use more than 2 relations */
    2139             :         /* For example a.x = b.y * c.z; */
    2140      152803 :         if (list_length(rels) >= 2 && sdje->h) {
    2141             :                 /* get the first expression */
    2142      152781 :                 cje = sdje->h->data;
    2143             : 
    2144             :                 /* find the involved relations */
    2145             : 
    2146             :                 /* complex expressions may touch multiple base tables
    2147             :                  * Should be pushed up to extra selection.
    2148             :                  * */
    2149      152781 :                 if (0 && popcount64(h[cje->tmp]) > 2)
    2150             :                         assert(0);
    2151      152781 :                 if (cje->type != e_cmp || is_complex_exp(cje->flag) || !find_prop(cje->p, PROP_HASHCOL) ||
    2152          29 :                    (cje->type == e_cmp && cje->f == NULL)) {
    2153      152781 :                         l = rels_a[r1[cje->tmp]];
    2154      152781 :                         r = rels_a[r2[cje->tmp]];
    2155      152781 :                         rel_mask |= h[cje->tmp];
    2156             :                 }
    2157      152781 :                 cje->tmp = 0;
    2158             : 
    2159      152781 :                 if (l && r && l != r)
    2160      152650 :                         list_remove_data(sdje, NULL, cje);
    2161             :         }
    2162      152803 :         if (l && r && l != r) {
    2163      152650 :                 list_remove_data(rels, NULL, l);
    2164      152650 :                 list_remove_data(rels, NULL, r);
    2165      152650 :                 if (!direct) {
    2166           1 :                         list_append(n_rels, l);
    2167           1 :                         list_append(n_rels, r);
    2168             :                 }
    2169             : 
    2170             :                 /* Create a relation between l and r. Since the calling
    2171             :                    functions rewrote the join tree, into a list of expressions
    2172             :                    and a list of (simple) relations, there are no outer joins
    2173             :                    involved, we can simply do a crossproduct here.
    2174             :                  */
    2175      152650 :                 rsingle = is_single(r);
    2176      152650 :                 reset_single(r);
    2177      152650 :                 top = rel_crossproduct(v->sql->sa, l, r, op_join);
    2178      152650 :                 if (rsingle)
    2179        5088 :                         set_single(r);
    2180      152650 :                 rel_join_add_exp(v->sql->sa, top, cje);
    2181             : 
    2182             :                 /* all other join expressions on these 2 relations */
    2183      156969 :                 for (node *en = exps->h; en; ) {
    2184        4319 :                         node *next = en->next;
    2185        4319 :                         sql_exp *e = en->data;
    2186        4319 :                         if (rel_rebind_exp(v->sql, top, e)) {
    2187        4141 :                                 rel_join_add_exp(v->sql->sa, top, e);
    2188        4141 :                                 list_remove_data(exps, NULL, e);
    2189             :                         }
    2190             :                         en = next;
    2191             :                 }
    2192             :                 fnd = 1;
    2193             :         }
    2194             :         /* build join tree using the ordered list */
    2195      270533 :         while(list_length(sdje) && fnd) {
    2196      117730 :                 fnd = 0;
    2197             :                 /* find the first expression which could be added */
    2198      872448 :                 for(djn = sdje->h; djn && !fnd && rels->h; djn = (!fnd)?djn->next:NULL) {
    2199      377359 :                         node *en;
    2200      377359 :                         l = r = NULL;
    2201             : 
    2202      377359 :                         cje = djn->data;
    2203      377359 :                         if ((h[cje->tmp] & rel_mask) > 0) {
    2204      117652 :                                 if (rel_mask & (((ulng)1)<<((r1[cje->tmp]-1)%64)))
    2205       66325 :                                         l = rels_a[r1[cje->tmp]];
    2206      117652 :                                 if (rel_mask & (((ulng)1)<<((r2[cje->tmp]-1)%64)))
    2207       51328 :                                         r = rels_a[r2[cje->tmp]];
    2208             :                         }
    2209      377359 :                         if (!direct) { /* check if at least one side in n_rels */
    2210        1040 :                                 if (l && !list_find(n_rels, l, NULL))
    2211        1007 :                                         l = NULL;
    2212        1040 :                                 if (r && !list_find(n_rels, r, NULL))
    2213           1 :                                         r = NULL;
    2214             :                         }
    2215             : 
    2216      377359 :                         if (l && r) {
    2217           0 :                                 assert(0);
    2218             :                                 /* create a selection on the current */
    2219             :                                 rel_join_add_exp(v->sql->sa, top, cje);
    2220             :                                 fnd = 1;
    2221      377359 :                         } else if (l || r) {
    2222             :                                 /* TODO: handle case for joins which need > 2 relations, ie where the current 'top' of the
    2223             :                                  * join tree needs to add more then one relation */
    2224      117652 :                                 rel_mask |= h[cje->tmp];
    2225      117652 :                                 if (l) {
    2226       66325 :                                         r = rels_a[r2[cje->tmp]];
    2227             :                                 } else {
    2228       51327 :                                         l = r;
    2229       51327 :                                         r = rels_a[r1[cje->tmp]];
    2230             :                                 }
    2231      117652 :                                 if (!r) {
    2232           0 :                                         fnd = 1; /* not really, but this bails out */
    2233           0 :                                         list_remove_data(sdje, NULL, cje); /* handle later as select */
    2234           0 :                                         continue;
    2235             :                                 }
    2236             : 
    2237             :                                 /* remove the expression from the lists */
    2238      117652 :                                 list_remove_data(sdje, NULL, cje);
    2239             : 
    2240      117652 :                                 list_remove_data(rels, NULL, r);
    2241      117652 :                                 if (!direct)
    2242          63 :                                         append(n_rels, r);
    2243             : 
    2244             :                                 /* create a join using the current expression */
    2245      117652 :                                 rsingle = is_single(r);
    2246      117652 :                                 reset_single(r);
    2247      117652 :                                 top = rel_crossproduct(v->sql->sa, top, r, op_join);
    2248      117652 :                                 if (rsingle)
    2249           0 :                                         set_single(r);
    2250      117652 :                                 rel_join_add_exp(v->sql->sa, top, cje);
    2251             : 
    2252             :                                 /* all join expressions on these tables */
    2253      118059 :                                 for (en = exps->h; en; ) {
    2254         407 :                                         node *next = en->next;
    2255         407 :                                         sql_exp *e = en->data;
    2256         407 :                                         if (rel_rebind_exp(v->sql, top, e)) {
    2257         176 :                                                 rel_join_add_exp(v->sql->sa, top, e);
    2258         176 :                                                 list_remove_data(exps, NULL, e);
    2259             :                                         }
    2260             :                                         en = next;
    2261             :                                 }
    2262             :                                 /* Remove other joins on the current 'n_rels'
    2263             :                                    set in the distinct list too */
    2264      691192 :                                 for (en = sdje->h; en; ) {
    2265      573540 :                                         node *next = en->next;
    2266      573540 :                                         sql_exp *e = en->data;
    2267      573540 :                                         if ((direct && ((e->flag <= cmp_notequal && (h[e->tmp] & rel_mask) == h[e->tmp]) || (e->flag > cmp_notequal && rel_rebind_exp(v->sql, top, e))))  ||
    2268        1953 :                                             (!direct && rel_rebind_exp(v->sql, top, e))) {
    2269        3248 :                                                 rel_join_add_exp(v->sql->sa, top, e);
    2270        3248 :                                                 list_remove_data(sdje, NULL, en->data);
    2271             :                                         }
    2272             :                                         en = next;
    2273             :                                 }
    2274             :                                 fnd = 1;
    2275             :                         }
    2276             :                 }
    2277             :         }
    2278      152803 :         if (list_length(rels)) { /* more relations */
    2279        1192 :                 node *n;
    2280        4108 :                 for(n=rels->h; n; n = n->next) {
    2281        2916 :                         sql_rel *nr = n->data;
    2282             : 
    2283        2916 :                         if (top) {
    2284        2763 :                                 rsingle = is_single(nr);
    2285        2763 :                                 reset_single(nr);
    2286        2763 :                                 top = rel_crossproduct(v->sql->sa, top, nr, op_join);
    2287        2763 :                                 if (rsingle)
    2288           0 :                                         set_single(nr);
    2289             :                         } else
    2290             :                                 top = nr;
    2291             :                 }
    2292             :         }
    2293      152803 :         if (list_length(sdje)) {
    2294         209 :                 if (list_empty(exps))
    2295             :                         exps = sdje;
    2296             :                 else
    2297           0 :                         exps = list_merge(exps, sdje, (fdup)NULL);
    2298             :         }
    2299      152803 :         if (list_length(exps)) { /* more expressions (add selects) */
    2300         233 :                 top = rel_select(v->sql->sa, top, NULL);
    2301         477 :                 for(node *n=exps->h; n; n = n->next) {
    2302         244 :                         sql_exp *e = n->data;
    2303             : 
    2304         244 :                         if (exp_is_join_exp(e) == 0) {
    2305         232 :                                 sql_rel *nr = NULL;
    2306         232 :                                 if (is_theta_exp(e->flag)) {
    2307         144 :                                         nr = rel_push_join(v->sql, top->l, e->l, e->r, e->f, e, 0);
    2308          88 :                                 } else if (e->flag == cmp_filter || e->flag == cmp_or) {
    2309          88 :                                         sql_exp *l = exps_find_one_multi_exp(e->l), *r = exps_find_one_multi_exp(e->r);
    2310          88 :                                         if (l && r)
    2311          82 :                                                 nr = rel_push_join(v->sql, top->l, l, r, NULL, e, 0);
    2312             :                                 }
    2313         226 :                                 if (!nr)
    2314           6 :                                         rel_join_add_exp(v->sql->sa, top->l, e);
    2315             :                         } else
    2316          12 :                                 rel_select_add_exp(v->sql->sa, top, e);
    2317             :                 }
    2318         233 :                 if (list_empty(top->exps)) { /* empty select */
    2319         221 :                         sql_rel *l = top->l;
    2320         221 :                         top->l = NULL;
    2321         221 :                         rel_destroy(top);
    2322         221 :                         top = l;
    2323             :                 }
    2324             :         }
    2325             :         return top;
    2326             : }
    2327             : 
    2328             : static int
    2329      425868 : rel_neg_in_size(sql_rel *r)
    2330             : {
    2331      425868 :         if ((is_union(r->op) /*|| is_munion(r->op)*/) && r->nrcols == 0)
    2332           0 :                 return -1 + rel_neg_in_size(r->l);
    2333      425868 :         if (is_project(r->op) && r->nrcols == 0)
    2334           0 :                 return -1;
    2335             :         return 0;
    2336             : }
    2337             : 
    2338      425868 : static void _rel_destroy(void *dummy, sql_rel *rel)
    2339             : {
    2340      425868 :         (void)dummy;
    2341      425868 :         rel_destroy(rel);
    2342      425868 : }
    2343             : 
    2344             : static list *
    2345      152803 : push_in_join_down(mvc *sql, list *rels, list *exps)
    2346             : {
    2347      152803 :         node *n;
    2348      152803 :         int restart = 1;
    2349      152803 :         list *nrels;
    2350             : 
    2351             :         /* we should sort these first, ie small in's before large one's */
    2352      152803 :         nrels = list_sort(rels, (fkeyvalue)&rel_neg_in_size, (fdup)&rel_dup);
    2353             : 
    2354             :         /* we need to cleanup, the new refs ! */
    2355      152803 :         rels->destroy = (fdestroy)_rel_destroy;
    2356      152803 :         list_destroy(rels);
    2357      152803 :         rels = nrels;
    2358             : 
    2359             :         /* one of the rels should be a op_union with nrcols == 0 */
    2360      458409 :         while (restart) {
    2361      578671 :                 for (n = rels->h; n; n = n->next) {
    2362      425868 :                         sql_rel *r = n->data;
    2363             : 
    2364      425868 :                         restart = 0;
    2365      425868 :                         if (is_project(r->op) && r->nrcols == 0) {
    2366             :                                 /* next step find expression on this relation */
    2367           0 :                                 node *m;
    2368           0 :                                 sql_rel *l = NULL;
    2369           0 :                                 sql_exp *je = NULL;
    2370             : 
    2371           0 :                                 for(m = exps->h; !je && m; m = m->next) {
    2372           0 :                                         sql_exp *e = m->data;
    2373             : 
    2374           0 :                                         if (e->type == e_cmp && e->flag == cmp_equal) {
    2375             :                                                 /* in values are on
    2376             :                                                         the right of the join */
    2377           0 :                                                 if (rel_has_exp(r, e->r, false) >= 0)
    2378           0 :                                                         je = e;
    2379             :                                         }
    2380             :                                 }
    2381             :                                 /* with this expression find other relation */
    2382           0 :                                 if (je && (l = find_rel(rels, je->l)) != NULL) {
    2383           0 :                                         unsigned int rsingle = is_single(r);
    2384           0 :                                         reset_single(r);
    2385           0 :                                         sql_rel *nr = rel_crossproduct(sql->sa, l, r, op_join);
    2386           0 :                                         if (rsingle)
    2387           0 :                                                 set_single(r);
    2388           0 :                                         rel_join_add_exp(sql->sa, nr, je);
    2389           0 :                                         list_append(rels, nr);
    2390           0 :                                         list_remove_data(rels, NULL, l);
    2391           0 :                                         list_remove_data(rels, NULL, r);
    2392           0 :                                         list_remove_data(exps, NULL, je);
    2393           0 :                                         restart = 1;
    2394           0 :                                         break;
    2395             :                                 }
    2396             : 
    2397             :                         }
    2398             :                 }
    2399             :         }
    2400      152803 :         return rels;
    2401             : }
    2402             : 
    2403             : static list *
    2404      727489 : push_up_join_exps( mvc *sql, sql_rel *rel)
    2405             : {
    2406      727489 :         if (rel_is_ref(rel))
    2407             :                 return NULL;
    2408             : 
    2409      686999 :         switch(rel->op) {
    2410      285336 :         case op_join: {
    2411      285336 :                 sql_rel *rl = rel->l;
    2412      285336 :                 sql_rel *rr = rel->r;
    2413      285336 :                 list *l, *r;
    2414             : 
    2415      285336 :                 if (rel_is_ref(rl) && rel_is_ref(rr)) {
    2416          16 :                         l = rel->exps;
    2417          16 :                         rel->exps = NULL;
    2418          16 :                         return l;
    2419             :                 }
    2420      285320 :                 l = push_up_join_exps(sql, rl);
    2421      285320 :                 r = push_up_join_exps(sql, rr);
    2422      285320 :                 if (l && r) {
    2423          34 :                         l = list_merge(l, r, (fdup)NULL);
    2424          34 :                         r = NULL;
    2425      285286 :                 } else if (!l) {
    2426      173674 :                         l = r;
    2427      173674 :                         r = NULL;
    2428             :                 }
    2429      285320 :                 if (rel->exps) {
    2430      253967 :                         if (l && !r)
    2431      101108 :                                 r = l;
    2432      253967 :                         l = list_merge(rel->exps, r, (fdup)NULL);
    2433             :                 }
    2434      285320 :                 rel->exps = NULL;
    2435      285320 :                 return l;
    2436             :         }
    2437             :         default:
    2438             :                 return NULL;
    2439             :         }
    2440             : }
    2441             : 
    2442             : static sql_rel *
    2443      283569 : reorder_join(visitor *v, sql_rel *rel)
    2444             : {
    2445      283569 :         list *exps, *rels;
    2446             : 
    2447      283569 :         if (is_innerjoin(rel->op) && !is_single(rel) && !rel_is_ref(rel) && list_empty(rel->attr)) {
    2448      174107 :                 if (list_empty(rel->exps)) {
    2449       22113 :                         sql_rel *l = rel->l, *r = rel->r;
    2450       22113 :                         if (!is_innerjoin(l->op) && !is_innerjoin(r->op))
    2451             :                                 return rel;
    2452             :                 }
    2453      156849 :                 rel->exps = push_up_join_exps(v->sql, rel);
    2454             :         }
    2455             : 
    2456      266311 :         if (!is_innerjoin(rel->op) || is_single(rel) || rel_is_ref(rel) || list_empty(rel->exps) || !list_empty(rel->attr)) {
    2457      113508 :                 if (!list_empty(rel->exps)) { /* cannot add join idxs to cross products */
    2458       77844 :                         exps = rel->exps;
    2459       77844 :                         rel->exps = NULL; /* should be all crosstables by now */
    2460       77844 :                         rels = sa_list(v->sql->ta);
    2461             :                         /* try to use an join index also for outer joins */
    2462       77844 :                         get_inner_relations(v->sql, rel, rels);
    2463       77844 :                         int cnt = list_length(exps);
    2464       77844 :                         rel->exps = find_fk(v->sql, rels, exps);
    2465       77844 :                         if (list_length(rel->exps) != cnt)
    2466       16435 :                                 rel->exps = order_join_expressions(v->sql, exps, rels);
    2467             :                 }
    2468      113508 :                 rel->l = rel_join_order_(v, rel->l);
    2469      113508 :                 rel->r = rel_join_order_(v, rel->r);
    2470             :         } else {
    2471      152803 :                 exps = rel->exps;
    2472      152803 :                 rel->exps = NULL; /* should be all crosstables by now */
    2473      152803 :                 rels = sa_list(v->sql->ta);
    2474      152803 :                 get_relations(v, rel, rels);
    2475      152803 :                 if (list_length(rels) > 1) {
    2476      152803 :                         rels = push_in_join_down(v->sql, rels, exps);
    2477      152803 :                         rel = order_joins(v, rels, exps);
    2478             :                 } else {
    2479           0 :                         rel->exps = exps;
    2480             :                 }
    2481             :         }
    2482             :         return rel;
    2483             : }
    2484             : 
    2485             : static sql_rel *
    2486     2395114 : rel_join_order_(visitor *v, sql_rel *rel)
    2487             : {
    2488     2395114 :         if (!rel)
    2489             :                 return rel;
    2490             : 
    2491     2379391 :         switch (rel->op) {
    2492             :         case op_basetable:
    2493             :                 break;
    2494        3851 :         case op_table:
    2495        3851 :                 if (IS_TABLE_PROD_FUNC(rel->flag) || rel->flag == TABLE_FROM_RELATION)
    2496        3851 :                         rel->l = rel_join_order_(v, rel->l);
    2497             :                 break;
    2498             :         case op_join:
    2499             :         case op_left:
    2500             :         case op_right:
    2501             :         case op_full:
    2502             :                 break;
    2503             : 
    2504       11411 :         case op_semi:
    2505             :         case op_anti:
    2506             : 
    2507             :         case op_union:
    2508             :         case op_inter:
    2509             :         case op_except:
    2510             :         case op_merge:
    2511       11411 :                 rel->l = rel_join_order_(v, rel->l);
    2512       11411 :                 rel->r = rel_join_order_(v, rel->r);
    2513       11411 :                 break;
    2514      115494 :         case op_munion:
    2515      115494 :                 assert(rel->l);
    2516      466316 :                 for (node *n = ((list*)rel->l)->h; n; n = n->next)
    2517      350822 :                         n->data = rel_join_order_(v, n->data);
    2518             :                 break;
    2519     1271339 :         case op_project:
    2520             :         case op_select:
    2521             :         case op_groupby:
    2522             :         case op_topn:
    2523             :         case op_sample:
    2524     1271339 :                 rel->l = rel_join_order_(v, rel->l);
    2525     1271339 :                 break;
    2526          52 :         case op_ddl:
    2527          52 :                 if (rel->flag == ddl_output || rel->flag == ddl_create_seq || rel->flag == ddl_alter_seq || rel->flag == ddl_alter_table || rel->flag == ddl_create_table || rel->flag == ddl_create_view) {
    2528           0 :                         rel->l = rel_join_order_(v, rel->l);
    2529             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
    2530          52 :                         rel->l = rel_join_order_(v, rel->l);
    2531          52 :                         rel->r = rel_join_order_(v, rel->r);
    2532             :                 }
    2533             :                 break;
    2534       11196 :         case op_insert:
    2535             :         case op_update:
    2536             :         case op_delete:
    2537       11196 :                 rel->r = rel_join_order_(v, rel->r);
    2538       11196 :                 break;
    2539             :         case op_truncate:
    2540             :                 break;
    2541             :         }
    2542     2379391 :         if (is_join(rel->op))
    2543      283569 :                 rel = reorder_join(v, rel);
    2544             :         return rel;
    2545             : }
    2546             : 
    2547             : static sql_rel *
    2548       82096 : rel_join_order(visitor *v, global_props *gp, sql_rel *rel)
    2549             : {
    2550       82096 :         (void) gp;
    2551       82096 :         sql_rel *r = rel_join_order_(v, rel);
    2552       82096 :         sa_reset(v->sql->ta);
    2553       82096 :         return r;
    2554             : }
    2555             : 
    2556             : run_optimizer
    2557      622727 : bind_join_order(visitor *v, global_props *gp)
    2558             : {
    2559      622727 :         int flag = v->sql->sql_optimizer;
    2560      622531 :         return gp->opt_level == 1 && gp->opt_cycle < 10 && !gp->cnt[op_update] && (gp->cnt[op_join] || gp->cnt[op_left] ||
    2561     1239211 :                    gp->cnt[op_right] || gp->cnt[op_full]) && (flag & join_order) ? rel_join_order : NULL;
    2562             : }
    2563             : 
    2564             : /* this join order is to be done once after statistics are gathered */
    2565             : run_optimizer
    2566      705405 : bind_join_order2(visitor *v, global_props *gp)
    2567             : {
    2568             :         /*int flag = v->sql->sql_optimizer;
    2569             :         return gp->opt_level == 1 && !gp->has_special_modify && !gp->cnt[op_update] && (gp->cnt[op_join] || gp->cnt[op_left] ||
    2570             :                    gp->cnt[op_right] || gp->cnt[op_full]) && (flag & join_order) ? rel_join_order : NULL;*/
    2571             :         /* TODO we have to propagate count statistics here */
    2572      705405 :         (void) v;
    2573      705405 :         (void) gp;
    2574      705405 :         return NULL;
    2575             : }
    2576             : 
    2577             : 
    2578             : static int
    2579       13661 : is_identity_of(sql_exp *e, sql_rel *l)
    2580             : {
    2581       13661 :         if (e->type != e_cmp)
    2582             :                 return 0;
    2583       13634 :         if (!is_identity(e->l, l) || !is_identity(e->r, l) || (e->f && !is_identity(e->f, l)))
    2584       13634 :                 return 0;
    2585             :         return 1;
    2586             : }
    2587             : 
    2588             : static inline sql_rel *
    2589       17839 : rel_rewrite_semijoin(visitor *v, sql_rel *rel)
    2590             : {
    2591       17839 :         assert(is_semi(rel->op));
    2592             :         {
    2593       17839 :                 sql_rel *l = rel->l;
    2594       17839 :                 sql_rel *r = rel->r;
    2595       17839 :                 sql_rel *rl = (r->l)?r->l:NULL;
    2596       17839 :                 int on_identity = 1;
    2597             : 
    2598       17839 :                 if (!rel->exps || list_length(rel->exps) != 1 || !is_identity_of(rel->exps->h->data, l))
    2599             :                         on_identity = 0;
    2600             : 
    2601             :                 /* rewrite {semi,anti}join (A, join(A,B)) into {semi,anti}join (A,B)
    2602             :                  * and     {semi,anti}join (A, join(B,A)) into {semi,anti}join (A,B)
    2603             :                  * Where the semi/anti join is done using the identity */
    2604           0 :                 if (on_identity && l->ref.refcnt == 2 && ((is_join(r->op) && (l == r->l || l == r->r)) ||
    2605           0 :                    (is_project(r->op) && rl && is_join(rl->op) && (l == rl->l || l == rl->r)))){
    2606           0 :                         sql_rel *or = r;
    2607             : 
    2608           0 :                         if (is_project(r->op))
    2609           0 :                                 r = rl;
    2610             : 
    2611           0 :                         if (l == r->r)
    2612           0 :                                 rel->r = rel_dup(r->l);
    2613             :                         else
    2614           0 :                                 rel->r = rel_dup(r->r);
    2615             : 
    2616           0 :                         rel->exps = r->exps;
    2617           0 :                         r->exps = NULL;
    2618           0 :                         rel->attr = r->attr;
    2619           0 :                         r->attr = NULL;
    2620           0 :                         rel_destroy(or);
    2621           0 :                         v->changes++;
    2622             :                 }
    2623             :         }
    2624             :         {
    2625       17839 :                 sql_rel *l = rel->l, *rl = NULL;
    2626       17839 :                 sql_rel *r = rel->r, *or = r;
    2627             : 
    2628       17839 :                 if (r)
    2629       17839 :                         rl = r->l;
    2630       17839 :                 if (r && is_project(r->op)) {
    2631       14735 :                         r = rl;
    2632       14735 :                         if (r)
    2633       14519 :                                 rl = r->l;
    2634             :                 }
    2635             : 
    2636             :                 /* More general case is (join reduction)
    2637             :                    {semi,anti}join (A, join(A,B) [A.c1 == B.c1]) [ A.c1 == B.c1 ]
    2638             :                    into {semi,anti}join (A,B) [ A.c1 == B.c1 ]
    2639             : 
    2640             :                    for semijoin also A.c1 == B.k1 ] [ A.c1 == B.k2 ] could be rewritten
    2641             :                  */
    2642       17839 :                 if (l && r && rl &&
    2643       16517 :                     is_basetable(l->op) && is_basetable(rl->op) &&
    2644        3968 :                     is_join(r->op) && l->l == rl->l)
    2645             :                 {
    2646          26 :                         node *n, *m;
    2647          26 :                         list *exps;
    2648             : 
    2649          51 :                         if (!rel->exps || !r->exps ||
    2650          25 :                             list_length(rel->exps) != list_length(r->exps))
    2651           1 :                                 return rel;
    2652          25 :                         exps = new_exp_list(v->sql->sa);
    2653             : 
    2654             :                         /* are the join conditions equal */
    2655          25 :                         for (n = rel->exps->h, m = r->exps->h;
    2656          25 :                              n && m; n = n->next, m = m->next)
    2657             :                         {
    2658          25 :                                 sql_exp *le = NULL, *oe = n->data;
    2659          25 :                                 sql_exp *re = NULL, *ne = m->data;
    2660          25 :                                 sql_column *cl;
    2661          25 :                                 int equal = 0;
    2662             : 
    2663          25 :                                 if (oe->type != e_cmp || ne->type != e_cmp ||
    2664          25 :                                     oe->flag != cmp_equal ||
    2665          25 :                                     ne->flag != cmp_equal || is_anti(oe) || is_anti(ne))
    2666             :                                         return rel;
    2667             : 
    2668          25 :                                 if ((cl = exp_find_column(rel->l, oe->l, -2)) != NULL) {
    2669          25 :                                         le = oe->l;
    2670          25 :                                         re = oe->r;
    2671           0 :                                 } else if ((cl = exp_find_column(rel->l, oe->r, -2)) != NULL) {
    2672           0 :                                         le = oe->r;
    2673           0 :                                         re = oe->l;
    2674             :                                 } else
    2675             :                                         return rel;
    2676             : 
    2677          25 :                                 if (exp_find_column(rl, ne->l, -2) == cl) {
    2678          25 :                                         sql_exp *e = (or != r)?rel_find_exp(or, re):re;
    2679             : 
    2680          25 :                                         if (e)
    2681          24 :                                                 equal = exp_match_exp(ne->r, e);
    2682          25 :                                         if (!e || !equal)
    2683             :                                                 return rel;
    2684           0 :                                         re = ne->r;
    2685           0 :                                 } else if (exp_find_column(rl, ne->r, -2) == cl) {
    2686           0 :                                         sql_exp *e = (or != r)?rel_find_exp(or, re):re;
    2687             : 
    2688           0 :                                         if (e)
    2689           0 :                                                 equal = exp_match_exp(ne->l, e);
    2690           0 :                                         if (!e || !equal)
    2691             :                                                 return rel;
    2692           0 :                                         re = ne->l;
    2693             :                                 } else
    2694             :                                         return rel;
    2695             : 
    2696           0 :                                 ne = exp_compare(v->sql->sa, le, re, cmp_equal);
    2697           0 :                                 append(exps, ne);
    2698             :                         }
    2699             : 
    2700           0 :                         rel->r = rel_dup(r->r);
    2701           0 :                         rel->exps = exps;
    2702           0 :                         rel_destroy(or);
    2703           0 :                         v->changes++;
    2704             :                 }
    2705             :         }
    2706             :         return rel;
    2707             : }
    2708             : 
    2709             : /*
    2710             :  * Push semijoins down, pushes the semijoin through a join.
    2711             :  *
    2712             :  * semijoin( join(A, B) [ A.x == B.y ], C ) [ A.z == C.c ]
    2713             :  * ->
    2714             :  * join( semijoin(A, C) [ A.z == C.c ], B ) [ A.x == B.y ]
    2715             :  *
    2716             :  * also push simple expressions of a semijoin down if they only
    2717             :  * involve the left sided of the semijoin.
    2718             :  *
    2719             :  * in some cases the other way is useful, ie push join down
    2720             :  * semijoin. When the join reduces (ie when there are selects on it).
    2721             :  *
    2722             :  * At the moment, we only flag changes by this optimizer on the first level of optimization
    2723             :  */
    2724             : static inline sql_rel *
    2725      460591 : rel_push_semijoin_down_or_up(visitor *v, sql_rel *rel)
    2726             : {
    2727      460591 :         uint8_t cycle = *(uint8_t*) v->data;
    2728             : 
    2729      460591 :         if (rel->op == op_join && rel->exps && rel->l) {
    2730      424978 :                 sql_rel *l = rel->l, *r = rel->r;
    2731             : 
    2732      424978 :                 if (is_semi(l->op) && !rel_is_ref(l) && is_select(r->op) && !rel_is_ref(r)) {
    2733          22 :                         rel->l = l->l;
    2734          22 :                         l->l = rel;
    2735          22 :                         if (cycle <= 0)
    2736           0 :                                 v->changes++;
    2737          22 :                         return l;
    2738             :                 }
    2739             :         }
    2740             :         /* also case with 2 joins */
    2741             :         /* join ( join ( semijoin(), table), select (table)); */
    2742      460569 :         if (rel->op == op_join && rel->exps && rel->l) {
    2743      424956 :                 sql_rel *l = rel->l, *r = rel->r;
    2744      424956 :                 sql_rel *ll;
    2745             : 
    2746      424956 :                 if (is_join(l->op) && !rel_is_ref(l) && is_select(r->op) && !rel_is_ref(r)) {
    2747        7925 :                         ll = l->l;
    2748        7925 :                         if (is_semi(ll->op) && !rel_is_ref(ll)) {
    2749          51 :                                 l->l = ll->l;
    2750          51 :                                 ll->l = rel;
    2751          51 :                                 if (cycle <= 0)
    2752          12 :                                         v->changes++;
    2753          51 :                                 return ll;
    2754             :                         }
    2755             :                 }
    2756             :         }
    2757             :         /* first push down the expressions involving only A */
    2758      460518 :         if (rel->op == op_semi && rel->exps && rel->l) {
    2759       12115 :                 sql_rel *jl = rel->l, *ojl = jl;
    2760             : 
    2761       12115 :                 set_processed(jl);
    2762       27720 :                 for (node *n = rel->exps->h; n;) {
    2763       15605 :                         node *next = n->next;
    2764       15605 :                         sql_exp *e = n->data;
    2765             : 
    2766       15605 :                         if (n != rel->exps->h && e->type == e_cmp && rel_rebind_exp(v->sql, jl, e)) {
    2767          16 :                                 if (!is_select(jl->op) || rel_is_ref(jl))
    2768          14 :                                         rel->l = jl = rel_select(v->sql->sa, jl, NULL);
    2769          16 :                                 rel_select_add_exp(v->sql->sa, jl, e);
    2770          16 :                                 list_remove_node(rel->exps, NULL, n);
    2771          16 :                                 if (cycle <= 0)
    2772          16 :                                         v->changes++;
    2773             :                         }
    2774             :                         n = next;
    2775             :                 }
    2776       12115 :                 if (ojl != jl)
    2777          14 :                         set_processed(jl);
    2778             :         }
    2779      460518 :         if (rel->op == op_semi && rel->exps && rel->l) {
    2780       12115 :                 operator_type op = rel->op, lop;
    2781       12115 :                 node *n;
    2782       12115 :                 sql_rel *l = rel->l, *ll = NULL, *lr = NULL;
    2783       12115 :                 sql_rel *r = rel->r;
    2784       12115 :                 list *exps = rel->exps, *nsexps, *njexps, *nsattr, *njattr;
    2785       12115 :                 int left = 1, right = 1;
    2786             : 
    2787             :                 /* handle project
    2788             :                 if (l->op == op_project && !need_distinct(l))
    2789             :                         l = l->l;
    2790             :                 */
    2791             : 
    2792       12115 :                 if (!is_join(l->op) || is_full(l->op) || rel_is_ref(l) || is_single(l))
    2793             :                         return rel;
    2794             : 
    2795        1169 :                 lop = l->op;
    2796        1169 :                 ll = l->l;
    2797        1169 :                 lr = l->r;
    2798             : 
    2799             :                 /* check which side is used and other exps are atoms or from right of semijoin */
    2800        2248 :                 for(n = exps->h; n; n = n->next) {
    2801        1272 :                         sql_exp *sje = n->data;
    2802             : 
    2803        1272 :                         if (sje->type != e_cmp || is_complex_exp(sje->flag))
    2804             :                                 return rel;
    2805             :                         /* sje->l from ll and sje->r/f from semijoin r ||
    2806             :                          * sje->l from semijoin r and sje->r/f from ll ||
    2807             :                          * sje->l from lr and sje->r/f from semijoin r ||
    2808             :                          * sje->l from semijoin r and sje->r/f from lr */
    2809        2480 :                         if (left &&
    2810        2480 :                            ((rel_rebind_exp(v->sql, ll, sje->l) && rel_rebind_exp(v->sql, rel->r, sje->r) && (!sje->f || rel_rebind_exp(v->sql, rel->r, sje->f))) ||
    2811        1232 :                             (rel_rebind_exp(v->sql, rel->r, sje->l) && rel_rebind_exp(v->sql, ll, sje->r) && (!sje->f || rel_rebind_exp(v->sql, ll, sje->f)))))
    2812             :                                 right = 0;
    2813             :                         else
    2814         905 :                                 left = 0;
    2815        1709 :                         if (right &&
    2816        1608 :                            ((rel_rebind_exp(v->sql, lr, sje->l) && rel_rebind_exp(v->sql, rel->r, sje->r) && (!sje->f || rel_rebind_exp(v->sql, rel->r, sje->f))) ||
    2817         566 :                             (rel_rebind_exp(v->sql, rel->r, sje->l) && rel_rebind_exp(v->sql, lr, sje->r) && (!sje->f || rel_rebind_exp(v->sql, lr, sje->f)))))
    2818             :                                 left = 0;
    2819             :                         else
    2820             :                                 right = 0;
    2821        1240 :                         if (!right && !left)
    2822             :                                 return rel;
    2823             :                 }
    2824         976 :                 if (left && is_right(lop))
    2825             :                         return rel;
    2826         975 :                 if (right && is_left(lop))
    2827             :                         return rel;
    2828         973 :                 nsexps = exps_copy(v->sql, rel->exps);
    2829         973 :                 nsattr = exps_copy(v->sql, rel->attr);
    2830         973 :                 njexps = exps_copy(v->sql, l->exps);
    2831         973 :                 njattr = exps_copy(v->sql, l->attr);
    2832         973 :                 if (left)
    2833         231 :                         l = rel_crossproduct(v->sql->sa, rel_dup(ll), rel_dup(r), op);
    2834             :                 else
    2835         742 :                         l = rel_crossproduct(v->sql->sa, rel_dup(lr), rel_dup(r), op);
    2836         973 :                 l->exps = nsexps;
    2837         973 :                 l->attr = nsattr;
    2838         973 :                 set_processed(l);
    2839         973 :                 if (left)
    2840         231 :                         l = rel_crossproduct(v->sql->sa, l, rel_dup(lr), lop);
    2841             :                 else
    2842         742 :                         l = rel_crossproduct(v->sql->sa, rel_dup(ll), l, lop);
    2843         973 :                 l->exps = njexps;
    2844         973 :                 l->attr = njattr;
    2845         973 :                 set_processed(l);
    2846         973 :                 rel_destroy(rel);
    2847         973 :                 rel = l;
    2848         973 :                 if (cycle <= 0)
    2849         570 :                         v->changes++;
    2850             :         }
    2851             :         return rel;
    2852             : }
    2853             : 
    2854             : /* antijoin(a, union(b,c)) -> antijoin(antijoin(a,b), c) */
    2855             : static inline sql_rel *
    2856        5670 : rel_rewrite_antijoin(visitor *v, sql_rel *rel)
    2857             : {
    2858        5670 :         sql_rel *l = rel->l;
    2859        5670 :         sql_rel *r = rel->r;
    2860             : 
    2861        5670 :         assert(rel->op == op_anti);
    2862        5670 :         if (l && !rel_is_ref(l) && r && !rel_is_ref(r) && is_union(r->op) && !is_single(r)) {
    2863           0 :                 sql_rel *rl = rel_dup(r->l), *nl;
    2864           0 :                 sql_rel *rr = rel_dup(r->r);
    2865             : 
    2866           0 :                 if (!is_project(rl->op))
    2867           0 :                         rl = rel_project(v->sql->sa, rl,
    2868             :                                 rel_projections(v->sql, rl, NULL, 1, 1));
    2869           0 :                 if (!is_project(rr->op))
    2870           0 :                         rr = rel_project(v->sql->sa, rr,
    2871             :                                 rel_projections(v->sql, rr, NULL, 1, 1));
    2872           0 :                 rel_rename_exps(v->sql, r->exps, rl->exps);
    2873           0 :                 rel_rename_exps(v->sql, r->exps, rr->exps);
    2874             : 
    2875           0 :                 nl = rel_crossproduct(v->sql->sa, rel->l, rl, op_anti);
    2876           0 :                 nl->exps = exps_copy(v->sql, rel->exps);
    2877           0 :                 nl->attr = exps_copy(v->sql, rel->attr);
    2878           0 :                 set_processed(nl);
    2879           0 :                 rel->l = nl;
    2880           0 :                 rel->r = rr;
    2881           0 :                 rel_destroy(r);
    2882           0 :                 v->changes++;
    2883           0 :                 return rel;
    2884             :         }
    2885             :         return rel;
    2886             : }
    2887             : 
    2888             : static sql_rel *
    2889     3424435 : rel_optimize_semi_and_anti_(visitor *v, sql_rel *rel)
    2890             : {
    2891             :         /* rewrite semijoin (A, join(A,B)) into semijoin (A,B) */
    2892     3424435 :         if (rel && is_semi(rel->op))
    2893       17839 :                 rel = rel_rewrite_semijoin(v, rel);
    2894             :         /* push semijoin through join */
    2895     3424435 :         if (rel && (is_semi(rel->op) || is_innerjoin(rel->op)))
    2896      460591 :                 rel = rel_push_semijoin_down_or_up(v, rel);
    2897             :         /* antijoin(a, union(b,c)) -> antijoin(antijoin(a,b), c) */
    2898     3424435 :         if (rel && rel->op == op_anti)
    2899        5670 :                 rel = rel_rewrite_antijoin(v, rel);
    2900     3424435 :         return rel;
    2901             : }
    2902             : 
    2903             : static sql_rel *
    2904       89049 : rel_optimize_semi_and_anti(visitor *v, global_props *gp, sql_rel *rel)
    2905             : {
    2906       89049 :         v->data = &gp->opt_cycle;
    2907       89049 :         rel = rel_visitor_bottomup(v, rel, &rel_optimize_semi_and_anti_);
    2908       89049 :         v->data = gp;
    2909       89049 :         return rel;
    2910             : }
    2911             : 
    2912             : run_optimizer
    2913      622727 : bind_optimize_semi_and_anti(visitor *v, global_props *gp)
    2914             : {
    2915             :         /* Important -> Re-write semijoins after rel_join_order */
    2916      622727 :         int flag = v->sql->sql_optimizer;
    2917      622531 :         return gp->opt_level == 1 && (gp->cnt[op_join] || gp->cnt[op_left] || gp->cnt[op_right]
    2918     1245258 :                    || gp->cnt[op_full] || gp->cnt[op_semi] || gp->cnt[op_anti]) && (flag & optimize_semi_and_anti) ? rel_optimize_semi_and_anti : NULL;
    2919             : }
    2920             : 
    2921             : 
    2922             : static sql_rel *
    2923     1583515 : rel_semijoin_use_fk(visitor *v, sql_rel *rel)
    2924             : {
    2925     1583515 :         if (is_semi(rel->op) && rel->exps) {
    2926        6238 :                 list *exps = rel->exps;
    2927        6238 :                 list *rels = sa_list(v->sql->sa);
    2928             : 
    2929        6238 :                 rel->exps = NULL;
    2930        6238 :                 append(rels, rel->l);
    2931        6238 :                 append(rels, rel->r);
    2932        6238 :                 (void) find_fk( v->sql, rels, exps);
    2933             : 
    2934        6238 :                 rel->exps = exps;
    2935             :         }
    2936     1583515 :         return rel;
    2937             : }
    2938             : 
    2939             : /*
    2940             :  * Push {semi}joins down, pushes the joins through group by expressions.
    2941             :  * When the join is on the group by columns, we can push the joins left
    2942             :  * under the group by. This should only be done, iff the new semijoin would
    2943             :  * reduce the input table to the groupby. So there should be a reduction
    2944             :  * (selection) on the table A and this should be propagated to the groupby via
    2945             :  * for example a primary key.
    2946             :  *
    2947             :  * {semi}join( A, groupby( B ) [gbe][aggrs] ) [ gbe == A.x ]
    2948             :  * ->
    2949             :  * {semi}join( A, groupby( semijoin(B,A) [gbe == A.x] ) [gbe][aggrs] ) [ gbe == A.x ]
    2950             :  */
    2951             : static inline sql_rel *
    2952     1583515 : rel_push_join_down(visitor *v, sql_rel *rel)
    2953             : {
    2954     1583515 :         if (!rel_is_ref(rel) && ((is_left(rel->op) || rel->op == op_join || is_semi(rel->op)) && rel->l && rel->exps)) {
    2955      231446 :                 sql_rel *gb = rel->r, *ogb = gb, *l = NULL, *rell = rel->l;
    2956             : 
    2957      231446 :                 if (is_simple_project(gb->op) && !rel_is_ref(gb))
    2958       45538 :                         gb = gb->l;
    2959             : 
    2960      231446 :                 if (rel_is_ref(rell) || !gb || rel_is_ref(gb))
    2961             :                         return rel;
    2962             : 
    2963      221658 :                 if (is_groupby(gb->op) && gb->r && list_length(gb->r)) {
    2964         190 :                         list *exps = rel->exps, *jes = new_exp_list(v->sql->sa), *gbes = gb->r;
    2965         190 :                         node *n, *m;
    2966             :                         /* find out if all group by expressions are used in the join */
    2967         195 :                         for(n = gbes->h; n; n = n->next) {
    2968         190 :                                 sql_exp *gbe = n->data;
    2969         190 :                                 int fnd = 0;
    2970         190 :                                 const char *rname = NULL, *name = NULL;
    2971             : 
    2972             :                                 /* project in between, ie find alias */
    2973             :                                 /* first find expression in expression list */
    2974         190 :                                 gbe = exps_uses_exp( gb->exps, gbe);
    2975         190 :                                 if (!gbe)
    2976           0 :                                         continue;
    2977         190 :                                 if (ogb != gb)
    2978         167 :                                         gbe = exps_uses_exp( ogb->exps, gbe);
    2979         190 :                                 if (gbe) {
    2980         149 :                                         rname = exp_find_rel_name(gbe);
    2981         149 :                                         name = exp_name(gbe);
    2982             :                                 }
    2983             : 
    2984         149 :                                 if (!name)
    2985          41 :                                         return rel;
    2986             : 
    2987         370 :                                 for (m = exps->h; m && !fnd; m = m->next) {
    2988         221 :                                         sql_exp *je = m->data;
    2989             : 
    2990         221 :                                         if (je->card >= CARD_ATOM && je->type == e_cmp &&
    2991         221 :                                             !is_complex_exp(je->flag)) {
    2992             :                                                 /* expect right expression to match */
    2993         221 :                                                 sql_exp *r = je->r;
    2994             : 
    2995         221 :                                                 if (r == 0 || r->type != e_column)
    2996          10 :                                                         continue;
    2997         211 :                                                 if (r->l && rname && strcmp(r->l, rname) == 0 && strcmp(r->r, name)==0) {
    2998             :                                                         fnd = 1;
    2999          83 :                                                 } else if (!r->l && !rname  && strcmp(r->r, name)==0) {
    3000             :                                                         fnd = 1;
    3001             :                                                 }
    3002             :                                                 if (fnd) {
    3003         128 :                                                         sql_exp *le = je->l;
    3004         128 :                                                         sql_exp *re = exp_push_down_prj(v->sql, r, gb, gb->l);
    3005         128 :                                                         if (!re || (list_length(jes) == 0 && !find_prop(le->p, PROP_HASHCOL))) {
    3006             :                                                                 fnd = 0;
    3007             :                                                         } else {
    3008           5 :                                                                 int anti = is_anti(je), semantics = is_semantics(je);
    3009             : 
    3010           5 :                                                                 je = exp_compare(v->sql->sa, le, re, je->flag);
    3011           5 :                                                                 if (anti) set_anti(je);
    3012           5 :                                                                 if (semantics) set_semantics(je);
    3013           5 :                                                                 list_append(jes, je);
    3014             :                                                         }
    3015             :                                                 }
    3016             :                                         }
    3017             :                                 }
    3018         149 :                                 if (!fnd)
    3019             :                                         return rel;
    3020             :                         }
    3021           5 :                         l = rel_dup(rel->l);
    3022             : 
    3023             :                         /* push join's left side (as semijoin) down group by */
    3024           5 :                         l = gb->l = rel_crossproduct(v->sql->sa, gb->l, l, op_semi);
    3025           5 :                         l->exps = jes;
    3026           5 :                         set_processed(l);
    3027           5 :                         v->changes++;
    3028           5 :                         return rel;
    3029             :                 }
    3030             :         }
    3031             :         return rel;
    3032             : }
    3033             : 
    3034             : static bool
    3035         728 : check_projection_on_foreignside(sql_rel *r, list *pexps, int fk_left)
    3036             : {
    3037             :         /* projection columns from the foreign side */
    3038         728 :         if (list_empty(pexps))
    3039             :                 return true;
    3040        3156 :         for (node *n = pexps->h; n; n = n->next) {
    3041        3091 :                 sql_exp *pe = n->data;
    3042             : 
    3043        3091 :                 if (pe && is_atom(pe->type))
    3044          23 :                         continue;
    3045        3068 :                 if (pe && !is_alias(pe->type))
    3046             :                         return false;
    3047             :                 /* check for columns from the pk side, then keep the join with the pk */
    3048        3047 :                 if ((fk_left && rel_find_exp(r->r, pe)) || (!fk_left && rel_find_exp(r->l, pe)))
    3049         594 :                         return false;
    3050             :         }
    3051             :         return true;
    3052             : }
    3053             : 
    3054             : static sql_rel *
    3055      237448 : rel_simplify_project_fk_join(mvc *sql, sql_rel *r, list *pexps, list *orderexps, int *changes)
    3056             : {
    3057      237448 :         sql_rel *rl = r->l, *rr = r->r, *nr = NULL;
    3058      237448 :         sql_exp *je, *le, *nje, *re;
    3059      237448 :         int fk_left = 1;
    3060             : 
    3061             :         /* check for foreign key join */
    3062      237448 :         if (list_length(r->exps) != 1 || !list_empty(r->attr))
    3063        7424 :                 return r;
    3064      230024 :         if (!(je = exps_find_prop(r->exps, PROP_JOINIDX)) || je->flag != cmp_equal)
    3065             :                 return r;
    3066             :         /* je->l == foreign expression, je->r == primary expression */
    3067        1204 :         if (rel_find_exp(r->l, je->l)) {
    3068             :                 fk_left = 1;
    3069          34 :         } else if (rel_find_exp(r->r, je->l)) {
    3070             :                 fk_left = 0;
    3071             :         } else { /* not found */
    3072             :                 return r;
    3073             :         }
    3074             : 
    3075             :         /* primary side must be a full table */
    3076        1170 :         if ((fk_left && (!is_left(r->op) && !is_full(r->op)) && !is_basetable(rr->op)) ||
    3077          34 :                 (!fk_left && (!is_right(r->op) && !is_full(r->op)) && !is_basetable(rl->op)))
    3078         554 :                 return r;
    3079             : 
    3080         650 :         if (!check_projection_on_foreignside(r, pexps, fk_left) || !check_projection_on_foreignside(r, orderexps, fk_left))
    3081         613 :                 return r;
    3082             : 
    3083             :         /* rewrite, ie remove pkey side if possible */
    3084          37 :         le = (sql_exp*)je->l, re = (sql_exp*)je->l;
    3085             : 
    3086             :         /* both have NULL and there are semantics, the join cannot be removed */
    3087          37 :         if (is_semantics(je) && has_nil(le) && has_nil(re))
    3088             :                 return r;
    3089             : 
    3090          37 :         (*changes)++;
    3091             :         /* if the foreign key column doesn't have NULL values, then return it */
    3092          37 :         if (!has_nil(le) || is_full(r->op) || (fk_left && is_left(r->op)) || (!fk_left && is_right(r->op))) {
    3093             :                 /* if ->attr, introduce group by on index */
    3094          31 :                 if (fk_left) {
    3095          23 :                         nr = rel_dup(r->l);
    3096             :                 } else {
    3097           8 :                         nr = rel_dup(r->r);
    3098             :                 }
    3099          31 :                 if (!list_empty(r->attr)) {
    3100           0 :                         nr = rel_groupby(sql, nr, NULL);
    3101           0 :                         if (nr) {
    3102             :                                 // printf("# introduced groupby  \n");
    3103           0 :                                 nr->r = append(sa_list(sql->sa), le);
    3104           0 :                                 nr->exps = r->attr;
    3105             :                         }
    3106             :                 }
    3107          31 :                 return nr;
    3108             :         }
    3109             : 
    3110             :         /* remove NULL values, ie generate a select not null */
    3111           6 :         nje = exp_compare(sql->sa, exp_ref(sql, le), exp_atom(sql->sa, atom_general(sql->sa, exp_subtype(le), NULL, 0)), cmp_equal);
    3112           6 :         set_anti(nje);
    3113           6 :         set_has_no_nil(nje);
    3114           6 :         set_semantics(nje);
    3115           6 :         if (fk_left) {
    3116           6 :                 nr = rel_dup(r->l);
    3117             :         } else {
    3118           0 :                 nr = rel_dup(r->r);
    3119             :         }
    3120           6 :         nr = rel_select(sql->sa, nr, nje);
    3121           6 :         set_processed(nr);
    3122           6 :         return nr;
    3123             : }
    3124             : 
    3125             : static sql_rel *
    3126        1853 : rel_simplify_count_fk_join(mvc *sql, sql_rel *r, list *gexps, list *gcols, int *changes)
    3127             : {
    3128        1853 :         sql_rel *rl = r->l, *rr = r->r, *nr = NULL;
    3129        1853 :         sql_exp *je, *le, *nje, *re, *oce;
    3130        1853 :         int fk_left = 1;
    3131             : 
    3132             :         /* check for foreign key join */
    3133        1853 :         if (list_length(r->exps) != 1)
    3134             :                 return r;
    3135        1852 :         if (!(je = exps_find_prop(r->exps, PROP_JOINIDX)) || je->flag != cmp_equal)
    3136             :                 return r;
    3137             :         /* je->l == foreign expression, je->r == primary expression */
    3138          63 :         if (rel_find_exp(r->l, je->l)) {
    3139             :                 fk_left = 1;
    3140           7 :         } else if (rel_find_exp(r->r, je->l)) {
    3141             :                 fk_left = 0;
    3142             :         } else { /* not found */
    3143             :                 return r;
    3144             :         }
    3145             : 
    3146          63 :         oce = gexps->h->data;
    3147          63 :         if (oce->l) /* we only handle COUNT(*) */
    3148             :                 return r;
    3149             : 
    3150             :         /* primary side must be a full table */
    3151          62 :         if ((fk_left && (!is_left(r->op) && !is_full(r->op)) && !is_basetable(rr->op)) ||
    3152           6 :                 (!fk_left && (!is_right(r->op) && !is_full(r->op)) && !is_basetable(rl->op)))
    3153             :                 return r;
    3154             : 
    3155          33 :         if (fk_left && is_join(rl->op) && !rel_is_ref(rl)) {
    3156          12 :                 r->l = rel_simplify_count_fk_join(sql, rl, gexps, gcols, changes);
    3157          12 :                 if (rl != r->l)
    3158           9 :                         rel_destroy(rl);
    3159             :         }
    3160          39 :         if (!fk_left && is_join(rr->op) && !rel_is_ref(rr)) {
    3161           2 :                 r->r = rel_simplify_count_fk_join(sql, rr, gexps, gcols, changes);
    3162           2 :                 if (rr != r->r)
    3163           2 :                         rel_destroy(rr);
    3164             :         }
    3165             : 
    3166          39 :         if (!check_projection_on_foreignside(r, gcols, fk_left))
    3167             :                 return r;
    3168             : 
    3169             :         /* rewrite, ie remove pkey side if possible */
    3170          37 :         le = (sql_exp*)je->l, re = (sql_exp*)je->l;
    3171             : 
    3172             :         /* both have NULL and there are semantics, the join cannot be removed */
    3173          37 :         if (is_semantics(je) && has_nil(le) && has_nil(re))
    3174             :                 return r;
    3175             : 
    3176          37 :         (*changes)++;
    3177             :         /* if the foreign key column doesn't have NULL values, then return it */
    3178          37 :         if (!has_nil(le) || is_full(r->op) || (fk_left && is_left(r->op)) || (!fk_left && is_right(r->op))) {
    3179          31 :                 if (fk_left) {
    3180          25 :                         nr = rel_dup(r->l);
    3181             :                 } else {
    3182           6 :                         nr = rel_dup(r->r);
    3183             :                 }
    3184          31 :                 return nr;
    3185             :         }
    3186             : 
    3187             :         /* remove NULL values, ie generate a select not null */
    3188           6 :         nje = exp_compare(sql->sa, exp_ref(sql, le), exp_atom(sql->sa, atom_general(sql->sa, exp_subtype(le), NULL, 0)), cmp_equal);
    3189           6 :         set_anti(nje);
    3190           6 :         set_has_no_nil(nje);
    3191           6 :         set_semantics(nje);
    3192           6 :         if (fk_left) {
    3193           6 :                 nr = rel_dup(r->l);
    3194             :         } else {
    3195           0 :                 nr = rel_dup(r->r);
    3196             :         }
    3197           6 :         nr = rel_select(sql->sa, nr, nje);
    3198           6 :         set_processed(nr);
    3199           6 :         return nr;
    3200             : }
    3201             : 
    3202             : /*
    3203             :  * Handle (left/right/outer/natural) join fk-pk rewrites
    3204             :  *   1 group by ( fk-pk-join () ) [ count(*) ] -> group by ( fk )
    3205             :  *   2 project ( fk-pk-join () ) [ fk-column ] -> project (fk table)[ fk-column ]
    3206             :  *   3 project ( fk1-pk1-join( fk2-pk2-join()) [ fk-column, pk1 column ] -> project (fk1-pk1-join)[ fk-column, pk1 column ]
    3207             :  */
    3208             : static inline sql_rel *
    3209     3636299 : rel_simplify_fk_joins(visitor *v, sql_rel *rel)
    3210             : {
    3211     3636299 :         sql_rel *r = NULL;
    3212             : 
    3213     3636299 :         if (is_simple_project(rel->op))
    3214     1193108 :                 r = rel->l;
    3215             : 
    3216     3636336 :         while (is_simple_project(rel->op) && r && list_length(r->exps) == 1 && (is_join(r->op) || r->op == op_semi) && !(rel_is_ref(r))) {
    3217      237448 :                 sql_rel *or = r;
    3218             : 
    3219      237448 :                 r = rel_simplify_project_fk_join(v->sql, r, rel->exps, rel->r, &v->changes);
    3220      237448 :                 if (r == or)
    3221             :                         return rel;
    3222          37 :                 rel_destroy(rel->l);
    3223          37 :                 rel->l = r;
    3224             :         }
    3225             : 
    3226     3398888 :         if (!is_groupby(rel->op))
    3227             :                 return rel;
    3228             : 
    3229       86661 :         r = rel->l;
    3230      130777 :         while(r && is_simple_project(r->op))
    3231       44116 :                 r = r->l;
    3232             : 
    3233      101065 :         while (is_groupby(rel->op) && !rel_is_ref(rel) && r && (is_join(r->op) || r->op == op_semi) && list_length(r->exps) == 1 && !(rel_is_ref(r)) &&
    3234             :                    /* currently only single count aggregation is handled, no other projects or aggregation */
    3235      105097 :                    list_length(rel->exps) == 1 && exp_aggr_is_count(rel->exps->h->data)) {
    3236        1839 :                 sql_rel *or = r;
    3237             : 
    3238        1839 :                 r = rel_simplify_count_fk_join(v->sql, r, rel->exps, rel->r, &v->changes);
    3239        1839 :                 if (r == or)
    3240             :                         return rel;
    3241          26 :                 rel_destroy(rel->l);
    3242          26 :                 rel->l = r;
    3243             :         }
    3244             :         return rel;
    3245             : }
    3246             : 
    3247             : /*
    3248             :  * Gets the column expressions of a diff function and adds them to "columns".
    3249             :  * The diff function has two possible argument types: either a sql_exp representing a column
    3250             :  * or a sql_exp representing another diff function, therefore this function is recursive.
    3251             :  */
    3252             : static void
    3253         168 : get_diff_function_columns(sql_exp *diffExp, list *columns) {
    3254         168 :         list *args = diffExp->l;
    3255             : 
    3256         370 :         for (node *arg = args->h; arg; arg = arg->next) {
    3257         202 :                 sql_exp *exp = arg->data;
    3258             : 
    3259             :                 // diff function
    3260         202 :                 if (exp->type == e_func) {
    3261          34 :                         get_diff_function_columns(exp, columns);
    3262             :                 }
    3263             :                 // column
    3264             :                 else {
    3265         168 :                         list_append(columns, exp);
    3266             :                 }
    3267             :         }
    3268         168 : }
    3269             : 
    3270             : /*
    3271             :  * Builds a list of aggregation key columns to be used by the select push down algorithm, namely for
    3272             :  * window functions. Returns NULL if the window function does not partition by any column
    3273             :  */
    3274             : static list *
    3275        3623 : get_aggregation_key_columns(allocator *sa, sql_rel *r) {
    3276       34495 :         for (node* n = r->exps->h; n; n = n->next) {
    3277       31096 :                 sql_exp *e = n->data;
    3278             : 
    3279       31096 :                 if (e->type == e_func) {
    3280        7923 :                         sql_subfunc *f = e->f;
    3281             : 
    3282             :                         // aggregation function
    3283        7923 :                         if (!strcmp(f->func->base.name, "rank")) {
    3284         224 :                                 list* rankArguments = e->l;
    3285             :                                 // the partition key is the second argument
    3286         224 :                                 sql_exp *partitionExp = rankArguments->h->next->data;
    3287             : 
    3288             :                                 // check if the key contains any columns, i.e., is a diff function
    3289         224 :                                 if (partitionExp->type == e_func) {
    3290             :                                         // get columns to list
    3291         134 :                                         list *aggColumns = sa_list(sa);
    3292         134 :                                         get_diff_function_columns(partitionExp, aggColumns);
    3293         134 :                                         return aggColumns;
    3294             :                                 }
    3295             :                                 // the function has no aggregation columns (e_atom of boolean)
    3296             :                                 else {
    3297             :                                         return NULL;
    3298             :                                 }
    3299             : 
    3300             :                         }
    3301             :                 }
    3302             :         }
    3303             :         return NULL;
    3304             : }
    3305             : 
    3306             : /*
    3307             :  * Checks if a filter column is also used as an aggregation key, so it can be later safely pushed down.
    3308             :  */
    3309             : static int
    3310         187 : filter_column_in_aggregation_columns(sql_exp *column, list *aggColumns) {
    3311             :         /* check if it is a column or an e_convert, and get the actual column if it is the latter */
    3312         187 :         if (column->type == e_convert) {
    3313           1 :                 column = column->l;
    3314             :         }
    3315             : 
    3316         187 :         char *tableName = column->l;
    3317         187 :         char *columnName = column->r;
    3318             : 
    3319         404 :         for (node *n = aggColumns->h; n; n = n->next) {
    3320         226 :                 sql_exp *aggCol = n->data;
    3321         226 :                 char *aggColTableName = aggCol->l;
    3322         226 :                 char *aggColColumnName = aggCol->r;
    3323             : 
    3324         226 :                 if (!strcmp(tableName, aggColTableName) && !strcmp(columnName, aggColColumnName)) {
    3325             :                         /* match */
    3326             :                         return 1;
    3327             :                 }
    3328             :         }
    3329             : 
    3330             :         /* no matches found */
    3331             :         return 0;
    3332             : }
    3333             : 
    3334             : 
    3335             : /*
    3336             :  * Push select down, pushes the selects through (simple) projections. Also
    3337             :  * it cleans up the projections which become useless.
    3338             :  *
    3339             :  * WARNING - Make sure to call try_remove_empty_select macro before returning so we ensure
    3340             :  * possible generated empty selects won't never be generated
    3341             :  */
    3342             : static sql_rel *
    3343     7199146 : rel_push_select_down(visitor *v, sql_rel *rel)
    3344             : {
    3345     7199146 :         list *exps = NULL;
    3346     7199146 :         sql_rel *r = NULL;
    3347     7199146 :         node *n;
    3348             : 
    3349     7199146 :         if (rel_is_ref(rel)) {
    3350      374422 :                 if (is_select(rel->op) && !list_empty(rel->exps)) {
    3351             :                         /* add inplace empty select */
    3352        1732 :                         sql_rel *l = rel_select(v->sql->sa, rel->l, NULL);
    3353             : 
    3354        1732 :                         l->exps = rel->exps;
    3355        1732 :                         set_processed(l);
    3356        1732 :                         rel->exps = NULL;
    3357        1732 :                         rel->l = l;
    3358        1732 :                         v->changes++;
    3359             :                 }
    3360      374422 :                 return rel;
    3361             :         }
    3362             : 
    3363             :         /* don't make changes for empty selects */
    3364     6824724 :         if (is_select(rel->op) && list_empty(rel->exps))
    3365          10 :                 return try_remove_empty_select(v, rel);
    3366             : 
    3367             :         /* merge 2 selects */
    3368     6824714 :         r = rel->l;
    3369     6824714 :         if (is_select(rel->op) && r && r->exps && is_select(r->op) && !(rel_is_ref(r)) && !exps_have_func(rel->exps)) {
    3370          27 :                 (void)list_merge(r->exps, rel->exps, (fdup)NULL);
    3371          27 :                 rel->l = NULL;
    3372          27 :                 rel_destroy(rel);
    3373          27 :                 v->changes++;
    3374          27 :                 return try_remove_empty_select(v, r);
    3375             :         }
    3376             :         /*
    3377             :          * Push select through semi/anti join
    3378             :          *      select (semi(A,B)) == semi(select(A), B)
    3379             :          */
    3380     6824687 :         if (is_select(rel->op) && r && is_semi(r->op) && !(rel_is_ref(r))) {
    3381         304 :                 rel->l = r->l;
    3382         304 :                 r->l = rel;
    3383         304 :                 v->changes++;
    3384             :                 /*
    3385             :                  * if A has 2 references (ie used on both sides of
    3386             :                  * the semi join), we also push the select into A.
    3387             :                  */
    3388         304 :                 if (rel_is_ref(rel->l) && rel->l == rel_find_ref(r->r)){
    3389           0 :                         sql_rel *lx = rel->l;
    3390           0 :                         sql_rel *rx = r->r;
    3391           0 :                         if (lx->ref.refcnt == 2 && !rel_is_ref(rx)) {
    3392           0 :                                 while (rx->l && !rel_is_ref(rx->l) &&
    3393           0 :                                        (is_project(rx->op) ||
    3394             :                                         is_select(rx->op) ||
    3395             :                                         is_join(rx->op)))
    3396             :                                                 rx = rx->l;
    3397             :                                 /* probably we need to introduce a project */
    3398           0 :                                 rel_destroy(rel->l);
    3399           0 :                                 lx = rel_project(v->sql->sa, rel, rel_projections(v->sql, rel, NULL, 1, 1));
    3400           0 :                                 r->l = lx;
    3401           0 :                                 rx->l = rel_dup(lx);
    3402             :                         }
    3403             :                 }
    3404         304 :                 return r;
    3405             :         }
    3406     6824383 :         exps = rel->exps;
    3407             : 
    3408             :         /* push select through join */
    3409     6824383 :         if (is_select(rel->op) && r && is_join(r->op) && !rel_is_ref(r) && !is_single(r)){
    3410       21975 :                 sql_rel *jl = r->l, *ojl = jl, *jr = r->r, *ojr = jr;
    3411       21975 :                 int left = r->op == op_join || r->op == op_left;
    3412       21975 :                 int right = r->op == op_join || r->op == op_right;
    3413             : 
    3414       21975 :                 if (r->op == op_full)
    3415             :                         return rel;
    3416             : 
    3417             :                 /* introduce selects under the join (if needed) */
    3418       21949 :                 set_processed(jl);
    3419       21949 :                 set_processed(jr);
    3420       48240 :                 for (n = exps->h; n;) {
    3421       26291 :                         node *next = n->next;
    3422       26291 :                         sql_exp *e = n->data;
    3423             : 
    3424       26291 :                         if (!exp_unsafe(e, false, true)) {
    3425       26085 :                                 if (left && rel_rebind_exp(v->sql, jl, e)) {
    3426       13257 :                                         if (!is_select(jl->op) || rel_is_ref(jl))
    3427       11071 :                                                 r->l = jl = rel_select(v->sql->sa, jl, NULL);
    3428       13257 :                                         rel_select_add_exp(v->sql->sa, jl, e);
    3429       13257 :                                         list_remove_node(exps, NULL, n);
    3430       13257 :                                         v->changes++;
    3431       12828 :                                 } else if (right && rel_rebind_exp(v->sql, jr, e)) {
    3432        5132 :                                         if (!is_select(jr->op) || rel_is_ref(jr))
    3433        4206 :                                                 r->r = jr = rel_select(v->sql->sa, jr, NULL);
    3434        5132 :                                         rel_select_add_exp(v->sql->sa, jr, e);
    3435        5132 :                                         list_remove_node(exps, NULL, n);
    3436        5132 :                                         v->changes++;
    3437             :                                 }
    3438             :                         }
    3439             :                         n = next;
    3440             :                 }
    3441       21949 :                 if (ojl != jl)
    3442       11071 :                         set_processed(jl);
    3443       21949 :                 if (ojr != jr)
    3444        4206 :                         set_processed(jr);
    3445             :         }
    3446             : 
    3447             :         /* merge select and cross product ? */
    3448     6824357 :         if (is_select(rel->op) && r && r->op == op_join && !rel_is_ref(r) && !is_single(r) && !exps_have_unsafe(exps, false, true)) {
    3449       14486 :                 for (n = exps->h; n;) {
    3450        1913 :                         node *next = n->next;
    3451        1913 :                         sql_exp *e = n->data;
    3452             : 
    3453        1913 :                         if (exp_is_join(e, NULL) == 0) {
    3454         693 :                                 if (!r->exps)
    3455         109 :                                         r->exps = sa_list(v->sql->sa);
    3456         693 :                                 append(r->exps, e);
    3457         693 :                                 list_remove_node(exps, NULL, n);
    3458         693 :                                 v->changes++;
    3459             :                         }
    3460             :                         n = next;
    3461             :                 }
    3462             :         }
    3463             : 
    3464     6824357 :         if (is_select(rel->op) && r && (is_simple_project(r->op) || (is_groupby(r->op) && !list_empty(r->r))) && !rel_is_ref(r) && !is_single(r)){
    3465       69594 :                 sql_rel *pl = r->l, *opl = pl;
    3466             :                 /* we cannot push through window functions (for safety I disabled projects over DDL too) */
    3467       69594 :                 if (pl && pl->op != op_ddl && !exps_have_unsafe(r->exps, false, false)) {
    3468             :                         /* introduce selects under the project (if needed) */
    3469       48768 :                         set_processed(pl);
    3470       48768 :                         if (!pl->exps)
    3471         411 :                                 pl->exps = sa_list(v->sql->sa);
    3472      103834 :                         for (n = exps->h; n;) {
    3473       55066 :                                 node *next = n->next;
    3474       55066 :                                 sql_exp *e = n->data, *ne = NULL;
    3475             : 
    3476             :                                 /* can we move it down */
    3477       55066 :                                 if (e->type == e_cmp && (ne = exp_push_down_prj(v->sql, e, r, pl)) && ne != e) {
    3478       25440 :                                         if (!(is_select(pl->op) && is_join(pl->op) && is_semi(pl->op)) || rel_is_ref(pl))
    3479       25440 :                                                 r->l = pl = rel_select(v->sql->sa, pl, NULL);
    3480       25440 :                                         rel_select_add_exp(v->sql->sa, pl, ne);
    3481       25440 :                                         list_remove_node(exps, NULL, n);
    3482       25440 :                                         v->changes++;
    3483             :                                 }
    3484             :                                 n = next;
    3485             :                         }
    3486       48768 :                         if (opl != pl)
    3487       18348 :                                 set_processed(pl);
    3488             :                 }
    3489             : 
    3490             :                 /* push filters if they match the aggregation key on a window function */
    3491        3623 :                 else if (pl && pl->op != op_ddl && exps_have_unsafe(r->exps, false, false)) {
    3492        3623 :                         set_processed(pl);
    3493             :                         /* list of aggregation key columns */
    3494        3623 :                         list *aggColumns = get_aggregation_key_columns(v->sql->sa, r);
    3495             : 
    3496             :                         /* aggregation keys found, check if any filter matches them */
    3497        3623 :                         if (aggColumns) {
    3498         325 :                                 for (n = exps->h; n;) {
    3499         191 :                                         node *next = n->next;
    3500         191 :                                         sql_exp *e = n->data, *ne = NULL;
    3501             : 
    3502         191 :                                         if (e->type == e_cmp) {
    3503             :                                                 /* simple comparison filter */
    3504         191 :                                                 if (e->flag == cmp_gt || e->flag == cmp_gte || e->flag == cmp_lte || e->flag == cmp_lt
    3505         191 :                                                         || e->flag == cmp_equal || e->flag == cmp_notequal || e->flag == cmp_in || e->flag == cmp_notin
    3506           5 :                                                         || (e->flag == cmp_filter && ((list*)e->l)->cnt == 1)) {
    3507         187 :                                                         sql_exp* column;
    3508             :                                                         /* the column in 'like' filters is stored inside a list */
    3509         187 :                                                         if (e->flag == cmp_filter) {
    3510           1 :                                                                 column = ((list*)e->l)->h->data;
    3511             :                                                         } else {
    3512         186 :                                                                 column = e->l;
    3513             :                                                         }
    3514             : 
    3515             :                                                         /* check if the expression matches any aggregation key, meaning we can
    3516             :                                                            try to safely push it down */
    3517         187 :                                                         if (filter_column_in_aggregation_columns(column, aggColumns)) {
    3518           9 :                                                                 ne = exp_push_down_prj(v->sql, e, r, pl);
    3519             : 
    3520             :                                                                 /* can we move it down */
    3521           9 :                                                                 if (ne && ne != e && pl->exps) {
    3522           9 :                                                                         if (!is_select(pl->op) || rel_is_ref(pl))
    3523           8 :                                                                                 r->l = pl = rel_select(v->sql->sa, pl, NULL);
    3524           9 :                                                                         rel_select_add_exp(v->sql->sa, pl, ne);
    3525           9 :                                                                         list_remove_node(exps, NULL, n);
    3526           9 :                                                                         v->changes++;
    3527             :                                                                 }
    3528             :                                                         }
    3529             :                                                 }
    3530             :                                         }
    3531             :                                         n = next;
    3532             :                                 }
    3533             : 
    3534             :                                 /* cleanup list */
    3535         134 :                                 list_destroy(aggColumns);
    3536             :                         }
    3537             :                 }
    3538             :         }
    3539             : 
    3540             :         /* try push select under set relation */
    3541     6824357 :         if (is_select(rel->op) && r && is_set(r->op) && !list_empty(r->exps) && !rel_is_ref(r) && !is_single(r) && !list_empty(exps)) {
    3542          19 :                 sql_rel *u = r, *ul = u->l, *ur = u->r;
    3543             : 
    3544          19 :                 ul = rel_dup(ul);
    3545          19 :                 ur = rel_dup(ur);
    3546          19 :                 if (!is_project(ul->op))
    3547           0 :                         ul = rel_project(v->sql->sa, ul,
    3548             :                                 rel_projections(v->sql, ul, NULL, 1, 1));
    3549          19 :                 if (!is_project(ur->op))
    3550           0 :                         ur = rel_project(v->sql->sa, ur,
    3551             :                                 rel_projections(v->sql, ur, NULL, 1, 1));
    3552          19 :                 rel_rename_exps(v->sql, u->exps, ul->exps);
    3553          19 :                 rel_rename_exps(v->sql, u->exps, ur->exps);
    3554             : 
    3555             :                 /* introduce selects under the set */
    3556          19 :                 ul = rel_select(v->sql->sa, ul, NULL);
    3557          19 :                 ul->exps = exps_copy(v->sql, exps);
    3558          19 :                 set_processed(ul);
    3559          19 :                 ur = rel_select(v->sql->sa, ur, NULL);
    3560          19 :                 ur->exps = exps_copy(v->sql, exps);
    3561          19 :                 set_processed(ur);
    3562             : 
    3563          19 :                 rel = rel_inplace_setop(v->sql, rel, ul, ur, u->op, rel_projections(v->sql, rel, NULL, 1, 1));
    3564          19 :                 if (need_distinct(u))
    3565           0 :                         set_distinct(rel);
    3566          19 :                 v->changes++;
    3567             :         }
    3568     6824357 :         if (is_select(rel->op) && r && is_munion(r->op) && !list_empty(r->exps) && !rel_is_ref(r) && !is_single(r) && !list_empty(exps)) {
    3569        4887 :                 sql_rel *u = r;
    3570        4887 :                 list *rels = u->l, *nrels = sa_list(v->sql->sa);
    3571       14687 :                 for(node *n = rels->h; n; n = n->next) {
    3572        9800 :                         sql_rel *ul = n->data;
    3573        9800 :                         ul = rel_dup(ul);
    3574        9800 :                         if (!is_project(ul->op))
    3575           8 :                                 ul = rel_project(v->sql->sa, ul,
    3576             :                                         rel_projections(v->sql, ul, NULL, 1, 1));
    3577        9800 :                         rel_rename_exps(v->sql, u->exps, ul->exps);
    3578             : 
    3579             :                         /* introduce selects under the set */
    3580        9800 :                         ul = rel_select(v->sql->sa, ul, NULL);
    3581        9800 :                         ul->exps = exps_copy(v->sql, exps);
    3582        9800 :                         set_processed(ul);
    3583        9800 :                         nrels = append(nrels, ul);
    3584             :                 }
    3585             : 
    3586        4887 :                 rel = rel_inplace_setop_n_ary(v->sql, rel, nrels, u->op, rel_projections(v->sql, rel, NULL, 1, 1));
    3587        4887 :                 if (need_distinct(u))
    3588           6 :                         set_distinct(rel);
    3589        4887 :                 v->changes++;
    3590             :         }
    3591             : 
    3592     6824357 :         return try_remove_empty_select(v, rel);
    3593             : }
    3594             : 
    3595             : static int
    3596       12033 : index_exp(sql_exp *e, sql_idx *i)
    3597             : {
    3598       12033 :         if (e->type == e_cmp && !is_complex_exp(e->flag)) {
    3599        6776 :                 switch(i->type) {
    3600        6776 :                 case hash_idx:
    3601             :                 case oph_idx:
    3602        6776 :                         if (e->flag == cmp_equal)
    3603             :                                 return 0;
    3604             :                         /* fall through */
    3605             :                 case join_idx:
    3606             :                 default:
    3607        1252 :                         return -1;
    3608             :                 }
    3609             :         }
    3610             :         return -1;
    3611             : }
    3612             : 
    3613             : /* find column for the select/join expression */
    3614             : static sql_column *
    3615        5524 : sjexp_col(sql_exp *e, sql_rel *r)
    3616             : {
    3617        5524 :         sql_column *res = NULL;
    3618             : 
    3619        5524 :         if (e->type == e_cmp && !is_complex_exp(e->flag)) {
    3620        5524 :                 res = exp_find_column(r, e->l, -2);
    3621        5524 :                 if (!res)
    3622         466 :                         res = exp_find_column(r, e->r, -2);
    3623             :         }
    3624        5524 :         return res;
    3625             : }
    3626             : 
    3627             : static sql_idx *
    3628     1768269 : find_index(allocator *sa, sql_rel *rel, sql_rel *sub, list **EXPS)
    3629             : {
    3630     1768269 :         node *n;
    3631             : 
    3632             :         /* any (partial) match of the expressions with the index columns */
    3633             :         /* Depending on the index type we may need full matches and only
    3634             :            limited number of cmp types (hash only equality etc) */
    3635             :         /* Depending on the index type we should (in the rel_bin) generate
    3636             :            more code, ie for spatial index add post filter etc, for hash
    3637             :            compute hash value and use index */
    3638             : 
    3639     1768269 :         if (sub->exps && rel->exps)
    3640     7102372 :         for(n = sub->exps->h; n; n = n->next) {
    3641     5516207 :                 prop *p;
    3642     5516207 :                 sql_exp *e = n->data;
    3643             : 
    3644     5516207 :                 if ((p = find_prop(e->p, PROP_HASHIDX)) != NULL) {
    3645        9408 :                         list *exps, *cols;
    3646        9408 :                         sql_idx *i = p->value.pval;
    3647        9408 :                         fcmp cmp = (fcmp)&sql_column_kc_cmp;
    3648             : 
    3649             :                         /* join indices are only interesting for joins */
    3650        9408 :                         if (i->type == join_idx || list_length(i->columns) <= 1)
    3651           0 :                                 continue;
    3652             :                         /* based on the index type, find qualifying exps */
    3653        9408 :                         exps = list_select(rel->exps, i, (fcmp) &index_exp, (fdup)NULL);
    3654        9408 :                         if (list_empty(exps))
    3655        4848 :                                 continue;
    3656             :                         /* now we obtain the columns, move into sql_column_kc_cmp! */
    3657        4560 :                         cols = list_map(exps, sub, (fmap) &sjexp_col);
    3658             : 
    3659             :                         /* TODO check that at most 2 relations are involved */
    3660             : 
    3661             :                         /* Match the index columns with the expression columns.
    3662             :                            TODO, Allow partial matches ! */
    3663        4560 :                         if (list_match(cols, i->columns, cmp) == 0) {
    3664             :                                 /* re-order exps in index order */
    3665         286 :                                 node *n, *m;
    3666         286 :                                 list *es = sa_list(sa);
    3667             : 
    3668         958 :                                 for(n = i->columns->h; n; n = n->next) {
    3669         672 :                                         int i = 0;
    3670        2152 :                                         for(m = cols->h; m; m = m->next, i++) {
    3671        2152 :                                                 if (cmp(m->data, n->data) == 0){
    3672         672 :                                                         sql_exp *e = list_fetch(exps, i);
    3673         672 :                                                         list_append(es, e);
    3674         672 :                                                         break;
    3675             :                                                 }
    3676             :                                         }
    3677             :                                 }
    3678             :                                 /* fix the destroy function */
    3679         286 :                                 cols->destroy = NULL;
    3680         286 :                                 *EXPS = es;
    3681         286 :                                 e->used = 1;
    3682         286 :                                 return i;
    3683             :                         }
    3684        4274 :                         cols->destroy = NULL;
    3685             :                 }
    3686             :         }
    3687             :         return NULL;
    3688             : }
    3689             : 
    3690             : static inline sql_rel *
    3691     1155269 : rel_use_index(visitor *v, sql_rel *rel)
    3692             : {
    3693     1155269 :         list *exps = NULL;
    3694     1155269 :         sql_idx *i = find_index(v->sql->sa, rel, rel->l, &exps);
    3695     1155269 :         int left = 1;
    3696             : 
    3697     1155269 :         assert(is_select(rel->op) || is_join(rel->op));
    3698     1155269 :         if (!i && is_join(rel->op)) {
    3699      613000 :                 left = 0;
    3700      613000 :                 i = find_index(v->sql->sa, rel, rel->r, &exps);
    3701             :         }
    3702             : 
    3703     1155089 :         if (i) {
    3704         286 :                 prop *p;
    3705         286 :                 node *n;
    3706         286 :                 int single_table = 1;
    3707         286 :                 sql_exp *re = NULL;
    3708             : 
    3709         956 :                 for( n = exps->h; n && single_table; n = n->next) {
    3710         670 :                         sql_exp *e = n->data, *nre = e->l;
    3711             : 
    3712         670 :                         if (!is_compare(e->type) || is_anti(e) || e->flag != cmp_equal)
    3713             :                                 return rel;
    3714         670 :                         if (is_join(rel->op) && ((left && !rel_find_exp(rel->l, nre)) || (!left && rel_find_exp(rel->r, nre))))
    3715         111 :                                 nre = e->r;
    3716         670 :                         single_table = (!re || (exp_relname(nre) && exp_relname(re) && strcmp(exp_relname(nre), exp_relname(re)) == 0));
    3717         670 :                         re = nre;
    3718             :                 }
    3719         286 :                 if (single_table) { /* add PROP_HASHCOL to all column exps */
    3720         932 :                         for( n = exps->h; n; n = n->next) {
    3721         654 :                                 sql_exp *e = n->data;
    3722             : 
    3723             :                                 /* swapped ? */
    3724         654 :                                 if (is_join(rel->op) && ((left && !rel_find_exp(rel->l, e->l)) || (!left && !rel_find_exp(rel->r, e->l)))) {
    3725         165 :                                         exp_swap(e);
    3726             :                                 }
    3727         654 :                                 p = find_prop(e->p, PROP_HASHCOL);
    3728         654 :                                 if (!p)
    3729         285 :                                         e->p = p = prop_create(v->sql->sa, PROP_HASHCOL, e->p);
    3730         654 :                                 p->value.pval = i;
    3731             :                         }
    3732             :                 }
    3733             :                 /* add the remaining exps to the new exp list */
    3734         286 :                 if (list_length(rel->exps) > list_length(exps)) {
    3735         108 :                         for( n = rel->exps->h; n; n = n->next) {
    3736          81 :                                 sql_exp *e = n->data;
    3737          81 :                                 if (!list_find(exps, e, (fcmp)&exp_cmp))
    3738          27 :                                         list_append(exps, e);
    3739             :                         }
    3740             :                 }
    3741         286 :                 rel->exps = exps;
    3742             :         }
    3743             :         return rel;
    3744             : }
    3745             : 
    3746             : static sql_rel *
    3747     3636299 : rel_select_leftgroup_2_semi(visitor *v, sql_rel *rel)
    3748             : {
    3749     3636299 :         if (rel_is_ref(rel) || !is_select(rel->op) || list_empty(rel->exps))
    3750     3104310 :                 return rel;
    3751      531989 :         sql_rel *l = rel->l;
    3752             : 
    3753      531989 :         if (!l || rel_is_ref(l) || !is_left(l->op) || list_empty(l->attr))
    3754      531003 :                 return rel;
    3755             : 
    3756        1964 :         for(node *n = rel->exps->h; n; n = n->next) {
    3757         986 :                 sql_exp *e = n->data;
    3758             : 
    3759         986 :                 if (e->type == e_cmp && !is_semantics(e) && !e->f) {
    3760         973 :                         list *attrs = l->attr;
    3761         973 :                         sql_exp *a = attrs->h->data;
    3762             : 
    3763         973 :                         if (exps_find_exp(l->attr, e->l) && exp_is_true(e->r) && e->flag == cmp_equal /*&& exp_is_true(a)*/) {
    3764             :                                 // printf("# optimize select leftgroup -> semi\n");
    3765           8 :                                 if (!list_empty(l->exps)) {
    3766          13 :                                         for(node *m = l->exps->h; m; m = m->next) {
    3767           7 :                                                 sql_exp *j = m->data;
    3768           7 :                                                 reset_any(j);
    3769             :                                         }
    3770             :                                 }
    3771           8 :                                 l->attr = NULL;
    3772           8 :                                 l->op = exp_is_true(a)?op_semi:op_anti;
    3773           8 :                                 list_remove_node(rel->exps, NULL, n);
    3774           8 :                                 rel = rel_project(v->sql->sa, rel, rel_projections(v->sql, rel, NULL, 1, 1));
    3775           8 :                                 list_append(rel->exps, attrs->h->data);
    3776           8 :                                 v->changes++;
    3777           8 :                                 return rel;
    3778             :                         }
    3779             :                 }
    3780             :         }
    3781             :         return rel;
    3782             : }
    3783             : 
    3784             : static sql_rel *
    3785     3636299 : rel_optimize_select_and_joins_topdown_(visitor *v, sql_rel *rel)
    3786             : {
    3787             :         /* push_join_down introduces semijoins */
    3788     3636299 :         uint8_t cycle = *(uint8_t*) v->data;
    3789     3636299 :         if (cycle <= 0) {
    3790     1583515 :                 rel = rel_semijoin_use_fk(v, rel);
    3791     1583515 :                 rel = rel_push_join_down(v, rel);
    3792             :         }
    3793             : 
    3794     3636299 :         rel = rel_simplify_fk_joins(v, rel);
    3795     3636299 :         rel = rel_push_select_down(v, rel);
    3796     3636299 :         rel = rel_select_leftgroup_2_semi(v, rel);
    3797     3636299 :         if (rel && rel->l && (is_select(rel->op) || is_join(rel->op)))
    3798     1155269 :                 rel = rel_use_index(v, rel);
    3799     3636299 :         return rel;
    3800             : }
    3801             : 
    3802             : static sql_rel *
    3803      125747 : rel_optimize_select_and_joins_topdown(visitor *v, global_props *gp, sql_rel *rel)
    3804             : {
    3805      125747 :         v->data = &gp->opt_cycle;
    3806      125747 :         rel = rel_visitor_topdown(v, rel, &rel_optimize_select_and_joins_topdown_);
    3807      125747 :         v->data = gp;
    3808      125747 :         return rel;
    3809             : }
    3810             : 
    3811             : run_optimizer
    3812      622727 : bind_optimize_select_and_joins_topdown(visitor *v, global_props *gp)
    3813             : {
    3814      622727 :         int flag = v->sql->sql_optimizer;
    3815      622531 :         return gp->opt_level == 1 && (gp->cnt[op_join] || gp->cnt[op_left] || gp->cnt[op_right]
    3816      538662 :                    || gp->cnt[op_full] || gp->cnt[op_semi] || gp->cnt[op_anti] ||
    3817     1245258 :                    gp->cnt[op_select]) && (flag & optimize_select_and_joins_topdown) ? rel_optimize_select_and_joins_topdown : NULL;
    3818             : }
    3819             : 
    3820             : 
    3821             : static int
    3822     1240438 : can_push_func(sql_exp *e, sql_rel *rel, int *must, int depth)
    3823             : {
    3824     1284462 :         switch(e->type) {
    3825     1086847 :         case e_cmp: {
    3826     1086847 :                 sql_exp *l = e->l, *r = e->r, *f = e->f;
    3827             : 
    3828             :                 /* don't push down functions inside attribute joins */
    3829     1086847 :                 if (e->flag == cmp_or || e->flag == cmp_in || e->flag == cmp_notin || e->flag == cmp_filter || (is_join(rel->op) && is_any(e)))
    3830             :                         return 0;
    3831     1031257 :                 if (depth > 0) { /* for comparisons under the top ones, they become functions */
    3832          58 :                         int lmust = 0;
    3833          58 :                         int res = can_push_func(l, rel, &lmust, depth + 1) && can_push_func(r, rel, &lmust, depth + 1) &&
    3834          20 :                                         (!f || can_push_func(f, rel, &lmust, depth + 1));
    3835          12 :                         if (res && !lmust)
    3836             :                                 return 1;
    3837          54 :                         (*must) |= lmust;
    3838          54 :                         return res;
    3839             :                 } else {
    3840     1031199 :                         int mustl = 0, mustr = 0, mustf = 0;
    3841     1031199 :                         return ((l->type == e_column || can_push_func(l, rel, &mustl, depth + 1)) && (*must = mustl)) ||
    3842     2055357 :                                         ((r->type == e_column || can_push_func(r, rel, &mustr, depth + 1)) && (*must = mustr)) ||
    3843        3644 :                                         ((f && (f->type == e_column || can_push_func(f, rel, &mustf, depth + 1)) && (*must = mustf)));
    3844             :                 }
    3845             :         }
    3846       44024 :         case e_convert:
    3847       44024 :                 return can_push_func(e->l, rel, must, depth + 1);
    3848        9457 :         case e_aggr:
    3849             :         case e_func: {
    3850        9457 :                 list *l = e->l;
    3851        9457 :                 int res = 1, lmust = 0;
    3852             : 
    3853        9457 :                 if (exp_unsafe(e, false, false))
    3854             :                         return 0;
    3855       26949 :                 if (l) for (node *n = l->h; n && res; n = n->next)
    3856       17492 :                         res &= can_push_func(n->data, rel, &lmust, depth + 1);
    3857        9457 :                 if (res && !lmust)
    3858             :                         return 1;
    3859        8610 :                 (*must) |= lmust;
    3860        8610 :                 return res;
    3861             :         }
    3862       50238 :         case e_column:
    3863       50238 :                 if (rel && !rel_find_exp(rel, e))
    3864             :                         return 0;
    3865       29605 :                 (*must) = 1;
    3866             :                 /* fall through */
    3867             :         default:
    3868             :                 return 1;
    3869             :         }
    3870             : }
    3871             : 
    3872             : static int
    3873      901506 : exps_can_push_func(list *exps, sql_rel *rel)
    3874             : {
    3875     3922134 :         for(node *n = exps->h; n; n = n->next) {
    3876     3044370 :                 sql_exp *e = n->data;
    3877     3044370 :                 int mustl = 0, mustr = 0;
    3878             : 
    3879     3044370 :                 if ((is_joinop(rel->op) || is_select(rel->op)) && ((can_push_func(e, rel->l, &mustl, 0) && mustl)))
    3880       23742 :                         return 1;
    3881     3040106 :                 if (is_joinop(rel->op) && can_push_func(e, rel->r, &mustr, 0) && mustr)
    3882             :                         return 1;
    3883             :         }
    3884             :         return 0;
    3885             : }
    3886             : 
    3887             : static int
    3888       81960 : exp_needs_push_down(sql_rel *rel, sql_exp *e)
    3889             : {
    3890      106354 :         switch(e->type) {
    3891       27512 :         case e_cmp:
    3892             :                 /* don't push down functions inside attribute joins */
    3893       27512 :                 if (e->flag == cmp_or || e->flag == cmp_in || e->flag == cmp_notin || e->flag == cmp_filter || (is_join(rel->op) && is_any(e)))
    3894             :                         return 0;
    3895       26576 :                 return exp_needs_push_down(rel, e->l) || exp_needs_push_down(rel, e->r) || (e->f && exp_needs_push_down(rel, e->f));
    3896       24394 :         case e_convert:
    3897       24394 :                 return exp_needs_push_down(rel, e->l);
    3898        1922 :         case e_aggr:
    3899             :         case e_func:
    3900        1922 :                 if (!e->l || exps_are_atoms(e->l))
    3901          20 :                         return 0;
    3902             :                 return 1;
    3903        1459 :         case e_atom:
    3904        1459 :                 if (!e->f || exps_are_atoms(e->f))
    3905        1459 :                         return 0;
    3906             :                 return 1;
    3907             :         case e_column:
    3908             :         default:
    3909             :                 return 0;
    3910             :         }
    3911             : }
    3912             : 
    3913             : static int
    3914       23742 : exps_need_push_down(sql_rel *rel, list *exps )
    3915             : {
    3916       49344 :         for(node *n = exps->h; n; n = n->next)
    3917       27504 :                 if (exp_needs_push_down(rel, n->data))
    3918             :                         return 1;
    3919             :         return 0;
    3920             : }
    3921             : 
    3922             : static sql_exp *exp_push_single_func_down(visitor *v, sql_rel *rel, sql_rel *ol, sql_rel *or, sql_exp *e, int depth);
    3923             : 
    3924             : static list *
    3925        2414 : exps_push_single_func_down(visitor *v, sql_rel *rel, sql_rel *ol, sql_rel *or, list *exps, int depth)
    3926             : {
    3927        4828 :         if (mvc_highwater(v->sql))
    3928             :                 return exps;
    3929             : 
    3930        6724 :         for (node *n = exps->h; n; n = n->next)
    3931        4310 :                 if ((n->data = exp_push_single_func_down(v, rel, ol, or, n->data, depth)) == NULL)
    3932             :                         return NULL;
    3933             :         return exps;
    3934             : }
    3935             : 
    3936             : static sql_exp *
    3937       15731 : exp_push_single_func_down(visitor *v, sql_rel *rel, sql_rel *ol, sql_rel *or, sql_exp *e, int depth)
    3938             : {
    3939       27503 :         if (mvc_highwater(v->sql))
    3940             :                 return e;
    3941             : 
    3942       15731 :         switch(e->type) {
    3943        4247 :         case e_cmp: {
    3944        4247 :                 if (e->flag == cmp_or || e->flag == cmp_filter) {
    3945         247 :                         if ((e->l = exps_push_single_func_down(v, rel, ol, or, e->l, depth + 1)) == NULL)
    3946             :                                 return NULL;
    3947         247 :                         if ((e->r = exps_push_single_func_down(v, rel, ol, or, e->r, depth + 1)) == NULL)
    3948             :                                 return NULL;
    3949        4000 :                 } else if (e->flag == cmp_in || e->flag == cmp_notin) {
    3950          18 :                         if ((e->l = exp_push_single_func_down(v, rel, ol, or, e->l, depth + 1)) == NULL)
    3951             :                                 return NULL;
    3952          18 :                         if ((e->r = exps_push_single_func_down(v, rel, ol, or, e->r, depth + 1)) == NULL)
    3953             :                                 return NULL;
    3954             :                 } else {
    3955        3982 :                         if ((e->l = exp_push_single_func_down(v, rel, ol, or, e->l, depth + 1)) == NULL)
    3956             :                                 return NULL;
    3957        3982 :                         if ((e->r = exp_push_single_func_down(v, rel, ol, or, e->r, depth + 1)) == NULL)
    3958             :                                 return NULL;
    3959        3982 :                         if (e->f && (e->f = exp_push_single_func_down(v, rel, ol, or, e->f, depth + 1)) == NULL)
    3960             :                                 return NULL;
    3961             :                 }
    3962             :         } break;
    3963        2004 :         case e_convert:
    3964        2004 :                 if ((e->l = exp_push_single_func_down(v, rel, ol, or, e->l, depth + 1)) == NULL)
    3965             :                         return NULL;
    3966             :                 break;
    3967        3982 :         case e_aggr:
    3968             :         case e_func: {
    3969        3982 :                 sql_rel *l = rel->l, *r = rel->r;
    3970        3982 :                 int must = 0, mustl = 0, mustr = 0;
    3971             : 
    3972        3982 :                 if (exp_unsafe(e, false, false))
    3973          23 :                         return e;
    3974        3982 :                 if (!e->l || exps_are_atoms(e->l))
    3975          23 :                         return e;
    3976        3959 :                 if ((is_joinop(rel->op) && ((can_push_func(e, l, &mustl, depth + 1) && mustl) || (can_push_func(e, r, &mustr, depth + 1) && mustr))) ||
    3977        2977 :                         (is_select(rel->op) && can_push_func(e, l, &must, depth + 1) && must)) {
    3978        3946 :                         exp_label(v->sql->sa, e, ++v->sql->label);
    3979             :                         /* we need a full projection, group by's and unions cannot be extended with more expressions */
    3980        3946 :                         if (mustr) {
    3981         352 :                                 if (r == or) /* don't project twice */
    3982         329 :                                         rel->r = r = rel_project(v->sql->sa, r, rel_projections(v->sql, r, NULL, 1, 1));
    3983         352 :                                 list_append(r->exps, e);
    3984             :                         } else {
    3985        3594 :                                 if (l == ol) /* don't project twice */
    3986        1838 :                                         rel->l = l = rel_project(v->sql->sa, l, rel_projections(v->sql, l, NULL, 1, 1));
    3987        3594 :                                 list_append(l->exps, e);
    3988             :                         }
    3989        3946 :                         e = exp_ref(v->sql, e);
    3990        3946 :                         v->changes++;
    3991             :                 }
    3992        3959 :         } break;
    3993        1156 :         case e_atom: {
    3994        1156 :                 if (e->f && (e->f = exps_push_single_func_down(v, rel, ol, or, e->f, depth + 1)) == NULL)
    3995             :                         return NULL;
    3996             :         } break;
    3997             :         case e_column:
    3998             :         case e_psm:
    3999             :                 break;
    4000             :         }
    4001             :         return e;
    4002             : }
    4003             : 
    4004             : static inline sql_rel *
    4005     3562847 : rel_push_func_down(visitor *v, sql_rel *rel)
    4006             : {
    4007     3562847 :         if ((is_select(rel->op) || is_joinop(rel->op)) && rel->l && rel->exps && !(rel_is_ref(rel))) {
    4008     1080818 :                 int changes = v->changes;
    4009     1080818 :                 sql_rel *l = rel->l, *r = rel->r;
    4010             : 
    4011             :                 /* only push down when is useful */
    4012     1080818 :                 if ((is_select(rel->op) && list_length(rel->exps) <= 1) || rel_is_ref(l) || (is_joinop(rel->op) && rel_is_ref(r)))
    4013      531530 :                         return rel;
    4014      549288 :                 if (exps_can_push_func(rel->exps, rel) && exps_need_push_down(rel, rel->exps) && !exps_push_single_func_down(v, rel, l, r, rel->exps, 0))
    4015             :                         return NULL;
    4016      549288 :                 if (v->changes > changes) /* once we get a better join order, we can try to remove this projection */
    4017        1902 :                         return rel_project(v->sql->sa, rel, rel_projections(v->sql, rel, NULL, 1, 1));
    4018             :         }
    4019     3029415 :         if (is_simple_project(rel->op) && rel->l && rel->exps) {
    4020     1125937 :                 sql_rel *pl = rel->l;
    4021             : 
    4022     1125937 :                 if (is_joinop(pl->op) && exps_can_push_func(rel->exps, rel)) {
    4023           0 :                         sql_rel *l = pl->l, *r = pl->r, *ol = l, *or = r;
    4024             : 
    4025           0 :                         for (node *n = rel->exps->h; n; ) {
    4026           0 :                                 node *next = n->next;
    4027           0 :                                 sql_exp *e = n->data;
    4028           0 :                                 int mustl = 0, mustr = 0;
    4029             : 
    4030           0 :                                 if ((can_push_func(e, l, &mustl, 0) && mustl) || (can_push_func(e, r, &mustr, 0) && mustr)) {
    4031           0 :                                         if (mustl) {
    4032           0 :                                                 if (l == ol) /* don't project twice */
    4033           0 :                                                         pl->l = l = rel_project(v->sql->sa, l, rel_projections(v->sql, l, NULL, 1, 1));
    4034           0 :                                                 list_append(l->exps, e);
    4035           0 :                                                 list_remove_node(rel->exps, NULL, n);
    4036           0 :                                                 v->changes++;
    4037             :                                         } else {
    4038           0 :                                                 if (r == or) /* don't project twice */
    4039           0 :                                                         pl->r = r = rel_project(v->sql->sa, r, rel_projections(v->sql, r, NULL, 1, 1));
    4040           0 :                                                 list_append(r->exps, e);
    4041           0 :                                                 list_remove_node(rel->exps, NULL, n);
    4042           0 :                                                 v->changes++;
    4043             :                                         }
    4044             :                                 }
    4045           0 :                                 n = next;
    4046             :                         }
    4047             :                 }
    4048             :         }
    4049             :         return rel;
    4050             : }
    4051             : 
    4052             : static sql_rel *
    4053     3562847 : rel_push_func_and_select_down_(visitor *v, sql_rel *rel)
    4054             : {
    4055     3562847 :         if (rel)
    4056     3562847 :                 rel = rel_push_func_down(v, rel);
    4057     3562847 :         if (rel)
    4058     3562847 :                 rel = rel_push_select_down(v, rel);
    4059     3562847 :         return rel;
    4060             : }
    4061             : 
    4062             : static sql_rel *
    4063      125747 : rel_push_func_and_select_down(visitor *v, global_props *gp, sql_rel *rel)
    4064             : {
    4065      125747 :         (void) gp;
    4066      125747 :         return rel_visitor_topdown(v, rel, &rel_push_func_and_select_down_);
    4067             : }
    4068             : 
    4069             : run_optimizer
    4070      622727 : bind_push_func_and_select_down(visitor *v, global_props *gp)
    4071             : {
    4072      622727 :         int flag = v->sql->sql_optimizer;
    4073      622531 :         return gp->opt_level == 1 && (gp->cnt[op_join] || gp->cnt[op_left] || gp->cnt[op_right]
    4074      538662 :                         || gp->cnt[op_full] || gp->cnt[op_semi] || gp->cnt[op_anti] || gp->cnt[op_select])
    4075      748473 :                         && (flag & push_func_and_select_down) ? rel_push_func_and_select_down : NULL;
    4076             : }

Generated by: LCOV version 1.14