LCOV - code coverage report
Current view: top level - sql/server - rel_optimize_others.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 634 769 82.4 %
Date: 2024-12-20 20:06:10 Functions: 27 29 93.1 %

          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.h"
      15             : #include "rel_optimizer_private.h"
      16             : #include "rel_exp.h"
      17             : #include "rel_select.h"
      18             : 
      19             : static void
      20           0 : rel_no_rename_exps( list *exps )
      21             : {
      22           0 :         for (node *n = exps->h; n; n = n->next) {
      23           0 :                 sql_exp *e = n->data;
      24             : 
      25           0 :                 exp_setalias(e, e->alias.label, e->l, e->r);
      26             :         }
      27           0 :         list_hash_clear(exps);
      28           0 : }
      29             : 
      30             : /* positional renames ! */
      31             : /* get the names (aka aliases) from the src_exps list and rename the dest_exps list */
      32             : void
      33       79973 : rel_rename_exps( mvc *sql, list *src_exps, list *dest_exps)
      34             : {
      35       79973 :         node *n, *m;
      36             : 
      37       79973 :         (void)sql;
      38             :         /* check if a column uses an alias earlier in the list */
      39             : 
      40       79973 :         assert(list_length(src_exps) <= list_length(dest_exps));
      41      670803 :         for (n = src_exps->h, m = dest_exps->h; n && m; n = n->next, m = m->next) {
      42      590830 :                 sql_exp *s = n->data;
      43      590830 :                 sql_exp *d = m->data;
      44      590830 :                 const char *rname = exp_relname(s);
      45             : 
      46      590830 :                 exp_setalias(d, s->alias.label, rname, exp_name(s));
      47             :         }
      48       79973 :         list_hash_clear(dest_exps);
      49       79973 : }
      50             : 
      51             : sql_rel *
      52      220471 : rel_find_ref( sql_rel *r)
      53             : {
      54      670481 :         while (!rel_is_ref(r) && r->l &&
      55      579400 :               (is_project(r->op) || is_select(r->op) /*|| is_join(r->op)*/))
      56             :                 r = r->l;
      57      220471 :         if (rel_is_ref(r))
      58       79750 :                 return r;
      59             :         return NULL;
      60             : }
      61             : 
      62             : /* merge projection */
      63             : 
      64             : /* push an expression through a projection.
      65             :  * The result should again be used in a projection.
      66             :  */
      67             : static list *
      68       56707 : exps_push_down_prj(mvc *sql, list *exps, sql_rel *f, sql_rel *t, bool keepalias)
      69             : {
      70       56707 :         node *n;
      71       56707 :         list *nl = new_exp_list(sql->sa);
      72             : 
      73      193782 :         for(n = exps->h; n; n = n->next) {
      74      139468 :                 sql_exp *arg = n->data, *narg = NULL;
      75             : 
      76      139468 :                 narg = exp_push_down_prj(sql, arg, f, t);
      77      139468 :                 if (!narg)
      78             :                         return NULL;
      79      137075 :                 narg = exp_propagate(sql->sa, narg, arg);
      80      137075 :                 if (!keepalias && narg->type == e_column)
      81       39685 :                         exp_setalias(narg, arg->alias.label, narg->l, narg->r);
      82      137075 :                 append(nl, narg);
      83             :         }
      84             :         return nl;
      85             : }
      86             : 
      87             : sql_exp *
      88     2657719 : exp_push_down_prj(mvc *sql, sql_exp *e, sql_rel *f, sql_rel *t)
      89             : {
      90     2657719 :         sql_exp *ne = NULL, *l = NULL, *r = NULL, *r2 = NULL;
      91             : 
      92     2657719 :         assert(is_project(f->op));
      93             : 
      94     2657719 :         switch(e->type) {
      95     2236857 :         case e_column:
      96     2236857 :                 assert(e->nid);
      97     2236857 :                 ne = exps_bind_nid(f->exps, e->nid);
      98     2236857 :                 if (!ne || (ne->type != e_column && (ne->type != e_atom || ne->f)))
      99             :                         return NULL;
     100     1909558 :                 while (ne && (has_label(ne) || is_selfref(ne) /*inside this list */) && is_simple_project(f->op) && ne->type == e_column) {
     101       11873 :                         sql_exp *oe = e, *one = ne;
     102             : 
     103       11873 :                         e = ne;
     104       11873 :                         ne = NULL;
     105       11873 :                         if (e->nid)
     106       11873 :                                 ne = exps_bind_nid(f->exps, e->nid);
     107       11873 :                         if (ne && ne != one && list_position(f->exps, ne) >= list_position(f->exps, one))
     108       11873 :                                 ne = NULL;
     109       11873 :                         if (!ne || ne == one) {
     110             :                                 ne = one;
     111     1909159 :                                 e = oe;
     112             :                                 break;
     113             :                         }
     114         399 :                         if (ne->type != e_column && (ne->type != e_atom || ne->f))
     115             :                                 return NULL;
     116             :                 }
     117             :                 /* possibly a groupby/project column is renamed */
     118     1909159 :                 if (is_groupby(f->op) && !list_empty(f->r) && ne->type == e_column) {
     119         130 :                         sql_exp *gbe = NULL;
     120         130 :                         if (ne->nid)
     121         130 :                                 gbe = exps_bind_nid(f->exps, ne->nid);
     122         130 :                         ne = gbe;
     123         130 :                         if (!ne || (ne->type != e_column && (ne->type != e_atom || ne->f)))
     124           0 :                                 return NULL;
     125             :                 }
     126     1909159 :                 return exp_copy(sql, ne);
     127       60505 :         case e_cmp:
     128       60505 :                 if (e->flag == cmp_or || e->flag == cmp_filter) {
     129        4265 :                         list *l = NULL, *r = NULL;
     130             : 
     131        4265 :                         if (!(l = exps_push_down_prj(sql, e->l, f, t, true)) || !(r = exps_push_down_prj(sql, e->r, f, t, true)))
     132        1246 :                                 return NULL;
     133        3019 :                         if (e->flag == cmp_filter) {
     134        1022 :                                 ne = exp_filter(sql->sa, l, r, e->f, is_anti(e));
     135             :                         } else {
     136        1997 :                                 ne = exp_or(sql->sa, l, r, is_anti(e));
     137             :                         }
     138       56240 :                 } else if (e->flag == cmp_in || e->flag == cmp_notin) {
     139        5699 :                         list *r = NULL;
     140             : 
     141        5699 :                         if (!(l = exp_push_down_prj(sql, e->l, f, t)) || !(r = exps_push_down_prj(sql, e->r, f, t, true)))
     142        5207 :                                 return NULL;
     143         492 :                         ne = exp_in(sql->sa, l, r, e->flag);
     144             :                 } else {
     145       50541 :                         if (!(l = exp_push_down_prj(sql, e->l, f, t)) || !(r = exp_push_down_prj(sql, e->r, f, t)) || (e->f && !(r2 = exp_push_down_prj(sql, e->f, f, t))))
     146       24271 :                                 return NULL;
     147       26270 :                         if (e->f) {
     148         741 :                                 ne = exp_compare2(sql->sa, l, r, r2, e->flag, is_symmetric(e));
     149             :                         } else {
     150       25529 :                                 ne = exp_compare(sql->sa, l, r, e->flag);
     151             :                         }
     152             :                 }
     153       29781 :                 if (!ne)
     154             :                         return NULL;
     155       29781 :                 return exp_propagate(sql->sa, ne, e);
     156      211441 :         case e_convert:
     157      211441 :                 if (!(l = exp_push_down_prj(sql, e->l, f, t)))
     158             :                         return NULL;
     159      143776 :                 ne = exp_convert(sql, l, exp_fromtype(e), exp_totype(e));
     160      143776 :                 return exp_propagate(sql->sa, ne, e);
     161       48793 :         case e_aggr:
     162             :         case e_func: {
     163       48793 :                 list *l = e->l, *nl = NULL;
     164       48793 :                 sql_exp *ne = NULL;
     165             : 
     166       48793 :                 if (e->type == e_func && exp_unsafe(e, false, false))
     167             :                         return NULL;
     168       48777 :                 if (!list_empty(l)) {
     169       48777 :                         nl = exps_push_down_prj(sql, l, f, t, false);
     170       48777 :                         if (!nl)
     171             :                                 return NULL;
     172             :                 }
     173       47630 :                 if (e->type == e_func)
     174       47630 :                         ne = exp_op(sql->sa, nl, e->f);
     175             :                 else
     176           0 :                         ne = exp_aggr(sql->sa, nl, e->f, need_distinct(e), need_no_nil(e), e->card, has_nil(e));
     177       47630 :                 return exp_propagate(sql->sa, ne, e);
     178             :         }
     179      100123 :         case e_atom: {
     180      100123 :                 list *l = e->f, *nl = NULL;
     181             : 
     182      100123 :                 if (!list_empty(l)) {
     183           0 :                         nl = exps_push_down_prj(sql, l, f, t, false);
     184           0 :                         if (!nl)
     185             :                                 return NULL;
     186           0 :                         ne = exp_values(sql->sa, nl);
     187             :                 } else {
     188      100123 :                         ne = exp_copy(sql, e);
     189             :                 }
     190      100123 :                 return exp_propagate(sql->sa, ne, e);
     191             :         }
     192             :         case e_psm:
     193             :                 if (e->type == e_atom && e->f) /* value list */
     194             :                         return NULL;
     195             :                 return e;
     196             :         }
     197             :         return NULL;
     198             : }
     199             : 
     200             : atom *
     201         628 : exp_flatten(mvc *sql, bool value_based_opt, sql_exp *e)
     202             : {
     203         628 :         if (e->type == e_atom) {
     204         379 :                 return value_based_opt ? exp_value(sql, e) : (atom *) e->l;
     205         249 :         } else if (e->type == e_convert) {
     206          51 :                 atom *v = exp_flatten(sql, value_based_opt, e->l);
     207             : 
     208          51 :                 if (v)
     209          24 :                         return atom_cast(sql->sa, v, exp_subtype(e));
     210         198 :         } else if (e->type == e_func) {
     211         198 :                 sql_subfunc *f = e->f;
     212         198 :                 list *l = e->l;
     213         198 :                 sql_arg *res = (f->func->res)?(f->func->res->h->data):NULL;
     214             : 
     215             :                 /* TODO handle date + x months */
     216         198 :                 if (!f->func->s && strcmp(f->func->base.name, "sql_add") == 0 && list_length(l) == 2 && res && EC_NUMBER(res->type.type->eclass)) {
     217          24 :                         atom *l1 = exp_flatten(sql, value_based_opt, l->h->data);
     218          24 :                         atom *l2 = exp_flatten(sql, value_based_opt, l->h->next->data);
     219          24 :                         if (l1 && l2)
     220           3 :                                 return atom_add(sql->sa, l1, l2);
     221         174 :                 } else if (!f->func->s && strcmp(f->func->base.name, "sql_sub") == 0 && list_length(l) == 2 && res && EC_NUMBER(res->type.type->eclass)) {
     222          10 :                         atom *l1 = exp_flatten(sql, value_based_opt, l->h->data);
     223          10 :                         atom *l2 = exp_flatten(sql, value_based_opt, l->h->next->data);
     224          10 :                         if (l1 && l2)
     225           9 :                                 return atom_sub(sql->sa, l1, l2);
     226             :                 }
     227             :         }
     228             :         return NULL;
     229             : }
     230             : 
     231             : int
     232         150 : exp_range_overlap(atom *min, atom *max, atom *emin, atom *emax, bool min_exclusive, bool max_exclusive)
     233             : {
     234         150 :         if (!min || !max || !emin || !emax || min->isnull || max->isnull || emin->isnull || emax->isnull)
     235             :                 return 0;
     236             : 
     237         150 :         if ((!min_exclusive && VALcmp(&(emax->data), &(min->data)) < 0) || (min_exclusive && VALcmp(&(emax->data), &(min->data)) <= 0))
     238          29 :                 return 0;
     239         121 :         if ((!max_exclusive && VALcmp(&(emin->data), &(max->data)) > 0) || (max_exclusive && VALcmp(&(emin->data), &(max->data)) >= 0))
     240          34 :                 return 0;
     241             :         return 1;
     242             : }
     243             : 
     244             : 
     245             : /* if local_proj is >= -1, the current expression is from the same projection
     246             :    if local_proj is -1, then we don't care about self references (eg used to check for order by exps) */
     247             : static int exp_mark_used(sql_rel *subrel, sql_exp *e, int local_proj);
     248             : 
     249             : static int
     250      801643 : exps_mark_used(sql_rel *subrel, list *l, int local_proj)
     251             : {
     252      801643 :         int nr = 0;
     253      801643 :         if (list_empty(l))
     254             :                 return nr;
     255             : 
     256     2587433 :         for (node *n = l->h; n != NULL; n = n->next)
     257     1785854 :                 nr += exp_mark_used(subrel, n->data, local_proj);
     258             :         return nr;
     259             : }
     260             : 
     261             : static int
     262     6920310 : exp_mark_used(sql_rel *subrel, sql_exp *e, int local_proj)
     263             : {
     264     7130165 :         int nr = 0;
     265     7130165 :         sql_exp *ne = NULL;
     266             : 
     267     7130165 :         switch(e->type) {
     268     4711881 :         case e_column:
     269     4711881 :                 ne = rel_find_exp(subrel, e);
     270             :                 /* if looking in the same projection, make sure 'ne' is projected before the searched column */
     271     4711888 :                 if (ne && local_proj > -1 && list_position(subrel->exps, ne) >= local_proj)
     272     5919998 :                         ne = NULL;
     273             :                 break;
     274      209855 :         case e_convert:
     275      209855 :                 return exp_mark_used(subrel, e->l, local_proj);
     276      762462 :         case e_aggr:
     277             :         case e_func: {
     278      762462 :                 if (e->l)
     279      730595 :                         nr += exps_mark_used(subrel, e->l, local_proj);
     280      762461 :                 assert(!e->r);
     281             :                 break;
     282             :         }
     283      445650 :         case e_cmp:
     284      445650 :                 if (e->flag == cmp_or || e->flag == cmp_filter) {
     285       22653 :                         nr += exps_mark_used(subrel, e->l, local_proj);
     286       22653 :                         nr += exps_mark_used(subrel, e->r, local_proj);
     287      422997 :                 } else if (e->flag == cmp_in || e->flag == cmp_notin) {
     288       20578 :                         nr += exp_mark_used(subrel, e->l, local_proj);
     289       20578 :                         nr += exps_mark_used(subrel, e->r, local_proj);
     290             :                 } else {
     291      402419 :                         nr += exp_mark_used(subrel, e->l, local_proj);
     292      402419 :                         nr += exp_mark_used(subrel, e->r, local_proj);
     293      402419 :                         if (e->f)
     294        6432 :                                 nr += exp_mark_used(subrel, e->f, local_proj);
     295             :                 }
     296             :                 break;
     297     1000317 :         case e_atom:
     298             :                 /* atoms are used in e_cmp */
     299     1000317 :                 e->used = 1;
     300             :                 /* return 0 as constants may require a full column ! */
     301     1000317 :                 if (e->f)
     302        5164 :                         nr += exps_mark_used(subrel, e->f, local_proj);
     303             :                 return nr;
     304           0 :         case e_psm:
     305           0 :                 if (e->flag & PSM_SET || e->flag & PSM_RETURN || e->flag & PSM_EXCEPTION) {
     306           0 :                         nr += exp_mark_used(subrel, e->l, local_proj);
     307           0 :                 } else if (e->flag & PSM_WHILE || e->flag & PSM_IF) {
     308           0 :                         nr += exp_mark_used(subrel, e->l, local_proj);
     309           0 :                         nr += exps_mark_used(subrel, e->r, local_proj);
     310           0 :                         if (e->flag == PSM_IF && e->f)
     311           0 :                                 nr += exps_mark_used(subrel, e->f, local_proj);
     312             :                 }
     313           0 :                 e->used = 1;
     314           0 :                 break;
     315             :         }
     316     5919998 :         if (ne && e != ne) {
     317     2570607 :                 if (local_proj == -2 || ne->type != e_column || (has_label(ne) || (ne->alias.rname && ne->alias.rname[0] == '%')) || (subrel->l && !is_munion(subrel->op) && !rel_find_exp(subrel->l, e)))
     318     2446528 :                         ne->used = 1;
     319     2570607 :                 return ne->used;
     320             :         }
     321             :         return nr;
     322             : }
     323             : 
     324             : static void
     325       44097 : positional_exps_mark_used( sql_rel *rel, sql_rel *subrel )
     326             : {
     327       44097 :         assert(rel->exps);
     328             : 
     329       44097 :         if ((is_topn(subrel->op) || is_sample(subrel->op)) && subrel->l)
     330       44097 :                 subrel = subrel->l;
     331             :         /* everything is used within the set operation */
     332       44097 :         if (rel->exps && subrel->exps) {
     333       44097 :                 node *m;
     334      373029 :                 for (m=subrel->exps->h; m; m = m->next) {
     335      328932 :                         sql_exp *se = m->data;
     336             : 
     337      328932 :                         se->used = 1;
     338             :                 }
     339             :         }
     340       44097 : }
     341             : 
     342             : static void
     343      766974 : rel_exps_mark_used(allocator *sa, sql_rel *rel, sql_rel *subrel)
     344             : {
     345      766974 :         int nr = 0;
     346             : 
     347      766974 :         if (rel->r && (is_simple_project(rel->op) || is_groupby(rel->op))) {
     348       32374 :                 list *l = rel->r;
     349       32374 :                 node *n;
     350             : 
     351      111431 :                 for (n=l->h; n; n = n->next) {
     352       79058 :                         sql_exp *e = n->data;
     353             : 
     354       79058 :                         e->used = 1;
     355       79058 :                         exp_mark_used(rel, e, -1);
     356             :                 }
     357             :         }
     358      766973 :         if (rel->attr) {
     359       26284 :                 for (node *n = rel->attr->h; n; n = n->next) {
     360       13142 :                         sql_exp *e = n->data;
     361             : 
     362       13142 :                         if (e->type != e_aggr) /* keep all group by's */
     363       13142 :                                 e->used = 1;
     364       13142 :                         if (e->used)
     365       13142 :                                 nr += exp_mark_used(subrel, e, -2);
     366             :                 }
     367             :         }
     368      766973 :         if (rel->exps) {
     369      727991 :                 node *n;
     370      727991 :                 int len = list_length(rel->exps), i;
     371      727991 :                 sql_exp **exps = SA_NEW_ARRAY(sa, sql_exp*, len);
     372             : 
     373     3575546 :                 for (n=rel->exps->h, i = 0; n; n = n->next, i++) {
     374     2847555 :                         sql_exp *e = exps[i] = n->data;
     375             : 
     376     2847555 :                         nr += e->used;
     377             :                 }
     378             : 
     379      727991 :                 if (!nr && is_project(rel->op) && len > 0) /* project at least one column if exists */
     380        6657 :                         exps[0]->used = 1;
     381             : 
     382     3575548 :                 for (i = len-1; i >= 0; i--) {
     383     2847557 :                         sql_exp *e = exps[i];
     384             : 
     385     2847557 :                         if (!is_project(rel->op) || (e->used && !is_set(rel->op))) {
     386     2275142 :                                 if (is_project(rel->op))
     387     1856069 :                                         nr += exp_mark_used(rel, e, i);
     388     2275143 :                                 nr += exp_mark_used(subrel, e, -2);
     389             :                         }
     390             :                 }
     391             :         }
     392             :         /* for count/rank we need at least one column */
     393      766973 :         if (!nr && subrel && (is_project(subrel->op) || is_base(subrel->op)) && !list_empty(subrel->exps) &&
     394       23974 :                 (is_simple_project(rel->op) && project_unsafe(rel, false))) {
     395          34 :                 sql_exp *e = subrel->exps->h->data;
     396          34 :                 e->used = 1;
     397             :         }
     398      766973 :         if (rel->r && (is_simple_project(rel->op) || is_groupby(rel->op))) {
     399       32374 :                 list *l = rel->r;
     400       32374 :                 node *n;
     401             : 
     402      111431 :                 for (n=l->h; n; n = n->next) {
     403       79057 :                         sql_exp *e = n->data;
     404             : 
     405       79057 :                         e->used = 1;
     406             :                         /* possibly project/groupby uses columns from the inner */
     407       79057 :                         exp_mark_used(subrel, e, -2);
     408             :                 }
     409             :         }
     410      766973 : }
     411             : 
     412             : static void exps_used(list *l);
     413             : 
     414             : static void
     415     3347595 : exp_used(sql_exp *e)
     416             : {
     417     3379122 :         if (e) {
     418     3360710 :                 e->used = 1;
     419             : 
     420     3360710 :                 switch (e->type) {
     421       30331 :                 case e_convert:
     422       30331 :                         exp_used(e->l);
     423       30331 :                         break;
     424       96592 :                 case e_func:
     425             :                 case e_aggr:
     426       96592 :                         exps_used(e->l);
     427       96592 :                         break;
     428        7918 :                 case e_cmp:
     429        7918 :                         if (e->flag == cmp_or || e->flag == cmp_filter) {
     430        1042 :                                 exps_used(e->l);
     431        1042 :                                 exps_used(e->r);
     432        6876 :                         } else if (e->flag == cmp_in || e->flag == cmp_notin) {
     433         232 :                                 exp_used(e->l);
     434         232 :                                 exps_used(e->r);
     435             :                         } else {
     436        6644 :                                 exp_used(e->l);
     437        6644 :                                 exp_used(e->r);
     438        6644 :                                 if (e->f)
     439             :                                         exp_used(e->f);
     440             :                         }
     441             :                         break;
     442             :                 default:
     443             :                         break;
     444             :                 }
     445             :         }
     446     3347595 : }
     447             : 
     448             : static void
     449      861361 : exps_used(list *l)
     450             : {
     451      861361 :         if (l) {
     452     4194236 :                 for (node *n = l->h; n; n = n->next)
     453     3332987 :                         exp_used(n->data);
     454             :         }
     455      861360 : }
     456             : 
     457             : static void
     458      798172 : rel_used(sql_rel *rel)
     459             : {
     460      798172 :         if (!rel)
     461             :                 return;
     462      754365 :         if (is_join(rel->op) || is_set(rel->op) || is_semi(rel->op) || is_modify(rel->op)) {
     463       65189 :                 rel_used(rel->l);
     464       65188 :                 rel_used(rel->r);
     465             :         } else if (rel->op == op_munion) {
     466       11968 :                 list *l = rel->l;
     467       36319 :                 for(node *n = l->h; n; n = n->next)
     468       24351 :                         rel_used(n->data);
     469             :         } else if (is_topn(rel->op) || is_select(rel->op) || is_sample(rel->op)) {
     470       20601 :                 rel_used(rel->l);
     471       20601 :                 rel = rel->l;
     472             :         } else if (is_ddl(rel->op)) {
     473      399967 :                 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) {
     474       34484 :                         rel_used(rel->l);
     475             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
     476         285 :                         rel_used(rel->l);
     477         285 :                         rel_used(rel->r);
     478             :                 } else if (rel->flag == ddl_psm) {
     479           7 :                         exps_used(rel->exps);
     480             :                 }
     481             :         } else if (rel->op == op_table) {
     482        1090 :                 if (IS_TABLE_PROD_FUNC(rel->flag) || rel->flag == TABLE_FROM_RELATION)
     483        1090 :                         rel_used(rel->l);
     484        1090 :                 exp_used(rel->r);
     485             :         }
     486      855418 :         if (rel && rel->exps) {
     487      742979 :                 exps_used(rel->exps);
     488      742977 :                 if (rel->r && (is_simple_project(rel->op) || is_groupby(rel->op)))
     489       19468 :                         exps_used(rel->r);
     490             :         }
     491             : }
     492             : 
     493             : static void
     494     1261422 : rel_mark_used(mvc *sql, sql_rel *rel, int proj)
     495             : {
     496     1874968 :         if (proj && (need_distinct(rel)))
     497       10169 :                 rel_used(rel);
     498             : 
     499     1874970 :         switch(rel->op) {
     500             :         case op_basetable:
     501             :         case op_truncate:
     502             :         case op_insert:
     503             :                 break;
     504             : 
     505       13430 :         case op_table:
     506             : 
     507       13430 :                 if (rel->l && rel->flag != TRIGGER_WRAPPER) {
     508         144 :                         rel_used(rel);
     509         144 :                         if (rel->r)
     510         144 :                                 exp_mark_used(rel->l, rel->r, -2);
     511         144 :                         rel_mark_used(sql, rel->l, proj);
     512             :                 }
     513             :                 break;
     514             : 
     515       16588 :         case op_topn:
     516             :         case op_sample:
     517       16588 :                 if (proj) {
     518       16505 :                         rel = rel ->l;
     519       16505 :                         rel_mark_used(sql, rel, proj);
     520       16505 :                         break;
     521             :                 }
     522             :                 /* fall through */
     523             :         case op_project:
     524             :         case op_groupby:
     525      513215 :                 if (proj && rel->l) {
     526      293672 :                         rel_exps_mark_used(sql->sa, rel, rel->l);
     527      293671 :                         rel_mark_used(sql, rel->l, 0);
     528       10962 :                 } else if (proj) {
     529       10879 :                         rel_exps_mark_used(sql->sa, rel, NULL);
     530             :                 }
     531             :                 break;
     532        7662 :         case op_update:
     533             :         case op_delete:
     534        7662 :                 if (proj && rel->r) {
     535        6116 :                         sql_rel *r = rel->r;
     536             : 
     537        6116 :                         if (!list_empty(r->exps)) {
     538        7218 :                                 for (node *n = r->exps->h; n; n = n->next) {
     539        6118 :                                         sql_exp *e = n->data;
     540        6118 :                                         const char *nname = exp_name(e);
     541             : 
     542        6118 :                                         if (nname && nname[0] == '%' && strcmp(nname, TID) == 0) { /* TID is used */
     543        5016 :                                                 e->used = 1;
     544        5016 :                                                 break;
     545             :                                         }
     546             :                                 }
     547             :                         }
     548        6116 :                         rel_exps_mark_used(sql->sa, rel, rel->r);
     549        6116 :                         rel_mark_used(sql, rel->r, 0);
     550             :                 }
     551             :                 break;
     552             : 
     553      398606 :         case op_ddl:
     554      398606 :                 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) {
     555       33123 :                         if (rel->l)
     556             :                                 rel_mark_used(sql, rel->l, 0);
     557             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
     558         285 :                         if (rel->l)
     559         285 :                                 rel_mark_used(sql, rel->l, 0);
     560         285 :                         if (rel->r)
     561             :                                 rel_mark_used(sql, rel->r, 0);
     562             :                 }
     563             :                 break;
     564             : 
     565      110350 :         case op_select:
     566      110350 :                 if (rel->l) {
     567      110350 :                         rel_exps_mark_used(sql->sa, rel, rel->l);
     568      110350 :                         rel_mark_used(sql, rel->l, 0);
     569             :                 }
     570             :                 break;
     571             : 
     572        5148 :         case op_union:
     573             :         case op_inter:
     574             :         case op_except:
     575             :                 /* For now we mark all union expression as used */
     576             : 
     577             :                 /* Later we should (in case of union all) remove unused
     578             :                  * columns from the projection.
     579             :                  *
     580             :                  * Project part of union is based on column position.
     581             :                  */
     582        5148 :                 if (proj && (need_distinct(rel) || !rel->exps)) {
     583        2334 :                         rel_used(rel);
     584        2334 :                         if (!rel->exps) {
     585           0 :                                 rel_used(rel->l);
     586           0 :                                 rel_used(rel->r);
     587             :                         }
     588        2334 :                         rel_mark_used(sql, rel->l, 0);
     589        2334 :                         rel_mark_used(sql, rel->r, 0);
     590         485 :                 } else if (proj && !need_distinct(rel)) {
     591         485 :                         sql_rel *l = rel->l;
     592             : 
     593         485 :                         positional_exps_mark_used(rel, l);
     594         485 :                         rel_exps_mark_used(sql->sa, rel, l);
     595         485 :                         rel_mark_used(sql, rel->l, 0);
     596             :                         /* based on child check set expression list */
     597         485 :                         if (is_project(l->op) && need_distinct(l))
     598           0 :                                 positional_exps_mark_used(l, rel);
     599         485 :                         positional_exps_mark_used(rel, rel->r);
     600         485 :                         rel_exps_mark_used(sql->sa, rel, rel->r);
     601         485 :                         rel_mark_used(sql, rel->r, 0);
     602             :                 }
     603             :                 break;
     604             : 
     605       48057 :         case op_munion:
     606       48057 :                 assert(rel->l);
     607             :                 // TODO: here we blindly follow the same logic as op_union. RE-evaluate
     608       48057 :                 if (proj && (need_distinct(rel) || !rel->exps)) {
     609        1980 :                         rel_used(rel);
     610        1980 :                         if (!rel->exps) {
     611           0 :                                 for (node *n = ((list*)rel->l)->h; n; n = n->next) {
     612           0 :                                         rel_used(n->data);
     613           0 :                                         rel_mark_used(sql, n->data, 0);
     614             :                                 }
     615             :                         }
     616       21400 :                 } else if (proj && !need_distinct(rel)) {
     617       21400 :                         bool first = true;
     618       64527 :                         for (node *n = ((list*)rel->l)->h; n; n = n->next) {
     619       43127 :                                 sql_rel *l = n->data;
     620             : 
     621       43127 :                                 positional_exps_mark_used(rel, l);
     622       43127 :                                 rel_exps_mark_used(sql->sa, rel, l);
     623       43127 :                                 rel_mark_used(sql, l, 0);
     624             :                                 /* based on child check set expression list */
     625       43127 :                                 if (first && is_project(l->op) && need_distinct(l))
     626           0 :                                         positional_exps_mark_used(l, rel);
     627       43127 :                                 first = false;
     628             :                         }
     629             :                 }
     630             :                 break;
     631      150930 :         case op_join:
     632             :         case op_left:
     633             :         case op_right:
     634             :         case op_full:
     635             :         case op_semi:
     636             :         case op_anti:
     637             :         case op_merge:
     638      150930 :                 rel_exps_mark_used(sql->sa, rel, rel->l);
     639      150930 :                 rel_exps_mark_used(sql->sa, rel, rel->r);
     640      150930 :                 rel_mark_used(sql, rel->l, 0);
     641      150930 :                 rel_mark_used(sql, rel->r, 0);
     642      150930 :                 break;
     643             :         }
     644     1261423 : }
     645             : 
     646             : static sql_rel * rel_dce_sub(mvc *sql, sql_rel *rel);
     647             : 
     648             : static sql_rel *
     649     1120605 : rel_remove_unused(mvc *sql, sql_rel *rel)
     650             : {
     651     1120605 :         int needed = 0;
     652             : 
     653     1120605 :         if (!rel)
     654             :                 return rel;
     655             : 
     656     1113737 :         switch(rel->op) {
     657      302191 :         case op_basetable: {
     658      302191 :                 sql_table *t = rel->l;
     659             : 
     660      302191 :                 if (t && isReplicaTable(t)) /* TODO fix rewriting in rel_distribute.c */
     661             :                         return rel;
     662             :         }
     663             :         /* fall through */
     664             :         case op_table:
     665      309039 :                 if (rel->exps && (rel->op != op_table || !IS_TABLE_PROD_FUNC(rel->flag))) {
     666     1346218 :                         for(node *n=rel->exps->h; n && !needed; n = n->next) {
     667     1044047 :                                 sql_exp *e = n->data;
     668             : 
     669     1044047 :                                 if (!e->used)
     670      226928 :                                         needed = 1;
     671             :                         }
     672             : 
     673      302171 :                         if (!needed)
     674             :                                 return rel;
     675             : 
     676     1340938 :                         for(node *n=rel->exps->h; n;) {
     677     1114009 :                                 node *next = n->next;
     678     1114009 :                                 sql_exp *e = n->data;
     679             : 
     680             :                                 /* at least one (needed for crossproducts, count(*), rank() and single value projections) !, handled by rel_exps_mark_used */
     681     1114009 :                                 if (!e->used && list_length(rel->exps) > 1)
     682      375172 :                                         list_remove_node(rel->exps, NULL, n);
     683             :                                 n = next;
     684             :                         }
     685             :                 }
     686      233797 :                 if (rel->op == op_table && (IS_TABLE_PROD_FUNC(rel->flag) || rel->flag == TABLE_FROM_RELATION))
     687        6868 :                         rel->l = rel_remove_unused(sql, rel->l);
     688             :                 return rel;
     689             : 
     690       16506 :         case op_topn:
     691             :         case op_sample:
     692             : 
     693       16506 :                 if (rel->l)
     694       16506 :                         rel->l = rel_remove_unused(sql, rel->l);
     695             :                 return rel;
     696             : 
     697      304563 :         case op_project:
     698             :         case op_groupby:
     699             : 
     700      304563 :                 if (/*rel->l &&*/ rel->exps) {
     701     1907178 :                         for(node *n=rel->exps->h; n && !needed; n = n->next) {
     702     1602615 :                                 sql_exp *e = n->data;
     703             : 
     704     1602615 :                                 if (!e->used)
     705       25461 :                                         needed = 1;
     706             :                         }
     707      304563 :                         if (!needed)
     708             :                                 return rel;
     709             : 
     710      589034 :                         for(node *n=rel->exps->h; n;) {
     711      563573 :                                 node *next = n->next;
     712      563573 :                                 sql_exp *e = n->data;
     713             : 
     714             :                                 /* at least one (needed for crossproducts, count(*), rank() and single value projections) */
     715      563573 :                                 if (!e->used && list_length(rel->exps) > 1)
     716      427798 :                                         list_remove_node(rel->exps, NULL, n);
     717             :                                 n = next;
     718             :                         }
     719             :                 }
     720             :                 return rel;
     721             : 
     722        3159 :         case op_join:
     723             :         case op_left:
     724             :         case op_right:
     725             :         case op_full:
     726        3159 :                 if (list_length(rel->attr) > 1) {
     727           0 :                         for(node *n=rel->attr->h; n && !needed; n = n->next) {
     728           0 :                                 sql_exp *e = n->data;
     729             : 
     730           0 :                                 if (!e->used)
     731           0 :                                         needed = 1;
     732             :                         }
     733           0 :                         if (!needed)
     734             :                                 return rel;
     735             : 
     736           0 :                         for(node *n=rel->attr->h; n;) {
     737           0 :                                 node *next = n->next;
     738           0 :                                 sql_exp *e = n->data;
     739             : 
     740           0 :                                 if (!e->used)
     741           0 :                                         list_remove_node(rel->attr, NULL, n);
     742             :                                 n = next;
     743             :                         }
     744             :                 }
     745             :                 return rel;
     746             : 
     747             :         case op_union:
     748             :         case op_inter:
     749             :         case op_except:
     750             :         case op_munion:
     751             : 
     752             :         case op_insert:
     753             :         case op_update:
     754             :         case op_delete:
     755             :         case op_truncate:
     756             :         case op_merge:
     757             : 
     758             :         case op_select:
     759             : 
     760             :         case op_semi:
     761             :         case op_anti:
     762             :                 return rel;
     763      398288 :         case op_ddl:
     764      398288 :                 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) {
     765       32849 :                         if (rel->l)
     766       32486 :                                 rel->l = rel_remove_unused(sql, rel->l);
     767             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
     768         241 :                         if (rel->l)
     769         241 :                                 rel->l = rel_remove_unused(sql, rel->l);
     770         241 :                         if (rel->r)
     771         241 :                                 rel->r = rel_remove_unused(sql, rel->r);
     772             :                 }
     773             :                 return rel;
     774             :         }
     775             :         return rel;
     776             : }
     777             : 
     778             : static void
     779     1308433 : rel_dce_refs(mvc *sql, sql_rel *rel, list *refs)
     780             : {
     781     1308433 :         if (!rel || (rel_is_ref(rel) && list_find(refs, rel, NULL)))
     782       14179 :                 return ;
     783             : 
     784     1294254 :         switch(rel->op) {
     785      401308 :         case op_table:
     786             :         case op_topn:
     787             :         case op_sample:
     788             :         case op_project:
     789             :         case op_groupby:
     790             :         case op_select:
     791             : 
     792      401308 :                 if (rel->l && (rel->op != op_table || rel->flag != TRIGGER_WRAPPER))
     793      385325 :                         rel_dce_refs(sql, rel->l, refs);
     794             :                 break;
     795             : 
     796             :         case op_basetable:
     797             :         case op_insert:
     798             :         case op_truncate:
     799             :                 break;
     800             : 
     801        6466 :         case op_update:
     802             :         case op_delete:
     803             : 
     804        6466 :                 if (rel->r)
     805        6116 :                         rel_dce_refs(sql, rel->r, refs);
     806             :                 break;
     807             : 
     808      144322 :         case op_union:
     809             :         case op_inter:
     810             :         case op_except:
     811             :         case op_join:
     812             :         case op_left:
     813             :         case op_right:
     814             :         case op_full:
     815             :         case op_semi:
     816             :         case op_anti:
     817             :         case op_merge:
     818             : 
     819      144322 :                 if (rel->l)
     820      144322 :                         rel_dce_refs(sql, rel->l, refs);
     821      144322 :                 if (rel->r)
     822      144322 :                         rel_dce_refs(sql, rel->r, refs);
     823             :                 break;
     824       22658 :         case op_munion:
     825       22658 :                 assert(rel->l);
     826       68594 :                 for (node *n = ((list*)rel->l)->h; n; n = n->next)
     827       45936 :                         rel_dce_refs(sql, n->data, refs);
     828             :                 break;
     829      399706 :         case op_ddl:
     830             : 
     831      399706 :                 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) {
     832       34223 :                         if (rel->l)
     833       33860 :                                 rel_dce_refs(sql, rel->l, refs);
     834             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
     835         285 :                         if (rel->l)
     836         285 :                                 rel_dce_refs(sql, rel->l, refs);
     837         285 :                         if (rel->r)
     838         251 :                                 rel_dce_refs(sql, rel->r, refs);
     839             :                 } break;
     840             :         }
     841             : 
     842     1294254 :         if (rel_is_ref(rel) && !list_find(refs, rel, NULL))
     843       16602 :                 list_prepend(refs, rel);
     844             : }
     845             : 
     846             : static sql_rel *
     847     1864354 : rel_dce_down(mvc *sql, sql_rel *rel, int skip_proj)
     848             : {
     849     1864354 :         if (!rel)
     850             :                 return rel;
     851             : 
     852     1864354 :         if (!skip_proj && rel_is_ref(rel))
     853             :                 return rel;
     854             : 
     855     1834092 :         switch(rel->op) {
     856      552971 :         case op_basetable:
     857             :         case op_table:
     858             : 
     859      552971 :                 if (skip_proj && rel->l && rel->op == op_table && rel->flag != TRIGGER_WRAPPER)
     860          83 :                         rel->l = rel_dce_down(sql, rel->l, 0);
     861      276240 :                 if (!skip_proj)
     862      276240 :                         rel_dce_sub(sql, rel);
     863             :                 /* fall through */
     864             : 
     865             :         case op_truncate:
     866             :                 return rel;
     867             : 
     868        7454 :         case op_insert:
     869        7454 :                 rel_used(rel->r);
     870        7454 :                 rel_dce_sub(sql, rel->r);
     871        7454 :                 return rel;
     872             : 
     873        7662 :         case op_update:
     874             :         case op_delete:
     875             : 
     876        7662 :                 if (skip_proj && rel->r)
     877        6116 :                         rel->r = rel_dce_down(sql, rel->r, 0);
     878        1196 :                 if (!skip_proj)
     879        1196 :                         rel_dce_sub(sql, rel);
     880             :                 return rel;
     881             : 
     882      525160 :         case op_topn:
     883             :         case op_sample:
     884             :         case op_project:
     885             :         case op_groupby:
     886             : 
     887      525160 :                 if (skip_proj && rel->l)
     888      310137 :                         rel->l = rel_dce_down(sql, rel->l, is_topn(rel->op) || is_sample(rel->op));
     889      204166 :                 if (!skip_proj)
     890      204166 :                         rel_dce_sub(sql, rel);
     891             :                 return rel;
     892             : 
     893        5141 :         case op_union:
     894             :         case op_inter:
     895             :         case op_except:
     896        5141 :                 if (skip_proj) {
     897        2819 :                         if (rel->l)
     898        2819 :                                 rel->l = rel_dce_down(sql, rel->l, 0);
     899        2819 :                         if (rel->r)
     900        2819 :                                 rel->r = rel_dce_down(sql, rel->r, 0);
     901             :                 }
     902        2322 :                 if (!skip_proj)
     903        2322 :                         rel_dce_sub(sql, rel);
     904             :                 return rel;
     905             : 
     906       45089 :         case op_munion:
     907       45089 :                 if (skip_proj) {
     908       70465 :                         for (node *n = ((list*)rel->l)->h; n; n = n->next)
     909       47087 :                                 n->data = rel_dce_down(sql, n->data, 0);
     910             :                 }
     911       21711 :                 if (!skip_proj)
     912       21711 :                         rel_dce_sub(sql, rel);
     913             :                 return rel;
     914      102799 :         case op_select:
     915      102799 :                 if (rel->l)
     916      102799 :                         rel->l = rel_dce_down(sql, rel->l, 0);
     917             :                 return rel;
     918             : 
     919      147467 :         case op_join:
     920             :         case op_left:
     921             :         case op_right:
     922             :         case op_full:
     923             :         case op_semi:
     924             :         case op_anti:
     925             :         case op_merge:
     926      147467 :                 if (rel->l)
     927      147467 :                         rel->l = rel_dce_down(sql, rel->l, 0);
     928      147467 :                 if (rel->r)
     929      147467 :                         rel->r = rel_dce_down(sql, rel->r, 0);
     930      147467 :                 if (!skip_proj && !list_empty(rel->attr))
     931        3159 :                         rel_dce_sub(sql, rel);
     932             :                 return rel;
     933             : 
     934      398409 :         case op_ddl:
     935      398409 :                 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) {
     936       32926 :                         if (rel->l)
     937       32760 :                                 rel->l = rel_dce_down(sql, rel->l, 0);
     938             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
     939         285 :                         if (rel->l)
     940         285 :                                 rel->l = rel_dce_down(sql, rel->l, 0);
     941         285 :                         if (rel->r)
     942         251 :                                 rel->r = rel_dce_down(sql, rel->r, 0);
     943             :                 }
     944             :                 return rel;
     945             :         }
     946             :         return rel;
     947             : }
     948             : 
     949             : /* DCE
     950             :  *
     951             :  * Based on top relation expressions mark sub expressions as used.
     952             :  * Then recurse down until the projections. Clean them up and repeat.
     953             :  */
     954             : 
     955             : static sql_rel *
     956     1064261 : rel_dce_sub(mvc *sql, sql_rel *rel)
     957             : {
     958     1064261 :         if (!rel)
     959             :                 return rel;
     960             : 
     961             :         /*
     962             :          * Mark used up until the next project
     963             :          * For setops we need to first mark, then remove
     964             :          * because of positional dependency
     965             :          */
     966     1064261 :         rel_mark_used(sql, rel, 1);
     967     1064263 :         rel = rel_remove_unused(sql, rel);
     968     1064264 :         rel_dce_down(sql, rel, 1);
     969     1064264 :         return rel;
     970             : }
     971             : 
     972             : /* add projects under set ops */
     973             : static sql_rel *
     974     2078964 : rel_add_projects(mvc *sql, sql_rel *rel)
     975             : {
     976     2078964 :         if (!rel)
     977             :                 return rel;
     978             : 
     979     2078964 :         switch(rel->op) {
     980             :         case op_basetable:
     981             :         case op_truncate:
     982             :                 return rel;
     983       13920 :         case op_insert:
     984             :         case op_update:
     985             :         case op_delete:
     986       13920 :                 if (rel->r)
     987       13570 :                         rel->r = rel_add_projects(sql, rel->r);
     988             :                 return rel;
     989        2915 :         case op_union:
     990             :         case op_inter:
     991             :         case op_except:
     992             :                 /* We can only reduce the list of expressions of an set op
     993             :                  * if the projection under it can also be reduced.
     994             :                  */
     995        2915 :                 if (rel->l) {
     996        2915 :                         sql_rel *l = rel->l;
     997             : 
     998        2915 :                         if (!is_project(l->op) && !need_distinct(rel))
     999           3 :                                 l = rel_project(sql->sa, l, rel_projections(sql, l, NULL, 1, 1));
    1000        2915 :                         rel->l = rel_add_projects(sql, l);
    1001             :                 }
    1002        2915 :                 if (rel->r) {
    1003        2915 :                         sql_rel *r = rel->r;
    1004             : 
    1005        2915 :                         if (!is_project(r->op) && !need_distinct(rel))
    1006           4 :                                 r = rel_project(sql->sa, r, rel_projections(sql, r, NULL, 1, 1));
    1007        2915 :                         rel->r = rel_add_projects(sql, r);
    1008             :                 }
    1009             :                 return rel;
    1010       33869 :         case op_munion:
    1011       33869 :                 assert(rel->l);
    1012      151342 :                 for (node *n = ((list*)rel->l)->h; n; n = n->next) {
    1013      117473 :                         sql_rel* r = n->data;
    1014      117473 :                         if (!is_project(r->op) && !need_distinct(rel))
    1015          23 :                                 r = rel_project(sql->sa, r, rel_projections(sql, r, NULL, 1, 1));
    1016      117473 :                         r = rel_add_projects(sql, r);
    1017      117473 :                         n->data = r;
    1018             :                 }
    1019             :                 return rel;
    1020      789319 :         case op_topn:
    1021             :         case op_sample:
    1022             :         case op_project:
    1023             :         case op_groupby:
    1024             :         case op_select:
    1025             :         case op_table:
    1026      789319 :                 if (rel->l && (rel->op != op_table || rel->flag != TRIGGER_WRAPPER))
    1027      758951 :                         rel->l = rel_add_projects(sql, rel->l);
    1028             :                 return rel;
    1029      300230 :         case op_join:
    1030             :         case op_left:
    1031             :         case op_right:
    1032             :         case op_full:
    1033             :         case op_semi:
    1034             :         case op_anti:
    1035             :         case op_merge:
    1036      300230 :                 if (rel->l)
    1037      300230 :                         rel->l = rel_add_projects(sql, rel->l);
    1038      300230 :                 if (rel->r)
    1039      300230 :                         rel->r = rel_add_projects(sql, rel->r);
    1040             :                 return rel;
    1041      399974 :         case op_ddl:
    1042      399974 :                 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) {
    1043       34491 :                         if (rel->l)
    1044       34128 :                                 rel->l = rel_add_projects(sql, rel->l);
    1045             :                 } else if (rel->flag == ddl_list || rel->flag == ddl_exception) {
    1046         285 :                         if (rel->l)
    1047         285 :                                 rel->l = rel_add_projects(sql, rel->l);
    1048         285 :                         if (rel->r)
    1049         251 :                                 rel->r = rel_add_projects(sql, rel->r);
    1050             :                 }
    1051             :                 return rel;
    1052             :         }
    1053             :         return rel;
    1054             : }
    1055             : 
    1056             : static sql_rel *
    1057      548017 : rel_dce_(mvc *sql, sql_rel *rel)
    1058             : {
    1059      548017 :         list *refs = sa_list(sql->sa);
    1060             : 
    1061      548017 :         rel_dce_refs(sql, rel, refs);
    1062      548017 :         if (refs) {
    1063      564619 :                 for(node *n = refs->h; n; n = n->next) {
    1064       16602 :                         sql_rel *i = n->data;
    1065             : 
    1066       16602 :                         while (!rel_is_ref(i) && i->l && !is_base(i->op))
    1067             :                                 i = i->l;
    1068       16602 :                         if (i)
    1069       16602 :                                 rel_used(i);
    1070             :                 }
    1071             :         }
    1072      548017 :         rel = rel_add_projects(sql, rel);
    1073      548016 :         rel_used(rel);
    1074      548013 :         rel_dce_sub(sql, rel);
    1075      548017 :         return rel;
    1076             : }
    1077             : 
    1078             : 
    1079             : /* Remove unused expressions */
    1080             : static sql_rel *
    1081      548017 : rel_dce(visitor *v, global_props *gp, sql_rel *rel)
    1082             : {
    1083      548017 :         (void) gp;
    1084      548017 :         return rel_dce_(v->sql, rel);
    1085             : }
    1086             : 
    1087             : /* keep export for other projects */
    1088             : sql_rel *
    1089           0 : rel_deadcode_elimination(mvc *sql, sql_rel *rel)
    1090             : {
    1091           0 :         return rel_dce_(sql, rel);
    1092             : }
    1093             : 
    1094             : run_optimizer
    1095      623706 : bind_dce(visitor *v, global_props *gp)
    1096             : {
    1097      623706 :         int flag = v->sql->sql_optimizer;
    1098      623706 :         return gp->opt_cycle == 0 && gp->opt_level == 1 && (flag & dce) ? rel_dce : NULL;
    1099             : }
    1100             : 
    1101             : 
    1102             : static int
    1103       84082 : topn_sample_safe_exps( list *exps, bool nil_limit )
    1104             : {
    1105             :         /* Limit only expression lists are always save */
    1106       84082 :         if (list_length(exps) == 1)
    1107             :                 return 1;
    1108        1206 :         for (node *n = exps->h; n; n = n->next ) {
    1109         822 :                 sql_exp *e = n->data;
    1110             : 
    1111         822 :                 if (!e || e->type != e_atom || (!nil_limit && exp_is_null(e)))
    1112          51 :                         return 0;
    1113             :         }
    1114             :         return 1;
    1115             : }
    1116             : 
    1117             : static list *
    1118         129 : sum_limit_offset(mvc *sql, sql_rel *rel)
    1119             : {
    1120             :         /* for sample we always propagate, or if the expression list only consists of a limit expression, we copy it */
    1121         129 :         if (is_sample(rel->op) || list_length(rel->exps) == 1)
    1122         126 :                 return exps_copy(sql, rel->exps);
    1123           3 :         assert(list_length(rel->exps) == 2);
    1124           3 :         sql_subtype *lng = sql_bind_localtype("lng");
    1125           3 :         sql_exp *add = rel_binop_(sql, NULL, exp_copy(sql, rel->exps->h->data), exp_copy(sql, rel->exps->h->next->data), "sys", "sql_add", card_value, true);
    1126             :         /* for remote plans, make sure the output type is a bigint */
    1127           3 :         if (subtype_cmp(lng, exp_subtype(add)) != 0)
    1128           3 :                 add = exp_convert(sql, add, exp_subtype(add), lng);
    1129           3 :         return list_append(sa_list(sql->sa), add);
    1130             : }
    1131             : 
    1132             : /*
    1133             :  * Push TopN (only LIMIT, no ORDER BY) down through projections underneath crossproduct, i.e.,
    1134             :  *
    1135             :  *     topn(                          topn(
    1136             :  *         project(                       project(
    1137             :  *             crossproduct(                  crossproduct(
    1138             :  *                 L,           =>                topn( L )[ n ],
    1139             :  *                 R                              topn( R )[ n ]
    1140             :  *             )                              )
    1141             :  *         )[ Cs ]*                       )[ Cs ]*
    1142             :  *     )[ n ]                         )[ n ]
    1143             :  *
    1144             :  *  (TODO: in case of n==1 we can omit the original top-level TopN)
    1145             :  *
    1146             :  * also push topn under (non reordering) projections.
    1147             :  */
    1148             : static sql_rel *
    1149      136852 : rel_push_topn_and_sample_down_(visitor *v, sql_rel *rel)
    1150             : {
    1151      136852 :         sql_rel *rp = NULL, *r = rel->l, *rpp = NULL;
    1152             : 
    1153      136852 :         if (is_topn(rel->op) && !rel_is_ref(rel) &&
    1154       50073 :                         r && r->op == op_table && r->flag != TRIGGER_WRAPPER && !rel_is_ref(r) && r->r) {
    1155           3 :                 sql_exp *op = r->r;
    1156           3 :                 sql_subfunc *f = op->f;
    1157             : 
    1158           3 :                 if (is_func(op->type) && strcmp(f->func->base.name, "file_loader") == 0 && !sql_func_mod(f->func)[0] && !sql_func_imp(f->func)[0]) {
    1159             :                         /* push limit, to arguments of file_loader */
    1160           0 :                         list *args = op->l;
    1161           0 :                         if (list_length(args) == 2) {
    1162           0 :                                 sql_exp *topN = rel->exps->h->data;
    1163           0 :                                 sql_exp *offset = rel->exps->h->next? rel->exps->h->next->data:NULL;
    1164           0 :                                 atom *topn = topN->l;
    1165           0 :                                 if (offset) {
    1166           0 :                                                 atom *b1 = (atom *)offset->l, *c = atom_add(v->sql->sa, b1, topn);
    1167             : 
    1168           0 :                                                 if (!c)
    1169             :                                                         return rel;
    1170           0 :                                                 if (atom_cmp(c, topn) < 0) /* overflow */
    1171             :                                                         return rel;
    1172             :                                                 topn = c;
    1173             :                                 }
    1174           0 :                                 append(args, exp_atom(v->sql->sa, topn));
    1175           0 :                                 v->changes++;
    1176             :                         }
    1177             :                 }
    1178             :         }
    1179             : 
    1180      136852 :         if ((is_topn(rel->op) || is_sample(rel->op)) && topn_sample_safe_exps(rel->exps, true)) {
    1181       50156 :                 sql_rel *(*func) (allocator *, sql_rel *, list *) = is_topn(rel->op) ? rel_topn : rel_sample;
    1182             : 
    1183             :                 /* nested topN relations */
    1184       50156 :                 if (r && is_topn(rel->op) && is_topn(r->op) && !rel_is_ref(r)) {
    1185           0 :                         sql_exp *topN1 = rel->exps->h->data, *topN2 = r->exps->h->data;
    1186           0 :                         sql_exp *offset1 = list_length(rel->exps) > 1 ? rel->exps->h->next->data : NULL;
    1187           0 :                         sql_exp *offset2 = list_length(r->exps) > 1 ? r->exps->h->next->data : NULL;
    1188             : 
    1189           0 :                         if (topN1->l && topN2->l && (!offset1 || offset1->l) && (!offset2 || offset2->l)) { /* no parameters */
    1190           0 :                                 bool changed = false;
    1191             : 
    1192           0 :                                 if ((!offset1 || (offset1->type == e_atom && offset1->l)) && (!offset2 || (offset2->type == e_atom && offset2->l))) { /* only atoms */
    1193           0 :                                         if (!offset1 && offset2) {
    1194           0 :                                                 list_append(rel->exps, exp_copy(v->sql, offset2));
    1195           0 :                                                 changed = true;
    1196           0 :                                         } else if (offset1 && offset2) { /* sum offsets */
    1197           0 :                                                 atom *b1 = (atom *)offset1->l, *b2 = (atom *)offset2->l, *c = atom_add(v->sql->sa, b1, b2);
    1198             : 
    1199           0 :                                                 if (!c) /* error, don't apply optimization, WARNING because of this the offset optimization must come before the limit one */
    1200             :                                                         return rel;
    1201           0 :                                                 if (atom_cmp(c, b2) < 0) /* overflow */
    1202           0 :                                                         c = atom_int(v->sql->sa, sql_bind_localtype("lng"), GDK_lng_max);
    1203           0 :                                                 offset1->l = c;
    1204           0 :                                                 changed = true;
    1205             :                                         }
    1206             :                                 }
    1207             : 
    1208           0 :                                 if (topN1->type == e_atom && topN1->l && topN2->type == e_atom && topN2->l) { /* only atoms */
    1209           0 :                                         atom *a1 = (atom *)topN1->l, *a2 = (atom *)topN2->l;
    1210             : 
    1211           0 :                                         if (!a2->isnull && (a1->isnull || atom_cmp(a1, a2) >= 0)) { /* topN1 is not set or is larger than topN2 */
    1212           0 :                                                 rel->exps->h->data = exp_copy(v->sql, topN2);
    1213           0 :                                                 changed = true;
    1214             :                                         }
    1215             :                                 }
    1216             : 
    1217           0 :                                 if (changed) {
    1218           0 :                                         rel->l = r->l;
    1219           0 :                                         r->l = NULL;
    1220           0 :                                         rel_destroy(r);
    1221           0 :                                         v->changes++;
    1222           0 :                                         return rel;
    1223             :                                 }
    1224             :                         }
    1225             :                 }
    1226             : 
    1227       50156 :                 if (r && is_simple_project(r->op) && need_distinct(r))
    1228             :                         return rel;
    1229             : 
    1230             :                 /* push topn/sample under projections */
    1231       50151 :                 if (!rel_is_ref(rel) && r && is_simple_project(r->op) && !need_distinct(r) && !rel_is_ref(r) && r->l && list_empty(r->r)) {
    1232             :                         sql_rel *x = r, *px = x;
    1233             : 
    1234       32477 :                         while (is_simple_project(x->op) && !need_distinct(x) && !rel_is_ref(x) && x->l && list_empty(x->r)) {
    1235       16250 :                                 px = x;
    1236       16250 :                                 x = x->l;
    1237             :                         }
    1238             :                         /* only push topn once */
    1239       16227 :                         if (x && x->op == rel->op)
    1240             :                                 return rel;
    1241             : 
    1242       16218 :                         rel->l = x;
    1243       16218 :                         px->l = rel;
    1244       16218 :                         rel = r;
    1245       16218 :                         v->changes++;
    1246       16218 :                         return rel;
    1247             :                 }
    1248             : 
    1249       33924 :                 if (!topn_sample_safe_exps(rel->exps, false))
    1250             :                         return rel;
    1251             : 
    1252             :                 /* duplicate topn/sample direct under union or crossproduct */
    1253       33874 :                 if (r && !rel_is_ref(r) && r->l && r->r && ((is_union(r->op) && r->exps) || (r->op == op_join && list_empty(r->exps)))) {
    1254         148 :                         sql_rel *u = r, *x;
    1255         148 :                         sql_rel *ul = u->l;
    1256         148 :                         sql_rel *ur = u->r;
    1257         148 :                         bool changed = false;
    1258             : 
    1259         148 :                         x = ul;
    1260         154 :                         while (is_simple_project(x->op) && !need_distinct(x) && !rel_is_ref(x) && x->l && list_empty(x->r))
    1261           6 :                                 x = x->l;
    1262         148 :                         if (x && x->op != rel->op) { /* only push topn once */
    1263          60 :                                 ul = func(v->sql->sa, ul, sum_limit_offset(v->sql, rel));
    1264          60 :                                 set_processed(ul);
    1265          60 :                                 u->l = ul;
    1266          60 :                                 changed = true;
    1267             :                         }
    1268             : 
    1269         148 :                         x = ur;
    1270         156 :                         while (is_simple_project(x->op) && !need_distinct(x) && !rel_is_ref(x) && x->l && list_empty(x->r))
    1271           8 :                                 x = x->l;
    1272         148 :                         if (x && x->op != rel->op) { /* only push topn once */
    1273          61 :                                 ur = func(v->sql->sa, ur, sum_limit_offset(v->sql, rel));
    1274          61 :                                 set_processed(ur);
    1275          61 :                                 u->r = ur;
    1276          61 :                                 changed = true;
    1277             :                         }
    1278             : 
    1279         148 :                         if (changed)
    1280          61 :                                 v->changes++;
    1281         148 :                         return rel;
    1282             :                 }
    1283             : 
    1284             :                 /* duplicate topn/sample + [ project-order ] under union */
    1285             :                 if (r && !rp)
    1286       33726 :                         rp = r->l;
    1287       33726 :                 if (r && r->exps && is_simple_project(r->op) && !rel_is_ref(r) && !list_empty(r->r) && r->l && is_union(rp->op)) {
    1288           0 :                         sql_rel *u = rp, *ou = u, *x, *ul = u->l, *ur = u->r;
    1289           0 :                         list *rcopy = NULL;
    1290             : 
    1291             :                         /* only push topn/sample once */
    1292           0 :                         x = ul;
    1293           0 :                         while (is_simple_project(x->op) && !need_distinct(x) && !rel_is_ref(x) && x->l && list_empty(x->r))
    1294           0 :                                 x = x->l;
    1295           0 :                         if (x && x->op == rel->op)
    1296             :                                 return rel;
    1297             :                         x = ur;
    1298           0 :                         while (is_simple_project(x->op) && !need_distinct(x) && !rel_is_ref(x) && x->l && list_empty(x->r))
    1299           0 :                                 x = x->l;
    1300           0 :                         if (x && x->op == rel->op)
    1301             :                                 return rel;
    1302             : 
    1303           0 :                         rcopy = exps_copy(v->sql, r->r);
    1304           0 :                         for (node *n = rcopy->h ; n ; n = n->next) {
    1305           0 :                                 sql_exp *e = n->data;
    1306           0 :                                 set_descending(e); /* remove ordering properties for projected columns */
    1307           0 :                                 set_nulls_first(e);
    1308             :                         }
    1309           0 :                         ul = rel_dup(ul);
    1310           0 :                         ur = rel_dup(ur);
    1311           0 :                         if (!is_project(ul->op))
    1312           0 :                                 ul = rel_project(v->sql->sa, ul,
    1313             :                                         rel_projections(v->sql, ul, NULL, 1, 1));
    1314           0 :                         if (!is_project(ur->op))
    1315           0 :                                 ur = rel_project(v->sql->sa, ur,
    1316             :                                         rel_projections(v->sql, ur, NULL, 1, 1));
    1317           0 :                         rel_rename_exps(v->sql, u->exps, ul->exps);
    1318           0 :                         rel_rename_exps(v->sql, u->exps, ur->exps);
    1319             : 
    1320             :                         /* introduce projects under the set */
    1321           0 :                         ul = rel_project(v->sql->sa, ul, NULL);
    1322           0 :                         ul->exps = exps_copy(v->sql, r->exps);
    1323             :                         /* possibly add order by column */
    1324           0 :                         ul->exps = list_distinct(list_merge(ul->exps, exps_copy(v->sql, rcopy), NULL), (fcmp) exp_equal, (fdup) NULL);
    1325           0 :                         ul->nrcols = list_length(ul->exps);
    1326           0 :                         ul->r = exps_copy(v->sql, r->r);
    1327           0 :                         set_processed(ul);
    1328           0 :                         ul = func(v->sql->sa, ul, sum_limit_offset(v->sql, rel));
    1329           0 :                         set_processed(ul);
    1330             : 
    1331           0 :                         ur = rel_project(v->sql->sa, ur, NULL);
    1332           0 :                         ur->exps = exps_copy(v->sql, r->exps);
    1333             :                         /* possibly add order by column */
    1334           0 :                         ur->exps = list_distinct(list_merge(ur->exps, exps_copy(v->sql, rcopy), NULL), (fcmp) exp_equal, (fdup) NULL);
    1335           0 :                         ur->nrcols = list_length(ur->exps);
    1336           0 :                         ur->r = exps_copy(v->sql, r->r);
    1337           0 :                         set_processed(ur);
    1338           0 :                         ur = func(v->sql->sa, ur, sum_limit_offset(v->sql, rel));
    1339           0 :                         set_processed(ur);
    1340             : 
    1341           0 :                         u = rel_setop(v->sql->sa, ul, ur, op_union);
    1342           0 :                         u->exps = exps_alias(v->sql, r->exps);
    1343           0 :                         u->nrcols = list_length(u->exps);
    1344           0 :                         set_processed(u);
    1345             :                         /* possibly add order by column */
    1346           0 :                         u->exps = list_distinct(list_merge(u->exps, rcopy, NULL), (fcmp) exp_equal, (fdup) NULL);
    1347           0 :                         if (need_distinct(r)) {
    1348           0 :                                 set_distinct(ul);
    1349           0 :                                 set_distinct(ur);
    1350             :                         }
    1351             : 
    1352             :                         /* zap names */
    1353           0 :                         rel_no_rename_exps(u->exps);
    1354           0 :                         rel_destroy(ou);
    1355             : 
    1356           0 :                         ur = rel_project(v->sql->sa, u, exps_alias(v->sql, r->exps));
    1357           0 :                         ur->r = r->r;
    1358           0 :                         r->l = NULL;
    1359             : 
    1360           0 :                         if (need_distinct(r))
    1361           0 :                                 set_distinct(ur);
    1362             : 
    1363           0 :                         rel_destroy(r);
    1364           0 :                         rel->l = ur;
    1365           0 :                         v->changes++;
    1366           0 :                         return rel;
    1367             :                 }
    1368             :                 /* a  left outer join b order by a.* limit L, can be copied into a */
    1369             :                 /* topn ( project (orderby)( optional project ( left ())
    1370             :                  * rel    r                                     rp */
    1371       33726 :                 if (r && !rp)
    1372          66 :                         rp = r->l;
    1373       33726 :                 if (r && rp && is_simple_project(rp->op) && !rp->r && rp->l)
    1374       33726 :                         rpp = rp->l;
    1375       33726 :                 if (r && r->exps && is_simple_project(r->op) && !rel_is_ref(r) && r->r && r->l && ((!rpp && is_left(rp->op)) ||
    1376         300 :                                 (rpp && is_left(rpp->op)))) {
    1377          24 :                         sql_rel *lj = rpp?rpp:rp;
    1378          24 :                         sql_rel *l = lj->l;
    1379          24 :                         list *obes = r->r, *nobes = sa_list(v->sql->sa);
    1380          24 :                         int fnd = 1;
    1381          63 :                         for (node *n = obes->h; n && fnd; n = n->next) {
    1382          41 :                                 sql_exp *obe = n->data;
    1383          41 :                                 int asc = is_ascending(obe);
    1384          41 :                                 int nl = nulls_last(obe);
    1385             :                                 /* only simple rename expressions */
    1386          41 :                                 sql_exp *pe = exps_find_exp(r->exps, obe);
    1387          41 :                                 if (pe && rpp)
    1388          33 :                                         pe = exps_find_exp(rp->exps, pe);
    1389          41 :                                 if (pe)
    1390          41 :                                         pe = rel_find_exp(l, pe);
    1391          41 :                                 if (pe) {
    1392          41 :                                         if (exp_is_atom(pe))
    1393             :                                                 return rel;
    1394          39 :                                         pe = exp_ref(v->sql, pe);
    1395          39 :                                         if (asc)
    1396          29 :                                                 set_ascending(pe);
    1397          39 :                                         if (nl)
    1398           5 :                                                 set_nulls_last(pe);
    1399          39 :                                         append(nobes, pe);
    1400             :                                 }
    1401             :                                 else
    1402             :                                         fnd = 0;
    1403             :                         }
    1404          22 :                         if (fnd && ((is_topn(rel->op) && !is_topn(l->op)) || (is_sample(rel->op) && !is_sample(l->op)))) {
    1405             :                                 /* inject topn */
    1406             :                                 /* Todo add order by */
    1407           8 :                                 sql_rel *ob = lj->l = rel_project(v->sql->sa, lj->l, rel_projections(v->sql, lj->l, NULL, 1, 1));
    1408           8 :                                 ob->r = nobes;
    1409           8 :                                 lj->l = func(v->sql->sa, lj->l, sum_limit_offset(v->sql, rel));
    1410           8 :                                 v->changes++;
    1411           8 :                                 return rel;
    1412             :                         }
    1413             :                 }
    1414             :         }
    1415             :         return rel;
    1416             : }
    1417             : 
    1418             : static sql_rel *
    1419       33455 : rel_push_topn_and_sample_down(visitor *v, global_props *gp, sql_rel *rel)
    1420             : {
    1421       33455 :         (void) gp;
    1422       33455 :         return rel_visitor_topdown(v, rel, &rel_push_topn_and_sample_down_);
    1423             : }
    1424             : 
    1425             : run_optimizer
    1426      623706 : bind_push_topn_and_sample_down(visitor *v, global_props *gp)
    1427             : {
    1428      623706 :         int flag = v->sql->sql_optimizer;
    1429      623510 :         return gp->opt_level == 1 && (gp->cnt[op_topn] || gp->cnt[op_sample]) &&
    1430      657161 :                    (flag & push_topn_and_sample_down) ? rel_push_topn_and_sample_down : NULL;
    1431             : }

Generated by: LCOV version 1.14