LCOV - code coverage report
Current view: top level - sql/server - rel_select.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 3733 4067 91.8 %
Date: 2024-10-03 20:03:20 Functions: 116 117 99.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_select.h"
      15             : #include "sql_tokens.h"
      16             : #include "sql_privileges.h"
      17             : #include "sql_env.h"
      18             : #include "sql_decimal.h"
      19             : #include "sql_qc.h"
      20             : #include "rel_rel.h"
      21             : #include "rel_basetable.h"
      22             : #include "rel_exp.h"
      23             : #include "rel_xml.h"
      24             : #include "rel_dump.h"
      25             : #include "rel_prop.h"
      26             : #include "rel_psm.h"
      27             : #include "rel_schema.h"
      28             : #include "rel_unnest.h"
      29             : #include "rel_sequence.h"
      30             : #include "rel_file_loader.h"
      31             : 
      32             : #define VALUE_FUNC(f) (f->func->type == F_FUNC || f->func->type == F_FILT)
      33             : #define check_card(card,f) ((card == card_none && !f->res) || (CARD_VALUE(card) && f->res && VALUE_FUNC(f)) || card == card_loader || (card == card_relation && f->func->type == F_UNION))
      34             : 
      35             : /* return all expressions, with table name == tname */
      36             : static list *
      37       56935 : rel_table_projections( mvc *sql, sql_rel *rel, char *tname, int level )
      38             : {
      39       57448 :         list *exps;
      40             : 
      41       57448 :         if (mvc_highwater(sql))
      42           0 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
      43             : 
      44       57448 :         if (!rel)
      45             :                 return NULL;
      46             : 
      47       57448 :         if (!tname)
      48       41708 :                 return _rel_projections(sql, rel, NULL, 1, 0, 1);
      49             : 
      50       15740 :         switch(rel->op) {
      51         521 :         case op_join:
      52             :         case op_left:
      53             :         case op_right:
      54             :         case op_full:
      55         521 :                 exps = rel_table_projections( sql, rel->l, tname, level+1);
      56         521 :                 if (exps)
      57             :                         return exps;
      58          13 :                 return rel_table_projections( sql, rel->r, tname, level+1);
      59         500 :         case op_semi:
      60             :         case op_anti:
      61             :         case op_select:
      62         500 :                 return rel_table_projections( sql, rel->l, tname, level+1);
      63             : 
      64          54 :         case op_topn:
      65             :         case op_sample:
      66             :         case op_groupby:
      67             :         case op_union:
      68             :         case op_except:
      69             :         case op_inter:
      70             :         case op_project:
      71          54 :                 if (!is_processed(rel) && level == 0)
      72           0 :                         return rel_table_projections( sql, rel->l, tname, level+1);
      73             :                 /* fall through */
      74             :         case op_munion:
      75          60 :                 if (!is_processed(rel) && level == 0) {
      76           0 :                         node *n = ((list*)rel->l)->h;
      77           0 :                         if (n)
      78           0 :                                 return rel_table_projections(sql, n->data, tname, level+1);
      79             :                 }
      80             :         /* fall through */
      81             :         case op_table:
      82             :         case op_basetable:
      83       14719 :                 if (is_basetable(rel->op) && !rel->exps)
      84       14159 :                         return rel_base_project_all(sql, rel, tname);
      85         560 :                 if (rel->exps) {
      86         560 :                         int rename = 0;
      87         560 :                         node *en;
      88             : 
      89             :                         /* first check alias */
      90         560 :                         if (!is_base(rel->op) && !level) {
      91          54 :                                 list *exps = sa_list(sql->sa);
      92             : 
      93         409 :                                 for (en = rel->exps->h; en && !rename; en = en->next) {
      94         355 :                                         sql_exp *e = en->data;;
      95             : 
      96         355 :                                         if ((is_basecol(e) && exp_relname(e) && strcmp(exp_relname(e), tname) == 0) ||
      97         138 :                                             (is_basecol(e) && !exp_relname(e) && e->l && strcmp(e->l, tname) == 0)) {
      98         217 :                                                 if (exp_name(e) && exps_bind_column2(exps, tname, exp_name(e), NULL))
      99             :                                                         rename = 1;
     100             :                                                 else
     101         217 :                                                         append(exps, e);
     102             :                                         }
     103             :                                 }
     104             :                         }
     105             : 
     106         560 :                         exps = new_exp_list(sql->sa);
     107        4930 :                         for (en = rel->exps->h; en; en = en->next) {
     108        4370 :                                 sql_exp *e = en->data;
     109        4370 :                                 if (is_basecol(e) && exp_relname(e) && strcmp(exp_relname(e), tname) == 0) {
     110        4230 :                                         if (rename)
     111           0 :                                                 append(exps, exp_alias_ref(sql, e));
     112             :                                         else {
     113        4230 :                                                 sql_exp *ne = exp_ref(sql, e);
     114        4230 :                                                 exp_setname(sql, ne, tname, exp_name(e));
     115        4230 :                                                 append(exps, ne);
     116             :                                         }
     117             :                                 }
     118        4370 :                                 if (is_basecol(e) && !exp_relname(e) && e->l && strcmp(e->l, tname) == 0) {
     119           0 :                                         if (rename)
     120           0 :                                                 append(exps, exp_alias_ref(sql, e));
     121             :                                         else {
     122           0 :                                                 sql_exp *ne = exp_ref(sql, e);
     123           0 :                                                 exp_setname(sql, ne, tname, exp_name(e));
     124           0 :                                                 append(exps, ne);
     125             :                                         }
     126             :                                 }
     127             : 
     128             :                         }
     129         560 :                         if (exps && list_length(exps))
     130             :                                 return exps;
     131             :                 }
     132             :                 /* fall through */
     133             :         default:
     134             :                 return NULL;
     135             :         }
     136             : }
     137             : 
     138             : static sql_exp *
     139           0 : rel_lastexp(mvc *sql, sql_rel *rel )
     140             : {
     141           0 :         sql_exp *e;
     142             : 
     143           0 :         if (!is_processed(rel) || is_topn(rel->op) || is_sample(rel->op))
     144           0 :                 rel = rel_parent(rel);
     145           0 :         assert(list_length(rel->exps));
     146           0 :         if (rel->op == op_project) {
     147           0 :                 list_hash_clear(rel->exps);
     148           0 :                 return exp_ref(sql, rel->exps->t->data);
     149             :         }
     150           0 :         assert(is_project(rel->op));
     151           0 :         e = rel->exps->t->data;
     152           0 :         return exp_ref(sql, e);
     153             : }
     154             : 
     155             : static sql_rel *
     156       36512 : rel_orderby(mvc *sql, sql_rel *l)
     157             : {
     158       36512 :         sql_rel *rel = rel_create(sql->sa);
     159       36512 :         if (!rel)
     160             :                 return NULL;
     161             : 
     162       36512 :         assert(l->op == op_project && !l->r);
     163       36512 :         rel->l = l;
     164       36512 :         rel->r = NULL;
     165       36512 :         rel->op = op_project;
     166       36512 :         rel->exps = rel_projections(sql, l, NULL, 1, 0);
     167       36512 :         rel->card = l->card;
     168       36512 :         rel->nrcols = l->nrcols;
     169       36512 :         return rel;
     170             : }
     171             : 
     172             : /* forward refs */
     173             : static sql_rel * rel_setquery(sql_query *query, symbol *sq);
     174             : static sql_rel * rel_joinquery(sql_query *query, symbol *sq, list *refs);
     175             : 
     176             : static sql_rel *
     177      202429 : rel_table_optname(mvc *sql, sql_rel *sq, symbol *optname, list *refs)
     178             : {
     179      202429 :         sql_rel *osq = sq;
     180      202429 :         node *ne;
     181             : 
     182      202429 :         if (optname && optname->token == SQL_NAME) {
     183       17970 :                 dlist *columnrefs = NULL;
     184       17970 :                 char *tname = optname->data.lval->h->data.sval;
     185       17970 :                 list *l = sa_list(sql->sa);
     186             : 
     187       17970 :                 columnrefs = optname->data.lval->h->next->data.lval;
     188       17970 :                 if (is_topn(sq->op) || is_sample(sq->op) || ((is_simple_project(sq->op) || is_groupby(sq->op)) && sq->r) || is_base(sq->op)) {
     189         110 :                         sq = rel_project(sql->sa, sq, rel_projections(sql, sq, NULL, 1, 0));
     190         110 :                         osq = sq;
     191             :                 }
     192       17970 :                 if (columnrefs && dlist_length(columnrefs) != list_length(sq->exps))
     193           6 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: The number of aliases don't match the number of columns (%d != %d)", dlist_length(columnrefs), sq->nrcols);
     194        5009 :                 if (columnrefs && sq->exps) {
     195        5009 :                         dnode *d = columnrefs->h;
     196             : 
     197        5009 :                         ne = sq->exps->h;
     198        5009 :                         list_hash_clear(sq->exps);
     199       20676 :                         for (; d && ne; d = d->next, ne = ne->next) {
     200       10659 :                                 sql_exp *e = ne->data;
     201             : 
     202       10659 :                                 if (exps_bind_column2(l, tname, d->data.sval, NULL))
     203           1 :                                         return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "SELECT: Duplicate column name '%s.%s'", tname, d->data.sval);
     204       10658 :                                 exp_setname(sql, e, tname, d->data.sval );
     205       10658 :                                 if (!is_intern(e))
     206       10658 :                                         set_basecol(e);
     207       10658 :                                 append(l, e);
     208             :                         }
     209             :                 }
     210       17963 :                 if (!columnrefs && sq->exps) {
     211       12955 :                         ne = sq->exps->h;
     212       12955 :                         list_hash_clear(sq->exps);
     213      126652 :                         for (; ne; ne = ne->next) {
     214      100742 :                                 sql_exp *e = ne->data;
     215      100742 :                                 char *name = NULL;
     216             : 
     217      100742 :                                 if (!is_intern(e)) {
     218      100742 :                                         if (!exp_name(e))
     219         108 :                                                 name = make_label(sql->sa, ++sql->label);
     220      100742 :                                         noninternexp_setname(sql, e, tname, name);
     221      100742 :                                         set_basecol(e);
     222             :                                 }
     223             :                         }
     224             :                 }
     225       17963 :                 if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
     226       17913 :                         if (list_find(refs, tname, (fcmp) &strcmp))
     227           6 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: relation name \"%s\" specified more than once", tname);
     228       17907 :                         assert(tname);
     229       17907 :                         list_append(refs, tname);
     230             :                 }
     231             :         } else {
     232      184459 :                 if (!is_project(sq->op) || is_topn(sq->op) || is_sample(sq->op) || ((is_simple_project(sq->op) || is_groupby(sq->op)) && sq->r)) {
     233       58555 :                         sq = rel_project(sql->sa, sq, rel_projections(sql, sq, NULL, 1, 1));
     234       58555 :                         osq = sq;
     235             :                 }
     236     2319772 :                 for (ne = osq->exps->h; ne; ne = ne->next) {
     237     2135313 :                         sql_exp *e = ne->data;
     238             : 
     239     2135313 :                         if (!is_intern(e))
     240     2008821 :                                 set_basecol(e);
     241             :                 }
     242             :         }
     243             :         return osq;
     244             : }
     245             : 
     246             : static sql_rel *
     247       97527 : rel_subquery_optname(sql_query *query, symbol *ast, list *refs)
     248             : {
     249       97527 :         mvc *sql = query->sql;
     250       97527 :         SelectNode *sn = (SelectNode *) ast;
     251       97527 :         exp_kind ek = {type_value, card_relation, TRUE};
     252       97527 :         sql_rel *sq = rel_subquery(query, ast, ek);
     253             : 
     254       97527 :         assert(ast->token == SQL_SELECT);
     255       97527 :         if (!sq)
     256             :                 return NULL;
     257             : 
     258       97511 :         return rel_table_optname(sql, sq, sn->name, refs);
     259             : }
     260             : 
     261             : sql_rel *
     262        6932 : rel_with_query(sql_query *query, symbol *q )
     263             : {
     264        6932 :         mvc *sql = query->sql;
     265        6932 :         dnode *d = q->data.lval->h;
     266        6932 :         symbol *next = d->next->data.sym;
     267        6932 :         sql_rel *rel;
     268             : 
     269        6932 :         if (!stack_push_frame(sql, NULL))
     270           0 :                 return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
     271             :         /* first handle all with's (ie inlined views) */
     272       19665 :         for (d = d->data.lval->h; d; d = d->next) {
     273       12739 :                 symbol *sym = d->data.sym;
     274       12739 :                 dnode *dn = sym->data.lval->h;
     275       12739 :                 char *rname = qname_schema_object(dn->data.lval);
     276       12739 :                 sql_rel *nrel;
     277             : 
     278       12739 :                 if (frame_find_rel_view(sql, rname)) {
     279           1 :                         stack_pop_frame(sql);
     280           1 :                         return sql_error(sql, 01, SQLSTATE(42000) "View '%s' already declared", rname);
     281             :                 }
     282       12738 :                 nrel = rel_semantic(query, sym);
     283       12738 :                 if (!nrel) {
     284           5 :                         stack_pop_frame(sql);
     285           5 :                         return NULL;
     286             :                 }
     287       12733 :                 if (!stack_push_rel_view(sql, rname, nrel)) {
     288           0 :                         stack_pop_frame(sql);
     289           0 :                         return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
     290             :                 }
     291       12733 :                 if (!is_project(nrel->op)) {
     292           0 :                         if (is_topn(nrel->op) || is_sample(nrel->op)) {
     293           0 :                                 nrel = rel_project(sql->sa, nrel, rel_projections(sql, nrel, NULL, 1, 1));
     294             :                         } else {
     295           0 :                                 stack_pop_frame(sql);
     296           0 :                                 return NULL;
     297             :                         }
     298             :                 }
     299       12733 :                 assert(is_project(nrel->op));
     300       12733 :                 if (is_project(nrel->op) && nrel->exps) {
     301       12733 :                         node *ne = nrel->exps->h;
     302             : 
     303       56473 :                         for (; ne; ne = ne->next) {
     304       43740 :                                 sql_exp *e = ne->data;
     305       43740 :                                 char *name = NULL;
     306             : 
     307       43740 :                                 if (!is_intern(e)) {
     308       43740 :                                         if (!exp_name(e))
     309          13 :                                                 name = make_label(sql->sa, ++sql->label);
     310       43740 :                                         noninternexp_setname(sql, e, rname, name);
     311       43740 :                                         set_basecol(e);
     312             :                                 }
     313             :                         }
     314       12733 :                         list_hash_clear(nrel->exps);
     315             :                 }
     316             :         }
     317        6926 :         rel = rel_semantic(query, next);
     318        6926 :         stack_pop_frame(sql);
     319        6926 :         return rel;
     320             : }
     321             : 
     322             : static sql_rel *
     323       59614 : query_exp_optname(sql_query *query, symbol *q, list *refs)
     324             : {
     325       59614 :         mvc *sql = query->sql;
     326       59614 :         switch (q->token) {
     327         943 :         case SQL_WITH:
     328             :         {
     329         943 :                 sql_rel *tq = rel_with_query(query, q);
     330             : 
     331         943 :                 if (!tq)
     332             :                         return NULL;
     333         943 :                 if (q->data.lval->t->type == type_symbol)
     334         943 :                         return rel_table_optname(sql, tq, q->data.lval->t->data.sym, refs);
     335             :                 return tq;
     336             :         }
     337       58671 :         case SQL_JOIN:
     338             :         {
     339       58671 :                 sql_rel *tq = rel_joinquery(query, q, refs);
     340             : 
     341       58671 :                 if (!tq)
     342             :                         return NULL;
     343       58630 :                 return rel_table_optname(sql, tq, q->data.lval->t->data.sym, NULL);
     344             :         }
     345           0 :         default:
     346           0 :                 (void) sql_error(sql, 02, SQLSTATE(42000) "case %d %s", (int) q->token, token2string(q->token));
     347             :         }
     348           0 :         return NULL;
     349             : }
     350             : 
     351             : static sql_subfunc *
     352      113342 : bind_func_(mvc *sql, char *sname, char *fname, list *ops, sql_ftype type, bool private, bool *found, bool exact)
     353             : {
     354      113342 :         sql_subfunc *sf = NULL;
     355             : 
     356      113567 :         if (sql->forward && strcmp(fname, sql->forward->base.name) == 0 &&
     357         225 :             list_cmp(sql->forward->ops, ops, (fcmp)&arg_subtype_cmp) == 0 &&
     358           0 :             execute_priv(sql, sql->forward) && type == sql->forward->type)
     359           0 :                 return sql_dup_subfunc(sql->sa, sql->forward, NULL, NULL);
     360      113342 :         sf = sql_bind_func_(sql, sname, fname, ops, type, private, exact);
     361      113342 :         if (found)
     362      112812 :                 *found |= sf != NULL;
     363      113342 :         if (sf && execute_priv(sql, sf->func))
     364             :                 return sf;
     365             :         return NULL;
     366             : }
     367             : 
     368             : static sql_subfunc *
     369      617069 : bind_func(mvc *sql, char *sname, char *fname, sql_subtype *t1, sql_subtype *t2, int nr, sql_ftype type, bool private, bool *found, bool exact)
     370             : {
     371      617069 :         list *tl = sa_list(sql->sa);
     372      617069 :         assert(nr >= 1 && nr <= 2);
     373      617069 :         append(tl, t1);
     374      617069 :         if (nr == 2)
     375      522588 :                 append(tl, t2);
     376      617069 :         sql_subfunc *sf = NULL;
     377             : 
     378      617069 :         if (sql->forward) {
     379      131598 :                 if (execute_priv(sql, sql->forward) &&
     380      131598 :                     strcmp(fname, sql->forward->base.name) == 0 &&
     381         230 :                    ((!t1 && list_length(sql->forward->ops) == 0) ||
     382         232 :                     (!t2 && list_length(sql->forward->ops) == 1 && arg_subtype_cmp(sql->forward->ops->h->data, t1) == 0) ||
     383         228 :                     (list_length(sql->forward->ops) == 2 &&
     384           0 :                         arg_subtype_cmp(sql->forward->ops->h->data, t1) == 0 &&
     385           2 :                         arg_subtype_cmp(sql->forward->ops->h->next->data, t2) == 0)) && type == sql->forward->type) {
     386           2 :                         return sql_dup_subfunc(sql->sa, sql->forward, NULL, NULL);
     387             :                 }
     388             :         }
     389      617067 :         sf = sql_bind_func_(sql, sname, fname, tl, type, private, exact);
     390      617067 :         if (found)
     391      617067 :                 *found |= sf != NULL;
     392      617067 :         if (sf && execute_priv(sql, sf->func))
     393             :                 return sf;
     394             :         return NULL;
     395             : }
     396             : 
     397             : static sql_subfunc *
     398      636535 : find_func(mvc *sql, char *sname, char *fname, int len, sql_ftype type, bool private, sql_subfunc *prev, bool *found)
     399             : {
     400      636535 :         sql_subfunc *sf = NULL;
     401             : 
     402      636535 :         if (sql->forward && strcmp(fname, sql->forward->base.name) == 0 && list_length(sql->forward->ops) == len && execute_priv(sql, sql->forward) && type == sql->forward->type)
     403           0 :                 return sql_dup_subfunc(sql->sa, sql->forward, NULL, NULL);
     404      636535 :         sf = sql_find_func(sql, sname, fname, len, type, private, prev);
     405      636535 :         if (found)
     406           0 :                 *found |= sf != NULL;
     407      636535 :         if (sf && execute_priv(sql, sf->func))
     408             :                 return sf;
     409             :         return NULL;
     410             : }
     411             : 
     412             : static sql_exp *
     413      694446 : exp_fix_scale(mvc *sql, sql_subtype *ct, sql_exp *e)
     414             : {
     415      694446 :         sql_subtype *et = exp_subtype(e);
     416             : 
     417      694446 :         if (ct->type->scale == SCALE_FIX && et->type->scale == SCALE_FIX) {
     418       82813 :                 int scale_diff = ((int) ct->scale - (int) et->scale);
     419             : 
     420       82813 :                 if (scale_diff) {
     421         132 :                         if (scale_diff < 0)
     422             :                                 return e;
     423         102 :                         sql_subtype st;
     424         102 :                         int scale = ct->scale;
     425         102 :                         int digits = ((et->type->eclass == EC_NUM)?bits2digits(et->digits):et->digits)-et->scale+scale;
     426         102 :                         (void)sql_find_subtype(&st, ct->type->base.name, digits, scale);
     427         102 :                         return exp_convert(sql, e, et, &st);
     428             :                 }
     429             :         }
     430             :         return e;
     431             : }
     432             : 
     433             : static lng
     434        9649 : rel_get_count(sql_rel *rel)
     435             : {
     436       31093 :         if (!rel)
     437             :                 return 0;
     438       31089 :         prop *p = NULL;
     439       31089 :         if (rel->p && (p = find_prop(rel->p, PROP_COUNT)) != NULL)
     440        3041 :                 return p->value.lval;
     441       28048 :         else if(is_munion(rel->op)) {
     442         168 :                 lng cnt = 0;
     443         168 :                 list *l = rel->l;
     444         504 :                 for (node *n = l->h; n; n = n->next) {
     445         336 :                         lng lcnt = rel_get_count(n->data);
     446         336 :                         if (lcnt == BUN_MAX)
     447             :                                 return BUN_MAX;
     448         336 :                         cnt += lcnt;
     449             :                 }
     450         168 :                 return cnt;
     451       27880 :         } else if(rel->l) {
     452       25209 :                 if (is_select(rel->op) || is_project(rel->op))
     453             :                         return rel_get_count(rel->l);
     454             :         }
     455             :         return 0;
     456             : }
     457             : 
     458             : #define is_sum_aggr(f) (f->type == F_AGGR && strcmp(f->base.name, "sum") == 0)
     459             : 
     460             : list *
     461      737859 : check_arguments_and_find_largest_any_type(mvc *sql, sql_rel *rel, list *exps, sql_subfunc *sf, int maybe_zero_or_one, bool internal)
     462             : {
     463      737859 :         list *nexps = new_exp_list(sql->sa);
     464      737859 :         sql_subtype *atp = NULL, super, *res = !list_empty(sf->res) ? sf->res->h->data: NULL;
     465      737859 :         unsigned int digits = 0, scale = 0;
     466             : 
     467             :         /* find largest any type argument */
     468     2178418 :         for (node *n = exps->h, *m = sf->func->ops->h; n && m; n = n->next, m = m->next) {
     469     1440559 :                 sql_arg *a = m->data;
     470     1440559 :                 sql_exp *e = n->data;
     471     1440559 :                 sql_subtype *t = exp_subtype(e);
     472             : 
     473     1440559 :                 if (a->type.type->eclass == EC_ANY) {
     474      265620 :                         if (t && atp) {
     475      114498 :                                 supertype(&super, t, atp);
     476      114498 :                                 atp = &super;
     477      151122 :                         } else if (t) {
     478             :                                 atp = t;
     479             :                         }
     480             :                 }
     481     1440556 :                 if (t && sf->func->fix_scale == SCALE_FIX && t->type->eclass == EC_DEC) {
     482        1263 :                         if (digits < t->digits)
     483             :                                 digits = t->digits;
     484        1263 :                         if (scale < t->scale)
     485             :                                 scale = t->scale;
     486             :                 }
     487             :         }
     488      737859 :         if (!atp && !list_empty(exps))
     489      586738 :                 atp = exp_subtype(exps->h->data);
     490             : 
     491      737859 :         if ((atp && atp->type->localtype == TYPE_void) || !atp) /* NULL */
     492        9418 :                 atp = sql_bind_localtype("str");
     493             : 
     494      737859 :         node *n, *m;
     495     2178418 :         for (n = exps->h, m = sf->func->ops->h; n && m; n = n->next, m = m->next) {
     496     1440559 :                 sql_arg *a = m->data;
     497     1440559 :                 sql_exp *e = n->data;
     498     1440559 :                 sql_subtype *ntp = &a->type, *t = exp_subtype(e);
     499             : 
     500     1440559 :                 if (!t) {
     501          38 :                         if (a->type.type->eclass == EC_ANY && atp)
     502           3 :                                 ntp = sql_create_subtype(sql->sa, atp->type, atp->digits, atp->scale);
     503          61 :                         rel_set_type_param(sql, ntp, rel, e, sf->func->fix_scale != INOUT && !UDF_LANG(sf->func->lang));
     504     1440521 :                 } else if (a->type.type->eclass == EC_ANY && atp) {
     505      265617 :                         ntp = sql_create_subtype(sql->sa, atp->type, atp->digits, atp->scale);
     506     1174904 :                 } else if (t && ntp->digits == 0 && EC_VARCHAR(a->type.type->eclass)) {
     507      510822 :                         ntp = sql_create_subtype(sql->sa, a->type.type, type_digits_to_char_digits(t), 0);
     508      664082 :                 } else if (t && ntp->digits > 0 && a->type.type->eclass == EC_NUM && t->type->eclass == EC_NUM) {
     509      359176 :                         ntp = sql_create_subtype(sql->sa, a->type.type, t->digits, 0);
     510      304906 :                 } else if (t && ntp->scale == 0 && ntp->type->eclass == EC_DEC && EC_VARCHAR(t->type->eclass)) {
     511           0 :                         sql_subtype *res = SA_NEW(sql->sa, sql_subtype);
     512           0 :                         int digits = t->digits?t->digits+3:ntp->digits;
     513           0 :                         (void)sql_find_subtype(res, a->type.type->base.name, digits, 3);
     514           0 :                         ntp = res;
     515      304906 :                 } else if (t && ntp->scale == 0 && ntp->type->eclass == EC_DEC) {
     516        4869 :                         ntp = sql_create_subtype(sql->sa, a->type.type, t->type->eclass == EC_NUM?bits2digits(t->digits):t->digits, t->scale);
     517      300037 :                 } else if (t->type == ntp->type) {
     518      297939 :                         ntp = t;
     519             :                 }
     520     1440559 :                 if (!(e = exp_check_type(sql, ntp, rel, e, type_equal)))
     521             :                         return NULL;
     522     1440559 :                 if (sf->func->fix_scale == SCALE_FIX) {
     523      523310 :                         ntp = sql_create_subtype(sql->sa, a->type.type->localtype?a->type.type:t?t->type:atp->type, digits, scale);
     524      523310 :                         e = exp_fix_scale(sql, ntp, e);
     525      917249 :                 } else if (sf->func->fix_scale == SCALE_EQ) {
     526      171136 :                         e = exp_fix_scale(sql, &a->type, e);
     527             :                 }
     528     1440559 :                 if (maybe_zero_or_one && e->card > CARD_ATOM) {
     529          22 :                         sql_subfunc *zero_or_one = sql_bind_func(sql, "sys", "zero_or_one", exp_subtype(e), NULL, F_AGGR, true, false);
     530          22 :                         e = exp_aggr1(sql->sa, e, zero_or_one, 0, 0, CARD_ATOM, has_nil(e));
     531             :                 }
     532     1440559 :                 append(nexps, e);
     533             :         }
     534             :         /* handle any extra arguments for rel_dump/analytic funcs */
     535      738078 :         for ( ; n; n = n->next)
     536         219 :                 append(nexps, n->data);
     537      737859 :         if (sf->func->fix_scale == SCALE_FIX || IS_ANALYTIC(sf->func)) {
     538      270467 :                 exps_scale_fix(sf, nexps, atp);
     539      467392 :         } else if (sf->func->fix_scale == MAX_BITS) {
     540      111642 :                 exps_max_bits(sf, nexps);
     541      355750 :         } else if (sf->func->fix_scale == SCALE_MUL) {
     542       25185 :                 exps_sum_scales(sf, nexps);
     543      330565 :         } else if (!internal && sf->func->fix_scale == SCALE_DIV) {
     544        2604 :                 if (!exps_scale_algebra(sql, sf, rel, nexps))
     545             :                         return NULL;
     546      327961 :         } else if (sf->func->fix_scale == DIGITS_ADD) {
     547      181313 :                 exps_digits_add(sf, nexps);
     548      146648 :         } else if (sf->func->fix_scale == INOUT) {
     549       19010 :                 exps_inout(sf, nexps);
     550      127638 :         } else if (is_sum_aggr(sf->func))
     551        9313 :                 exps_largest_int(sf, nexps, rel_get_count(rel));
     552             : 
     553             :         /* dirty hack */
     554      737857 :         if (sf->func->type != F_PROC && sf->func->type != F_UNION && sf->func->type != F_LOADER && res) {
     555      733220 :                 if (res->type->eclass == EC_ANY && atp)
     556          73 :                         sf->res->h->data = sql_create_subtype(sql->sa, atp->type, atp->digits, atp->scale);
     557             :         }
     558             :         return nexps;
     559             : }
     560             : 
     561             : static char *
     562          32 : nary_function_arg_types_2str(mvc *sql, list* types, int N)
     563             : {
     564          32 :         char *arg_list = NULL;
     565          32 :         int i = 0;
     566             : 
     567         116 :         for (node *n = types->h; n && i < N; n = n->next) {
     568          84 :                 sql_subtype *t = (sql_subtype *) n->data;
     569          84 :                 char *tpe = t ? sql_subtype_string(sql->ta, t) : "?";
     570             : 
     571          84 :                 if (arg_list) {
     572          52 :                         arg_list = sa_message(sql->ta, "%s, %s", arg_list, tpe);
     573             :                 } else {
     574             :                         arg_list = tpe;
     575             :                 }
     576          84 :                 i++;
     577             :         }
     578          32 :         return arg_list;
     579             : }
     580             : 
     581             : static char *
     582          33 : file_loader_add_table_column_types(mvc *sql, sql_subfunc *f, list *exps, list *res_exps, char *tname)
     583             : {
     584          33 :         sql_exp *file = exps->h->data;
     585          33 :         if (!exp_is_atom(file))
     586             :                 return "Filename missing";
     587             : 
     588          33 :         atom *a = file->l;
     589          33 :         if (a->data.vtype != TYPE_str || !a->data.val.sval)
     590             :                 return "Filename missing";
     591             : 
     592          33 :         char *filename = a->data.val.sval;
     593          33 :         if (strcmp(filename, "") == 0)
     594             :                 return "Filename missing";
     595             : 
     596          31 :         char *ext = strrchr(filename, '.'), *ep = ext;
     597             : 
     598          31 :         if (ext) {
     599          28 :                 ext = ext + 1;
     600          28 :                 ext = mkLower(sa_strdup(sql->sa, ext));
     601             :         }
     602          28 :         if (!ext)
     603           3 :                 return "Filename extension missing";
     604             : 
     605          28 :         file_loader_t *fl = fl_find(ext);
     606          28 :         if (!fl) {
     607             :                 /* maybe compressed */
     608          10 :                 char *p = ep - 1;
     609          66 :                 while (p > filename && *p != '.')
     610          56 :                         p--;
     611          10 :                 if (p != filename) {
     612           8 :                         ext = p + 1;
     613           8 :                         ext = sa_strdup(sql->sa, ext);
     614           8 :                         char *d = strchr(ext, '.');
     615           8 :                         assert(d);
     616           8 :                         *d = 0;
     617           8 :                         fl = fl_find(ext);
     618             :                 }
     619          10 :                 if (!fl) /* fallback */
     620           2 :                         fl = fl_find("csv");
     621           2 :                 if (!fl) /* not expected */
     622           0 :                         return sa_message(sql->ta, "Filename extension '%s' missing", ext?ext:"");
     623             :         }
     624          28 :         str err = fl->add_types(sql, f, filename, res_exps, tname);
     625          28 :         if (err)
     626             :                 return err;
     627          14 :         sql_subtype *st = sql_bind_localtype("str");
     628          14 :         sql_exp *ext_exp = exp_atom(sql->sa, atom_string(sql->sa, st, ext));
     629          14 :         if (!ext_exp)
     630             :                 return MAL_MALLOC_FAIL;
     631          14 :         append(exps, ext_exp);
     632          14 :         return NULL;
     633             : }
     634             : 
     635             : static sql_rel *
     636          33 : rel_file_loader(mvc *sql, list *exps, list *tl, char *tname)
     637             : {
     638          33 :         sql_subfunc *f = NULL;
     639          33 :         bool found = false;
     640             : 
     641          33 :         if ((f = bind_func_(sql, NULL, "file_loader", tl, F_UNION, true, &found, false))) {
     642          33 :                 list *nexps = exps;
     643          33 :                 if (list_empty(tl) || f->func->vararg || (nexps = check_arguments_and_find_largest_any_type(sql, NULL, exps, f, 1, false))) {
     644          33 :                         list *res_exps = sa_list(sql->sa);
     645          33 :                         if (list_length(exps) == 1 && f && f->func->varres && strlen(f->func->mod) == 0 && strlen(f->func->imp) == 0) {
     646          33 :                                 char *err = file_loader_add_table_column_types(sql, f, nexps, res_exps, tname);
     647          33 :                                 if (err)
     648          19 :                                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: file_loader function failed '%s'", err);
     649             :                         }
     650          14 :                         sql_exp *e = exp_op(sql->sa, nexps, f);
     651          14 :                         sql_rel *rel = rel_table_func(sql->sa, NULL, e, res_exps, TABLE_PROD_FUNC);
     652          14 :                         if (rel)
     653          14 :                                 rel = rel_project(sql->sa, rel, exps_alias(sql, res_exps));
     654          14 :                         return rel;
     655             :                 }
     656             :         }
     657             :         return NULL;
     658             : }
     659             : 
     660             : sql_exp *
     661       10854 : find_table_function(mvc *sql, char *sname, char *fname, list *exps, list *tl, sql_ftype type)
     662             : {
     663       10854 :         bool found = false;
     664       10854 :         sql_subfunc *f = NULL;
     665             : 
     666       10854 :         assert(type == F_UNION || type == F_LOADER);
     667       10854 :         if ((f = bind_func_(sql, sname, fname, tl, type, false, &found, false))) {
     668       10834 :                 list *nexps = exps;
     669       10834 :                 if (list_empty(tl) || f->func->vararg || (nexps = check_arguments_and_find_largest_any_type(sql, NULL, exps, f, 1, false)))
     670       10834 :                         return exp_op(sql->sa, nexps, f);
     671           0 :                 found = false;
     672             :         }
     673          20 :         char *arg_list = list_length(tl) ? nary_function_arg_types_2str(sql, tl, list_length(tl)) : NULL;
     674          55 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s %s function %s%s%s'%s'(%s)",
     675          20 :                                          found ? "insufficient privileges for" : "no such", type == F_UNION ? "table returning" : "loader", sname ? "'":"", sname ? sname : "",
     676             :                                          sname ? "'.":"", fname, arg_list ? arg_list : "");
     677             : }
     678             : 
     679             : static sql_rel *
     680       10868 : rel_named_table_function(sql_query *query, sql_rel *rel, symbol *ast, int lateral, list *refs)
     681             : {
     682       10868 :         mvc *sql = query->sql;
     683       10868 :         list *exps = NULL, *tl;
     684       10868 :         node *m;
     685       10868 :         exp_kind ek = {type_value, card_relation, TRUE};
     686       10868 :         sql_rel *sq = NULL, *outer = NULL;
     687       10868 :         sql_exp *e = NULL;
     688       10868 :         sql_subfunc *sf = NULL;
     689       10868 :         symbol *sym = ast->data.lval->h->data.sym, *subquery = NULL;
     690       10868 :         dnode *l = sym->data.lval->h, *n;
     691       10868 :         char *tname = NULL;
     692       10868 :         char *fname = qname_schema_object(l->data.lval);
     693       10868 :         char *sname = qname_schema(l->data.lval);
     694             : 
     695       10868 :         tl = sa_list(sql->sa);
     696       10868 :         exps = sa_list(sql->sa);
     697       10868 :         if (l->next)
     698       10868 :                 l = l->next; /* skip distinct */
     699       10868 :         if (l->next) { /* table call with subquery */
     700        1029 :                 int is_value = 1;
     701        1029 :                 if (l->next->type == type_symbol || l->next->type == type_list) {
     702        1029 :                         exp_kind iek = {type_value, card_set, TRUE};
     703        1029 :                         int count = 0;
     704             : 
     705        1029 :                         if (l->next->type == type_symbol)
     706             :                                 n = l->next;
     707             :                         else
     708         673 :                                 n = l->next->data.lval->h;
     709             : 
     710        3654 :                         for (dnode *m = n; m; m = m->next) {
     711        2625 :                                 if (m->type == type_symbol && m->data.sym->token == SQL_SELECT)
     712        2625 :                                         subquery = m->data.sym;
     713        2625 :                                 count++;
     714             :                         }
     715        1029 :                         if (subquery && count > 1)
     716          17 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: The input for the table returning function %s%s%s'%s' must be either a single sub query, or a list of values",
     717             :                                                                  sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
     718             : 
     719        1024 :                         if (subquery) {
     720          40 :                                 if (!(sq = rel_subquery(query, subquery, ek)))
     721             :                                         return NULL;
     722             :                                 is_value = 0;
     723             :                         } else {
     724        3548 :                                 for ( ; n; n = n->next) {
     725        2570 :                                         sql_exp *e = rel_value_exp(query, &outer, n->data.sym, sql_sel | sql_from, iek);
     726             : 
     727        2570 :                                         if (!e)
     728             :                                                 return NULL;
     729        2564 :                                         append(exps, e);
     730        2564 :                                         is_value &= exp_is_atom(e);
     731             :                                 }
     732         978 :                                 if (!is_value || (lateral && outer))
     733          14 :                                         sq = rel_project(sql->sa, NULL, exps);
     734          14 :                                 if (lateral && outer) {
     735           0 :                                         sq = rel_crossproduct(sql->sa, sq, outer, op_join);
     736           0 :                                         set_dependent(sq);
     737           0 :                                         set_processed(sq);
     738             :                                 }
     739             :                         }
     740             :                 }
     741        1017 :                 if (!is_value && (!sq || (!lateral && outer)))
     742           0 :                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: no such table returning function %s%s%s'%s'", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
     743        1017 :                 if (!is_value) {
     744          53 :                         if (list_length(exps))
     745          14 :                                 exps = sa_list(sql->sa);
     746         171 :                         for (node *en = sq->exps->h; en; en = en->next) {
     747         118 :                                 sql_exp *e = en->data;
     748             : 
     749         118 :                                 if (!e->alias.label)
     750          28 :                                         exp_label(sql->sa, e, ++sql->label);
     751         118 :                                 sql_exp *ne = exp_ref(sql, e);
     752             :                                 /* allow for table functions with table input */
     753         118 :                                 ne->card = CARD_ATOM;
     754         118 :                                 exp_setname(sql, ne, tname, exp_name(e));
     755         118 :                                 append(exps, ne);
     756         118 :                                 append(tl, exp_subtype(e));
     757             :                         }
     758             :                 } else {
     759        3503 :                         for (node *en = exps->h; en; en = en->next)
     760        2539 :                                 append(tl, exp_subtype(en->data));
     761             :                 }
     762             :         }
     763             : 
     764       10856 :         rel = NULL;
     765       10856 :         if (ast->data.lval->t->type == type_symbol && ast->data.lval->t->data.sym)
     766        1191 :                 tname = ast->data.lval->t->data.sym->data.lval->h->data.sval;
     767             :         else
     768        9665 :                 tname = make_label(sql->sa, ++sql->label);
     769             : 
     770       10856 :         if (!sname && strcmp(fname, "file_loader") == 0) {
     771          33 :                 rel = rel_file_loader(sql, exps, tl, tname);
     772          33 :                 if (!rel)
     773             :                         return NULL;
     774       20662 :         } else if (!(e = find_table_function(sql, sname, fname, list_empty(exps) ? NULL : exps, tl, F_UNION)))
     775             :                 return NULL;
     776             : 
     777       10804 :         if (!rel) {
     778       10804 :                 rel = sq;
     779             : 
     780             :                 /* column or table function */
     781       10804 :                 sf = e->f;
     782       10804 :                 if (e->type != e_func || sf->func->type != F_UNION)
     783           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: '%s' does not return a table", exp_func_name(e));
     784             : 
     785       10804 :                 if (sq) {
     786         171 :                         for (node *n = sq->exps->h, *m = sf->func->ops->h ; n && m ; n = n->next, m = m->next) {
     787         118 :                                 sql_exp *e = (sql_exp*) n->data;
     788         118 :                                 sql_arg *a = (sql_arg*) m->data;
     789         118 :                                 if (!exp_subtype(e) && rel_set_type_param(sql, &(a->type), sq, e, 0) < 0)
     790             :                                         return NULL;
     791             :                         }
     792             :                 }
     793             : 
     794             :                 /* for each column add table.column name */
     795       10804 :                 exps = new_exp_list(sql->sa);
     796      107106 :                 for (m = sf->func->res->h; m; m = m->next) {
     797       96302 :                         sql_arg *a = m->data;
     798       96302 :                         sql_exp *e = exp_column(sql->sa, tname, a->name, &a->type, CARD_MULTI, 1, 0, 0);
     799       96302 :                         e->alias.label = -(sql->nid++);
     800             : 
     801       96302 :                         set_basecol(e);
     802       96302 :                         append(exps, e);
     803             :                 }
     804       21555 :                 rel = rel_table_func(sql->sa, rel, e, exps, (sq)?TABLE_FROM_RELATION:TABLE_PROD_FUNC);
     805             :         }
     806       10818 :         if (ast->data.lval->t->type == type_symbol && ast->data.lval->t->data.sym && ast->data.lval->t->data.sym->data.lval->h->next->data.lval) {
     807          25 :                 rel = rel_table_optname(sql, rel, ast->data.lval->t->data.sym, refs);
     808       10793 :         } else if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
     809       10793 :                 if (list_find(refs, tname, (fcmp) &strcmp))
     810           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: relation name \"%s\" specified more than once", tname);
     811       10793 :                 list_append(refs, tname);
     812             :         }
     813             :         return rel;
     814             : }
     815             : 
     816             : static sql_exp *
     817        1826 : rel_op_(mvc *sql, char *sname, char *fname, exp_kind ek)
     818             : {
     819        1826 :         bool found = false;
     820        1826 :         sql_subfunc *f = NULL;
     821        1826 :         sql_ftype type = (ek.card == card_loader)?F_LOADER:((ek.card == card_none)?F_PROC:
     822             :                    ((ek.card == card_relation)?F_UNION:F_FUNC));
     823             : 
     824        1826 :         if ((f = bind_func_(sql, sname, fname, NULL, type, false, &found, true))) {
     825        1810 :                 if (check_card(ek.card, f))
     826        1810 :                         return exp_op(sql->sa, NULL, f);
     827           0 :                 found = false;
     828             :         }
     829          32 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s operator %s%s%s'%s'()",
     830          16 :                                          found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
     831             : }
     832             : 
     833             : static sql_exp*
     834        4098 : exp_tuples_set_supertype(mvc *sql, list *tuple_values, sql_exp *tuples)
     835             : {
     836        4098 :         assert(is_values(tuples));
     837        4098 :         list *vals = exp_get_values(tuples);
     838        4098 :         if (!vals || !vals->h)
     839             :                 return NULL;
     840             : 
     841        4098 :         int tuple_width = list_length(tuple_values), i;
     842        4098 :         sql_subtype *types = SA_NEW_ARRAY(sql->sa, sql_subtype, tuple_width);
     843        4098 :         bool *has_type = SA_NEW_ARRAY(sql->sa, bool, tuple_width);
     844        4098 :         node *n;
     845             : 
     846        4098 :         memset(has_type, 0, sizeof(bool)*tuple_width);
     847       13338 :         for(n = tuple_values->h, i = 0; n; n = n->next, i++) {
     848        9240 :                 sql_exp *e = n->data;
     849        9240 :                 if (exp_subtype(e)) {
     850        9238 :                         types[i] = *exp_subtype(e);
     851        9238 :                         has_type[i] = 1;
     852             :                 }
     853             :         }
     854             : 
     855        8198 :         for (node *m = vals->h; m; m = m->next) {
     856        4100 :                 sql_exp *tuple = m->data;
     857        4100 :                 if (is_values(tuple)) {
     858           3 :                         list *exps = tuple->f;
     859           9 :                         for(n = exps->h, i = 0; n; n = n->next, i++) {
     860           6 :                                 sql_subtype *tpe;
     861           6 :                                 sql_exp *e = n->data;
     862             : 
     863           6 :                                 if (has_type[i] && e->type == e_atom && !e->l && !e->r && !e->f && !e->tpe.type) {
     864           0 :                                         if (set_type_param(sql, types+i, e->flag) == 0)
     865           0 :                                                 e->tpe = types[i];
     866             :                                         else
     867             :                                                 return NULL;
     868             :                                 }
     869           6 :                                 tpe = exp_subtype(e);
     870           6 :                                 if (!tpe)
     871             :                                         return NULL;
     872           6 :                                 if (has_type[i] && tpe) {
     873           6 :                                         supertype(types+i, types+i, tpe);
     874             :                                 } else {
     875           0 :                                         has_type[i] = 1;
     876           0 :                                         types[i] = *tpe;
     877             :                                 }
     878             :                         }
     879             :                 } else {
     880        4097 :                         sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, tuple);
     881             : 
     882       13335 :                         for(n = tuple_relation->exps->h, i = 0; n; n = n->next, i++) {
     883        9238 :                                 sql_subtype *tpe;
     884        9238 :                                 sql_exp *e = n->data;
     885             : 
     886        9238 :                                 if (has_type[i] && e->type == e_atom && !e->l && !e->r && !e->f && !e->tpe.type) {
     887           5 :                                         if (set_type_param(sql, types+i, e->flag) == 0)
     888           5 :                                                 e->tpe = types[i];
     889             :                                         else
     890             :                                                 return NULL;
     891             :                                 }
     892        9238 :                                 tpe = exp_subtype(e);
     893        9238 :                                 if (!tpe)
     894             :                                         return NULL;
     895        9238 :                                 if (has_type[i] && tpe) {
     896        9236 :                                         cmp_supertype(types+i, types+i, tpe);
     897             :                                 } else {
     898           2 :                                         has_type[i] = 1;
     899           2 :                                         types[i] = *tpe;
     900             :                                 }
     901             :                         }
     902             :                 }
     903             :         }
     904             : 
     905        8198 :         for (node *m = vals->h; m; m = m->next) {
     906        4100 :                 sql_exp *tuple = m->data;
     907        4100 :                 if (is_values(tuple)) {
     908           3 :                         list *exps = tuple->f;
     909           3 :                         list *nexps = sa_list(sql->sa);
     910           9 :                         for(n = exps->h, i = 0; n; n = n->next, i++) {
     911           6 :                                 sql_exp *e = n->data;
     912             : 
     913           6 :                                 e = exp_check_type(sql, types+i, NULL, e, type_equal);
     914           6 :                                 if (!e)
     915             :                                         return NULL;
     916           6 :                                 exp_label(sql->sa, e, ++sql->label);
     917           6 :                                 append(nexps, e);
     918             :                         }
     919           3 :                         tuple->f = nexps;
     920             :                 } else {
     921        4097 :                         sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, tuple);
     922             : 
     923        4097 :                         list *nexps = sa_list(sql->sa);
     924       13335 :                         for(n = tuple_relation->exps->h, i = 0; n; n = n->next, i++) {
     925        9238 :                                 sql_exp *e = n->data;
     926             : 
     927        9238 :                                 e = exp_check_type(sql, types+i, NULL, e, type_equal);
     928        9238 :                                 if (!e)
     929             :                                         return NULL;
     930        9238 :                                 append(nexps, e);
     931             :                         }
     932        4097 :                         tuple_relation->exps = nexps;
     933             :                 }
     934             :         }
     935             :         return tuples;
     936             : }
     937             : 
     938             : static int
     939        9240 : rel_binop_check_types(mvc *sql, sql_rel *rel, sql_exp *ls, sql_exp *rs, int upcast)
     940             : {
     941        9240 :         sql_subtype *t1 = exp_subtype(ls), *t2 = exp_subtype(rs);
     942             : 
     943        9240 :         if (!t1 || !t2) {
     944           2 :                 if (t2 && !t1 && rel_set_type_param(sql, t2, rel, ls, upcast) < 0)
     945             :                         return -1;
     946           2 :                 if (t1 && !t2 && rel_set_type_param(sql, t1, rel, rs, upcast) < 0)
     947             :                         return -1;
     948             :         }
     949        9240 :         if (!exp_subtype(ls) && !exp_subtype(rs)) {
     950           0 :                 (void) sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
     951           0 :                 return -1;
     952             :         }
     953             :         return 0;
     954             : }
     955             : 
     956             : static list *
     957        4098 : tuples_check_types(mvc *sql, list *tuple_values, sql_exp *tuples)
     958             : {
     959        4098 :         list *tuples_list = exp_get_values(tuples);
     960        4098 :         sql_exp *first_tuple = tuples_list->h->data;
     961        4098 :         list *nvalues = sa_list(sql->sa);
     962        4098 :         if (is_values(first_tuple)) {
     963           1 :                 list *vals = first_tuple->f;
     964             : 
     965           3 :                 for (node *n = tuple_values->h, *m = vals->h; n && m; n = n->next, m = m->next) {
     966           2 :                         sql_exp *le = n->data, *re = m->data;
     967             : 
     968           2 :                         if (rel_binop_check_types(sql, NULL, le, re, 0) < 0)
     969             :                                 return NULL;
     970           2 :                         if ((le = exp_check_type(sql, exp_subtype(re), NULL, le, type_equal)) == NULL)
     971             :                                 return NULL;
     972           2 :                         append(nvalues, le);
     973             :                 }
     974             :                 return nvalues;
     975             :         } else {
     976        4097 :                 sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, first_tuple);
     977             : 
     978        4097 :                 assert(list_length(tuple_values) == list_length(tuple_relation->exps));
     979       13335 :                 for (node *n = tuple_values->h, *m = tuple_relation->exps->h; n && m; n = n->next, m = m->next) {
     980        9238 :                         sql_exp *le = n->data, *re = m->data;
     981             : 
     982        9238 :                         if (rel_binop_check_types(sql, NULL, le, re, 0) < 0)
     983             :                                 return NULL;
     984        9238 :                         if ((le = exp_check_type(sql, exp_subtype(re), NULL, le, type_equal)) == NULL)
     985             :                                 return NULL;
     986        9238 :                         append(nvalues, le);
     987             :                 }
     988             :                 return nvalues;
     989             :         }
     990             :         return tuple_values;
     991             : }
     992             : 
     993             : static sql_rel *
     994        3730 : rel_values(sql_query *query, symbol *tableref, list *refs)
     995             : {
     996        3730 :         mvc *sql = query->sql;
     997        3730 :         sql_rel *r = NULL;
     998        3730 :         dlist *rowlist = tableref->data.lval->h->data.lval;
     999        3730 :         symbol *optname = tableref->data.lval->t->type == type_symbol ? tableref->data.lval->t->data.sym : NULL;
    1000        3730 :         node *m;
    1001        3730 :         list *exps = sa_list(sql->sa);
    1002        3730 :         exp_kind ek = {type_value, card_value, TRUE};
    1003             : 
    1004       14940 :         for (dnode *o = rowlist->h; o; o = o->next) {
    1005       11220 :                 dlist *values = o->data.lval;
    1006             : 
    1007       11220 :                 if (!list_empty(exps) && list_length(exps) != dlist_length(values)) {
    1008           3 :                         return sql_error(sql, 02, SQLSTATE(42000) "VALUES: number of columns doesn't match between rows");
    1009             :                 } else {
    1010       11217 :                         dnode *n;
    1011             : 
    1012       11217 :                         if (list_empty(exps)) {
    1013       10637 :                                 for (n = values->h; n; n = n->next) {
    1014        6907 :                                         sql_exp *vals = exp_values(sql->sa, sa_list(sql->sa));
    1015             : 
    1016        6907 :                                         exp_label(sql->sa, vals, ++sql->label);
    1017        6907 :                                         list_append(exps, vals);
    1018             :                                 }
    1019             :                         }
    1020       34319 :                         for (n = values->h, m = exps->h; n && m; n = n->next, m = m->next) {
    1021       23109 :                                 sql_exp *vals = m->data;
    1022       23109 :                                 list *vals_list = vals->f;
    1023       23109 :                                 sql_exp *e = rel_value_exp(query, NULL, n->data.sym, sql_sel | sql_values, ek);
    1024       23109 :                                 if (!e)
    1025             :                                         return NULL;
    1026       23102 :                                 list_append(vals_list, e);
    1027             :                         }
    1028             :                 }
    1029             :         }
    1030             : 
    1031             :         /* loop to check types and cardinality */
    1032        3720 :         unsigned int card = exps->h && list_length(((sql_exp*)exps->h->data)->f) > 1 ? CARD_MULTI : CARD_ATOM;
    1033       10610 :         for (m = exps->h; m; m = m->next) {
    1034        6893 :                 sql_exp *e = m->data;
    1035             : 
    1036        6893 :                 if (!(e = exp_values_set_supertype(sql, e, NULL)))
    1037             :                         return NULL;
    1038        6890 :                 e->card = card;
    1039        6890 :                 m->data = e;
    1040             :         }
    1041             : 
    1042        3717 :         r = rel_project(sql->sa, NULL, exps);
    1043        3717 :         r->nrcols = list_length(exps);
    1044        3717 :         r->card = card;
    1045        3717 :         return rel_table_optname(sql, r, optname, refs);
    1046             : }
    1047             : 
    1048             : static int
    1049      496303 : check_is_lateral(symbol *tableref)
    1050             : {
    1051      496303 :         if (tableref->token == SQL_NAME || tableref->token == SQL_TABLE ||
    1052             :                 tableref->token == SQL_VALUES) {
    1053      444945 :                 if (dlist_length(tableref->data.lval) == 3)
    1054      444133 :                         return tableref->data.lval->h->next->data.i_val;
    1055             :                 return 0;
    1056             :         } else if (tableref->token == SQL_WITH) {
    1057         941 :                 if (dlist_length(tableref->data.lval) == 4)
    1058           5 :                         return tableref->data.lval->h->next->next->data.i_val;
    1059             :                 return 0;
    1060             :         } else if (tableref->token == SQL_SELECT) {
    1061        3612 :                 SelectNode *sn = (SelectNode *) tableref;
    1062        3612 :                 return sn->lateral;
    1063             :         } else if (tableref->token == SQL_EXCEPT || tableref->token == SQL_INTERSECT ||
    1064             :                            tableref->token == SQL_UNION) {
    1065       10678 :                 if (dlist_length(tableref->data.lval) == 6)
    1066        9016 :                         return tableref->data.lval->h->next->next->next->next->data.i_val;
    1067             :                 return 0;
    1068             :         } else {
    1069             :                 return 0;
    1070             :         }
    1071             : }
    1072             : 
    1073             : static sql_rel *
    1074          25 : rel_reduce_on_column_privileges(mvc *sql, sql_rel *rel, sql_table *t)
    1075             : {
    1076          25 :         list *exps = sa_list(sql->sa);
    1077             : 
    1078          99 :         for (node *n = rel->exps->h, *m = ol_first_node(t->columns); n && m; n = n->next, m = m->next) {
    1079          74 :                 sql_exp *e = n->data;
    1080          74 :                 sql_column *c = m->data;
    1081             : 
    1082          74 :                 if (column_privs(sql, c, PRIV_SELECT))
    1083          12 :                         append(exps, e);
    1084             :         }
    1085          25 :         if (!list_empty(exps)) {
    1086           9 :                 rel->exps = exps;
    1087           9 :                 return rel;
    1088             :         }
    1089             :         return NULL;
    1090             : }
    1091             : 
    1092             : sql_rel *
    1093      677173 : table_ref(sql_query *query, symbol *tableref, int lateral, list *refs)
    1094             : {
    1095      677173 :         mvc *sql = query->sql;
    1096      677173 :         char *tname = NULL;
    1097      677173 :         sql_table *t = NULL;
    1098      677173 :         sql_rel *res = NULL;
    1099             : 
    1100      677173 :         if (tableref->token == SQL_NAME) {
    1101      466228 :                 dlist *name = tableref->data.lval->h->data.lval;
    1102      466228 :                 sql_rel *temp_table = NULL;
    1103      466228 :                 char *sname = qname_schema(name);
    1104      466228 :                 int allowed = 1;
    1105             : 
    1106      466228 :                 tname = qname_schema_object(name);
    1107             : 
    1108      466228 :                 if (dlist_length(name) > 2)
    1109           4 :                         return sql_error(sql, 02, SQLSTATE(3F000) "SELECT: only a schema and table name expected");
    1110             : 
    1111      466224 :                 if (!sname)
    1112      113372 :                         temp_table = stack_find_rel_view(sql, tname);
    1113      113372 :                 if (!temp_table)
    1114      449393 :                         t = find_table_or_view_on_scope(sql, NULL, sname, tname, "SELECT", false);
    1115      466224 :                 if (!t && !temp_table)
    1116             :                         return NULL;
    1117      466125 :                 if (!temp_table && !table_privs(sql, t, PRIV_SELECT))
    1118      466125 :                         allowed = 0;
    1119             : 
    1120      466125 :                 if (tableref->data.lval->t->type == type_symbol && tableref->data.lval->t->data.sym) /* AS */
    1121      272587 :                         tname = tableref->data.lval->t->data.sym->data.lval->h->data.sval;
    1122      466125 :                 if (temp_table && !t) {
    1123       16831 :                         node *n;
    1124       16831 :                         int needed = !is_simple_project(temp_table->op);
    1125             : 
    1126       16831 :                         if (is_basetable(temp_table->op) && !temp_table->exps) {
    1127           0 :                                 if (strcmp(rel_base_name(temp_table), tname) != 0)
    1128           0 :                                         rel_base_rename(temp_table, tname);
    1129             :                         } else {
    1130       60210 :                                 for (n = temp_table->exps->h; n && !needed; n = n->next) {
    1131       43379 :                                         sql_exp *e = n->data;
    1132             : 
    1133       43379 :                                         if (!exp_relname(e) || strcmp(exp_relname(e), tname) != 0)
    1134             :                                                 needed = 1;
    1135             :                                 }
    1136             : 
    1137       16831 :                                 if (needed) {
    1138        6817 :                                         list *exps = rel_projections(sql, temp_table, NULL, 1, 1);
    1139             : 
    1140        6817 :                                         temp_table = rel_project(sql->sa, temp_table, exps);
    1141       24458 :                                         for (n = exps->h; n; n = n->next) {
    1142       17641 :                                                 sql_exp *e = n->data;
    1143             : 
    1144       17641 :                                                 noninternexp_setname(sql, e, tname, NULL);
    1145       17641 :                                                 set_basecol(e);
    1146             :                                         }
    1147        6817 :                                         list_hash_clear(exps);
    1148             :                                 }
    1149             :                         }
    1150       16831 :                         if (temp_table && tableref->data.lval->t->type == type_symbol && tableref->data.lval->t->data.sym && tableref->data.lval->t->data.sym->data.lval->h->next->data.lval) /* AS with column aliases */
    1151           1 :                                 temp_table = rel_table_optname(sql, temp_table, tableref->data.lval->t->data.sym, refs);
    1152       16831 :                         if (allowed)
    1153             :                                 return temp_table;
    1154           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: access denied for %s to table '%s'", get_string_global_var(sql, "current_user"), tname);
    1155      449294 :                 } else if (isView(t)) {
    1156             :                         /* instantiate base view */
    1157       69477 :                         node *n,*m;
    1158       69477 :                         sql_rel *rel;
    1159             : 
    1160       69477 :                         if (sql->emode == m_deps) {
    1161       24382 :                                 rel = rel_basetable(sql, t, tname);
    1162       24382 :                                 if (!allowed)
    1163           0 :                                         rel_base_disallow(rel);
    1164             :                         } else {
    1165             :                                 /* when recreating a view, the view itself can't be found */
    1166       45095 :                                 if (sql->objid && sql->objid == t->base.id)
    1167           1 :                                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: attempting to recursively bind view '%s'.'%s'", t->s->base.name, tname);
    1168       45094 :                                 rel = rel_parse(sql, t->s, t->query, m_instantiate);
    1169       45094 :                                 if (rel && sql->emode == m_deps)
    1170           0 :                                         rel = rel_unnest(sql, rel);
    1171             :                         }
    1172             : 
    1173       69474 :                         if (!rel)
    1174           2 :                                 return NULL;
    1175             :                         /* Rename columns of the rel_parse relation */
    1176       69474 :                         if (sql->emode != m_deps) {
    1177       45092 :                                 assert(is_project(rel->op));
    1178       45092 :                                 set_processed(rel);
    1179       45092 :                                 if (is_mset(rel->op) || is_simple_project(rel->op) || (is_groupby(rel->op) && !list_empty(rel->r))) {
    1180             :                                         /* it's unsafe to set the projection names because of possible dependent sorting/grouping columns */
    1181       45092 :                                         rel = rel_project(sql->sa, rel, rel_projections(sql, rel, NULL, 0, 0));
    1182       45092 :                                         set_processed(rel);
    1183             :                                 }
    1184      407450 :                                 for (n = ol_first_node(t->columns), m = rel->exps->h; n && m; n = n->next, m = m->next) {
    1185      362358 :                                         sql_column *c = n->data;
    1186      362358 :                                         sql_exp *e = m->data;
    1187             : 
    1188      362358 :                                         exp_setname(sql, e, tname, c->base.name);
    1189      362358 :                                         set_basecol(e);
    1190             :                                 }
    1191       45092 :                                 list_hash_clear(rel->exps);
    1192             :                         }
    1193       69474 :                         if (rel && !allowed && t->query && (rel = rel_reduce_on_column_privileges(sql, rel, t)) == NULL)
    1194          16 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: access denied for %s to view '%s.%s'", get_string_global_var(sql, "current_user"), t->s->base.name, tname);
    1195       69458 :                         return rel;
    1196             :                 }
    1197      379817 :                 if ((isMergeTable(t) || isReplicaTable(t)) && list_length(t->members)==0)
    1198          14 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s '%s'.'%s' should have at least one table associated",
    1199          14 :                                                         TABLE_TYPE_DESCRIPTION(t->type, t->properties), t->s->base.name, tname);
    1200      379803 :                 res = rel_basetable(sql, t, tname);
    1201      379803 :                 if (!allowed) {
    1202          53 :                         rel_base_disallow(res);
    1203          53 :                         if (rel_base_has_column_privileges(sql, res) == 0)
    1204          62 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: access denied for %s to %s '%s.%s'", get_string_global_var(sql, "current_user"), isView(t) ? "view" : "table", t->s->base.name, tname);
    1205             :                 }
    1206      379772 :                 if (tableref->data.lval->t->type == type_symbol && tableref->data.lval->t->data.sym && tableref->data.lval->t->data.sym->data.lval->h->next->data.lval) { /* AS with column aliases */
    1207           8 :                         res = rel_table_optname(sql, res, tableref->data.lval->t->data.sym, refs);
    1208      379764 :                 } else if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
    1209      379759 :                         if (list_find(refs, tname, (fcmp) &strcmp))
    1210           7 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: relation name \"%s\" specified more than once", tname);
    1211      379752 :                         assert(tname);
    1212      379752 :                         list_append(refs, tname);
    1213             :                 }
    1214      379765 :                 return res;
    1215             :         } else if (tableref->token == SQL_VALUES) {
    1216        1340 :                 return rel_values(query, tableref, refs);
    1217             :         } else if (tableref->token == SQL_TABLE) {
    1218       10868 :                 return rel_named_table_function(query, NULL, tableref, lateral, refs);
    1219             :         } else if (tableref->token == SQL_SELECT) {
    1220       97527 :                 return rel_subquery_optname(query, tableref, refs);
    1221             :         } else if (tableref->token == SQL_UNION || tableref->token == SQL_EXCEPT || tableref->token == SQL_INTERSECT) {
    1222             :                 /* subqueries will be called, ie no need to test for duplicate references */
    1223       41596 :                 sql_rel *tq = rel_setquery(query, tableref);
    1224             : 
    1225       41596 :                 if (!tq)
    1226             :                         return NULL;
    1227             :                 /* look for lateral joins */
    1228       41594 :                 symbol *optname = tableref->data.lval->t->type == type_symbol ? tableref->data.lval->t->data.sym : NULL;
    1229       41594 :                 return rel_table_optname(sql, tq, optname, refs);
    1230             :         } else {
    1231       59614 :                 return query_exp_optname(query, tableref, refs);
    1232             :         }
    1233             : }
    1234             : 
    1235             : static sql_exp *
    1236      120835 : rel_exp_variable_on_scope(mvc *sql, const char *sname, const char *vname)
    1237             : {
    1238      120835 :         sql_subtype *tpe = NULL;
    1239      120835 :         sql_var *var = NULL;
    1240      120835 :         sql_arg *a = NULL;
    1241      120835 :         int level = 1;
    1242             : 
    1243      120835 :         if (find_variable_on_scope(sql, sname, vname, &var, &a, &tpe, &level, "SELECT")) {
    1244      119930 :                 if (var) /* if variable is known from the stack or a global var */
    1245       37360 :                         return exp_param_or_declared(sql->sa, var->sname ? sa_strdup(sql->sa, var->sname) : NULL, sa_strdup(sql->sa, var->name), &(var->var.tpe), level);
    1246       87550 :                 if (a) /* if variable is a parameter */
    1247       87550 :                         return exp_param_or_declared(sql->sa, NULL, sa_strdup(sql->sa, vname), &(a->type), level);
    1248             :         }
    1249             :         return NULL;
    1250             : }
    1251             : 
    1252             : static sql_exp *
    1253        9247 : exps_get_exp(list *exps, int nth)
    1254             : {
    1255        9247 :         node *n = NULL;
    1256        9247 :         int i = 0;
    1257             : 
    1258        9247 :         if (exps)
    1259       27170 :                 for (n=exps->h, i=1; n && i<nth; n=n->next, i++)
    1260             :                         ;
    1261        9247 :         if (n && i == nth)
    1262        9244 :                 return n->data;
    1263             :         return NULL;
    1264             : }
    1265             : 
    1266             : static sql_rel *
    1267       27795 : rel_find_groupby(sql_rel *groupby)
    1268             : {
    1269       27795 :         if (groupby && !is_processed(groupby) && !is_base(groupby->op)) {
    1270       37391 :                 while(!is_processed(groupby) && !is_base(groupby->op)) {
    1271       29593 :                         if (is_groupby(groupby->op) || !groupby->l)
    1272             :                                 break;
    1273             :                         if (groupby->l)
    1274             :                                 groupby = groupby->l;
    1275             :                 }
    1276       27671 :                 if (groupby && is_groupby(groupby->op))
    1277       19873 :                         return groupby;
    1278             :         }
    1279             :         return NULL;
    1280             : }
    1281             : 
    1282             : static int
    1283         306 : is_groupby_col(sql_rel *gb, sql_exp *e)
    1284             : {
    1285         306 :         gb = rel_find_groupby(gb);
    1286             : 
    1287         306 :         if (gb) {
    1288         174 :                 if (exp_relname(e)) {
    1289         163 :                         if (exp_name(e) && exps_bind_column2(gb->r, exp_relname(e), exp_name(e), NULL))
    1290             :                                 return 1;
    1291             :                 } else {
    1292          11 :                         if (exp_name(e) && exps_bind_column(gb->r, exp_name(e), NULL, NULL, 1))
    1293             :                                 return 1;
    1294             :                 }
    1295             :         }
    1296             :         return 0;
    1297             : }
    1298             : 
    1299             : static void
    1300        4721 : set_dependent_( sql_rel *r)
    1301             : {
    1302        4721 :         if (is_select(r->op))
    1303        3581 :                 r = r->l;
    1304        4721 :         if (r && is_join(r->op))
    1305        1194 :                 set_dependent(r);
    1306        4721 : }
    1307             : 
    1308             : static
    1309          15 : sql_rel* find_union(visitor *v, sql_rel *rel) {
    1310          15 :         if (rel->op == op_union || rel->op == op_munion)
    1311           1 :                 v->data = rel;
    1312          15 :         return rel;
    1313             : }
    1314             : 
    1315             : static inline
    1316          54 : bool group_by_pk_project_uk_cond(mvc* sql, sql_rel* inner, sql_exp* exp,const char* sname, const char* tname) {
    1317          54 :         sql_table* t = find_table_or_view_on_scope(sql, NULL, sname, tname, "SELECT", false);
    1318          54 :         bool allow = false;
    1319          54 :         if (t) {
    1320          17 :                 sql_idx* pki = NULL;
    1321          17 :                 list *ukil = sa_list(sql->sa);
    1322             : 
    1323          23 :                 for (node * n = ol_first_node(t->idxs); n; n = n->next) {
    1324           6 :                         sql_idx *i = n->data;
    1325           6 :                         if (!i->key)
    1326           1 :                                 continue;
    1327           5 :                         switch (i->key->type) {
    1328           3 :                         case pkey:
    1329           3 :                                 pki = i;
    1330           3 :                                 continue;
    1331           2 :                         case ukey:
    1332             :                         case unndkey:
    1333           2 :                                 list_append(ukil, i);
    1334           2 :                                 continue;
    1335           0 :                         default:
    1336           0 :                                 continue;
    1337             :                         }
    1338             :                 }
    1339          17 :                 if (pki && pki->columns->cnt == 1 && inner->r && ((list*) inner->r)->cnt == 1) {
    1340             :                         /* for now only check simple case where primary key and group by expression is a single column*/
    1341           3 :                         sql_exp* gbe = ((list*) inner->r)->h->data;
    1342           3 :                         sql_column* pkc = ((sql_kc *)pki->columns->h->data)->c;
    1343           3 :                         if (gbe->type == e_column && strcmp(gbe->alias.name, pkc->base.name) == 0) {
    1344           2 :                                 node *n;
    1345           2 :                                 for (n = ukil->h; n; n = n->next){
    1346           2 :                                         sql_idx* uki = n->data;
    1347           2 :                                         if (uki->columns->cnt == 1) {
    1348             :                                                 /* for now only check simple case where unique key is a single column*/
    1349           2 :                                                 sql_column* ukc = ((sql_kc *)uki->columns->h->data)->c;
    1350           2 :                                                 if (strcmp(exp->alias.name, ukc->base.name) == 0) {
    1351             :                                                         allow = true;
    1352             :                                                         break;
    1353             :                                                 }
    1354             :                                         }
    1355             :                                 }
    1356             :                         }
    1357             :                 }
    1358             : 
    1359           2 :                 if (allow) {
    1360             :                         /* sufficiency condition: abort if relation contains union subrelation
    1361             :                         * because it may break functional dependency between pk and uk */
    1362           2 :                         visitor v = {.sql=sql};
    1363           2 :                         rel_visitor_topdown(&v, inner, &find_union);
    1364           2 :                         if (v.data)
    1365           1 :                                 allow = false;
    1366             :                 }
    1367             :         }
    1368             : 
    1369          54 :         return allow;
    1370             : 
    1371             : }
    1372             : 
    1373             : static sql_exp *
    1374     2335273 : rel_column_ref(sql_query *query, sql_rel **rel, symbol *column_r, int f)
    1375             : {
    1376     2335273 :         mvc *sql = query->sql;
    1377     2335273 :         sql_exp *exp = NULL;
    1378     2335273 :         dlist *l = NULL;
    1379     2335273 :         sql_rel *inner = rel?*rel:NULL, *outer = NULL;
    1380     2335273 :         int used_lower_after_processed = 0;
    1381             : 
    1382     2335273 :         assert((column_r->token == SQL_COLUMN || column_r->token == SQL_IDENT) && column_r->type == type_list);
    1383     2335273 :         l = column_r->data.lval;
    1384             : 
    1385     2335273 :         if (dlist_length(l) == 1) {
    1386     1103895 :                 const char *name = l->h->data.sval;
    1387             : 
    1388     1103895 :                 if (!exp && inner)
    1389     1009546 :                         if (!(exp = rel_bind_column(sql, inner, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    1390             :                                 return NULL;
    1391     1103881 :                 if (!exp && inner && ((is_sql_aggr(f) && (is_groupby(inner->op) || is_select(inner->op))) ||
    1392       23869 :                                                      (is_groupby(inner->op) && inner->flag))) {
    1393             :                         /* if inner is selection, ie having clause, get the left relation to reach group by */
    1394             :                         sql_rel *gp = inner;
    1395         258 :                         while (gp && is_select(gp->op))
    1396          27 :                                 gp = gp->l;
    1397         231 :                         if (gp && !is_basetable(gp->op) && gp->l && !(exp = rel_bind_column(sql, gp->l, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    1398             :                                 return NULL;
    1399             :                 }
    1400     1103881 :                 if (!exp && query && query_has_outer(query)) {
    1401         448 :                         int i;
    1402             : 
    1403         501 :                         for (i=query_has_outer(query)-1; i>= 0 && !exp && (outer = query_fetch_outer(query,i)); i--) {
    1404         472 :                                 if (!(exp = rel_bind_column(sql, outer, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    1405             :                                         return NULL;
    1406          84 :                                 if (!exp && is_groupby(outer->op)) {
    1407          31 :                                         if (!(exp = rel_bind_column(sql, outer->l, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    1408             :                                                 return NULL;
    1409             :                                         else
    1410          31 :                                                 used_lower_after_processed = is_processed(outer);
    1411             :                                 }
    1412         472 :                                 if (exp && is_simple_project(outer->op) && !rel_find_exp(outer, exp))
    1413           0 :                                         exp = rel_project_add_exp(sql, outer, exp);
    1414         419 :                                 if (exp)
    1415             :                                         break;
    1416             :                         }
    1417         448 :                         if (exp && exp->card != CARD_AGGR && is_groupby(outer->op) && !is_sql_aggr(f) && rel_find_exp(outer->l, exp))
    1418           5 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", name);
    1419         443 :                         if (exp && outer && outer->card <= CARD_AGGR && exp->card > CARD_AGGR && !is_sql_aggr(f))
    1420           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", name);
    1421         443 :                         if (exp && outer && !is_sql_aggr(f) && !is_sql_aggr(query_fetch_outer_state(query, i))) {
    1422         275 :                                 if (used_lower_after_processed || query_outer_used_exp( query, i, exp, f)) {
    1423           0 :                                         sql_exp *lu = used_lower_after_processed?exp:query_outer_last_used(query, i);
    1424           0 :                                         if (exp_name(lu) && exp_relname(lu) && !has_label(lu))
    1425           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", exp_relname(lu), exp_name(lu));
    1426           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    1427             :                                 }
    1428             :                         }
    1429         443 :                         if (exp) {
    1430         414 :                                 int of = query_fetch_outer_state(query, i);
    1431         414 :                                 if (is_groupby(outer->op) && !is_sql_aggr(f)) {
    1432          37 :                                         exp = rel_groupby_add_aggr(sql, outer, exp);
    1433          37 :                                         exp->card = CARD_ATOM;
    1434         377 :                                 } else if (is_groupby(outer->op) && is_sql_aggr(f) && exps_any_match(outer->exps, exp))
    1435          57 :                                         exp = exp_ref(sql, exp);
    1436             :                                 else
    1437         320 :                                         exp->card = CARD_ATOM;
    1438         414 :                                 set_freevar(exp, i);
    1439             :                                 /*
    1440             :                                 if (exp->alias.label == exp->nid)
    1441             :                                         exp->alias.label = -(sql->nid++);
    1442             :                                         */
    1443         414 :                                 if (!is_sql_where(of) && !is_sql_aggr(of) && !is_sql_aggr(f) && !outer->grouped)
    1444         125 :                                         set_outer(outer);
    1445             :                         }
    1446         443 :                         if (exp && outer && (is_select(outer->op) || is_join(outer->op)))
    1447          31 :                                 set_dependent_(outer);
    1448             :                 }
    1449             : 
    1450             :                 /* some views are just in the stack, like before and after updates views */
    1451     1103876 :                 if (rel && sql->use_views) {
    1452          13 :                         sql_rel *v = NULL;
    1453          13 :                         int dup = stack_find_rel_view_projection_columns(sql, name, &v); /* trigger views are basetables relations, so those may conflict */
    1454             : 
    1455          13 :                         if (dup < 0 || (v && exp && *rel && is_base(v->op) && v != *rel)) /* comparing pointers, ugh */
    1456           2 :                                 return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "SELECT: identifier '%s' ambiguous", name);
    1457          11 :                         if (v && !exp) {
    1458           4 :                                 if (*rel)
    1459           1 :                                         *rel = rel_crossproduct(sql->sa, *rel, rel_dup(v), op_join);
    1460             :                                 else
    1461           3 :                                         *rel = rel_dup(v);
    1462           4 :                                 exp = rel_bind_column(sql, *rel, name, f, 0);
    1463             :                         }
    1464             :                 }
    1465     1103874 :                 if (!exp) /* If no column was found, try a variable or parameter */
    1466      117828 :                         exp = rel_exp_variable_on_scope(sql, NULL, name);
    1467             : 
    1468      117828 :                 if (!exp) {
    1469         905 :                         if (inner && !is_sql_aggr(f) && is_groupby(inner->op) && inner->l && (exp = rel_bind_column(sql, inner->l, name, f, 0)))
    1470          46 :                                 return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", name);
    1471             :                 }
    1472             : 
    1473     1102969 :                 if (!exp)
    1474         859 :                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: identifier '%s' unknown", name);
    1475     1102969 :                 if (exp && inner && inner->card <= CARD_AGGR && exp->card > CARD_AGGR && (is_sql_sel(f) || is_sql_having(f)) && (!is_sql_aggr(f) && !(inner->flag)))
    1476           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", name);
    1477     1102969 :                 if (exp && inner && is_groupby(inner->op) && !is_sql_aggr(f) && !is_freevar(exp) && !inner->flag)
    1478       25016 :                         exp = rel_groupby_add_aggr(sql, inner, exp);
    1479     1231378 :         } else if (dlist_length(l) == 2 || dlist_length(l) == 3) {
    1480     1231378 :                 const char *sname = NULL;
    1481     1231378 :                 const char *tname = l->h->data.sval;
    1482     1231378 :                 const char *cname = l->h->next->data.sval;
    1483     1231378 :                 if (dlist_length(l) == 3) {
    1484           1 :                         sname = l->h->data.sval;
    1485           1 :                         tname = l->h->next->data.sval;
    1486           1 :                         cname = l->h->next->next->data.sval;
    1487             :                 }
    1488             : 
    1489     1231378 :                 if (!exp && rel && inner)
    1490     1231251 :                         if (!(exp = rel_bind_column3(sql, inner, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
    1491             :                                 return NULL;
    1492     1231377 :                 if (!exp && inner && is_sql_aggr(f) && (is_groupby(inner->op) || is_select(inner->op))) {
    1493             :                         /* if inner is selection, ie having clause, get the left relation to reach group by */
    1494             :                         sql_rel *gp = inner;
    1495          56 :                         while (gp && is_select(gp->op))
    1496           4 :                                 gp = gp->l;
    1497          52 :                         if (gp && !is_basetable(gp->op) && gp->l && !(exp = rel_bind_column3(sql, gp->l, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
    1498             :                                 return NULL;
    1499             :                 }
    1500     1231377 :                 if (!exp && query && query_has_outer(query)) {
    1501       11808 :                         int i;
    1502             : 
    1503       12018 :                         for (i=query_has_outer(query)-1; i>= 0 && !exp && (outer = query_fetch_outer(query,i)); i--) {
    1504       12017 :                                 if (!(exp = rel_bind_column3(sql, outer, sname, tname, cname, f | sql_outer)) && sql->session->status == -ERR_AMBIGUOUS)
    1505             :                                         return NULL;
    1506         293 :                                 if (!exp && is_groupby(outer->op)) {
    1507         102 :                                         if (!(exp = rel_bind_column3(sql, outer->l, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
    1508             :                                                 return NULL;
    1509             :                                         else
    1510         102 :                                                 used_lower_after_processed = is_processed(outer);
    1511             :                                 }
    1512       12017 :                                 if (exp && is_simple_project(outer->op) && !rel_find_exp(outer, exp))
    1513           0 :                                         exp = rel_project_add_exp(sql, outer, exp);
    1514       11807 :                                 if (exp)
    1515             :                                         break;
    1516             :                         }
    1517       11808 :                         if (exp && exp->card != CARD_AGGR && is_groupby(outer->op) && !is_sql_aggr(f) && rel_find_exp(outer->l, exp))
    1518           6 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", tname, cname);
    1519       11802 :                         if (exp && outer && outer->card <= CARD_AGGR && exp->card > CARD_AGGR && !is_sql_aggr(f))
    1520           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", tname, cname);
    1521       11802 :                         if (exp && outer && !is_sql_aggr(f)) {
    1522       11527 :                                 if (used_lower_after_processed || query_outer_used_exp( query, i, exp, f)) {
    1523           0 :                                         sql_exp *lu = used_lower_after_processed?exp:query_outer_last_used(query, i);
    1524           0 :                                         if (exp_name(lu) && exp_relname(lu) && !has_label(lu))
    1525           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", exp_relname(lu), exp_name(lu));
    1526           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    1527             :                                 }
    1528             :                         }
    1529       11802 :                         if (exp) {
    1530       11801 :                                 int of = query_fetch_outer_state(query, i);
    1531       11801 :                                 if (is_groupby(outer->op) && !is_sql_aggr(f)) {
    1532          64 :                                         exp = rel_groupby_add_aggr(sql, outer, exp);
    1533          64 :                                         exp->card = CARD_ATOM;
    1534       11737 :                                 } else if (is_groupby(outer->op) && is_sql_aggr(f) && exps_any_match(outer->exps, exp))
    1535          52 :                                         exp = exp_ref(sql, exp);
    1536             :                                 else
    1537       11685 :                                         exp->card = CARD_ATOM;
    1538       11801 :                                 set_freevar(exp, i);
    1539             :                                 /*
    1540             :                                 if (exp->alias.label == exp->nid)
    1541             :                                         exp->alias.label = -(sql->nid++);
    1542             :                                         */
    1543       11801 :                                 if (!is_sql_where(of) && !is_sql_aggr(of) && !is_sql_aggr(f) && !outer->grouped)
    1544       10113 :                                         set_outer(outer);
    1545             :                         }
    1546       11802 :                         if (exp && outer && (is_select(outer->op) || is_join(outer->op)))
    1547        4690 :                                 set_dependent_(outer);
    1548             :                 }
    1549             : 
    1550             :                 /* some views are just in the stack, like before and after updates views */
    1551     1231371 :                 if (rel && sql->use_views) {
    1552          40 :                         sql_rel *v = stack_find_rel_view(sql, tname);
    1553             : 
    1554          40 :                         if (v && exp && *rel && is_base(v->op) && v != *rel) /* trigger views are basetables relations, so those may conflict */
    1555           0 :                                 return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "SELECT: identifier '%s.%s' ambiguous", tname, cname);
    1556          40 :                         if (v && !exp) {
    1557          20 :                                 if (*rel)
    1558           0 :                                         *rel = rel_crossproduct(sql->sa, *rel, rel_dup(v), op_join);
    1559             :                                 else
    1560          20 :                                         *rel = rel_dup(v);
    1561          20 :                                 if (!(exp = rel_bind_column3(sql, *rel, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
    1562             :                                         return NULL;
    1563             :                         }
    1564             :                 }
    1565     1231351 :                 if (!exp) { /* If no column was found, try a global variable */
    1566       66249 :                         sql_var *var = NULL;
    1567       66249 :                         sql_subtype *tpe = NULL;
    1568       66249 :                         int level = 0;
    1569       66249 :                         sql_arg *a = NULL;
    1570             : 
    1571       66249 :                         if (find_variable_on_scope(sql, tname, cname, &var, &a, &tpe, &level, "SELECT")) { /* search schema with table name, ugh */
    1572          10 :                                 assert(level == 0);
    1573          10 :                                 exp = exp_param_or_declared(sql->sa, sa_strdup(sql->sa, var->sname), sa_strdup(sql->sa, var->name), &(var->var.tpe), 0);
    1574             :                         }
    1575             :                 }
    1576       66249 :                 if (!exp) {
    1577       66239 :                         if (inner && !is_sql_aggr(f) && is_groupby(inner->op) && inner->l && (exp = rel_bind_column3(sql, inner->l, sname, tname, cname, f))) {
    1578          54 :                                 if (group_by_pk_project_uk_cond(sql, inner, exp, sname, tname)) {
    1579             :                                         /* SQL23 feature: very special case where primary key is used in GROUP BY expression and
    1580             :                                          * unique key is in the project list or ORDER BY clause */
    1581           1 :                                         sql->session->status = 0;
    1582           1 :                                         sql->errstr[0] = 0;
    1583           1 :                                         exp->card = CARD_AGGR;
    1584           1 :                                         list_append(inner->exps, exp);
    1585             :                                 }
    1586             :                                 else
    1587          53 :                                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", tname, cname);
    1588             :                         }
    1589             :                 }
    1590             : 
    1591           1 :                 if (!exp)
    1592       66185 :                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42S22) "SELECT: no such column '%s.%s'", tname, cname);
    1593     1165133 :                 if (exp && inner && inner->card <= CARD_AGGR && exp->card > CARD_AGGR && (is_sql_sel(f) || is_sql_having(f)) && !is_sql_aggr(f))
    1594           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", tname, cname);
    1595     1165133 :                 if (exp && inner && is_groupby(inner->op) && !is_sql_aggr(f) && !is_freevar(exp))
    1596        5655 :                         exp = rel_groupby_add_aggr(sql, inner, exp);
    1597           0 :         } else if (dlist_length(l) > 3) {
    1598           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "cross-database references are not implemented");
    1599             :         }
    1600     2268102 :         if (exp && !exp_is_atom(exp) && rel && !outer) {
    1601     2138960 :                 if (query->last_exp && query->last_rel == *rel && !is_sql_aggr(query->last_state) && is_sql_aggr(f)) {
    1602          52 :                         if (!is_groupby(query->last_rel->op) || list_empty(query->last_rel->r) || !exps_find_exp(query->last_rel->r, query->last_exp)) {
    1603          31 :                                 if (exp_relname(query->last_exp) && exp_name(query->last_exp) && !has_label(query->last_exp))
    1604          31 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", exp_relname(query->last_exp), exp_name(query->last_exp));
    1605           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1606             :                         }
    1607             :                 }
    1608     2138929 :                 query->prev = query->last_exp;
    1609     2138929 :                 query->last_exp = exp;
    1610     2138929 :                 query->last_state = f;
    1611     2138929 :                 query->last_rel = *rel;
    1612             :         }
    1613             :         return exp;
    1614             : }
    1615             : 
    1616             : int
    1617      975453 : rel_convert_types(mvc *sql, sql_rel *ll, sql_rel *rr, sql_exp **L, sql_exp **R, int scale_fixing, check_type tpe)
    1618             : {
    1619      975453 :         sql_exp *ls = *L;
    1620      975453 :         sql_exp *rs = *R;
    1621      975453 :         sql_subtype *lt = exp_subtype(ls);
    1622      975453 :         sql_subtype *rt = exp_subtype(rs);
    1623             : 
    1624      975453 :         if (!rt && !lt) {
    1625           2 :                 sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
    1626           2 :                 return -1;
    1627             :         }
    1628      975451 :         if (rt && (!lt || !lt->type))
    1629           7 :                  return rel_set_type_param(sql, rt, ll, ls, 0);
    1630      975444 :         if (lt && (!rt || !rt->type))
    1631         648 :                  return rel_set_type_param(sql, lt, rr, rs, 0);
    1632             : 
    1633      974796 :         if (rt && lt) {
    1634      974796 :                 sql_subtype *i = lt;
    1635      974796 :                 sql_subtype *r = rt;
    1636             : 
    1637      974796 :                 if (subtype_cmp(lt, rt) != 0 || (tpe == type_equal_no_any && (lt->type->localtype==0 || rt->type->localtype==0))) {
    1638      267929 :                         sql_subtype super;
    1639             : 
    1640      267929 :                         cmp_supertype(&super, r, i);
    1641      267929 :                         if (scale_fixing) {
    1642             :                                 /* convert ls to super type */
    1643      267929 :                                 ls = exp_check_type(sql, &super, ll, ls, tpe);
    1644             :                                 /* convert rs to super type */
    1645      267929 :                                 rs = exp_check_type(sql, &super, rr, rs, tpe);
    1646             :                         } else {
    1647             :                                 /* convert ls to super type */
    1648           0 :                                 super.scale = lt->scale;
    1649           0 :                                 ls = exp_check_type(sql, &super, ll, ls, tpe);
    1650             :                                 /* convert rs to super type */
    1651           0 :                                 super.scale = rt->scale;
    1652           0 :                                 rs = exp_check_type(sql, &super, rr, rs, tpe);
    1653             :                         }
    1654             :                 }
    1655      974796 :                 *L = ls;
    1656      974796 :                 *R = rs;
    1657      974796 :                 if (!ls || !rs)
    1658             :                         return -1;
    1659             :                 return 0;
    1660             :         }
    1661             :         return -1;
    1662             : }
    1663             : 
    1664             : static sql_rel *
    1665      108202 : push_select_exp(mvc *sql, sql_rel *rel, sql_exp *e, sql_exp *ls, int f)
    1666             : {
    1667      108202 :         if (is_outerjoin(rel->op)) {
    1668        1178 :                 if ((is_left(rel->op) || is_full(rel->op)) && rel_find_exp(rel->l, ls)) {
    1669          38 :                         rel_join_add_exp(sql->sa, rel, e);
    1670          38 :                         return rel;
    1671        1140 :                 } else if ((is_right(rel->op) || is_full(rel->op)) && rel_find_exp(rel->r, ls)) {
    1672           5 :                         rel_join_add_exp(sql->sa, rel, e);
    1673           5 :                         return rel;
    1674             :                 }
    1675        1135 :                 if (is_left(rel->op) && rel_find_exp(rel->r, ls)) {
    1676        1109 :                         rel->r = rel_push_select(sql, rel->r, ls, e, f);
    1677        1109 :                         return rel;
    1678          26 :                 } else if (is_right(rel->op) && rel_find_exp(rel->l, ls)) {
    1679          11 :                         rel->l = rel_push_select(sql, rel->l, ls, e, f);
    1680          11 :                         return rel;
    1681             :                 }
    1682             :         }
    1683             :         /* push select into the given relation */
    1684      107039 :         return rel_push_select(sql, rel, ls, e, f);
    1685             : }
    1686             : 
    1687             : static sql_rel *
    1688      204486 : push_join_exp(mvc *sql, sql_rel *rel, sql_exp *e, sql_exp *L, sql_exp *R, sql_exp *R2, int f)
    1689             : {
    1690      204486 :         sql_rel *r;
    1691      204486 :         if (/*is_semi(rel->op) ||*/ (is_outerjoin(rel->op) && !is_processed((rel)))) {
    1692       21985 :                 rel_join_add_exp(sql->sa, rel, e);
    1693       21985 :                 return rel;
    1694             :         }
    1695             :         /* push join into the given relation */
    1696      182501 :         if ((r = rel_push_join(sql, rel, L, R, R2, e, f)) != NULL)
    1697             :                 return r;
    1698           0 :         rel_join_add_exp(sql->sa, rel, e);
    1699           0 :         return rel;
    1700             : }
    1701             : 
    1702             : static sql_rel *
    1703        3351 : rel_select_push_filter_exp_down(mvc *sql, sql_rel *rel, sql_exp *e, list *l, list *r, int ff)
    1704             : {
    1705        3351 :         sql_exp *ll, *rr;
    1706        3351 :         if (exps_card(r) <= CARD_ATOM && (exps_are_atoms(r) || exps_have_freevar(sql, r) || exps_have_freevar(sql, l))) {
    1707        3255 :                 if (exps_card(l) == exps_card(r) || rel->processed)  /* bin compare op */
    1708          98 :                         return rel_select(sql->sa, rel, e);
    1709        3157 :                 if ((ll = exps_find_one_multi_exp(l)))
    1710        3157 :                         return push_select_exp(sql, rel, e, ll, ff);
    1711          96 :         } else if ((ll = exps_find_one_multi_exp(l)) && (rr = exps_find_one_multi_exp(r))) { /* join */
    1712          57 :                 return push_join_exp(sql, rel, e, ll, rr, NULL, ff);
    1713             :         }
    1714          39 :         if (is_outerjoin(rel->op))
    1715           3 :                 return rel_select(sql->sa, rel, e);
    1716          36 :         return rel_select_add_exp(sql->sa, rel, e);
    1717             : }
    1718             : 
    1719             : static sql_rel *
    1720        3350 : rel_filter(mvc *sql, sql_rel *rel, list *l, list *r, char *sname, char *filter_op, int anti, int ff)
    1721             : {
    1722        3350 :         node *n;
    1723        3350 :         sql_exp *e = NULL;
    1724        3350 :         sql_subfunc *f = NULL;
    1725        3350 :         list *tl = sa_list(sql->sa);
    1726        3350 :         bool found = false;
    1727             : 
    1728        6700 :         for (n = l->h; n; n = n->next){
    1729        3350 :                 sql_exp *e = n->data;
    1730             : 
    1731        3350 :                 list_append(tl, exp_subtype(e));
    1732             :         }
    1733       13323 :         for (n = r->h; n; n = n->next){
    1734        9973 :                 sql_exp *e = n->data;
    1735             : 
    1736        9973 :                 list_append(tl, exp_subtype(e));
    1737             :         }
    1738             :         /* find filter function */
    1739        3350 :         f = bind_func_(sql, sname, filter_op, tl, F_FILT, false, &found, false);
    1740        3350 :         if (f) {
    1741        3348 :                 node *n,*m = f->func->ops->h;
    1742        3348 :                 list *nexps = sa_list(sql->sa);
    1743             : 
    1744        6696 :                 for(n=l->h; m && n; m = m->next, n = n->next) {
    1745        3348 :                         sql_arg *a = m->data;
    1746        3348 :                         sql_exp *e = n->data;
    1747             : 
    1748        3348 :                         e = exp_check_type(sql, &a->type, rel, e, type_equal);
    1749        3348 :                         if (!e)
    1750             :                                 return NULL;
    1751        3348 :                         list_append(nexps, e);
    1752             :                 }
    1753        3348 :                 l = nexps;
    1754        3348 :                 nexps = sa_list(sql->sa);
    1755       13313 :                 for(n=r->h; m && n; m = m->next, n = n->next) {
    1756        9965 :                         sql_arg *a = m->data;
    1757        9965 :                         sql_exp *e = n->data;
    1758             : 
    1759        9965 :                         e = exp_check_type(sql, &a->type, rel, e, type_equal);
    1760        9965 :                         if (!e)
    1761             :                                 return NULL;
    1762        9965 :                         list_append(nexps, e);
    1763             :                 }
    1764             :                 r = nexps;
    1765             :         }
    1766        3350 :         if (!f)
    1767           4 :                 return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s FILTER function %s%s%s'%s'",
    1768           2 :                                                  found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", filter_op);
    1769        3348 :         e = exp_filter(sql->sa, l, r, f, anti);
    1770             : 
    1771        3348 :         if (exps_one_is_rel(l) || exps_one_is_rel(r)) /* uncorrelated subquery case */
    1772           9 :                 return rel_select(sql->sa, rel, e);
    1773             :         /* atom or row => select */
    1774        6678 :         for (node *n=l->h; n; n = n->next) {
    1775        3339 :                 sql_exp *ls = n->data;
    1776             : 
    1777        3339 :                 if (ls->card > rel->card) {
    1778           0 :                         if (exp_name(ls) && !has_label(ls))
    1779           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(ls));
    1780           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1781             :                 }
    1782             :         }
    1783       13277 :         for (node *n=r->h; n; n = n->next) {
    1784        9938 :                 sql_exp *rs = n->data;
    1785             : 
    1786        9938 :                 if (rs->card > rel->card) {
    1787           0 :                         if (exp_name(rs) && !has_label(rs))
    1788           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(rs));
    1789           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1790             :                 }
    1791             :         }
    1792        3339 :         return rel_select_push_filter_exp_down(sql, rel, e, l, r, ff);
    1793             : }
    1794             : 
    1795             : static sql_rel *
    1796        3290 : rel_filter_exp_(mvc *sql, sql_rel *rel, sql_exp *ls, sql_exp *r1, sql_exp *r2, sql_exp *r3, char *filter_op, int anti, int f)
    1797             : {
    1798        3290 :         list *l = sa_list(sql->sa);
    1799        3290 :         list *r = sa_list(sql->sa);
    1800             : 
    1801        3290 :         list_append(l, ls);
    1802        3290 :         list_append(r, r1);
    1803        3290 :         if (r2)
    1804        3290 :                 list_append(r, r2);
    1805        3290 :         if (r3)
    1806        3290 :                 list_append(r, r3);
    1807        3290 :         return rel_filter(sql, rel, l, r, "sys", filter_op, anti, f);
    1808             : }
    1809             : 
    1810             : static sql_rel *
    1811      377530 : rel_select_push_compare_exp_down(mvc *sql, sql_rel *rel, sql_exp *e, sql_exp *ls, sql_exp *rs, sql_exp *rs2, int f)
    1812             : {
    1813      377530 :         if (!is_join(rel->op) && !is_select(rel->op))
    1814       85629 :                 return rel_select(sql->sa, rel, e);
    1815      379909 :         if ((rs->card <= CARD_ATOM || (rs2 && ls->card <= CARD_ATOM)) &&
    1816      176016 :                 (exp_is_atom(rs) || (rs2 && exp_is_atom(ls)) || exp_has_freevar(sql, rs) || exp_has_freevar(sql, ls)) &&
    1817         485 :                 (!rs2 || (rs2->card <= CARD_ATOM && (exp_is_atom(rs2) || exp_has_freevar(sql, rs2))))) {
    1818       87472 :                 if (ls->card == rs->card || (rs2 && (ls->card == rs2->card || rs->card == rs2->card)) || rel->processed) /* bin compare op */
    1819         991 :                         return rel_select(sql->sa, rel, e);
    1820             : 
    1821       86481 :                 return push_select_exp(sql, rel, e, ls, f);
    1822             :         } else { /* join */
    1823      204429 :                 return push_join_exp(sql, rel, e, ls, rs, rs2, f);
    1824             :         }
    1825             :         return rel;
    1826             : }
    1827             : 
    1828             : static sql_rel *
    1829      350818 : rel_compare_exp_(sql_query *query, sql_rel *rel, sql_exp *ls, sql_exp *rs, sql_exp *rs2, int type, int anti, int quantifier, int f, int symmetric, int is_semantics)
    1830             : {
    1831      350818 :         mvc *sql = query->sql;
    1832      350818 :         sql_exp *e = NULL;
    1833             : 
    1834      350818 :         if (quantifier || exp_is_rel(ls) || exp_is_rel(rs) || (rs2 && exp_is_rel(rs2))) {
    1835        3178 :                 if (rs2) {
    1836           7 :                         e = exp_compare2(sql->sa, ls, rs, rs2, type, symmetric);
    1837           7 :                         if (anti)
    1838           0 :                                 set_anti(e);
    1839             :                 } else {
    1840        3171 :                         assert(!symmetric);
    1841        3171 :                         if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
    1842             :                                 return NULL;
    1843        3171 :                         e = exp_compare_func(sql, ls, rs, compare_func((comp_type)type, anti), quantifier);
    1844             :                 }
    1845        3178 :                 return rel_select(sql->sa, rel, e);
    1846      347640 :         } else if (!rs2) {
    1847      344693 :                 assert(!symmetric);
    1848      344693 :                 if (ls->card < rs->card) {
    1849       12636 :                         sql_exp *swap = ls;
    1850       12636 :                         ls = rs;
    1851       12636 :                         rs = swap;
    1852       12636 :                         type = (int)swap_compare((comp_type)type);
    1853             :                 }
    1854      344693 :                 if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
    1855             :                         return NULL;
    1856      344690 :                 e = exp_compare(sql->sa, ls, rs, type);
    1857      344690 :                 if (is_semantics) set_semantics(e);
    1858             :         } else {
    1859        2947 :                 assert(rs2);
    1860        2947 :                 if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
    1861             :                         return NULL;
    1862        2947 :                 if (!(rs2 = exp_check_type(sql, exp_subtype(ls), rel, rs2, type_equal)))
    1863             :                         return NULL;
    1864        2947 :                 e = exp_compare2(sql->sa, ls, rs, rs2, type, symmetric);
    1865             :         }
    1866      347637 :         if (anti)
    1867         847 :                 set_anti(e);
    1868             : 
    1869      347637 :         if (!rel)
    1870           0 :                 return rel_select(sql->sa, rel_project_exp(sql, exp_atom_bool(sql->sa, 1)), e);
    1871             : 
    1872             :         /* atom or row => select */
    1873      347637 :         if (ls->card > rel->card || rs->card > rel->card || (rs2 && rs2->card > rel->card)) {
    1874           0 :                 sql_exp *e = ls->card > rel->card ? ls : rs->card > rel->card ? rs : rs2;
    1875           0 :                 if (exp_name(e) && !has_label(e))
    1876           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(e));
    1877           0 :                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1878             :         }
    1879      347637 :         return rel_select_push_compare_exp_down(sql, rel, e, ls, rs, rs2, f);
    1880             : }
    1881             : 
    1882             : static sql_rel *
    1883      347864 : rel_compare_exp(sql_query *query, sql_rel *rel, sql_exp *ls, sql_exp *rs, char *compare_op, int reduce, int quantifier, int need_not, int f, int is_semantics)
    1884             : {
    1885      347864 :         mvc *sql = query->sql;
    1886      347864 :         comp_type type = cmp_equal;
    1887             : 
    1888      347864 :         if (!ls || !rs)
    1889             :                 return NULL;
    1890             : 
    1891      347864 :         if (!quantifier && ((!rel && !query_has_outer(query)) || !reduce)) {
    1892             :                 /* TODO to handle filters here */
    1893           0 :                 sql_exp *e;
    1894             : 
    1895           0 :                 if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
    1896             :                         return NULL;
    1897           0 :                 e = rel_binop_(sql, rel, ls, rs, "sys", compare_op, card_value, true);
    1898             : 
    1899           0 :                 if (!e)
    1900             :                         return NULL;
    1901           0 :                 if (!reduce) {
    1902           0 :                         if (rel->op == op_project) {
    1903           0 :                                 append(rel->exps, e);
    1904             :                         } else {
    1905           0 :                                 list *exps = new_exp_list(sql->sa);
    1906             : 
    1907           0 :                                 append(exps, e);
    1908           0 :                                 return rel_project(sql->sa, rel, exps);
    1909             :                         }
    1910             :                 } else {
    1911           0 :                         return rel_select(sql->sa, rel, e);
    1912             :                 }
    1913             :         }
    1914      347864 :         type = compare_str2type(compare_op);
    1915      347864 :         assert(type != cmp_filter);
    1916      347864 :         return rel_compare_exp_(query, rel, ls, rs, NULL, type, need_not, quantifier, f, 0, is_semantics);
    1917             : }
    1918             : 
    1919             : static sql_rel *
    1920      347844 : rel_compare(sql_query *query, sql_rel *rel, symbol *sc, symbol *lo, symbol *ro, char *compare_op, int f, exp_kind k, int quantifier, int is_semantics)
    1921             : {
    1922      347844 :         mvc *sql = query->sql;
    1923      347844 :         sql_exp *rs = NULL, *ls;
    1924      347844 :         comp_type cmp_type = compare_str2type(compare_op);
    1925      347844 :         exp_kind ek = {type_value, card_column, FALSE};
    1926      347844 :         int need_not = 0;
    1927             : 
    1928      347844 :         if ((quantifier == 1 && cmp_type == cmp_equal) ||
    1929      347809 :             (quantifier == 2 && cmp_type == cmp_notequal)) {
    1930          63 :                 dnode *n = sc->data.lval->h;
    1931          63 :                 dlist *dl = dlist_create(sql->sa);
    1932             :                 /* map into IN/NOT IN */
    1933          63 :                 sc->token = cmp_type==cmp_equal?SQL_IN:SQL_NOT_IN;
    1934          63 :                 n->next->type = type_list;
    1935          63 :                 n->next->data.lval = dl;
    1936          63 :                 n->next->next->next = NULL; /* remove quantifier */
    1937          63 :                 dl->h = n->next->next;
    1938          63 :                 n->next->next = NULL; /* (remove comparison) moved righthand side */
    1939          63 :                 return rel_logical_exp(query, rel, sc, f);
    1940             :         }
    1941             :         /* <> ANY -> NOT (= ALL) */
    1942      347781 :         if (quantifier == 1 && cmp_type == cmp_notequal) {
    1943           5 :                 need_not = 1;
    1944           5 :                 quantifier = 2;
    1945           5 :                 cmp_type = cmp_equal;
    1946           5 :                 compare_op = "=";
    1947             :         }
    1948             : 
    1949      347781 :         if ((lo->token == SQL_SELECT || lo->token == SQL_UNION || lo->token == SQL_EXCEPT || lo->token == SQL_INTERSECT || lo->token == SQL_VALUES) &&
    1950          43 :                 (ro->token != SQL_SELECT && ro->token != SQL_UNION && ro->token != SQL_EXCEPT && ro->token != SQL_INTERSECT && ro->token != SQL_VALUES)) {
    1951          30 :                 symbol *tmp = lo; /* swap subquery to the right hand side */
    1952             : 
    1953          30 :                 lo = ro;
    1954          30 :                 ro = tmp;
    1955             : 
    1956          30 :                 if (compare_op[0] == '>')
    1957          16 :                         compare_op[0] = '<';
    1958          14 :                 else if (compare_op[0] == '<' && compare_op[1] != '>')
    1959           1 :                         compare_op[0] = '>';
    1960          30 :                 cmp_type = swap_compare(cmp_type);
    1961             :         }
    1962             : 
    1963      347781 :         ls = rel_value_exp(query, &rel, lo, f|sql_farg, ek);
    1964      347781 :         if (!ls)
    1965             :                 return NULL;
    1966      347732 :         if (ls && rel && exp_has_freevar(sql, ls) && is_sql_sel(f))
    1967           0 :                 ls = rel_project_add_exp(sql, rel, ls);
    1968      347732 :         if (quantifier)
    1969          58 :                 ek.card = card_set;
    1970             : 
    1971      347732 :         rs = rel_value_exp(query, &rel, ro, f|sql_farg, ek);
    1972      347732 :         if (!rs)
    1973             :                 return NULL;
    1974      347704 :         if (ls->card > rs->card && rs->card == CARD_AGGR && is_sql_having(f)) {
    1975           0 :                 if (exp_name(ls) && exp_relname(ls) && !has_label(ls))
    1976           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", exp_relname(ls), exp_name(ls));
    1977           0 :                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1978             :         }
    1979      347704 :         if (rs->card > ls->card && ls->card == CARD_AGGR && is_sql_having(f)) {
    1980           0 :                 if (exp_name(rs) && exp_relname(rs) && !has_label(rs))
    1981           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", exp_relname(rs), exp_name(rs));
    1982           0 :                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    1983             :         }
    1984      347704 :         return rel_compare_exp(query, rel, ls, rs, compare_op, k.reduce, quantifier, need_not, f, is_semantics);
    1985             : }
    1986             : 
    1987             : static sql_exp*
    1988       78857 : _rel_nop(mvc *sql, char *sname, char *fname, list *tl, sql_rel *rel, list *exps, exp_kind ek)
    1989             : {
    1990       78857 :         bool found = false;
    1991       78857 :         int table_func = (ek.card == card_relation);
    1992       78857 :         sql_ftype type = (ek.card == card_loader)?F_LOADER:((ek.card == card_none)?F_PROC:
    1993             :                    ((ek.card == card_relation)?F_UNION:F_FUNC));
    1994             : 
    1995       78857 :         sql_subfunc *f = bind_func_(sql, sname, fname, tl, type, false, &found, false);
    1996       78857 :         if (f && !(exps = check_arguments_and_find_largest_any_type(sql, rel, exps, f, table_func, false)))
    1997             :                 f = NULL;
    1998             : 
    1999       78841 :         if (f)
    2000       78841 :                 return exp_op(sql->sa, exps, f);
    2001          16 :         char *arg_list = nary_function_arg_types_2str(sql, tl, list_length(tl));
    2002          32 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s operator %s%s%s'%s'(%s)",
    2003          16 :                                          found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname, arg_list ? arg_list : "");
    2004             : }
    2005             : 
    2006             : static sql_exp *
    2007        2050 : exp_exist(sql_query *query, sql_rel *rel, sql_exp *le, int exists)
    2008             : {
    2009        2050 :         mvc *sql = query->sql;
    2010        2050 :         sql_subfunc *exists_func = NULL;
    2011        2050 :         sql_subtype *t;
    2012        2050 :         sql_exp *res;
    2013             : 
    2014        2050 :         if (!exp_name(le))
    2015         753 :                 exp_label(sql->sa, le, ++sql->label);
    2016        2050 :         if (exp_is_rel(le)) { /* for the subquery case, propagate to the inner query */
    2017        2050 :                 sql_rel *r = exp_rel_get_rel(sql->sa, le);
    2018        2050 :                 if (is_project(r->op) && !list_empty(r->exps)) {
    2019        5849 :                         for (node *n = r->exps->h; n; n = n->next)
    2020        3799 :                                 if (!exp_subtype(n->data) && rel_set_type_param(sql, sql_bind_localtype("bit"), r, n->data, 0) < 0) /* workaround */
    2021             :                                         return NULL;
    2022        2050 :                         le->tpe = *exp_subtype(r->exps->h->data); /* just take the first expression type */
    2023             :                 }
    2024           0 :         } else if (!exp_subtype(le) && rel_set_type_param(sql, sql_bind_localtype("bit"), rel, le, 0) < 0) /* workaround */
    2025             :                 return NULL;
    2026        2050 :         t = exp_subtype(le);
    2027             : 
    2028        2111 :         if (!(exists_func = sql_bind_func(sql, "sys", exists ? "sql_exists" : "sql_not_exists", t, NULL, F_FUNC, true, true)))
    2029           0 :                 return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "exist operator on type %s missing", t ? t->type->base.name : "unknown");
    2030        2050 :         res = exp_unop(sql->sa, le, exists_func);
    2031        2050 :         set_has_no_nil(res);
    2032        2050 :         return res;
    2033             : }
    2034             : 
    2035             : static sql_exp *
    2036        1071 : rel_exists_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f)
    2037             : {
    2038        1071 :         exp_kind ek = {type_value, card_exists, FALSE};
    2039        1071 :         sql_exp *le, *e;
    2040             : 
    2041        1071 :         le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
    2042        1071 :         if (!le)
    2043             :                 return NULL;
    2044        1070 :         if (!(e = exp_exist(query, rel ? *rel : NULL, le, sc->token == SQL_EXISTS)))
    2045             :                 return NULL;
    2046             :         /* only freevar should have CARD_AGGR */
    2047        1070 :         e->card = CARD_ATOM;
    2048        1070 :         return e;
    2049             : }
    2050             : 
    2051             : static sql_rel *
    2052         986 : rel_exists_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
    2053             : {
    2054         986 :         exp_kind ek = {type_value, card_exists, TRUE};
    2055         986 :         mvc *sql = query->sql;
    2056         986 :         sql_rel *sq = NULL;
    2057             : 
    2058         986 :         if (is_psm_call(f) || is_sql_merge(f))
    2059           3 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: subqueries not supported inside %s", is_psm_call(f) ? "CALL" : "MERGE", is_psm_call(f) ? "CALL statements" : "MERGE conditions");
    2060         985 :         if (rel) {
    2061         985 :                 query_processed(query);
    2062         985 :                 query_push_outer(query, rel, f);
    2063             :         }
    2064         985 :         sq = rel_subquery(query, sc->data.sym, ek);
    2065         985 :         if (rel)
    2066         985 :                 rel = query_pop_outer(query);
    2067         985 :         assert(!is_sql_sel(f));
    2068         985 :         if (sq) {
    2069         980 :                 sql_exp *e = exp_rel(sql, sq);
    2070         980 :                 if (!(e = exp_exist(query, rel, e, sc->token == SQL_EXISTS)))
    2071             :                         return NULL;
    2072             :                 /* only freevar should have CARD_AGGR */
    2073         980 :                 e->card = CARD_ATOM;
    2074         980 :                 rel = rel_select_add_exp(sql->sa, rel, e);
    2075         980 :                 return rel;
    2076             :         }
    2077             :         return NULL;
    2078             : }
    2079             : 
    2080             : static int
    2081        7007 : is_project_true(sql_rel *r)
    2082             : {
    2083        7007 :         if (r && !r->l && list_length(r->exps) == 1) {
    2084          82 :                 sql_exp *e = r->exps->h->data;
    2085          82 :                 if (exp_is_atom(e) && exp_is_true(e))
    2086             :                         return 1;
    2087             :         }
    2088             :         return 0;
    2089             : }
    2090             : 
    2091             : static sql_exp *
    2092       62223 : rel_in_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f)
    2093             : {
    2094       62223 :         mvc *sql = query->sql;
    2095       62223 :         exp_kind ek = {type_value, card_column, TRUE};
    2096       62223 :         dlist *dl = sc->data.lval;
    2097       62223 :         symbol *lo = NULL;
    2098       62223 :         dnode *n = dl->h->next, *dn = NULL;
    2099       62223 :         sql_exp *le = NULL, *re, *e = NULL;
    2100       62223 :         list *ll = sa_list(sql->sa);
    2101       62223 :         int is_tuple = 0, add_select = 0;
    2102             : 
    2103             :         /* complex case */
    2104       62223 :         if (dl->h->type == type_list) { /* (a,b..) in (.. ) */
    2105        4107 :                 dn = dl->h->data.lval->h;
    2106        4107 :                 lo = dn->data.sym;
    2107        4107 :                 dn = dn->next;
    2108             :         } else {
    2109       58116 :                 lo = dl->h->data.sym;
    2110             :         }
    2111      196963 :         for( ; lo; lo = dn?dn->data.sym:NULL, dn = dn?dn->next:NULL ) {
    2112       67374 :                 le = rel_value_exp(query, rel, lo, f|sql_farg, ek);
    2113       67374 :                 if (!le)
    2114             :                         return NULL;
    2115       67370 :                 append(ll, le);
    2116             :         }
    2117       62219 :         if (list_length(ll) == 1) {
    2118       58112 :                 le = ll->h->data;
    2119       58112 :                 ek.card = card_set;
    2120             :         } else {
    2121        4107 :                 le = exp_values(sql->sa, ll);
    2122        4107 :                 exp_label(sql->sa, le, ++sql->label);
    2123        4107 :                 ek.type = list_length(ll);
    2124        4107 :                 is_tuple = list_length(ll);
    2125             :         }
    2126             :         /* list of values or subqueries */
    2127             :         /* 3 right hand side cases,
    2128             :          *      1 - value/tuple list of atoms
    2129             :          *      2 - list of scalar sub queries (needs check on 1 row/column per query)
    2130             :          *      3 - single tabular ie. multi column, multi row query
    2131             :          */
    2132       62219 :         if (n->type == type_list) {
    2133       62219 :                 sql_exp *values;
    2134       62219 :                 list *vals = sa_list(sql->sa);
    2135             : 
    2136       62219 :                 n = dl->h->next;
    2137       62219 :                 n = n->data.lval->h;
    2138             : 
    2139      308783 :                 for (; n; n = n->next) {
    2140      246596 :                         if (n->type == type_list) {
    2141           3 :                                 dnode *m = n->data.lval->h;
    2142           3 :                                 list *rl = sa_list(sql->sa);
    2143          12 :                                 for (; m; m = m->next) {
    2144           6 :                                         assert(m->type == type_symbol);
    2145           6 :                                         sql_exp *re = rel_value_exp(query, rel, m->data.sym, f|sql_farg, ek);
    2146           6 :                                         if (!re)
    2147             :                                                 return NULL;
    2148           6 :                                         append(rl, re);
    2149             :                                 }
    2150           3 :                                 re = exp_values(sql->sa, rl);
    2151             :                         } else {
    2152      246593 :                                 assert(n->type == type_symbol);
    2153      246593 :                                 re = rel_value_exp(query, rel, n->data.sym, f|sql_farg, ek);
    2154             :                         }
    2155      246596 :                         if (!re)
    2156             :                                 return NULL;
    2157      246573 :                         if (is_tuple && (!exp_is_rel(re) && !is_values(re)))
    2158           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Cannot match a tuple to a single value");
    2159        8206 :                         if (is_tuple && exp_is_rel(re)) {
    2160        4106 :                                 sql_rel *r = exp_rel_get_rel(sql->sa, re);
    2161             : 
    2162        4106 :                                 if (!r)
    2163           0 :                                         return sql_error(sql, 02, SQLSTATE(42000) "Subquery missing");
    2164        4106 :                                 if (r->nrcols != ek.type)
    2165          12 :                                         return sql_error(sql, 02, SQLSTATE(42000) "Subquery has too %s columns", (r->nrcols < ek.type) ? "few" : "many");
    2166        4097 :                                 re = exp_rel_label(sql, re);
    2167      242467 :                         } else if (exp_is_rel(re)) {
    2168        7008 :                                 sql_rel *r = exp_rel_get_rel(sql->sa, re);
    2169        7008 :                                 add_select = 1;
    2170        7008 :                                 if (rel && *rel && is_join((*rel)->op))
    2171        2933 :                                         set_dependent((*rel));
    2172        7008 :                                 if (is_project(r->op) && is_project_true(r->l) && list_length(r->exps) == 1)
    2173          80 :                                         re = r->exps->h->data;
    2174      235459 :                         } else if (is_values(re) && is_tuple != list_length(exp_get_values(re))) {
    2175           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Tuple sizes do not match");
    2176             :                         }
    2177      246564 :                         append(vals, re);
    2178             :                 }
    2179             : 
    2180       62187 :                 if (list_empty(vals))
    2181           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "The list of values for IN operator cannot be empty");
    2182             : 
    2183       62187 :                 values = exp_values(sql->sa, vals);
    2184       62187 :                 exp_label(sql->sa, values, ++sql->label);
    2185       62187 :                 if (is_tuple) {
    2186        4098 :                         if (!(values = exp_tuples_set_supertype(sql, exp_get_values(le), values)))
    2187             :                                 return NULL;
    2188        4098 :                         if (!(le->f = tuples_check_types(sql, exp_get_values(le), values)))
    2189             :                                 return NULL;
    2190             :                 } else { /* if it's not a tuple, enforce coercion on the type for every element on the list */
    2191       58089 :                         sql_subtype super, *le_tpe = exp_subtype(le), *values_tpe = NULL;
    2192             : 
    2193      300552 :                         for (node *m = vals->h; m; m = m->next) { /* first get values supertype */
    2194      242463 :                                 sql_exp *e = m->data;
    2195      242463 :                                 sql_subtype *tpe = exp_subtype(e);
    2196             : 
    2197      242463 :                                 if (values_tpe && tpe) {
    2198      184371 :                                         cmp_supertype(&super, values_tpe, tpe);
    2199      184371 :                                         *values_tpe = super;
    2200       58092 :                                 } else if (!values_tpe && tpe) {
    2201       58085 :                                         super = *tpe;
    2202       58085 :                                         values_tpe = &super;
    2203             :                                 }
    2204             :                         }
    2205       58089 :                         if (!le_tpe)
    2206           2 :                                 le_tpe = values_tpe;
    2207       58089 :                         if (!values_tpe)
    2208           4 :                                 values_tpe = le_tpe;
    2209       58089 :                         if (!le_tpe || !values_tpe)
    2210           1 :                                 return sql_error(sql, 01, SQLSTATE(42000) "For the IN operator, both sides must have a type defined");
    2211       58088 :                         cmp_supertype(&super, values_tpe, le_tpe); /* compute supertype */
    2212             : 
    2213             :                         /* on selection/join cases we can generate cmp expressions instead of anyequal for trivial cases */
    2214       58088 :                         if ((is_sql_where(f) || is_sql_having(f)) && !is_sql_farg(f) && !exp_has_rel(le) && exps_are_atoms(vals)) {
    2215       23948 :                                 if (list_length(vals) == 1) { /* use cmp_equal instead of cmp_in for 1 expression */
    2216         115 :                                         sql_exp *first = vals->h->data;
    2217         115 :                                         if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &le, &first, 1, type_equal_no_any) < 0)
    2218           0 :                                                 return NULL;
    2219         140 :                                         e = exp_compare(sql->sa, le, first, (sc->token == SQL_IN) ? cmp_equal : cmp_notequal);
    2220             :                                 } else { /* use cmp_in instead of anyequal for n simple expressions */
    2221      120568 :                                         for (node *n = vals->h ; n ; n = n->next)
    2222       96735 :                                                 if ((n->data = exp_check_type(sql, &super, rel ? *rel : NULL, n->data, type_equal)) == NULL)
    2223             :                                                         return NULL;
    2224       23833 :                                         if ((le = exp_check_type(sql, &super, rel ? *rel : NULL, le, type_equal)) == NULL)
    2225             :                                                 return NULL;
    2226       32423 :                                         e = exp_in(sql->sa, le, vals, (sc->token == SQL_IN) ? cmp_in : cmp_notin);
    2227             :                                 }
    2228             :                         }
    2229       23948 :                         if (!e) { /* after computing supertype, check types for each IN value */
    2230      179752 :                                 for (node *n = vals->h ; n ; n = n->next)
    2231      145612 :                                         if ((n->data = exp_check_type(sql, &super, rel ? *rel : NULL, n->data, type_equal)) == NULL)
    2232             :                                                 return NULL;
    2233       34140 :                                 values->tpe = *exp_subtype(vals->h->data);
    2234       34140 :                                 if (!(le = exp_check_type(sql, &super, rel ? *rel : NULL, le, type_equal)))
    2235             :                                         return NULL;
    2236             :                         }
    2237             :                 }
    2238       58088 :                 if (!e) {
    2239       38238 :                         if (add_select && rel && *rel && !is_project((*rel)->op) && !is_select((*rel)->op) && !is_base((*rel)->op))
    2240        2932 :                                 *rel = rel_select(sql->sa, *rel, NULL);
    2241       38238 :                         if ((rel && *rel) || exp_has_rel(le) || exp_has_rel(values))
    2242       32676 :                                 e = exp_in_func(sql, le, values, (sc->token == SQL_IN), is_tuple);
    2243             :                         else
    2244        5562 :                                 e = exp_in_aggr(sql, le, values, (sc->token == SQL_IN), is_tuple);
    2245             :                 }
    2246             :         }
    2247             :         return e;
    2248             : }
    2249             : 
    2250             : static sql_rel *
    2251       32521 : rel_in_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
    2252             : {
    2253       32521 :         mvc *sql = query->sql;
    2254       32521 :         sql_exp *e = rel_in_value_exp(query, &rel, sc, f);
    2255             : 
    2256       32521 :         assert(!is_sql_sel(f));
    2257       32521 :         if (!e || !rel)
    2258             :                 return NULL;
    2259             : 
    2260       32497 :         if (e->type == e_cmp) { /* it's a exp_in or cmp_equal of simple expressions, push down early on if possible */
    2261       23946 :                 sql_exp *ls = e->l;
    2262       23946 :                 bool rlist = (e->flag == cmp_in || e->flag == cmp_notin);
    2263       23946 :                 unsigned int rcard = rlist ? exps_card(e->r) : exp_card(e->r);
    2264       23946 :                 int r_is_atoms = rlist ? exps_are_atoms(e->r) : exp_is_atom(e->r);
    2265       23946 :                 int r_has_freevar = rlist ? exps_have_freevar(sql, e->r) : exp_has_freevar(sql, e->r);
    2266             : 
    2267       23946 :                 if (rcard <= CARD_ATOM && (r_is_atoms || r_has_freevar || exp_has_freevar(sql, ls))) {
    2268       23946 :                         if ((exp_card(ls) == rcard) || rel->processed) /* bin compare op */
    2269        5382 :                                 return rel_select(sql->sa, rel, e);
    2270             : 
    2271       18564 :                         return push_select_exp(sql, rel, e, ls, f);
    2272             :                 } else { /* join */
    2273           0 :                         sql_exp *rs = rlist ? exps_find_one_multi_exp(e->r) : e->r;
    2274           0 :                         if (rs)
    2275           0 :                                 return push_join_exp(sql, rel, e, ls, rs, NULL, f);
    2276             :                 }
    2277             :         }
    2278        8551 :         if (is_outerjoin(rel->op))
    2279          13 :                 return rel_select(sql->sa, rel, e);
    2280        8538 :         return rel_select_add_exp(sql->sa, rel, e);
    2281             : }
    2282             : 
    2283             : static bool
    2284       52569 : not_symbol_can_be_propagated(mvc *sql, symbol *sc)
    2285             : {
    2286       52569 :         switch (sc->token) {
    2287             :         case SQL_IN:
    2288             :         case SQL_NOT_IN:
    2289             :         case SQL_EXISTS:
    2290             :         case SQL_NOT_EXISTS:
    2291             :         case SQL_LIKE:
    2292             :         case SQL_NOT_LIKE:
    2293             :         case SQL_BETWEEN:
    2294             :         case SQL_NOT_BETWEEN:
    2295             :         case SQL_IS_NULL:
    2296             :         case SQL_IS_NOT_NULL:
    2297             :         case SQL_NOT:
    2298             :         case SQL_COMPARE:
    2299             :                 return true;
    2300        6822 :         case SQL_AND:
    2301             :         case SQL_OR: {
    2302        6822 :                 symbol *lo = sc->data.lval->h->data.sym;
    2303        6822 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2304        6826 :                 return not_symbol_can_be_propagated(sql, lo) && not_symbol_can_be_propagated(sql, ro);
    2305             :         }
    2306       36501 :         default:
    2307       36501 :                 return false;
    2308             :         }
    2309             : }
    2310             : 
    2311             : /* Warning, this function assumes the entire bison tree can be negated, so call it after 'not_symbol_can_be_propagated' */
    2312             : static symbol *
    2313       16063 : negate_symbol_tree(mvc *sql, symbol *sc)
    2314             : {
    2315       16063 :         switch (sc->token) {
    2316        1454 :         case SQL_IN:
    2317        1454 :                 sc->token = SQL_NOT_IN;
    2318        1454 :                 break;
    2319          22 :         case SQL_NOT_IN:
    2320          22 :                 sc->token = SQL_IN;
    2321          22 :                 break;
    2322           0 :         case SQL_EXISTS:
    2323           0 :                 sc->token = SQL_NOT_EXISTS;
    2324           0 :                 break;
    2325           0 :         case SQL_NOT_EXISTS:
    2326           0 :                 sc->token = SQL_EXISTS;
    2327           0 :                 break;
    2328           7 :         case SQL_LIKE:
    2329           7 :                 sc->token = SQL_NOT_LIKE;
    2330           7 :                 break;
    2331           0 :         case SQL_NOT_LIKE:
    2332           0 :                 sc->token = SQL_LIKE;
    2333           0 :                 break;
    2334          17 :         case SQL_BETWEEN:
    2335          17 :                 sc->token = SQL_NOT_BETWEEN;
    2336          17 :                 break;
    2337          11 :         case SQL_NOT_BETWEEN:
    2338          11 :                 sc->token = SQL_BETWEEN;
    2339          11 :                 break;
    2340          32 :         case SQL_IS_NULL:
    2341          32 :                 sc->token = SQL_IS_NOT_NULL;
    2342          32 :                 break;
    2343          15 :         case SQL_IS_NOT_NULL:
    2344          15 :                 sc->token = SQL_IS_NULL;
    2345          15 :                 break;
    2346          27 :         case SQL_NOT: { /* nested NOTs eliminate each other */
    2347          27 :                 if (sc->data.sym->token == SQL_ATOM) {
    2348           5 :                         AtomNode *an = (AtomNode*) sc->data.sym;
    2349           5 :                         sc = newAtomNode(sql->sa, an->a);
    2350          22 :                 } else if (sc->data.sym->token == SQL_SELECT) {
    2351           2 :                         SelectNode *sn = (SelectNode*) sc->data.sym;
    2352           2 :                         sc = newSelectNode(sql->sa, sn->distinct, sn->selection, sn->into, sn->from, sn->where, sn->groupby, sn->having,
    2353             :                                                            sn->orderby, sn->name, sn->limit, sn->offset, sn->sample, sn->seed, sn->window);
    2354             :                 } else {
    2355          20 :                         memmove(sc, sc->data.sym, sizeof(symbol));
    2356             :                 }
    2357             :         } break;
    2358        7660 :         case SQL_COMPARE: {
    2359        7660 :                 dnode *cmp_n = sc->data.lval->h;
    2360        7660 :                 comp_type neg_cmp_type = negate_compare(compare_str2type(cmp_n->next->data.sval)); /* negate the comparator */
    2361        7660 :                 if (cmp_n->next->next->next) {
    2362          22 :                         switch(cmp_n->next->next->next->data.i_val)
    2363             :                         {
    2364          12 :                         case 0: /* negating ANY/ALL */
    2365          12 :                                 cmp_n->next->next->next->data.i_val = 1;
    2366          12 :                                 break;
    2367           7 :                         case 1: /* negating ANY/ALL */
    2368           7 :                                 cmp_n->next->next->next->data.i_val = 0;
    2369           7 :                                 break;
    2370           2 :                         case 2: /* negating IS [NOT] DINSTINCT FROM */
    2371           2 :                                 cmp_n->next->next->next->data.i_val = 3;
    2372           2 :                                 break;
    2373           1 :                         case 3: /* negating IS [NOT] DINSTINCT FROM */
    2374           1 :                                 cmp_n->next->next->next->data.i_val = 2;
    2375           1 :                                 break;
    2376             :                         }
    2377             :                 }
    2378        7660 :                 cmp_n->next->data.sval = sa_strdup(sql->sa, compare_func(neg_cmp_type, 0));
    2379        7660 :         } break;
    2380        6818 :         case SQL_AND:
    2381             :         case SQL_OR: {
    2382        6818 :                 sc->data.lval->h->data.sym = negate_symbol_tree(sql, sc->data.lval->h->data.sym);
    2383        6818 :                 sc->data.lval->h->next->data.sym= negate_symbol_tree(sql, sc->data.lval->h->next->data.sym);
    2384        6818 :                 sc->token = sc->token == SQL_AND ? SQL_OR : SQL_AND;
    2385        6818 :         } break;
    2386             :         default:
    2387             :                 break;
    2388             :         }
    2389       16063 :         return sc;
    2390             : }
    2391             : 
    2392             : static int
    2393        3111 : exp_between_check_types(sql_subtype *res, sql_subtype *t1, sql_subtype *t2, sql_subtype *t3)
    2394             : {
    2395        3111 :         bool type_found = false;
    2396        3111 :         sql_subtype super;
    2397             : 
    2398        3111 :         if (t1 && t2) {
    2399        3105 :                 cmp_supertype(&super, t2, t1);
    2400        3105 :                 type_found = true;
    2401           6 :         } else if (t1) {
    2402           3 :                 super = *t1;
    2403           3 :                 type_found = true;
    2404           3 :         } else if (t2) {
    2405           1 :                 super = *t2;
    2406           1 :                 type_found = true;
    2407             :         }
    2408        3111 :         if (t3) {
    2409        3108 :                 if (type_found)
    2410        3107 :                         cmp_supertype(&super, t3, &super);
    2411             :                 else
    2412           1 :                         super = *t3;
    2413             :                 type_found = true;
    2414             :         }
    2415           3 :         if (!type_found)
    2416             :                 return -1;
    2417        3110 :         *res = super;
    2418        3110 :         return 0;
    2419             : }
    2420             : 
    2421             : static bool
    2422      116641 : exp_is_null_no_value_opt(sql_exp *e)
    2423             : {
    2424      116641 :         if (!e)
    2425             :                 return false;
    2426      120555 :         while (is_convert(e->type))
    2427        3914 :                 e = e->l;
    2428      233255 :         return e->type == e_atom && e->l && atom_null(e->l);
    2429             : }
    2430             : 
    2431             : sql_exp *
    2432     2535000 : rel_logical_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f, exp_kind ek)
    2433             : {
    2434     2535098 :         mvc *sql = query->sql;
    2435             : 
    2436     2535098 :         if (!sc)
    2437             :                 return NULL;
    2438             : 
    2439     2535098 :         if (mvc_highwater(sql))
    2440           0 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    2441             : 
    2442     2535097 :         switch (sc->token) {
    2443       51511 :         case SQL_OR:
    2444             :         case SQL_AND:
    2445             :         {
    2446       51511 :                 symbol *lo = sc->data.lval->h->data.sym;
    2447       51511 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2448       51511 :                 sql_exp *ls, *rs;
    2449             : 
    2450       51511 :                 if (!(ls = rel_value_exp(query, rel, lo, f|sql_farg, ek)))
    2451             :                         return NULL;
    2452       51511 :                 if (!(rs = rel_value_exp(query, rel, ro, f|sql_farg, ek)))
    2453             :                         return NULL;
    2454       90908 :                 return rel_binop_(sql, rel ? *rel : NULL, ls, rs, "sys", sc->token == SQL_OR ? "or": "and", card_value, false);
    2455             :         }
    2456           5 :         case SQL_FILTER:
    2457             :                 /* [ x,..] filter [ y,..] */
    2458             :                 /* todo add anti, [ x,..] not filter [ y,...] */
    2459             :                 /* no correlation */
    2460             :         {
    2461           5 :                 dnode *ln = sc->data.lval->h->data.lval->h;
    2462           5 :                 dnode *rn = sc->data.lval->h->next->next->data.lval->h;
    2463           5 :                 dlist *filter_op = sc->data.lval->h->next->data.lval;
    2464           5 :                 char *fname = qname_schema_object(filter_op);
    2465           5 :                 char *sname = qname_schema(filter_op);
    2466           5 :                 list *exps, *tl;
    2467           5 :                 sql_subtype *obj_type = NULL;
    2468             : 
    2469           5 :                 exps = sa_list(sql->sa);
    2470           5 :                 tl = sa_list(sql->sa);
    2471          15 :                 for (; ln; ln = ln->next) {
    2472           5 :                         symbol *sym = ln->data.sym;
    2473             : 
    2474           5 :                         sql_exp *e = rel_value_exp(query, rel, sym, f|sql_farg, ek);
    2475           5 :                         if (!e)
    2476             :                                 return NULL;
    2477           5 :                         if (!obj_type)
    2478           5 :                                 obj_type = exp_subtype(e);
    2479           5 :                         list_append(exps, e);
    2480           5 :                         append(tl, exp_subtype(e));
    2481             :                 }
    2482          13 :                 for (; rn; rn = rn->next) {
    2483          10 :                         symbol *sym = rn->data.sym;
    2484             : 
    2485          10 :                         sql_exp *e = rel_value_exp(query, rel, sym, f|sql_farg, ek);
    2486          10 :                         if (!e)
    2487             :                                 return NULL;
    2488           8 :                         list_append(exps, e);
    2489           8 :                         append(tl, exp_subtype(e));
    2490             :                 }
    2491             :                 /* find the predicate filter function */
    2492           3 :                 return _rel_nop(sql, sname, fname, tl, rel ? *rel : NULL, exps, ek);
    2493             :         }
    2494      116357 :         case SQL_COMPARE:
    2495             :         {
    2496      116357 :                 dnode *n = sc->data.lval->h;
    2497      116357 :                 symbol *lo = n->data.sym;
    2498      116357 :                 symbol *ro = n->next->next->data.sym;
    2499      116357 :                 char *compare_op = n->next->data.sval;
    2500      116357 :                 int quantifier = 0, need_not = 0;
    2501      116357 :                 sql_exp *rs = NULL, *ls;
    2502      116357 :                 comp_type cmp_type = compare_str2type(compare_op);
    2503      116357 :                 bool is_not_distinct_from = false;
    2504      116357 :                 bool is_distinct_from = false;
    2505             : 
    2506             :                 /*
    2507             :                  * = ANY -> IN, <> ALL -> NOT( = ANY) -> NOT IN
    2508             :                  * = ALL -> all(groupby(all, nil)), <> ANY -> NOT ( = ALL )
    2509             :                  */
    2510      116357 :                 if (n->next->next->next)
    2511         256 :                         quantifier = n->next->next->next->data.i_val + 1;
    2512         256 :                 assert(quantifier == 0 || quantifier == 1 || quantifier == 2 || quantifier == 3 || quantifier == 4);
    2513             : 
    2514             :                 /* [NOT] DISTINCT FROM */
    2515      116357 :                 if (quantifier == 3) {
    2516             :                                 is_not_distinct_from = true;
    2517             :                                 quantifier = 0;
    2518             :                 }
    2519      116344 :                 else if (quantifier == 4) {
    2520          14 :                                 is_distinct_from = true;
    2521          14 :                                 quantifier = 0;
    2522             :                 }
    2523             : 
    2524      116357 :                 if ((quantifier == 1 && cmp_type == cmp_equal) ||
    2525      116291 :                     (quantifier == 2 && cmp_type == cmp_notequal)) {
    2526          93 :                         dlist *dl = dlist_create(sql->sa);
    2527             :                         /* map into IN/NOT IN */
    2528          93 :                         sc->token = cmp_type==cmp_equal?SQL_IN:SQL_NOT_IN;
    2529          93 :                         n->next->type = type_list;
    2530          93 :                         n->next->data.lval = dl;
    2531          93 :                         n->next->next->next = NULL; /* remove quantifier */
    2532          93 :                         dl->h = n->next->next;
    2533          93 :                         n->next->next = NULL; /* (remove comparison) moved righthand side */
    2534          93 :                         return rel_logical_value_exp(query, rel, sc, f, ek);
    2535             :                 }
    2536             :                 /* <> ANY -> NOT (= ALL) */
    2537      116264 :                 if (quantifier == 1 && cmp_type == cmp_notequal) {
    2538          15 :                         need_not = 1;
    2539          15 :                         quantifier = 2;
    2540          15 :                         cmp_type = cmp_equal;
    2541          15 :                         compare_op = "=";
    2542             :                 }
    2543             : 
    2544      116264 :                 ls = rel_value_exp(query, rel, lo, f|sql_farg, ek);
    2545      116264 :                 if (!ls)
    2546             :                         return NULL;
    2547      116252 :                 if (quantifier)
    2548         136 :                         ek.card = card_set;
    2549             : 
    2550      116252 :                 rs = rel_value_exp(query, rel, ro, f|sql_farg, ek);
    2551      116252 :                 if (!rs)
    2552             :                         return NULL;
    2553             : 
    2554      116242 :                 if (is_distinct_from || is_not_distinct_from) {
    2555          27 :                         if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &ls, &rs, 1, type_equal_no_any) < 0)
    2556             :                                 return NULL;
    2557          41 :                         sql_exp* e = exp_compare(sql->sa, ls, rs, is_not_distinct_from?cmp_equal:cmp_notequal);
    2558          27 :                         set_semantics(e);
    2559          27 :                         return e;
    2560             :                 }
    2561             : 
    2562      116215 :                 if (rs->type == e_atom)
    2563      104919 :                         quantifier = 0;
    2564             : 
    2565      116215 :                 if (!exp_is_rel(ls) && !exp_is_rel(rs) && ls->card < rs->card) {
    2566          14 :                         sql_exp *swap = ls; /* has to swap parameters like in the rel_logical_exp case */
    2567          14 :                         ls = rs;
    2568          14 :                         rs = swap;
    2569          14 :                         cmp_type = swap_compare(cmp_type);
    2570             :                 }
    2571             : 
    2572      116215 :                 if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &ls, &rs, 1, type_equal_no_any) < 0)
    2573             :                         return NULL;
    2574      116212 :                 if (exp_is_null_no_value_opt(ls) && exp_is_null_no_value_opt(rs))
    2575           7 :                         return exp_atom(sql->sa, atom_general(sql->sa, sql_bind_localtype("bit"), NULL, 0));
    2576             : 
    2577      116205 :                 return exp_compare_func(sql, ls, rs, compare_func(cmp_type, need_not), quantifier);
    2578             :         }
    2579             :         /* Set Member ship */
    2580       29702 :         case SQL_IN:
    2581             :         case SQL_NOT_IN:
    2582       29702 :                 return rel_in_value_exp(query, rel, sc, f);
    2583        1071 :         case SQL_EXISTS:
    2584             :         case SQL_NOT_EXISTS:
    2585        1071 :                 return rel_exists_value_exp(query, rel, sc, f);
    2586         347 :         case SQL_LIKE:
    2587             :         case SQL_NOT_LIKE:
    2588             :         {
    2589         347 :                 symbol *lo = sc->data.lval->h->data.sym;
    2590         347 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2591         347 :                 int insensitive = sc->data.lval->h->next->next->data.i_val;
    2592         347 :                 int anti = (sc->token == SQL_NOT_LIKE) != (sc->data.lval->h->next->next->next->data.i_val != 0);
    2593         347 :                 sql_subtype *st = sql_bind_localtype("str");
    2594         347 :                 sql_exp *le = rel_value_exp(query, rel, lo, f|sql_farg, ek), *re, *ee = NULL, *ie = exp_atom_bool(sql->sa, insensitive);
    2595             : 
    2596         347 :                 if (!le)
    2597             :                         return NULL;
    2598             : 
    2599         347 :                 if (!exp_subtype(le))
    2600           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameter not allowed on "
    2601             :                                         "left hand side of LIKE operator");
    2602             : 
    2603         347 :                 lo = ro->data.lval->h->data.sym;
    2604             :                 /* like uses a single string pattern */
    2605         347 :                 ek.card = card_value;
    2606         347 :                 re = rel_value_exp(query, rel, lo, f|sql_farg, ek);
    2607         347 :                 if (!re)
    2608             :                         return NULL;
    2609         343 :                 if ((re = exp_check_type(sql, st, rel ? *rel : NULL, re, type_equal)) == NULL)
    2610           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
    2611         343 :                 if ((le = exp_check_type(sql, st, rel ? *rel : NULL, le, type_equal)) == NULL)
    2612           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
    2613             :                 /* Do we need to escape ? */
    2614         343 :                 if (dlist_length(ro->data.lval) == 2) {
    2615          63 :                         char *escape = ro->data.lval->h->next->data.sval;
    2616          63 :                         ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, escape)));
    2617             :                 } else {
    2618         280 :                         ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, "")));
    2619             :                 }
    2620         573 :                 return rel_nop_(sql, rel ? *rel : NULL, le, re, ee, ie, "sys", anti ? "not_like" : "like", card_value);
    2621             :         }
    2622         164 :         case SQL_BETWEEN:
    2623             :         case SQL_NOT_BETWEEN:
    2624             :         {
    2625         164 :                 symbol *lo = sc->data.lval->h->data.sym;
    2626         164 :                 int symmetric = sc->data.lval->h->next->data.i_val;
    2627         164 :                 symbol *ro1 = sc->data.lval->h->next->next->data.sym;
    2628         164 :                 symbol *ro2 = sc->data.lval->h->next->next->next->data.sym;
    2629         164 :                 sql_exp *le, *re1, *re2;
    2630         164 :                 sql_subtype super;
    2631             : 
    2632         164 :                 assert(sc->data.lval->h->next->type == type_int);
    2633             : 
    2634         164 :                 if (!(le = rel_value_exp(query, rel, lo, f|sql_farg, ek)))
    2635             :                         return NULL;
    2636         163 :                 if (!(re1 = rel_value_exp(query, rel, ro1, f|sql_farg, ek)))
    2637             :                         return NULL;
    2638         160 :                 if (!(re2 = rel_value_exp(query, rel, ro2, f|sql_farg, ek)))
    2639             :                         return NULL;
    2640             : 
    2641         155 :                 if (exp_between_check_types(&super, exp_subtype(le), exp_subtype(re1), exp_subtype(re2)) < 0)
    2642           0 :                         return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
    2643             : 
    2644         155 :                 if ((le = exp_check_type(sql, &super, rel ? *rel:NULL, le, type_equal)) == NULL ||
    2645         155 :                     (re1 = exp_check_type(sql, &super, rel ? *rel:NULL, re1, type_equal)) == NULL ||
    2646         155 :                     (re2 = exp_check_type(sql, &super, rel ? *rel:NULL, re2, type_equal)) == NULL)
    2647           0 :                         return NULL;
    2648             : 
    2649         155 :                 le = exp_compare2(sql->sa, le, re1, re2, 3, symmetric);
    2650         155 :                 if (sc->token == SQL_NOT_BETWEEN)
    2651          56 :                         set_anti(le);
    2652             :                 return le;
    2653             :         }
    2654       16276 :         case SQL_IS_NULL:
    2655             :         case SQL_IS_NOT_NULL:
    2656             :         /* is (NOT) NULL */
    2657             :         {
    2658       16276 :                 sql_exp *le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
    2659             : 
    2660       16276 :                 if (!le)
    2661             :                         return NULL;
    2662       20526 :                 le = rel_unop_(sql, rel ? *rel : NULL, le, "sys", sc->token == SQL_IS_NULL ? "isnull" : "isnotnull", card_value);
    2663       16273 :                 if (!le)
    2664             :                         return NULL;
    2665       16273 :                 set_has_no_nil(le);
    2666       16273 :                 return le;
    2667             :         }
    2668       18890 :         case SQL_NOT: {
    2669       18890 :                 if (not_symbol_can_be_propagated(sql, sc->data.sym)) {
    2670          98 :                         sc->data.sym = negate_symbol_tree(sql, sc->data.sym);
    2671          98 :                         return rel_logical_value_exp(query, rel, sc->data.sym, f, ek);
    2672             :                 }
    2673       18792 :                 sql_exp *le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
    2674             : 
    2675       18792 :                 if (!le)
    2676             :                         return NULL;
    2677       18791 :                 return rel_unop_(sql, rel ? *rel : NULL, le, "sys", "not", card_value);
    2678             :         }
    2679             :         case SQL_ATOM: {
    2680     2279879 :                 AtomNode *an = (AtomNode *) sc;
    2681     2279879 :                 assert(an && an->a);
    2682     2279879 :                 return exp_atom(sql->sa, an->a);
    2683             :         }
    2684       20378 :         case SQL_IDENT:
    2685             :         case SQL_COLUMN:
    2686       20378 :                 return rel_column_ref(query, rel, sc, f);
    2687         201 :         case SQL_UNION:
    2688             :         case SQL_EXCEPT:
    2689             :         case SQL_INTERSECT: {
    2690         201 :                 sql_rel *sq;
    2691             : 
    2692         201 :                 if (is_psm_call(f) || is_sql_merge(f))
    2693           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: subqueries not supported inside %s", is_psm_call(f) ? "CALL" : "MERGE", is_psm_call(f) ? "CALL statements" : "MERGE conditions");
    2694         199 :                 if (rel && *rel)
    2695         141 :                         query_push_outer(query, *rel, f);
    2696         199 :                 sq = rel_setquery(query, sc);
    2697         199 :                 if (rel && *rel) {
    2698         141 :                         *rel = query_pop_outer(query);
    2699         141 :                         if (is_sql_join(f) && is_groupby((*rel)->op)) {
    2700           0 :                                 return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
    2701         141 :                         } else if (is_sql_where(f) && is_groupby((*rel)->op)) {
    2702           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
    2703         141 :                         } else if ((is_sql_update_set(f) || is_sql_psm(f)) && is_groupby((*rel)->op)) {
    2704           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
    2705             :                         }
    2706             :                 }
    2707         199 :                 if (!sq)
    2708             :                         return NULL;
    2709         197 :                 if (ek.type == type_value && ek.card <= card_set && is_project(sq->op) && list_length(sq->exps) > 1)
    2710           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
    2711         196 :                 if (ek.type == type_relation && is_project(sq->op) && list_length(sq->exps) != ek.type)
    2712           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery has too %s columns", list_length(sq->exps) < ek.type ? "few" : "many");
    2713         302 :                 if (ek.type == type_value && ek.card < card_set && sq->card >= CARD_AGGR && (is_sql_sel(f) | is_sql_having(f) | is_sql_farg(f) |
    2714         106 :                         ( is_sql_where(f) && rel && (!*rel || is_basetable((*rel)->op) || is_simple_project((*rel)->op) || is_joinop((*rel)->op)))))
    2715         106 :                         sq = rel_zero_or_one(sql, sq, ek);
    2716         196 :                 return exp_rel(sql, sq);
    2717             :         }
    2718           1 :         case SQL_DEFAULT:
    2719           1 :                 return sql_error(sql, 02, SQLSTATE(42000) "DEFAULT keyword not allowed outside insert and update statements");
    2720         315 :         default: {
    2721         315 :                 sql_exp *le = rel_value_exp(query, rel, sc, f|sql_farg, ek);
    2722         315 :                 sql_subtype bt;
    2723             : 
    2724         315 :                 if (!le)
    2725             :                         return NULL;
    2726         313 :                 sql_find_subtype(&bt, "boolean", 0, 0);
    2727         313 :                 if ((le = exp_check_type(sql, &bt, rel ? *rel : NULL, le, type_equal)) == NULL)
    2728             :                         return NULL;
    2729         313 :                 return rel_binop_(sql, rel ? *rel : NULL, le, exp_atom_bool(sql->sa, 1), "sys", "=", 0, true);
    2730             :         }
    2731             :         }
    2732             :         /* never reached, as all switch cases have a `return` */
    2733             : }
    2734             : 
    2735             : sql_rel *
    2736      629838 : rel_logical_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
    2737             : {
    2738      629838 :         mvc *sql = query->sql;
    2739      629838 :         exp_kind ek = {type_value, card_column, TRUE};
    2740             : 
    2741      629838 :         if (!sc)
    2742             :                 return NULL;
    2743             : 
    2744      629838 :         if (mvc_highwater(sql))
    2745           0 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    2746             : 
    2747      629838 :         switch (sc->token) {
    2748       18945 :         case SQL_OR:
    2749             :         {
    2750       18945 :                 list *exps = NULL, *lexps = NULL, *rexps = NULL;
    2751       18945 :                 symbol *lo = sc->data.lval->h->data.sym;
    2752       18945 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2753       18945 :                 sql_rel *lr, *rr;
    2754             : 
    2755       18945 :                 if (!rel)
    2756             :                         return NULL;
    2757             : 
    2758       18945 :                 lr = rel;
    2759       18945 :                 rr = rel_dup(lr);
    2760             : 
    2761       18945 :                 if (is_outerjoin(rel->op) && !is_processed(rel)) {
    2762          44 :                         exps = rel->exps;
    2763             : 
    2764          44 :                         lr = rel_select_copy(sql->sa, lr, sa_list(sql->sa));
    2765          44 :                         lr = rel_logical_exp(query, lr, lo, f | sql_or);
    2766          44 :                         if (!lr)
    2767             :                                 return NULL;
    2768          43 :                         query_processed(query);
    2769          43 :                         rr = rel_select_copy(sql->sa, rr, sa_list(sql->sa));
    2770          43 :                         rr = rel_logical_exp(query, rr, ro, f | sql_or);
    2771          43 :                         if (!rr)
    2772             :                                 return NULL;
    2773          42 :                         if (lr->l == rr->l) {
    2774          42 :                                 lexps = lr->exps;
    2775          42 :                                 lr = lr->l;
    2776          42 :                                 rexps = rr->exps;
    2777          42 :                                 rr = rr->l;
    2778             :                         }
    2779          42 :                         rel = NULL;
    2780             :                 } else {
    2781       18901 :                         lr = rel_logical_exp(query, lr, lo, f | sql_or);
    2782       18901 :                         if (!lr)
    2783             :                                 return NULL;
    2784       18899 :                         rr = rel_logical_exp(query, rr, ro, f | sql_or);
    2785             :                 }
    2786             : 
    2787       18941 :                 if (!lr || !rr)
    2788             :                         return NULL;
    2789       18941 :                 return rel_or(sql, rel, lr, rr, exps, lexps, rexps);
    2790             :         }
    2791      190961 :         case SQL_AND:
    2792             :         {
    2793      190961 :                 symbol *lo = sc->data.lval->h->data.sym;
    2794      190961 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2795      190961 :                 rel = rel_logical_exp(query, rel, lo, f);
    2796      190961 :                 if (!rel)
    2797             :                         return NULL;
    2798      190954 :                 return rel_logical_exp(query, rel, ro, f);
    2799             :         }
    2800          60 :         case SQL_FILTER:
    2801             :                 /* [ x,..] filter [ y,..] */
    2802             :                 /* todo add anti, [ x,..] NOT filter [ y,...] */
    2803             :                 /* no correlation */
    2804             :         {
    2805          60 :                 dnode *ln = sc->data.lval->h->data.lval->h;
    2806          60 :                 dnode *rn = sc->data.lval->h->next->next->data.lval->h;
    2807          60 :                 dlist *filter_op = sc->data.lval->h->next->data.lval;
    2808          60 :                 char *fname = qname_schema_object(filter_op);
    2809          60 :                 char *sname = qname_schema(filter_op);
    2810          60 :                 list *l, *r;
    2811             : 
    2812          60 :                 l = sa_list(sql->sa);
    2813          60 :                 r = sa_list(sql->sa);
    2814         180 :                 for (; ln; ln = ln->next) {
    2815          60 :                         symbol *sym = ln->data.sym;
    2816             : 
    2817          60 :                         sql_exp *e = rel_value_exp(query, &rel, sym, f|sql_farg, ek);
    2818          60 :                         if (!e)
    2819             :                                 return NULL;
    2820          60 :                         list_append(l, e);
    2821             :                 }
    2822         163 :                 for (; rn; rn = rn->next) {
    2823         103 :                         symbol *sym = rn->data.sym;
    2824             : 
    2825         103 :                         sql_exp *e = rel_value_exp(query, &rel, sym, f|sql_farg, ek);
    2826         103 :                         if (!e)
    2827             :                                 return NULL;
    2828         103 :                         list_append(r, e);
    2829             :                 }
    2830          60 :                 return rel_filter(sql, rel, l, r, sname, fname, 0, f);
    2831             :         }
    2832      347844 :         case SQL_COMPARE:
    2833             :         {
    2834      347844 :                 dnode *n = sc->data.lval->h;
    2835      347844 :                 symbol *lo = n->data.sym;
    2836      347844 :                 symbol *ro = n->next->next->data.sym;
    2837      347844 :                 char *compare_op = n->next->data.sval;
    2838      347844 :                 int quantifier = 0;
    2839      347844 :                 int is_semantics = 0;
    2840      347844 :                 bool is_distinct_from = false;
    2841             : 
    2842      347844 :                 if (n->next->next->next)
    2843         131 :                         quantifier = n->next->next->next->data.i_val + 1;
    2844         131 :                 assert(quantifier == 0 || quantifier == 1 || quantifier == 2 || quantifier == 3 || quantifier == 4);
    2845             : 
    2846      347844 :                 if (quantifier >= 3) {
    2847          10 :                         if (quantifier == 4) {
    2848           6 :                                 is_distinct_from = true;
    2849           6 :                                 compare_op = "<>";
    2850             :                         }
    2851             :                         quantifier = 0;
    2852             :                         is_semantics = 1;
    2853             :                 }
    2854      347844 :                 if (is_distinct_from) {
    2855           6 :                         sql_exp* ls = rel_value_exp(query, &rel, lo, f|sql_farg, ek);
    2856           6 :                         if (!ls)
    2857             :                                 return NULL;
    2858           6 :                         sql_exp* rs = rel_value_exp(query, &rel, ro, f|sql_farg, ek);
    2859           6 :                         if (!rs)
    2860             :                                 return NULL;
    2861             : 
    2862           6 :                         bool ls_is_non_null_atom = exp_is_atom(ls) && exp_is_not_null(ls);
    2863           6 :                         bool rs_is_non_null_atom = exp_is_atom(rs) && exp_is_not_null(rs);
    2864             : 
    2865           6 :                         if (ls_is_non_null_atom || rs_is_non_null_atom) {
    2866           4 :                                 sql_rel *r = rel_dup(rel);
    2867           4 :                                 sql_rel* l = rel_compare(query, rel, sc, lo, ro, compare_op, f | sql_or, ek, quantifier, 0);
    2868           4 :                                 if (!l)
    2869             :                                         return NULL;
    2870           3 :                                 sql_subtype *t;
    2871           5 :                                 if (!(t = exp_subtype(rs_is_non_null_atom?ls:rs)))
    2872           0 :                                         return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter for IS NULL operator");
    2873           3 :                                 sql_exp* e = exp_compare(sql->sa, rs_is_non_null_atom?ls:rs, exp_atom(sql->sa, atom_general(sql->sa, t, NULL, 0)), cmp_equal);
    2874           3 :                                 set_has_no_nil(e);
    2875           3 :                                 set_semantics(e);
    2876             : 
    2877           3 :                                 r = rel_select_push_compare_exp_down(sql, r, e, e->l, e->r, NULL, f | sql_or);
    2878           3 :                                 if (!r)
    2879             :                                         return NULL;
    2880           3 :                                 return rel_or(sql, rel, l, r, NULL, NULL, NULL);
    2881             :                         }
    2882             :                 }
    2883             : 
    2884             :                 /* [NOT] DISTINCT FROM */
    2885      347840 :                 return rel_compare(query, rel, sc, lo, ro, compare_op, f, ek, quantifier, is_semantics);
    2886             :         }
    2887             :         /* Set Member ship */
    2888       32521 :         case SQL_IN:
    2889             :         case SQL_NOT_IN:
    2890       32521 :                 return rel_in_exp(query, rel, sc, f);
    2891         986 :         case SQL_EXISTS:
    2892             :         case SQL_NOT_EXISTS:
    2893         986 :                 return rel_exists_exp(query, rel , sc, f);
    2894        3293 :         case SQL_LIKE:
    2895             :         case SQL_NOT_LIKE:
    2896             :         {
    2897        3293 :                 symbol *lo = sc->data.lval->h->data.sym;
    2898        3293 :                 symbol *ro = sc->data.lval->h->next->data.sym;
    2899        3293 :                 int insensitive = sc->data.lval->h->next->next->data.i_val;
    2900        3293 :                 int anti = (sc->token == SQL_NOT_LIKE) != (sc->data.lval->h->next->next->next->data.i_val != 0);
    2901        3293 :                 sql_subtype *st = sql_bind_localtype("str");
    2902        3293 :                 sql_exp *le = rel_value_exp(query, &rel, lo, f|sql_farg, ek), *re, *ee = NULL, *ie = exp_atom_bool(sql->sa, insensitive);
    2903             : 
    2904        3293 :                 if (!le)
    2905             :                         return NULL;
    2906             : 
    2907        3291 :                 if (!exp_subtype(le))
    2908           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameter not allowed on "
    2909             :                                         "left hand side of LIKE operator");
    2910             : 
    2911             :                 /* Do we need to escape ? */
    2912        3291 :                 if (dlist_length(ro->data.lval) == 2) {
    2913          82 :                         char *escape = ro->data.lval->h->next->data.sval;
    2914          82 :                         ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, escape)));
    2915             :                 } else {
    2916        3209 :                         ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, "")));
    2917             :                 }
    2918        3291 :                 ro = ro->data.lval->h->data.sym;
    2919        3291 :                 re = rel_value_exp(query, &rel, ro, f|sql_farg, ek);
    2920        3291 :                 if (!re)
    2921             :                         return NULL;
    2922        3290 :                 if ((re = exp_check_type(sql, st, rel, re, type_equal)) == NULL)
    2923           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
    2924        3290 :                 if ((le = exp_check_type(sql, st, rel, le, type_equal)) == NULL)
    2925           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
    2926        3290 :                 return rel_filter_exp_(sql, rel, le, re, ee, ie, "like", anti, f);
    2927             :         }
    2928        2960 :         case SQL_BETWEEN:
    2929             :         case SQL_NOT_BETWEEN:
    2930             :         {
    2931        2960 :                 symbol *lo = sc->data.lval->h->data.sym;
    2932        2960 :                 int symmetric = sc->data.lval->h->next->data.i_val;
    2933        2960 :                 symbol *ro1 = sc->data.lval->h->next->next->data.sym;
    2934        2960 :                 symbol *ro2 = sc->data.lval->h->next->next->next->data.sym;
    2935        2960 :                 sql_exp *le, *re1, *re2;
    2936        2960 :                 sql_subtype super;
    2937             : 
    2938        2960 :                 assert(sc->data.lval->h->next->type == type_int);
    2939             : 
    2940        2960 :                 if (!(le = rel_value_exp(query, &rel, lo, f|sql_farg, ek)))
    2941             :                         return NULL;
    2942        2958 :                 if (!(re1 = rel_value_exp(query, &rel, ro1, f|sql_farg, ek)))
    2943             :                         return NULL;
    2944        2956 :                 if (!(re2 = rel_value_exp(query, &rel, ro2, f|sql_farg, ek)))
    2945             :                         return NULL;
    2946             : 
    2947        2956 :                 if (exp_between_check_types(&super, exp_subtype(le), exp_subtype(re1), exp_subtype(re2)) < 0)
    2948           1 :                         return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
    2949             : 
    2950        2955 :                 if ((le = exp_check_type(sql, &super, rel, le, type_equal)) == NULL ||
    2951        2955 :                     (re1 = exp_check_type(sql, &super, rel, re1, type_equal)) == NULL ||
    2952        2955 :                     (re2 = exp_check_type(sql, &super, rel, re2, type_equal)) == NULL)
    2953           1 :                         return NULL;
    2954             : 
    2955        2954 :                 return rel_compare_exp_(query, rel, le, re1, re2, 3, sc->token == SQL_NOT_BETWEEN ? 1 : 0, 0, f, symmetric, 0);
    2956             :         }
    2957       10558 :         case SQL_IS_NULL:
    2958             :         case SQL_IS_NOT_NULL:
    2959             :         /* is (NOT) NULL */
    2960             :         {
    2961       10558 :                 sql_exp *le = rel_value_exp(query, &rel, sc->data.sym, f|sql_farg, ek);
    2962       10558 :                 sql_subtype *t;
    2963             : 
    2964       10558 :                 if (!le)
    2965             :                         return NULL;
    2966       10554 :                 if (!(t = exp_subtype(le)))
    2967           1 :                         return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for IS%s NULL operator", sc->token == SQL_IS_NOT_NULL ? " NOT" : "");
    2968       10553 :                 le = exp_compare(sql->sa, le, exp_atom(sql->sa, atom_general(sql->sa, t, NULL, 0)), cmp_equal);
    2969       10553 :                 if (sc->token == SQL_IS_NOT_NULL)
    2970        2561 :                         set_anti(le);
    2971       10553 :                 set_has_no_nil(le);
    2972       10553 :                 set_semantics(le);
    2973       10553 :                 return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
    2974             :         }
    2975       20038 :         case SQL_NOT: {
    2976       20038 :                 if (not_symbol_can_be_propagated(sql, sc->data.sym)) {
    2977        2329 :                         sc->data.sym = negate_symbol_tree(sql, sc->data.sym);
    2978        2329 :                         return rel_logical_exp(query, rel, sc->data.sym, f);
    2979             :                 }
    2980       17709 :                 sql_exp *le = rel_value_exp(query, &rel, sc->data.sym, f|sql_farg, ek);
    2981       17709 :                 sql_subtype bt;
    2982             : 
    2983       17709 :                 sql_find_subtype(&bt, "boolean", 0, 0);
    2984       17709 :                 if (!le || !(le = exp_check_type(sql, &bt, rel, le, type_equal)))
    2985           1 :                         return NULL;
    2986       17708 :                 le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 0), cmp_equal);
    2987       17708 :                 return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
    2988             :         }
    2989         626 :         case SQL_ATOM: {
    2990             :                 /* TRUE or FALSE */
    2991         626 :                 sql_rel *or = rel;
    2992         626 :                 AtomNode *an = (AtomNode *) sc;
    2993         626 :                 sql_exp *e = exp_atom(sql->sa, an->a);
    2994             : 
    2995         626 :                 if (e) {
    2996         626 :                         sql_subtype bt;
    2997             : 
    2998         626 :                         sql_find_subtype(&bt, "boolean", 0, 0);
    2999         626 :                         e = exp_check_type(sql, &bt, rel, e, type_equal);
    3000             :                 }
    3001         626 :                 if (!e || or != rel)
    3002           1 :                         return NULL;
    3003         625 :                 e = exp_compare(sql->sa, e, exp_atom_bool(sql->sa, 1), cmp_equal);
    3004         625 :                 return rel_select_push_compare_exp_down(sql, rel, e, e->l, e->r, NULL, f);
    3005             :         }
    3006         708 :         case SQL_IDENT:
    3007             :         case SQL_COLUMN: {
    3008         708 :                 sql_rel *or = rel;
    3009         708 :                 sql_exp *e = rel_column_ref(query, &rel, sc, f);
    3010             : 
    3011         708 :                 if (e) {
    3012         705 :                         sql_subtype bt;
    3013             : 
    3014         705 :                         sql_find_subtype(&bt, "boolean", 0, 0);
    3015         705 :                         e = exp_check_type(sql, &bt, rel, e, type_equal);
    3016             :                 }
    3017         705 :                 if (!e || or != rel)
    3018           3 :                         return NULL;
    3019         705 :                 e = exp_compare(sql->sa, e, exp_atom_bool(sql->sa, 1), cmp_equal);
    3020         705 :                 return rel_select_push_compare_exp_down(sql, rel, e, e->l, e->r, NULL, f);
    3021             :         }
    3022          12 :         case SQL_UNION:
    3023             :         case SQL_EXCEPT:
    3024             :         case SQL_INTERSECT: {
    3025          12 :                 sql_rel *sq;
    3026             : 
    3027          12 :                 if (is_psm_call(f) || is_sql_merge(f))
    3028           3 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: set operations not supported inside %s", is_psm_call(f) ? "CALL" : "MERGE", is_psm_call(f) ? "CALL statements" : "MERGE conditions");
    3029          11 :                 if (rel)
    3030          11 :                         query_push_outer(query, rel, f);
    3031          11 :                 sq = rel_setquery(query, sc);
    3032          11 :                 if (rel) {
    3033          11 :                         rel = query_pop_outer(query);
    3034          11 :                         if (is_sql_join(f) && is_groupby(rel->op)) {
    3035           0 :                                 return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
    3036          11 :                         } else if (is_sql_where(f) && is_groupby(rel->op)) {
    3037           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
    3038          11 :                         } else if ((is_sql_update_set(f) || is_sql_psm(f)) && is_groupby(rel->op)) {
    3039           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
    3040             :                         }
    3041             :                 }
    3042          11 :                 if (!sq)
    3043             :                         return NULL;
    3044          11 :                 assert(ek.type == type_value); /* I don't expect IN tuple matching calls to land here */
    3045          11 :                 if (is_sql_where(f) && is_groupby(rel->op))
    3046           0 :                         assert(0);
    3047          11 :                 if (ek.card <= card_set && is_project(sq->op) && list_length(sq->exps) > 1)
    3048           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
    3049          10 :                 if (!rel)
    3050             :                         return sq;
    3051          10 :                 sq = rel_zero_or_one(sql, sq, ek);
    3052          10 :                 if (is_sql_where(f) || is_sql_having(f)) {
    3053          10 :                         sql_exp *le = exp_rel(sql, sq);
    3054          10 :                         sql_subtype bt;
    3055             : 
    3056          10 :                         sql_find_subtype(&bt, "boolean", 0, 0);
    3057          10 :                         le = exp_check_type(sql, &bt, rel, le, type_equal);
    3058          10 :                         if (!le)
    3059             :                                 return NULL;
    3060          10 :                         le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 1), cmp_equal);
    3061          10 :                         return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
    3062             :                 } else {
    3063           0 :                         sq = rel_crossproduct(sql->sa, rel, sq, (f==sql_sel || is_single(sq))?op_left:op_join);
    3064           0 :                         set_processed(sq);
    3065             :                 }
    3066           0 :                 return sq;
    3067             :         }
    3068           0 :         case SQL_DEFAULT:
    3069           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "DEFAULT keyword not allowed outside insert and update statements");
    3070         326 :         default: {
    3071         326 :                 sql_exp *le = rel_value_exp(query, &rel, sc, f|sql_farg, ek);
    3072         326 :                 sql_subtype bt;
    3073             : 
    3074         326 :                 if (!le)
    3075             :                         return NULL;
    3076         301 :                 if (le && (!is_compare(le->type) || le->flag > cmp_filter)) {
    3077         288 :                         sql_find_subtype(&bt, "boolean", 0, 0);
    3078         288 :                         if (!(le = exp_check_type(sql, &bt, rel, le, type_equal)))
    3079             :                                 return NULL;
    3080         288 :                         le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 1), cmp_equal);
    3081             :                 }
    3082         301 :                 if (le->flag == cmp_filter)
    3083          12 :                         return rel_select_push_filter_exp_down(sql, rel, le, le->l, le->r, f);
    3084             :                 else
    3085         289 :                         return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, le->f, f);
    3086             :         }
    3087             :         }
    3088             :         /* never reached, as all switch cases have a `return` */
    3089             : }
    3090             : 
    3091             : static sql_exp * _rel_aggr(sql_query *query, sql_rel **rel, int distinct, char *sname, char *aname, dnode *arguments, int f);
    3092             : static sql_exp *rel_aggr(sql_query *query, sql_rel **rel, symbol *se, int f);
    3093             : 
    3094             : static sql_exp *
    3095        1826 : rel_op(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek )
    3096             : {
    3097        1826 :         mvc *sql = query->sql;
    3098        1826 :         dnode *l = se->data.lval->h;
    3099        1826 :         char *fname = qname_schema_object(l->data.lval);
    3100        1826 :         char *sname = qname_schema(l->data.lval);
    3101             : 
    3102        1826 :         if (find_func(sql, sname, fname, 0, F_AGGR, false, NULL, NULL))
    3103           0 :                 return _rel_aggr(query, rel, 0, sname, fname, NULL, f);
    3104        1826 :         sql->session->status = 0; /* if the function was not found clean the error */
    3105        1826 :         sql->errstr[0] = '\0';
    3106        1826 :         return rel_op_(sql, sname, fname, ek);
    3107             : }
    3108             : 
    3109             : sql_exp *
    3110       94481 : rel_unop_(mvc *sql, sql_rel *rel, sql_exp *e, char *sname, char *fname, int card)
    3111             : {
    3112       94481 :         bool found = false;
    3113       94481 :         sql_subtype *t = exp_subtype(e);
    3114       94481 :         sql_ftype type = (card == card_loader)?F_LOADER:((card == card_none)?F_PROC:
    3115             :                    ((card == card_relation)?F_UNION:F_FUNC));
    3116             : 
    3117       94481 :         sql_subfunc *f = bind_func(sql, sname, fname, t, NULL, 1, type, false, &found, false);
    3118       94481 :         if (f && !f->func->vararg) {
    3119       94410 :                 sql_arg *a = f->func->ops->h->data;
    3120       94410 :                 t = &a->type;
    3121             :         }
    3122       94481 :         if (f && t && type_has_tz(t) && f->func->fix_scale == SCALE_FIX) {
    3123             :                 /* set timezone (using msec (.3)) */
    3124           0 :                 sql_subtype *intsec = sql_bind_subtype(sql->sa, "sec_interval", 10 /*hour to second */, 3);
    3125           0 :                 atom *a = atom_int(sql->sa, intsec, sql->timezone);
    3126           0 :                 sql_exp *tz = exp_atom(sql->sa, a);
    3127             : 
    3128           0 :                 e = rel_binop_(sql, rel, e, tz, "sys", "sql_add", card, true);
    3129           0 :                 if (!e)
    3130             :                         return NULL;
    3131             :         }
    3132       94459 :         if (f) {
    3133       94411 :                 if (check_card(card, f)) {
    3134       94411 :                         list *args = list_append(sa_list(sql->sa), e);
    3135       94411 :                         if (!f->func->vararg)
    3136      188820 :                                 args = check_arguments_and_find_largest_any_type(sql, rel, args, f, card == card_relation && e->card > CARD_ATOM, false);
    3137       94411 :                         if (args)
    3138       94411 :                                 return exp_op(sql->sa, args, f);
    3139             :                 }
    3140           0 :                 found = false; /* reset found */
    3141           0 :                 f = NULL;
    3142             :         }
    3143             :         /* reset error */
    3144          70 :         sql->session->status = 0;
    3145          70 :         sql->errstr[0] = '\0';
    3146         209 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s unary operator %s%s%s'%s'(%s)",
    3147         139 :                                          found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname, t ? t->type->base.name : "?");
    3148             : }
    3149             : 
    3150             : static sql_exp *
    3151       77585 : rel_unop(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
    3152             : {
    3153       77585 :         mvc *sql = query->sql;
    3154       77585 :         dnode *l = se->data.lval->h;
    3155       77585 :         char *fname = qname_schema_object(l->data.lval);
    3156       77585 :         char *sname = qname_schema(l->data.lval);
    3157       77585 :         exp_kind iek = {type_value, card_column, FALSE};
    3158       77585 :         sql_exp *e = NULL;
    3159             : 
    3160       77585 :         if (find_func(sql, sname, fname, 1, F_AGGR, false, NULL, NULL))
    3161       18935 :                 return rel_aggr(query, rel, se, f);
    3162             : 
    3163       58650 :         sql->session->status = 0; /* if the function was not found clean the error */
    3164       58650 :         sql->errstr[0] = '\0';
    3165       58650 :         if (!(e = rel_value_exp(query, rel, l->next->next->data.sym, f|sql_farg, iek)))
    3166             :                 return NULL;
    3167       58636 :         return rel_unop_(sql, rel ? *rel : NULL, e, sname, fname, ek.card);
    3168             : }
    3169             : 
    3170             : sql_exp *
    3171      522588 : rel_binop_(mvc *sql, sql_rel *rel, sql_exp *l, sql_exp *r, char *sname, char *fname, int card, bool exact)
    3172             : {
    3173      522588 :         sql_subtype *t1 = exp_subtype(l), *t2 = exp_subtype(r);
    3174      522588 :         sql_ftype type = (card == card_loader)?F_LOADER:((card == card_none)?F_PROC:((card == card_relation)?F_UNION:F_FUNC));
    3175      522588 :         bool found = false;
    3176             : 
    3177      522588 :         if (card == card_loader)
    3178           0 :                 card = card_none;
    3179             : 
    3180      522588 :         if (is_commutative(sname, fname) && l->card < r->card) { /* move constants to the right if possible */
    3181             :                 sql_subtype *tmp = t1;
    3182      522588 :                 t1 = t2;
    3183      522588 :                 t2 = tmp;
    3184             :                 sql_exp *res = l;
    3185      522588 :                 l = r;
    3186      522588 :                 r = res;
    3187             :         }
    3188             :         /* swap complex types (intervals) to left side of +, * */
    3189      522588 :         if (t1 && t2 && is_commutative(sname, fname)) {
    3190      121289 :                 if ((EC_INTERVAL(t1->type->eclass) && EC_TEMP(t2->type->eclass)) ||
    3191      121287 :            ((!EC_TEMP(t1->type->eclass) && !EC_INTERVAL(t1->type->eclass)) && EC_INTERVAL(t2->type->eclass))) {
    3192             :                         sql_subtype *tmp = t1;
    3193      522588 :                         t1 = t2;
    3194      522588 :                         t2 = tmp;
    3195             :                         sql_exp *res = l;
    3196      522588 :                         l = r;
    3197      522588 :                         r = res;
    3198             :                 }
    3199             :         }
    3200             : 
    3201      522588 :         sql_subfunc *f = bind_func(sql, sname, fname, t1, t2, 2, type, false, &found, exact);
    3202      522588 :         if (f && check_card(card,f)) {
    3203      522426 :                 t1 = exp_subtype(l);
    3204      522426 :                 t2 = exp_subtype(r);
    3205      522426 :                 list *args = list_append(list_append(sa_list(sql->sa), l), r);
    3206      522426 :                 if (!f->func->vararg)
    3207      522425 :                         args = check_arguments_and_find_largest_any_type(sql, rel, args, f, 0, false);
    3208      522426 :                 if (args)
    3209      522424 :                                 return exp_op(sql->sa, args, f);
    3210             :                 return NULL;
    3211             :         }
    3212             : 
    3213         162 :         if (!exp_subtype(l) || !exp_subtype(r))
    3214           0 :                 return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
    3215         162 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s binary operator %s%s%s'%s'(%s,%s)",
    3216         162 :                                          found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname,
    3217         162 :                                          exp_subtype(l)->type->base.name, exp_subtype(r)->type->base.name);
    3218             : }
    3219             : 
    3220             : static sql_exp *
    3221      373833 : rel_binop(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
    3222             : {
    3223      373833 :         mvc *sql = query->sql;
    3224      373833 :         dnode *dl = se->data.lval->h;
    3225      373833 :         sql_exp *l, *r;
    3226      373833 :         char *fname = qname_schema_object(dl->data.lval);
    3227      373833 :         char *sname = qname_schema(dl->data.lval);
    3228      373833 :         exp_kind iek = {type_value, card_column, FALSE};
    3229             : 
    3230      373833 :         if (find_func(sql, sname, fname, 2, F_AGGR, false, NULL, NULL))
    3231        4190 :                 return rel_aggr(query, rel, se, f);
    3232             : 
    3233      369643 :         sql->session->status = 0; /* if the function was not found clean the error */
    3234      369643 :         sql->errstr[0] = '\0';
    3235      369643 :         if (!(l = rel_value_exp(query, rel, dl->next->next->data.sym, f|sql_farg, iek)))
    3236             :                 return NULL;
    3237      369614 :         if (!(r = rel_value_exp(query, rel, dl->next->next->next->data.sym, f|sql_farg, iek)))
    3238             :                 return NULL;
    3239      369575 :         return rel_binop_(sql, rel ? *rel : NULL, l, r, sname, fname, ek.card, false);
    3240             : }
    3241             : 
    3242             : sql_exp *
    3243         530 : rel_nop_(mvc *sql, sql_rel *rel, sql_exp *a1, sql_exp *a2, sql_exp *a3, sql_exp *a4, char *sname, char *fname, int card)
    3244             : {
    3245         530 :         list *tl = sa_list(sql->sa);
    3246         530 :         sql_subfunc *f = NULL;
    3247         530 :         sql_ftype type = (card == card_none)?F_PROC:((card == card_relation)?F_UNION:F_FUNC);
    3248             : 
    3249             :         /* rel_nop_ should only be called for functions available to everyone, ie defined at sql_types! */
    3250         530 :         (void) rel;
    3251         530 :         append(tl, exp_subtype(a1));
    3252         530 :         append(tl, exp_subtype(a2));
    3253         530 :         append(tl, exp_subtype(a3));
    3254         530 :         if (a4)
    3255         371 :                 append(tl, exp_subtype(a4));
    3256             : 
    3257         530 :         if (!(f = bind_func_(sql, sname, fname, tl, type, false, NULL, true)))
    3258             :                 return NULL;
    3259         530 :         if (!a4)
    3260         159 :                 return exp_op3(sql->sa, a1,a2,a3,f);
    3261         371 :         return exp_op4(sql->sa, a1,a2,a3,a4,f);
    3262             : }
    3263             : 
    3264             : static sql_func *
    3265           3 : inplace_func(mvc *sql)
    3266             : {
    3267           3 :         sql_func *f = SA_NEW(sql->sa, sql_func);
    3268             : 
    3269           3 :     *f = (sql_func) {
    3270             :         .mod = "",
    3271             :         .imp = "",
    3272             :         .type = F_PROC,
    3273             :         .lang = FUNC_LANG_INT,
    3274             :         .query = NULL,
    3275           3 :         .ops = sql->params,
    3276             :         .res = NULL,
    3277             :     };
    3278           3 :     base_init(sql->sa, &f->base, 0, true, NULL);
    3279           3 :     f->base.new = 1;
    3280           3 :     f->base.id = -1;
    3281           3 :     f->base.name = "-1";
    3282           3 :     f->instantiated = TRUE;
    3283           3 :         return f;
    3284             : }
    3285             : 
    3286             : static list *
    3287           3 : reorder_args(mvc *sql, list *exps, list *names, list *params)
    3288             : {
    3289           3 :         list *nexps = sa_list(sql->sa);
    3290           8 :         for(node *n = params->h; n; n = n->next) {
    3291           5 :                 sql_arg *a = n->data;
    3292           5 :                 int found =0;
    3293           7 :                 for(node *m = names->h, *o = exps->h; m && o; m = m->next, o = o->next) {
    3294           7 :                         if (strcmp(m->data, a->name) == 0) {
    3295           5 :                                 append(nexps, o->data);
    3296           5 :                                 found = 1;
    3297           5 :                                 break;
    3298             :                         }
    3299             :                 }
    3300           5 :                 if (!found)
    3301             :                         return NULL;
    3302             :         }
    3303             :         return nexps;
    3304             : }
    3305             : 
    3306             : static sql_exp *
    3307       84769 : rel_nop(sql_query *query, sql_rel **rel, symbol *se, int fs, exp_kind ek)
    3308             : {
    3309       84769 :         mvc *sql = query->sql;
    3310       84769 :         int nr_args = 0, err = 0;
    3311       84769 :         dnode *l = se->data.lval->h;
    3312       84769 :         dnode *ops = l->next->next->data.lval?l->next->next->data.lval->h:NULL;
    3313       84769 :         list *exps = sa_list(sql->sa), *tl = sa_list(sql->sa);
    3314       84769 :         exp_kind iek = {type_value, card_column, FALSE};
    3315       84769 :         char buf[ERRSIZE];
    3316       84769 :         int split = (l->type == type_int && l->data.i_val == -1);
    3317       84769 :         list *names = NULL;
    3318             : 
    3319           3 :         if (split)
    3320           3 :                 names = sa_list(sql->sa);
    3321      348674 :         for (; ops; ops = ops->next, nr_args++) {
    3322      263905 :                 if (!err) { /* we need the nr_args count at the end, but if an error is found, stop calling rel_value_exp */
    3323      263883 :                         sql_exp *e = rel_value_exp(query, rel, ops->data.sym, fs|sql_farg, iek);
    3324      263883 :                         if (!e) {
    3325           6 :                                 err = sql->session->status;
    3326           6 :                                 strcpy(buf, sql->errstr);
    3327           6 :                                 continue;
    3328             :                         }
    3329      263877 :                         if (split) {
    3330           5 :                                 ops = ops->next;
    3331           5 :                                 append(names, ops->data.sval);
    3332             :                         }
    3333      263877 :                         append(exps, e);
    3334      263877 :                         append(tl, exp_subtype(e));
    3335             :                 }
    3336             :         }
    3337       84769 :         if (l->type == type_int) {
    3338             :                 /* exec nr (ops)*/
    3339        5909 :                 int nr = l->data.i_val;
    3340        5909 :                 cq *q = NULL;
    3341             : 
    3342        5909 :                 if (err)
    3343             :                         return NULL;
    3344        5908 :                 if (nr == -1 || (q = qc_find(sql->qc, nr))) {
    3345        5906 :                         list *nexps = new_exp_list(sql->sa);
    3346        5906 :                         sql_func *f = q?q->f:inplace_func(sql);
    3347        5906 :                         list *ops = q?f->ops:sql->params;
    3348             : 
    3349        5906 :                         tl = sa_list(sql->sa);
    3350        5906 :                         if (list_length(ops) != list_length(exps))
    3351           3 :                                 return sql_error(sql, 02, SQLSTATE(42000) "EXEC called with wrong number of arguments: expected %d, got %d", list_length(ops), list_length(exps));
    3352        5903 :                         if (split) {
    3353           3 :                                 exps = reorder_args(sql, exps, names, ops);
    3354           3 :                                 if (!exps)
    3355           0 :                                         return sql_error(sql, 02, SQLSTATE(42000) "EXEC called with wrong arguments");
    3356             :                         }
    3357        5903 :                         if (exps->h && ops) {
    3358       21927 :                                 for (node *n = exps->h, *m = ops->h; n && m; n = n->next, m = m->next) {
    3359       16115 :                                         sql_arg *a = m->data;
    3360       16115 :                                         sql_exp *e = n->data;
    3361       16115 :                                         sql_subtype *ntp = &a->type;
    3362             : 
    3363       16115 :                                         if (ntp && ntp->type)
    3364       16115 :                                                 e = exp_check_type(sql, ntp, NULL, e, type_equal);
    3365             :                                         else
    3366           0 :                                                 a->type = *exp_subtype(e);
    3367       16115 :                                         if (!e) {
    3368           1 :                                                 err = sql->session->status;
    3369           1 :                                                 strcpy(buf, sql->errstr);
    3370           1 :                                                 break;
    3371             :                                         }
    3372       16114 :                                         append(nexps, e);
    3373       16114 :                                         append(tl, exp_subtype(e));
    3374             :                                 }
    3375             :                         }
    3376             : 
    3377        5903 :                         if (err)
    3378             :                                 return NULL;
    3379        5902 :                         if (q)
    3380        5899 :                                 sql->type = q->type;
    3381        5992 :                         return exp_op(sql->sa, list_empty(nexps) ? NULL : nexps, sql_dup_subfunc(sql->sa, f, tl, NULL));
    3382             :                 } else {
    3383           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "EXEC: PREPARED Statement missing '%d'", nr);
    3384             :                 }
    3385             :         }
    3386       78860 :         char *fname = qname_schema_object(l->data.lval);
    3387       78860 :         char *sname = qname_schema(l->data.lval);
    3388             : 
    3389       78860 :         if (!sname && strcmp(fname, "field") == 0) { /* map into join */
    3390           2 :                 if (err)
    3391           2 :                         return NULL;
    3392           1 :                 if (list_length(exps) < 2)
    3393           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "Field function called with not enough arguments");
    3394           0 :                 sql_exp *le = exps->h->data;
    3395           0 :                 set_freevar(le, 1);
    3396           0 :                 list_remove_data(exps, NULL, le);
    3397           0 :                 sql_exp *re = exp_values(sql->sa, exps);
    3398           0 :                 exp_label(sql->sa, re, ++sql->label);
    3399           0 :                 sql_rel *r = rel_project(sql->sa, NULL, append(sa_list(sql->sa), re));
    3400           0 :                 sql_exp *id = NULL;
    3401           0 :                 rel_add_identity(sql, r, &id);
    3402           0 :                 re = exp_ref(sql, re);
    3403           0 :                 id = exp_ref(sql, id);
    3404           0 :                 if (r) {
    3405           0 :                         r->nrcols = list_length(exps);
    3406           0 :                         sql_exp *e = exp_compare(sql->sa, le, re, cmp_equal);
    3407           0 :                         r = rel_select(sql->sa, r, e);
    3408           0 :                         r = rel_project(sql->sa, r, append(sa_list(sql->sa), exp_convert(sql, id, exp_subtype(id), sql_bind_localtype("int"))));
    3409           0 :                         re = exp_rel(sql, r);
    3410           0 :                         return re;
    3411             :                 }
    3412             :         }
    3413             :         /* first try aggregate */
    3414       78858 :         if (find_func(sql, sname, fname, nr_args, F_AGGR, false, NULL, NULL)) { /* We have to pass the arguments properly, so skip call to rel_aggr */
    3415             :                 /* reset error */
    3416           2 :                 sql->session->status = 0;
    3417           2 :                 sql->errstr[0] = '\0';
    3418           2 :                 return _rel_aggr(query, rel, l->next->data.i_val, sname, fname, l->next->next->data.lval->h, fs);
    3419             :         }
    3420       78856 :         if (err) {
    3421           2 :                 sql->session->status = err;
    3422           2 :                 strcpy(sql->errstr, buf);
    3423           2 :                 return NULL;
    3424             :         }
    3425       78854 :         sql->session->status = 0; /* if the function was not found clean the error */
    3426       78854 :         sql->errstr[0] = '\0';
    3427       78854 :         return _rel_nop(sql, sname, fname, tl, rel ? *rel : NULL, exps, ek);
    3428             : }
    3429             : 
    3430             : typedef struct aggr_input {
    3431             :         sql_query *query;
    3432             :         int groupby;
    3433             :         char *err;
    3434             : } aggr_input;
    3435             : 
    3436             : static sql_exp *
    3437         372 : exp_valid(visitor *v, sql_rel *rel, sql_exp *e, int depth)
    3438             : {
    3439         372 :         aggr_input *ai = v->data;
    3440         372 :         (void)rel; (void)depth;
    3441             : 
    3442         372 :         int vf = is_freevar(e);
    3443         372 :         if (!v->changes && vf && vf < ai->groupby) { /* check need with outer query */
    3444          14 :                 sql_rel *sq = query_fetch_outer(ai->query, vf-1);
    3445             : 
    3446             :                 /* problem freevar have cardinality CARD_ATOM */
    3447          14 :                 if (sq->card <= CARD_AGGR && exp_card(e) != CARD_AGGR && is_alias(e->type)) {
    3448           4 :                         if (!exps_bind_column(sq->exps, e->l, e->r, NULL, 0)) {
    3449           1 :                                 v->changes = 1;
    3450           1 :                                 ai->err = SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query";
    3451             :                         }
    3452             :                 }
    3453         358 :         } else if (!v->changes && vf && vf == ai->groupby) { /* check if input is already aggregated */
    3454         279 :                 sql_rel *sq = query_fetch_outer(ai->query, vf-1);
    3455         279 :                 sql_exp *a = NULL;
    3456             : 
    3457         279 :                 if (sq->card <= CARD_AGGR && is_alias(e->type)) {
    3458         187 :                         if ((a = exps_bind_column(sq->exps, e->l, e->r, NULL, 0)) && is_aggr(a->type)) { /* aggregate */
    3459           9 :                                 v->changes = 1;
    3460           9 :                                 ai->err = SQLSTATE(42000) "SELECT: aggregate function calls cannot be nested";
    3461             :                         }
    3462             :                 }
    3463             :         }
    3464         372 :         return e;
    3465             : }
    3466             : 
    3467             : static char *
    3468         272 : exps_valid(sql_query *query, list *exps, int groupby)
    3469             : {
    3470         272 :         aggr_input ai = { .query = query, .groupby = groupby };
    3471         272 :         visitor v = { .sql = query->sql, .data = &ai };
    3472             : 
    3473         272 :         exps_exp_visitor_topdown(&v, NULL, exps, 0, &exp_valid, true);
    3474         272 :         if (v.changes)
    3475          10 :                 return ai.err;
    3476             :         return NULL;
    3477             : }
    3478             : 
    3479             : static sql_exp *
    3480       41967 : _rel_aggr(sql_query *query, sql_rel **rel, int distinct, char *sname, char *aname, dnode *args, int f)
    3481             : {
    3482       41967 :         mvc *sql = query->sql;
    3483       41967 :         exp_kind ek = {type_value, card_column, FALSE};
    3484       41967 :         sql_subfunc *a = NULL;
    3485       41967 :         int no_nil = 0, group = 0, all_aggr = query_has_outer(query), i;
    3486       41967 :         unsigned int all_freevar = 0;
    3487       41967 :         sql_rel *groupby = rel ? *rel : NULL, *sel = NULL, *gr, *og = NULL, *res = groupby;
    3488       41967 :         sql_rel *subquery = NULL;
    3489       41967 :         list *exps = NULL, *ungrouped_cols = NULL;
    3490       41967 :         bool is_grouping = !strcmp(aname, "grouping"), has_args = false, found = false, used_rel = false;
    3491             : 
    3492       41967 :         if (!all_aggr) {
    3493       27738 :                 if (!groupby) {
    3494           4 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3495           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: missing group by", toUpperCopy(uaname, aname));
    3496       27734 :                 } else if (is_sql_groupby(f)) {
    3497           8 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3498           8 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate function '%s' not allowed in GROUP BY clause", toUpperCopy(uaname, aname), aname);
    3499       27726 :                 } else if (is_sql_values(f)) {
    3500           1 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3501           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed on an unique value", toUpperCopy(uaname, aname));
    3502       27725 :                 } else if (is_sql_join(f)) { /* the is_sql_join test must come before is_sql_where, because the join conditions are handled with sql_where */
    3503           3 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3504           3 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in JOIN conditions", toUpperCopy(uaname, aname));
    3505       27722 :                 } else if (is_sql_where(f)) {
    3506           4 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3507           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
    3508       27718 :                 } else if (is_sql_update_set(f) || is_sql_psm(f)) {
    3509           1 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3510           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses (use subquery)", toUpperCopy(uaname, aname));
    3511       27717 :                 } else if (is_sql_aggr(f)) {
    3512           4 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3513           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
    3514       27713 :                 } else if (is_psm_call(f)) {
    3515           0 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3516           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed inside CALL", toUpperCopy(uaname, aname));
    3517       27713 :                 } else if (is_sql_from(f)) {
    3518           0 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3519           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in functions in FROM", toUpperCopy(uaname, aname));
    3520             :                 }
    3521             :         }
    3522             : 
    3523       41942 :         exps = sa_list(sql->sa);
    3524       41942 :         if (args && args->data.sym) {
    3525       23217 :                 bool arguments_correlated = true, all_const = true;
    3526             : 
    3527       23217 :                 all_freevar = all_aggr?1:0;
    3528       50646 :                 for (i = 0; args && args->data.sym; args = args->next, i++) {
    3529       27486 :                         int base = (!groupby || !is_project(groupby->op) || is_base(groupby->op) || is_processed(groupby));
    3530       19624 :                         sql_rel *gl = base?groupby:groupby->l, *ogl = gl; /* handle case of subqueries without correlation */
    3531       27486 :                         sql_exp *e = rel_value_exp(query, &gl, args->data.sym, (f | sql_aggr)& ~sql_farg, ek);
    3532       27486 :                         bool found_one_freevar = false;
    3533             : 
    3534       27486 :                         if (!e)
    3535          57 :                                 return NULL;
    3536       27435 :                         used_rel |= (rel_has_exp(gl, e, true) == 0);
    3537       27435 :                         has_args = true;
    3538       27435 :                         if (gl && gl != ogl) {
    3539           5 :                                 if (gl->grouped) {
    3540           5 :                                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3541           5 :                                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
    3542             :                                 }
    3543           0 :                                 if (!base)
    3544           0 :                                         groupby->l = subquery = gl;
    3545             :                                 else
    3546             :                                         groupby = subquery = gl;
    3547             :                         }
    3548       27430 :                         sql_subtype *t = exp_subtype(e);
    3549       27430 :                         if (!t) { /* we also do not expect parameters here */
    3550           1 :                                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3551           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to aggregate functions", toUpperCopy(uaname, aname));
    3552             :                         }
    3553       27429 :                         if (!t->type->localtype) {
    3554          47 :                                 if (e->type == e_atom && !e->f) {
    3555          44 :                                         t = sql_bind_localtype("bte");
    3556          44 :                                         e->tpe = *t;
    3557          44 :                                         if (e->l)
    3558          44 :                                                 e->l = atom_set_type(sql->sa, e->l, t);
    3559             :                                 }
    3560             :                         }
    3561             : 
    3562       27429 :                         all_aggr &= (exp_card(e) <= CARD_AGGR && !exp_is_atom(e) && is_aggr(e->type) && !is_func(e->type) && (!groupby || !is_groupby(groupby->op) || !groupby->r || !exps_find_exp(groupby->r, e)));
    3563       27429 :                         exp_only_freevar(query, e, &arguments_correlated, &found_one_freevar, &ungrouped_cols);
    3564       27429 :                         all_freevar &= (arguments_correlated && found_one_freevar) || (is_atom(e->type)?all_freevar:0); /* no uncorrelated variables must be found, plus at least one correlated variable to push this aggregate to an outer query */
    3565       27429 :                         all_const &= is_atom(e->type);
    3566       27429 :                         list_append(exps, e);
    3567             :                 }
    3568       23160 :                 if (all_const)
    3569         203 :                         all_freevar = 0;
    3570             :         }
    3571       41885 :         if (!all_freevar) {
    3572       41593 :                 if (is_sql_groupby(f)) {
    3573           1 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3574           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate function '%s' not allowed in GROUP BY clause", toUpperCopy(uaname, aname), aname);
    3575       41592 :                 } else if (is_sql_from(f)) {
    3576           2 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3577           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in functions in FROM", toUpperCopy(uaname, aname));
    3578       41590 :                 } else if (is_sql_aggr(f) && groupby->grouped) {
    3579           2 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3580           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
    3581       41588 :                 } else if (is_sql_values(f)) {
    3582           1 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3583           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed on an unique value", toUpperCopy(uaname, aname));
    3584       41587 :                 } else if (is_sql_join(f)) { /* the is_sql_join test must come before is_sql_where, because the join conditions are handled with sql_where */
    3585           1 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3586           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in JOIN conditions", toUpperCopy(uaname, aname));
    3587       41586 :                 } else if (is_sql_where(f)) {
    3588           5 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3589           5 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
    3590       41581 :                 } else if (!all_aggr && !list_empty(ungrouped_cols)) {
    3591         123 :                         for (node *n = ungrouped_cols->h ; n ; n = n->next) {
    3592          66 :                                 sql_rel *outer;
    3593          66 :                                 sql_exp *e = (sql_exp*) n->data;
    3594             : 
    3595          66 :                                 if ((outer = query_fetch_outer(query, is_freevar(e)-1))) {
    3596          66 :                                         int of = query_fetch_outer_state(query, is_freevar(e)-1);
    3597          66 :                                         if (outer->grouped) {
    3598          24 :                                                 bool err = false, was_processed = false;
    3599             : 
    3600          24 :                                                 if (is_processed(outer)) {
    3601           5 :                                                         was_processed = true;
    3602           5 :                                                         reset_processed(outer);
    3603             :                                                 }
    3604          24 :                                                 if (!is_groupby_col(outer, e))
    3605           3 :                                                         err = true;
    3606          24 :                                                 if (was_processed)
    3607           5 :                                                         set_processed(outer);
    3608          24 :                                                 if (err) {
    3609           3 :                                                         if (exp_name(e) && exp_relname(e) && !has_label(e))
    3610           3 :                                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", exp_relname(e), exp_name(e));
    3611           0 :                                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    3612             :                                                 }
    3613          42 :                                         } else if (!used_rel && is_sql_where(of)) {
    3614           2 :                                                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3615           2 :                                                 return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
    3616          40 :                                         } else if (!is_sql_aggr(of)) {
    3617          36 :                                                 set_outer(outer);
    3618             :                                         }
    3619             :                                 }
    3620             :                         }
    3621             :                 }
    3622             :         }
    3623             : 
    3624       41868 :         if (all_freevar) { /* case 2, ie use outer */
    3625         292 :                 int card;
    3626         292 :                 sql_exp *exp = NULL;
    3627             :                 /* find proper groupby relation */
    3628         591 :                 for (node *n = exps->h; n; n = n->next) {
    3629         299 :                         sql_exp *e = n->data;
    3630             : 
    3631         299 :                         int vf = exp_freevar_offset(sql, e);
    3632         299 :                         if (vf > (int)all_freevar)
    3633          23 :                                 all_freevar = vf;
    3634         299 :                         exp = e;
    3635             :                 }
    3636         292 :                 if (query_has_outer(query) >= all_freevar) {
    3637         292 :                         int sql_state = query_fetch_outer_state(query,all_freevar-1);
    3638         292 :                         res = groupby = query_fetch_outer(query, all_freevar-1);
    3639         292 :                         card = query_outer_used_card(query, all_freevar-1);
    3640             :                         /* given groupby validate all input expressions */
    3641         292 :                         char *err;
    3642         292 :                         if (groupby && !is_groupby(groupby->op)) {
    3643         111 :                                 sql_exp *p = query_outer_last_used(query, all_freevar-1);
    3644         111 :                                 if (p && !is_aggr(p->type) && !is_groupby_col(groupby, p)) {
    3645          20 :                                         if (p->type == e_column)
    3646          20 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", (char*)p->l, (char*)p->r);
    3647           0 :                                         if (exp_name(p) && exp_relname(p) && !has_label(p))
    3648           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", exp_relname(p), exp_name(p));
    3649           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    3650             :                                 }
    3651             :                         }
    3652         272 :                         if ((err = exps_valid(query, exps, all_freevar)) != NULL) {
    3653          10 :                                 strcpy(sql->errstr, err);
    3654          10 :                                 sql->session->status = -ERR_GROUPBY;
    3655          10 :                                 return NULL;
    3656             :                         }
    3657         262 :                         if (exp && !is_groupby_col(res, exp)) {
    3658         191 :                                 if (is_sql_groupby(sql_state))
    3659           2 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate function '%s' not allowed in GROUP BY clause", aname);
    3660         189 :                                 if (is_sql_aggr(sql_state) && groupby->grouped) {
    3661           3 :                                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3662           3 :                                         return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
    3663             :                                 }
    3664         186 :                                 if (is_sql_values(sql_state))
    3665           0 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed on an unique value");
    3666         186 :                                 if (is_sql_update_set(sql_state) || is_sql_psm(f))
    3667           2 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
    3668         184 :                                 if (is_sql_join(sql_state))
    3669           4 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
    3670         180 :                                 if (is_sql_where(sql_state))
    3671           3 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
    3672         177 :                                 if (is_psm_call(sql_state))
    3673           0 :                                         return sql_error(sql, 05, SQLSTATE(42000) "CALL: aggregate functions not allowed inside CALL");
    3674         177 :                                 if (is_sql_from(sql_state))
    3675           0 :                                         return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in functions in FROM");
    3676         177 :                                 if (card > CARD_AGGR) { /* used an expression before on the non grouped relation */
    3677           0 :                                         sql_exp *lu = query_outer_last_used(query, all_freevar-1);
    3678           0 :                                         if (lu->type == e_column)
    3679           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", (char*)lu->l, (char*)lu->r);
    3680           0 :                                         if (exp_name(lu) && exp_relname(lu) && !has_label(lu))
    3681           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", exp_relname(lu), exp_name(lu));
    3682           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    3683             :                                 }
    3684         177 :                                 if (is_outer(groupby))
    3685           2 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    3686             :                         }
    3687             :                 } else {
    3688             :                         all_freevar = 0;
    3689             :                 }
    3690       41576 :         } else if (!subquery && groupby && is_outer(groupby) && !is_groupby(groupby->op))
    3691           1 :                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
    3692             : 
    3693             :         /* find having select */
    3694       41821 :         if (!subquery && groupby && !is_processed(groupby) && is_sql_having(f)) {
    3695         104 :                 og = groupby;
    3696         104 :                 while(!is_processed(groupby) && !is_base(groupby->op)) {
    3697          59 :                         if (is_select(groupby->op) || !groupby->l)
    3698             :                                 break;
    3699             :                         if (groupby->l)
    3700             :                                 groupby = groupby->l;
    3701             :                 }
    3702          63 :                 if (groupby && is_select(groupby->op) && !is_processed(groupby)) {
    3703          18 :                         group = 1;
    3704          18 :                         sel = groupby;
    3705             :                         /* At the end we switch back to the old projection relation og.
    3706             :                          * During the partitioning and ordering we add the expressions to the intermediate relations. */
    3707             :                 }
    3708          18 :                 if (!sel)
    3709             :                         groupby = og;
    3710          18 :                 if (sel && sel->l)
    3711          18 :                         groupby = sel->l;
    3712             :         }
    3713             : 
    3714             :         /* find groupby */
    3715       41821 :         if (!subquery && groupby && !is_processed(groupby) && !is_base(groupby->op)) {
    3716       27489 :                 og = groupby;
    3717       27489 :                 groupby = rel_find_groupby(groupby);
    3718       27489 :                 if (groupby)
    3719             :                         group = 1;
    3720             :                 else
    3721             :                         groupby = og;
    3722             :         }
    3723             : 
    3724        7790 :         if (!groupby && exps_card(exps) > CARD_ATOM) {
    3725           0 :                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3726           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: missing group by", toUpperCopy(uaname, aname));
    3727             :         }
    3728             : 
    3729       41821 :         if (!subquery && groupby && groupby->op != op_groupby) {             /* implicit groupby */
    3730       20392 :                 if (!all_freevar && query->last_exp && !is_sql_aggr(query->last_state)) {
    3731           9 :                         if (exp_relname(query->last_exp) && exp_name(query->last_exp) && !has_label(query->last_exp))
    3732           9 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s.%s' in query results without an aggregate function", exp_relname(query->last_exp), exp_name(query->last_exp));
    3733           0 :                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    3734             :                 }
    3735       20383 :                 res = groupby = rel_groupby(sql, groupby, NULL);
    3736             :         }
    3737       41812 :         if (subquery) {
    3738           0 :                 assert(!all_freevar);
    3739           0 :                 res = groupby;
    3740           0 :                 if (is_sql_sel(f) && is_left(subquery->op) && !is_groupby(groupby->op)) {
    3741           0 :                         res = groupby = rel_groupby(sql, groupby, NULL);
    3742           0 :                         exps_set_freevar(sql, exps, groupby); /* mark free variables */
    3743           0 :                 } else if (!is_groupby(groupby->op)) {
    3744           0 :                         res = groupby = rel_groupby(sql, groupby, NULL);
    3745             :                 }
    3746           0 :                 assert(!is_base(groupby->op));
    3747             :         }
    3748       41812 :         if ((!exps || exps_card(exps) > CARD_ATOM) && (!res || !groupby))
    3749             :                 return NULL;
    3750             : 
    3751       41812 :         if (all_freevar) {
    3752         246 :                 query_update_outer(query, res, all_freevar-1);
    3753       41566 :         } else if (rel) {
    3754       41566 :                 *rel = res;
    3755       41566 :                 if (query->last_rel != res) {
    3756       37636 :                         query->last_rel = res;
    3757       37636 :                         query->last_state |= sql_aggr;
    3758             :                 }
    3759             :         }
    3760             : 
    3761       41812 :         if (!has_args) {        /* count(*) case */
    3762       18721 :                 sql_exp *e;
    3763             : 
    3764       18721 :                 if (strcmp(aname, "count") != 0) {
    3765           2 :                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3766           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: unable to perform '%s(*)'", toUpperCopy(uaname, aname), aname);
    3767             :                 }
    3768       18719 :                 a = sql_bind_func(sql, "sys", aname, sql_bind_localtype("void"), NULL, F_AGGR, true, true);
    3769       18719 :                 e = exp_aggr(sql->sa, NULL, a, distinct, 0, groupby?groupby->card:CARD_ATOM, 0);
    3770             : 
    3771       18719 :                 if (!groupby)
    3772             :                         return e;
    3773       18719 :                 if (all_freevar)
    3774           0 :                         query_outer_used_exp(query, all_freevar-1, e, sql_aggr);
    3775       18719 :                 e = rel_groupby_add_aggr(sql, groupby, e);
    3776       18719 :                 if (!group && !all_freevar)
    3777             :                         return e;
    3778        3202 :                 if (all_freevar) {
    3779           0 :                         assert(!is_simple_project(res->op));
    3780           0 :                         e->card = CARD_ATOM;
    3781           0 :                         set_freevar(e, all_freevar-1);
    3782           0 :                         return e;
    3783             :                 }
    3784             :                 return e;
    3785             :         }
    3786             : 
    3787             :         /* use cnt as nils shouldn't be counted */
    3788       23091 :         no_nil = 1;
    3789             : 
    3790       23091 :         gr = groupby;
    3791       23091 :         if (gr && gr->op == op_project && gr->l)
    3792             :                 gr = gr->l;
    3793             : 
    3794       23091 :         if (is_grouping) {
    3795         109 :                 sql_subtype *tpe;
    3796         109 :                 list *l = (list*) groupby->r;
    3797             : 
    3798         109 :                 if (list_length(l) <= 7)
    3799         107 :                         tpe = sql_bind_localtype("bte");
    3800           2 :                 else if (list_length(l) <= 15)
    3801           2 :                         tpe = sql_bind_localtype("sht");
    3802           0 :                 else if (list_length(l) <= 31)
    3803           0 :                         tpe = sql_bind_localtype("int");
    3804           0 :                 else if (list_length(l) <= 63)
    3805           0 :                         tpe = sql_bind_localtype("lng");
    3806             : #ifdef HAVE_HGE
    3807           0 :                 else if (list_length(l) <= 127)
    3808           0 :                         tpe = sql_bind_localtype("hge");
    3809             : #endif
    3810             :                 else
    3811           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: GROUPING the number of grouping columns is larger"
    3812             :                                                                 " than the maximum number of representable bits from this server (%d > %d)", list_length(l),
    3813             : #ifdef HAVE_HGE
    3814             :                                                         127
    3815             : #else
    3816             :                                                          63
    3817             : #endif
    3818             :                                                         );
    3819         109 :                 a = sql_bind_func_result(sql, sname, aname, F_AGGR, true, tpe, 1, exp_subtype(exps->h->data));
    3820             :         } else
    3821       22982 :                 a = sql_bind_func_(sql, sname, aname, exp_types(sql->sa, exps), F_AGGR, false, false);
    3822             : 
    3823       23091 :         if (a) {
    3824       23086 :                 found = true;
    3825       23086 :                 if (!execute_priv(sql, a->func))
    3826           0 :                         a = NULL;
    3827       23086 :                 if (!is_grouping && a && !(exps = check_arguments_and_find_largest_any_type(sql, rel ? *rel : NULL, exps, a, 0, false)))
    3828           0 :                         a = NULL;
    3829             :         }
    3830             : 
    3831       23091 :         if (a) {
    3832       23086 :                 bool hasnil = have_nil(exps) || (strcmp(aname, "count") != 0 && (!groupby || list_empty(groupby->r))); /* for global case, the aggregate may return NULL */
    3833       23086 :                 sql_exp *e = exp_aggr(sql->sa, exps, a, distinct, no_nil, groupby?groupby->card:CARD_ATOM, hasnil);
    3834             : 
    3835       23086 :                 if (!groupby)
    3836             :                         return e;
    3837       23086 :                 if (all_freevar)
    3838         246 :                         query_outer_aggregated(query, all_freevar-1, e);
    3839       23086 :                 e = rel_groupby_add_aggr(sql, groupby, e);
    3840       23086 :                 if (!group && !all_freevar)
    3841             :                         return e;
    3842       16610 :                 if (all_freevar) {
    3843         246 :                         rel_bind_vars(sql, groupby->l, exps);
    3844         246 :                         assert(!is_simple_project(res->op));
    3845         246 :                         e->card = CARD_ATOM;
    3846         246 :                         set_freevar(e, all_freevar-1);
    3847         246 :                         return e;
    3848             :                 }
    3849             :                 return e;
    3850             :         }
    3851           5 :         const char *type = "unknown";
    3852           5 :         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    3853             : 
    3854           5 :         if (!list_empty(exps)) {
    3855           5 :                 sql_exp *e = exps->h->data;
    3856           5 :                 type = exp_subtype(e)->type->base.name;
    3857             :         }
    3858          15 :         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "%s: %s aggregate %s%s%s'%s'(%s)", toUpperCopy(uaname, aname), found ? "insufficient privileges for" : "no such",
    3859             :                                          sname ? "'":"", sname ? sname : "", sname ? "'.":"", aname, type);
    3860             : }
    3861             : 
    3862             : static sql_exp *
    3863       41965 : rel_aggr(sql_query *query, sql_rel **rel, symbol *se, int f)
    3864             : {
    3865       41965 :         dlist *l = se->data.lval;
    3866       41965 :         dnode *d = l->h->next->next;
    3867       41965 :         int distinct = l->h->next->data.i_val;
    3868       41965 :         char *aname = qname_schema_object(l->h->data.lval);
    3869       41965 :         char *sname = qname_schema(l->h->data.lval);
    3870             : 
    3871       41965 :         return _rel_aggr(query, rel, distinct, sname, aname, d, f);
    3872             : }
    3873             : 
    3874             : static sql_exp *
    3875      100621 : rel_case(sql_query *query, sql_rel **rel, symbol *opt_cond, dlist *when_search_list, symbol *opt_else, int f)
    3876             : {
    3877      100621 :         mvc *sql = query->sql;
    3878      100621 :         sql_subtype *tpe = NULL;
    3879      100621 :         list *conds = new_exp_list(sql->sa), *results = new_exp_list(sql->sa);
    3880      100621 :         sql_subtype *restype = NULL, *condtype = NULL, ctype, rtype, bt;
    3881      100621 :         sql_exp *res = NULL, *opt_cond_exp = NULL;
    3882      100621 :         exp_kind ek = {type_value, card_column, FALSE};
    3883             : 
    3884      100621 :         if (opt_cond) {
    3885        9436 :                 if (!(opt_cond_exp = rel_value_exp(query, rel, opt_cond, f, ek)))
    3886             :                         return NULL;
    3887        9435 :                 condtype = exp_subtype(opt_cond_exp);
    3888             :         }
    3889             : 
    3890      248297 :         for (dnode *dn = when_search_list->h; dn; dn = dn->next) {
    3891      147686 :                 sql_exp *cond = NULL, *result = NULL;
    3892      147686 :                 dlist *when = dn->data.sym->data.lval;
    3893             : 
    3894      147686 :                 if (opt_cond)
    3895       45602 :                         cond = rel_value_exp(query, rel, when->h->data.sym, f, ek);
    3896             :                 else
    3897      102084 :                         cond = rel_logical_value_exp(query, rel, when->h->data.sym, f, ek);
    3898      147686 :                 if (!cond)
    3899             :                         return NULL;
    3900      147680 :                 append(conds, cond);
    3901      147680 :                 tpe = exp_subtype(cond);
    3902      147680 :                 if (tpe && condtype) {
    3903       56495 :                         result_datatype(&ctype, condtype, tpe);
    3904       56495 :                         condtype = &ctype;
    3905       91185 :                 } else if (tpe) {
    3906       91183 :                         condtype = tpe;
    3907             :                 }
    3908             : 
    3909      147680 :                 if (!(result = rel_value_exp(query, rel, when->h->next->data.sym, f, ek)))
    3910             :                         return NULL;
    3911      147677 :                 append(results, result);
    3912      147677 :                 tpe = exp_subtype(result);
    3913      147677 :                 if (tpe && restype) {
    3914       47063 :                         result_datatype(&rtype, restype, tpe);
    3915       47063 :                         restype = &rtype;
    3916      100614 :                 } else if (tpe) {
    3917      100608 :                         restype = tpe;
    3918             :                 }
    3919             :         }
    3920      100611 :         if (opt_else) {
    3921       98041 :                 if (!(res = rel_value_exp(query, rel, opt_else, f, ek)))
    3922             :                         return NULL;
    3923             : 
    3924       98041 :                 tpe = exp_subtype(res);
    3925       98041 :                 if (tpe && restype) {
    3926       98036 :                         result_datatype(&rtype, restype, tpe);
    3927       98036 :                         restype = &rtype;
    3928           5 :                 } else if (tpe) {
    3929             :                         restype = tpe;
    3930             :                 }
    3931             : 
    3932       98039 :                 if (!restype)
    3933           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "Result type missing");
    3934       98039 :                 if (restype->type->localtype == TYPE_void) /* NULL */
    3935           0 :                         restype = sql_bind_localtype("str");
    3936             : 
    3937       98039 :                 if (!(res = exp_check_type(sql, restype, rel ? *rel : NULL, res, type_equal)))
    3938             :                         return NULL;
    3939             :         } else {
    3940        2570 :                 if (!restype)
    3941           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "Result type missing");
    3942        2570 :                 if (restype->type->localtype == TYPE_void) /* NULL */
    3943           7 :                         restype = sql_bind_localtype("str");
    3944        2570 :                 res = exp_null(sql->sa, restype);
    3945             :         }
    3946             : 
    3947      100609 :         if (!condtype)
    3948           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "Condition type missing");
    3949      100609 :         if (condtype->type->localtype == TYPE_void) /* NULL */
    3950           0 :                 condtype = sql_bind_localtype("str");
    3951      100609 :         if (opt_cond_exp && !(opt_cond_exp = exp_check_type(sql, condtype, rel ? *rel : NULL, opt_cond_exp, type_equal)))
    3952             :                 return NULL;
    3953      100609 :         sql_find_subtype(&bt, "boolean", 0, 0);
    3954      100609 :         list *args = sa_list(sql->sa);
    3955      100609 :         if (opt_cond_exp)
    3956        9429 :                 append(args, opt_cond_exp);
    3957      248279 :         for (node *n = conds->h, *m = results->h; n && m; n = n->next, m = m->next) {
    3958      147671 :                 sql_exp *cond = n->data;
    3959      147671 :                 sql_exp *result = m->data;
    3960             : 
    3961      147671 :                 if (!(result = exp_check_type(sql, restype, rel ? *rel : NULL, result, type_equal)))
    3962             :                         return NULL;
    3963             : 
    3964      147671 :                 if (!(cond = exp_check_type(sql, condtype, rel ? *rel : NULL, cond, type_equal)))
    3965             :                         return NULL;
    3966      147670 :                 if (!opt_cond_exp && !(cond = exp_check_type(sql, &bt, rel ? *rel : NULL, cond, type_equal)))
    3967             :                         return NULL;
    3968      147670 :                 append(args, cond);
    3969      147670 :                 append(args, result);
    3970             :         }
    3971      100608 :         assert(res);
    3972      100608 :         list_append(args, res);
    3973      100608 :         list *types = sa_list(sql->sa);
    3974      100608 :         types = append(append(types, restype), restype);
    3975      191788 :         sql_subfunc *case_func = find_func(sql, NULL, opt_cond_exp?"casewhen":"case", list_length(types), F_FUNC, true, NULL, NULL);
    3976      100608 :         res = exp_op(sql->sa, args, case_func);
    3977      100608 :         ((sql_subfunc*)res->f)->res->h->data = sql_create_subtype(sql->sa, restype->type, restype->digits, restype->scale);
    3978      100608 :         return res;
    3979             : }
    3980             : 
    3981             : static sql_exp *
    3982        3838 : rel_complex_case(sql_query *query, sql_rel **rel, dlist *case_args, int f, str func)
    3983             : {
    3984        3838 :         exp_kind ek = {type_value, card_column, FALSE};
    3985        3838 :         list *args = sa_list(query->sql->sa);
    3986        3838 :         sql_subtype *restype = NULL, rtype;
    3987        3838 :         sql_exp *res;
    3988             : 
    3989             :         /* generate nested func calls */
    3990       11970 :         for(dnode *dn = case_args->h; dn; dn = dn->next) {
    3991        8145 :                 sql_exp *a = rel_value_exp(query, rel, dn->data.sym, f, ek);
    3992        8145 :                 if (!a)
    3993             :                         return NULL;
    3994        8132 :                 append(args, a);
    3995             :                 /* all arguments should have the same type */
    3996        8132 :                 sql_subtype *tpe = exp_subtype(a);
    3997        8132 :                 if (tpe && restype) {
    3998        4296 :                         result_datatype(&rtype, restype, tpe);
    3999        4296 :                         restype = &rtype;
    4000        3836 :                 } else if (tpe) {
    4001        3836 :                         restype = tpe;
    4002             :                 }
    4003             :         }
    4004        3825 :         if (!restype)
    4005           0 :                 return sql_error(query->sql, 02, SQLSTATE(42000) "Result type missing");
    4006        3825 :         if (restype->type->localtype == TYPE_void) /* NULL */
    4007           0 :                 restype = sql_bind_localtype("str");
    4008        3825 :         list *nargs = sa_list(query->sql->sa);
    4009       11942 :         for (node *m = args->h; m; m = m->next) {
    4010        8117 :                 sql_exp *result = m->data;
    4011             : 
    4012        8117 :                 if (!(result = exp_check_type(query->sql, restype, rel ? *rel : NULL, result, type_equal)))
    4013             :                         return NULL;
    4014        8117 :                 append(nargs, result);
    4015             :         }
    4016        3825 :         list *types = append(append(sa_list(query->sql->sa), restype), restype);
    4017        3825 :         sql_subfunc *fnc = find_func(query->sql, NULL, func, list_length(types), F_FUNC, true, NULL, NULL);
    4018        3825 :         res = exp_op(query->sql->sa, nargs, fnc);
    4019        3825 :         ((sql_subfunc*)res->f)->res->h->data = sql_create_subtype(query->sql->sa, restype->type, restype->digits, restype->scale);
    4020        3825 :         return res;
    4021             : }
    4022             : 
    4023             : static sql_exp *
    4024      104459 : rel_case_exp(sql_query *query, sql_rel **rel, symbol *se, int f)
    4025             : {
    4026      104459 :         dlist *l = se->data.lval;
    4027             : 
    4028      104459 :         if (se->token == SQL_COALESCE) {
    4029        3687 :                 return rel_complex_case(query, rel, l, f | sql_farg, "coalesce");
    4030      100772 :         } else if (se->token == SQL_NULLIF) {
    4031         151 :                 return rel_complex_case(query, rel, l, f | sql_farg, "nullif");
    4032      100621 :         } else if (l->h->type == type_list) {
    4033       91185 :                 dlist *when_search_list = l->h->data.lval;
    4034       91185 :                 symbol *opt_else = l->h->next->data.sym;
    4035             : 
    4036       91185 :                 return rel_case(query, rel, NULL, when_search_list, opt_else, f | sql_farg);
    4037             :         } else {
    4038        9436 :                 symbol *scalar_exp = l->h->data.sym;
    4039        9436 :                 dlist *when_value_list = l->h->next->data.lval;
    4040        9436 :                 symbol *opt_else = l->h->next->next->data.sym;
    4041             : 
    4042        9436 :                 return rel_case(query, rel, scalar_exp, when_value_list, opt_else, f | sql_farg);
    4043             :         }
    4044             : }
    4045             : 
    4046             : #define E_ATOM_STRING(e) ((atom*)(e)->l)->data.val.sval
    4047             : 
    4048             : static sql_exp *
    4049      169014 : rel_cast(sql_query *query, sql_rel **rel, symbol *se, int f)
    4050             : {
    4051      169014 :         mvc *sql = query->sql;
    4052      169014 :         dlist *dl = se->data.lval;
    4053      169014 :         symbol *s = dl->h->data.sym;
    4054      169014 :         sql_subtype *tpe = &dl->h->next->data.typeval;
    4055      169014 :         exp_kind ek = {type_value, card_column, FALSE};
    4056      169014 :         sql_exp *e = rel_value_exp(query, rel, s, f|sql_farg, ek);
    4057             : 
    4058      169014 :         if (!e)
    4059             :                 return NULL;
    4060             : 
    4061             :         /* strings may need to be truncated */
    4062      168999 :         if (EC_VARCHAR(tpe->type->eclass) && tpe->digits > 0) {
    4063       82568 :                 sql_subtype *et = exp_subtype(e);
    4064             :                 /* truncate only if the number of digits are smaller or from clob */
    4065       82568 :                 if (et && EC_VARCHAR(et->type->eclass) && (tpe->digits < et->digits || et->digits == 0)) {
    4066        2870 :                         sql_subfunc *c = sql_bind_func(sql, "sys", "truncate", et, sql_bind_localtype("int"), F_FUNC, true, true);
    4067        2870 :                         if (c)
    4068        2870 :                                 e = exp_binop(sql->sa, e, exp_atom_int(sql->sa, tpe->digits), c);
    4069             :                 }
    4070             :         }
    4071             : 
    4072      168999 :         if (e->type == e_atom && tpe->type->eclass == EC_DEC) {
    4073          86 :                 sql_subtype *et = exp_subtype(e);
    4074          86 :                 if (et->type->eclass == EC_NUM) {
    4075          42 :                         unsigned int min_precision = atom_num_digits(e->l);
    4076          42 :                         if (min_precision > tpe->digits)
    4077           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Precision (%d) should be at least (%d)", tpe->digits, min_precision);
    4078          42 :                         tpe = sql_bind_subtype(sql->sa, "decimal", min_precision, et->scale);
    4079          44 :                 } else if (EC_VARCHAR(et->type->eclass)) {
    4080          12 :                         char *s = E_ATOM_STRING(e);
    4081          12 :                         unsigned int min_precision = 0, min_scale = 0;
    4082          12 :                         bool dot_seen = false;
    4083          61 :                         for (size_t i = 0; i < strlen(s); i++) {
    4084          49 :                                 if (isdigit(s[i])) {
    4085          41 :                                         min_precision++;
    4086          41 :                                         if (dot_seen)
    4087          14 :                                                 min_scale++;
    4088           8 :                                 } else if (s[i] == '.') {
    4089           7 :                                         dot_seen = true;
    4090             :                                 }
    4091             :                         }
    4092          12 :                         tpe = sql_bind_subtype(sql->sa, "decimal", min_precision, min_scale);
    4093             :                 }
    4094             :         }
    4095             : 
    4096             :         if (e)
    4097      168999 :                 e = exp_check_type(sql, tpe, rel ? *rel : NULL, e, type_cast);
    4098             : 
    4099      168999 :         if (e && e->type == e_convert)
    4100       47984 :                 exp_label(sql->sa, e, ++sql->label);
    4101             : 
    4102             :         return e;
    4103             : }
    4104             : 
    4105             : static sql_exp *
    4106        1584 : rel_next_value_for( mvc *sql, symbol *se )
    4107             : {
    4108        1584 :         char *sname = qname_schema(se->data.lval);
    4109        1584 :         char *seqname = qname_schema_object(se->data.lval);
    4110        1584 :         sql_sequence *seq = NULL;
    4111        1584 :         sql_subtype t;
    4112        1584 :         sql_subfunc *f;
    4113             : 
    4114        1584 :         if (!stack_find_rel_view(sql, seqname)) {
    4115        1388 :                 if (!(seq = find_sequence_on_scope(sql, sname, seqname, "NEXT VALUE FOR")))
    4116             :                         return NULL;
    4117        1386 :                 if (!mvc_schema_privs(sql, seq->s))
    4118           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "NEXT VALUE FOR: access denied for %s to schema '%s'", get_string_global_var(sql, "current_user"), seq->s->base.name);
    4119             :         }
    4120        1582 :         sql_find_subtype(&t, "varchar", 0, 0);
    4121        1582 :         f = sql_bind_func(sql, "sys", "next_value_for", &t, &t, F_FUNC, true, true);
    4122        1582 :         assert(f);
    4123             :         /* sequence found in the stack. use session's schema? */
    4124        1582 :         return exp_binop(sql->sa, exp_atom_str(sql->sa, seq && seq->s ? seq->s->base.name : "sys", &t), exp_atom_str(sql->sa, seqname, &t), f);
    4125             : }
    4126             : 
    4127             : /* some users like to use aliases already in the groupby */
    4128             : static sql_exp *
    4129         165 : rel_selection_ref(sql_query *query, sql_rel **rel, char *name, dlist *selection)
    4130             : {
    4131         165 :         allocator *sa = query->sql->sa;
    4132         165 :         dlist *nl;
    4133         165 :         exp_kind ek = {type_value, card_column, FALSE};
    4134         165 :         sql_exp *res = NULL;
    4135         165 :         symbol *nsym;
    4136             : 
    4137         165 :         if (!selection)
    4138             :                 return NULL;
    4139             : 
    4140         679 :         for (dnode *n = selection->h; n; n = n->next) {
    4141             :                 /* we only look for columns */
    4142         517 :                 tokens to = n->data.sym->token;
    4143         517 :                 if (to == SQL_COLUMN || to == SQL_IDENT) {
    4144         515 :                         dlist *l = n->data.sym->data.lval;
    4145             :                         /* AS name */
    4146         515 :                         if (l->h->next->data.sval && strcmp(l->h->next->data.sval, name) == 0) {
    4147         146 :                                 sql_exp *ve = rel_value_exp(query, rel, l->h->data.sym, sql_sel|sql_groupby, ek);
    4148         146 :                                 if (ve) {
    4149         145 :                                         if (res)
    4150           1 :                                                 return sql_error(query->sql, ERR_AMBIGUOUS, SQLSTATE(42000) "SELECT: identifier '%s' ambiguous", name);
    4151         144 :                                         res = ve;
    4152             : 
    4153         144 :                                         nl = dlist_create(sa);
    4154         144 :                                         exp_setname(query->sql, ve, NULL, name);
    4155             :                                         /* now we should rewrite the selection such that it uses the new group by column */
    4156         144 :                                         dlist_append_string(sa, nl, sa_strdup(sa, name));
    4157         144 :                                         nsym = symbol_create_list(sa, to, nl);
    4158         144 :                                         nl = dlist_create(sa);
    4159         144 :                                         dlist_append_symbol(sa, nl, nsym);
    4160             :                                         /* no alias */
    4161         144 :                                         dlist_append_symbol(sa, nl, NULL);
    4162         144 :                                         n->data.sym = symbol_create_list(sa, to, nl);
    4163             :                                 }
    4164             :                         }
    4165             :                 }
    4166             :         }
    4167             :         return res;
    4168             : }
    4169             : 
    4170             : static char*
    4171         197 : symbol_get_identifier(symbol *sym)
    4172             : {
    4173         197 :         dlist *syml;
    4174             : 
    4175         197 :         if (sym->token != SQL_COLUMN && sym->token != SQL_IDENT)
    4176             :                 return NULL;
    4177         182 :         syml = sym->data.lval;
    4178         182 :         if (dlist_length(syml) > 1)
    4179             :                 return NULL;
    4180             : 
    4181         165 :         return syml->h->data.sval;
    4182             : }
    4183             : 
    4184             : static sql_exp*
    4185       23642 : rel_group_column(sql_query *query, sql_rel **rel, symbol *grp, dlist *selection, list *exps, int f)
    4186             : {
    4187       23642 :         sql_query *lquery = query_create(query->sql);
    4188       23642 :         mvc *sql = query->sql;
    4189       23642 :         exp_kind ek = {type_value, card_value, TRUE};
    4190       23642 :         sql_exp *e = rel_value_exp2(lquery, rel, grp, f, ek);
    4191             : 
    4192       23642 :         if (e && exp_is_atom(e)) {
    4193          34 :                 sql_subtype *tpe = exp_subtype(e);
    4194          34 :                 if (!is_atom(e->type) ||!tpe || tpe->type->eclass != EC_NUM) {
    4195           2 :                         if (!tpe)
    4196           2 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Cannot have a parameter (?) for group by column");
    4197           3 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: non-integer constant in GROUP BY");
    4198             :                 }
    4199             :         }
    4200             : 
    4201         192 :         if (!e) {
    4202         192 :                 char buf[ERRSIZE], *name;
    4203         192 :                 int status = sql->session->status;
    4204         192 :                 strcpy(buf, sql->errstr);
    4205             :                 /* reset error */
    4206         192 :                 sql->session->status = 0;
    4207         192 :                 sql->errstr[0] = '\0';
    4208             : 
    4209         192 :                 if ((name = symbol_get_identifier(grp))) {
    4210         163 :                         e = rel_selection_ref(query, rel, name, selection);
    4211         163 :                         if (!e) { /* attempt to find in the existing list of group by expressions */
    4212          29 :                                 for (node *n = exps->h ; n && !e ; n = n->next) {
    4213           9 :                                         sql_exp *ge = (sql_exp *) n->data;
    4214           9 :                                         const char *gen = exp_name(ge);
    4215             : 
    4216           9 :                                         if (gen && strcmp(name, gen) == 0)
    4217           5 :                                                 e = exp_ref(sql, ge);
    4218             :                                 }
    4219             :                         }
    4220             :                 }
    4221          49 :                 if (!e && query_has_outer(query)) {
    4222             :                         /* reset error */
    4223          32 :                         sql->session->status = 0;
    4224          32 :                         sql->errstr[0] = '\0';
    4225          32 :                         e = rel_value_exp2(query, rel, grp, f, ek);
    4226             :                 }
    4227          44 :                 if (!e) {
    4228          13 :                         if (sql->errstr[0] == 0) {
    4229          10 :                                 sql->session->status = status;
    4230          10 :                                 strcpy(sql->errstr, buf);
    4231             :                         }
    4232          13 :                         return NULL;
    4233             :                 }
    4234             :         }
    4235       23624 :         if (!exp_subtype(e))
    4236           0 :                 return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for group by column");
    4237             :         return e;
    4238             : }
    4239             : 
    4240             : static list*
    4241          44 : list_power_set(allocator *sa, list* input) /* cube */
    4242             : {
    4243          44 :         list *res = sa_list(sa);
    4244             :         /* N stores total number of subsets */
    4245          44 :         int N = (int) pow(2, input->cnt);
    4246             : 
    4247             :         /* generate each subset one by one */
    4248         266 :         for (int i = 0; i < N; i++) {
    4249         222 :                 list *ll = sa_list(sa);
    4250         222 :                 int j = 0; /* check every bit of i */
    4251         844 :                 for (node *n = input->h ; n ; n = n->next) {
    4252             :                         /* if j'th bit of i is set, then append */
    4253         622 :                         if (i & (1 << j))
    4254         311 :                                 list_prepend(ll, n->data);
    4255         622 :                         j++;
    4256             :                 }
    4257         222 :                 list_prepend(res, ll);
    4258             :         }
    4259          44 :         return res;
    4260             : }
    4261             : 
    4262             : static list*
    4263          61 : list_rollup(allocator *sa, list* input)
    4264             : {
    4265          61 :         list *res = sa_list(sa);
    4266             : 
    4267         188 :         for (int counter = input->cnt; counter > 0; counter--) {
    4268         127 :                 list *ll = sa_list(sa);
    4269         127 :                 int j = 0;
    4270         376 :                 for (node *n = input->h; n && j < counter; j++, n = n->next)
    4271         249 :                         list_append(ll, n->data);
    4272         127 :                 list_append(res, ll);
    4273             :         }
    4274          61 :         list_append(res, sa_list(sa)); /* global aggregate case */
    4275          61 :         return res;
    4276             : }
    4277             : 
    4278             : static int
    4279         320 : list_equal(list* list1, list* list2)
    4280             : {
    4281         375 :         for (node *n = list1->h; n ; n = n->next) {
    4282         328 :                 sql_exp *e = (sql_exp*) n->data;
    4283         328 :                 if (!exps_find_exp(list2, e))
    4284             :                         return 1;
    4285             :         }
    4286          78 :         for (node *n = list2->h; n ; n = n->next) {
    4287          47 :                 sql_exp *e = (sql_exp*) n->data;
    4288          47 :                 if (!exps_find_exp(list1, e))
    4289             :                         return 1;
    4290             :         }
    4291             :         return 0;
    4292             : }
    4293             : 
    4294             : static list*
    4295          26 : lists_cartesian_product_and_distinct(allocator *sa, list *l1, list *l2)
    4296             : {
    4297          26 :         list *res = sa_list(sa);
    4298             : 
    4299             :         /* for each list of l2, merge into each list of l1 while removing duplicates */
    4300         116 :         for (node *n = l1->h ; n ; n = n->next) {
    4301          90 :                 list *sub_list = (list*) n->data;
    4302             : 
    4303         279 :                 for (node *m = l2->h ; m ; m = m->next) {
    4304         189 :                         list *other = (list*) m->data;
    4305         189 :                         list_append(res, list_distinct(list_merge(list_dup(sub_list, (fdup) NULL), other, (fdup) NULL), (fcmp) list_equal, (fdup) NULL));
    4306             :                 }
    4307             :         }
    4308          26 :         return res;
    4309             : }
    4310             : 
    4311             : static list*
    4312        9801 : rel_groupings(sql_query *query, sql_rel **rel, symbol *groupby, dlist *selection, int f, bool grouping_sets, list **sets)
    4313             : {
    4314        9801 :         mvc *sql = query->sql;
    4315        9801 :         list *exps = new_exp_list(sql->sa);
    4316             : 
    4317        9801 :         if (mvc_highwater(sql))
    4318           0 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    4319             : 
    4320       33351 :         for (dnode *o = groupby->data.lval->h; o; o = o->next) {
    4321       23569 :                 symbol *grouping = o->data.sym;
    4322       23569 :                 list *next_set = NULL;
    4323             : 
    4324       23569 :                 if (grouping->token == SQL_GROUPING_SETS) { /* call recursively, and merge the generated sets */
    4325          39 :                         list *other = rel_groupings(query, rel, grouping, selection, f, true, &next_set);
    4326          39 :                         if (!other)
    4327          19 :                                 return NULL;
    4328          39 :                         exps = list_distinct(list_merge(exps, other, (fdup) NULL), (fcmp) exp_equal, (fdup) NULL);
    4329             :                 } else {
    4330       23530 :                         dlist *dl = grouping->data.lval;
    4331       23530 :                         if (dl) {
    4332       23504 :                                 list *set_cols = new_exp_list(sql->sa); /* columns and combination of columns to be used for the next set */
    4333             : 
    4334       47098 :                                 for (dnode *oo = dl->h; oo; oo = oo->next) {
    4335       23612 :                                         symbol *grp = oo->data.sym;
    4336       23612 :                                         list *next_tuple = new_exp_list(sql->sa); /* next tuple of columns */
    4337             : 
    4338       23612 :                                         if (grp->token == SQL_COLUMN_GROUP) { /* set of columns */
    4339          71 :                                                 assert(is_sql_group_totals(f));
    4340         172 :                                                 for (dnode *ooo = grp->data.lval->h; ooo; ooo = ooo->next) {
    4341         101 :                                                         symbol *elm = ooo->data.sym;
    4342         101 :                                                         sql_exp *e = rel_group_column(query, rel, elm, selection, exps, f);
    4343         101 :                                                         if (!e)
    4344             :                                                                 return NULL;
    4345         101 :                                                         assert(e->type == e_column);
    4346         101 :                                                         list_append(next_tuple, e);
    4347         101 :                                                         list_append(exps, e);
    4348             :                                                 }
    4349             :                                         } else { /* single column or expression */
    4350       23541 :                                                 sql_exp *e = rel_group_column(query, rel, grp, selection, exps, f);
    4351       23541 :                                                 if (!e)
    4352             :                                                         return NULL;
    4353       23523 :                                                 if (e->type != e_column && !exp_is_atom(e)) { /* store group by expressions in the stack */
    4354         140 :                                                         if (is_sql_group_totals(f))
    4355           0 :                                                                 return sql_error(sql, 02, SQLSTATE(42000) "GROUP BY: grouping expressions not possible with ROLLUP, CUBE and GROUPING SETS");
    4356         140 :                                                         if (!exp_has_rel(e) && !frame_push_groupby_expression(sql, grp, e))
    4357             :                                                                 return NULL;
    4358             :                                                 }
    4359       23523 :                                                 list_append(next_tuple, e);
    4360       23523 :                                                 list_append(exps, e);
    4361             :                                         }
    4362       23594 :                                         list_append(set_cols, next_tuple);
    4363             :                                 }
    4364       23486 :                                 if (is_sql_group_totals(f)) {
    4365         178 :                                         if (grouping->token == SQL_ROLLUP)
    4366          61 :                                                 next_set = list_rollup(sql->sa, set_cols);
    4367         117 :                                         else if (grouping->token == SQL_CUBE)
    4368          44 :                                                 next_set = list_power_set(sql->sa, set_cols);
    4369             :                                         else /* the list of sets is not used in the "GROUP BY a, b, ..." case */
    4370          73 :                                                 next_set = list_append(new_exp_list(sql->sa), set_cols);
    4371             :                                 }
    4372          26 :                         } else if (is_sql_group_totals(f) && grouping_sets) /* The GROUP BY () case is the global aggregate which is always added by ROLLUP and CUBE */
    4373          17 :                                 next_set = list_append(new_exp_list(sql->sa), new_exp_list(sql->sa));
    4374             :                 }
    4375       23551 :                 if (is_sql_group_totals(f)) { /* if there are no sets, set the found one, otherwise calculate cartesian product and merge the distinct ones */
    4376         235 :                         if (!next_set)
    4377           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "GROUP BY: GROUPING SETS is empty");
    4378         234 :                         if (!*sets)
    4379         157 :                                 *sets = next_set;
    4380             :                         else
    4381          77 :                                 *sets = grouping_sets ? list_merge(*sets, next_set, (fdup) NULL) : lists_cartesian_product_and_distinct(sql->sa, *sets, next_set);
    4382             :                 }
    4383             :         }
    4384             :         return exps;
    4385             : }
    4386             : 
    4387             : static list*
    4388        8208 : rel_partition_groupings(sql_query *query, sql_rel **rel, symbol *partitionby, dlist *selection, int f)
    4389             : {
    4390        8208 :         mvc *sql = query->sql;
    4391        8208 :         dnode *o = partitionby->data.lval->h;
    4392        8208 :         list *exps = new_exp_list(sql->sa);
    4393             : 
    4394       24650 :         for (; o; o = o->next) {
    4395        8242 :                 symbol *grp = o->data.sym;
    4396        8242 :                 exp_kind ek = {type_value, card_value, TRUE};
    4397        8242 :                 sql_exp *e = rel_value_exp2(query, rel, grp, f, ek);
    4398             : 
    4399        8242 :                 if (!e) {
    4400           5 :                         int status = sql->session->status;
    4401           5 :                         char buf[ERRSIZE], *name;
    4402             : 
    4403             :                         /* reset error */
    4404           5 :                         sql->session->status = 0;
    4405           5 :                         strcpy(buf, sql->errstr);
    4406           5 :                         sql->errstr[0] = '\0';
    4407             : 
    4408           5 :                         if ((name = symbol_get_identifier(grp))) {
    4409           2 :                                 e = rel_selection_ref(query, rel, name, selection);
    4410           2 :                                 if (!e) { /* attempt to find in the existing list of partition by expressions */
    4411           3 :                                         for (node *n = exps->h ; n ; n = n->next) {
    4412           1 :                                                 sql_exp *ge = (sql_exp *) n->data;
    4413           1 :                                                 const char *gen = exp_name(ge);
    4414             : 
    4415           1 :                                                 if (gen && strcmp(name, gen) == 0) {
    4416           0 :                                                         e = exp_ref(sql, ge);
    4417           0 :                                                         break;
    4418             :                                                 }
    4419             :                                         }
    4420             :                                 }
    4421             :                         }
    4422           5 :                         if (!e) {
    4423           5 :                                 if (sql->errstr[0] == 0) {
    4424           5 :                                         sql->session->status = status;
    4425           5 :                                         strcpy(sql->errstr, buf);
    4426             :                                 }
    4427           5 :                                 return NULL;
    4428             :                         }
    4429             :                 }
    4430             : 
    4431        8237 :                 if (exp_has_rel(e))
    4432           3 :                         return sql_error(sql, 02, SQLSTATE(42000) "PARTITION BY: subqueries not allowed in PARTITION BY clause");
    4433             : 
    4434        8234 :                 if (e->type != e_column) { /* store group by expressions in the stack */
    4435          36 :                         if (!frame_push_groupby_expression(sql, grp, e))
    4436             :                                 return NULL;
    4437             :                 }
    4438             : 
    4439        8234 :                 if (e->card > CARD_AGGR)
    4440        8114 :                         e->card = CARD_AGGR;
    4441        8234 :                 append(exps, e);
    4442             :         }
    4443             :         return exps;
    4444             : }
    4445             : 
    4446             : /* find selection expressions matching the order by column expression */
    4447             : /* complex columns only */
    4448             : static sql_exp *
    4449       66939 : rel_order_by_column_exp(sql_query *query, sql_rel **R, symbol *column_r, int needs_distinct, int f)
    4450             : {
    4451       66939 :         mvc *sql = query->sql;
    4452       66939 :         sql_rel *r = *R, *p = NULL;
    4453       66939 :         sql_exp *e = NULL, *found = NULL;
    4454       66939 :         exp_kind ek = {type_value, card_column, FALSE};
    4455             : 
    4456       66939 :         if (!r)
    4457             :                 return e;
    4458             : 
    4459       66939 :         if (is_simple_project(r->op) && r->l && is_processed(r)) {
    4460       66877 :                 p = r;
    4461       66877 :                 r = r->l;
    4462             :         }
    4463             : 
    4464       66939 :         e = rel_value_exp(query, &r, column_r, f, ek);
    4465             : 
    4466       66939 :         if (r && !p)
    4467          62 :                 *R = r;
    4468       66877 :         else if (r)
    4469       66877 :                 p->l = r;
    4470       66939 :         if (e && p) {
    4471       66850 :                 if (is_project(p->op) && (found = exps_any_match(p->exps, e))) { /* if one of the projections matches, return a reference to it */
    4472       59401 :                         e = exp_ref(sql, found);
    4473             :                 } else {
    4474        7449 :                         if (needs_distinct)
    4475           2 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
    4476        7447 :                         e = rel_project_add_exp(sql, p, e);
    4477        7447 :                         if (r) {
    4478      121019 :                                 for (node *n = p->exps->h ; n ; n = n->next) {
    4479      113574 :                                         sql_exp *ee = n->data;
    4480             : 
    4481      113574 :                                         if (ee->card > r->card) {
    4482           2 :                                                 if (exp_name(ee) && !has_label(ee))
    4483           2 :                                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(ee));
    4484           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    4485             :                                         }
    4486             :                                 }
    4487             :                         }
    4488             :                 }
    4489       66846 :                 return e;
    4490             :         }
    4491          89 :         if (e && r && is_project(r->op)) {
    4492          28 :                 sql_exp *found = exps_find_exp(r->exps, e);
    4493             : 
    4494          28 :                 if (!found) {
    4495           8 :                         if (needs_distinct)
    4496           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
    4497           8 :                         if (!is_simple_project(r->op) && !is_groupby(r->op))
    4498           1 :                                 *R = r = rel_project(sql->sa, r, rel_projections(sql, r, NULL, 1, 0));
    4499           8 :                         append(r->exps, e);
    4500             :                 } else {
    4501             :                         e = found;
    4502             :                 }
    4503          28 :                 e = exp_ref(sql, e);
    4504             :         }
    4505             :         return e;
    4506             : }
    4507             : 
    4508             : static dlist *
    4509      114437 : simple_selection(symbol *sq)
    4510             : {
    4511      114437 :         if (sq->token == SQL_SELECT) {
    4512          13 :                 SelectNode *sn;
    4513          13 :                 sn = (SelectNode *) sq;
    4514             : 
    4515          13 :                 if (!sn->from && !sn->where && !sn->distinct && !sn->window && dlist_length(sn->selection) == 1)
    4516           7 :                         return sn->selection;
    4517             :         }
    4518             :         return NULL;
    4519             : }
    4520             : 
    4521             : static list *
    4522       45376 : rel_order_by(sql_query *query, sql_rel **R, symbol *orderby, int needs_distinct, int f)
    4523             : {
    4524       45376 :         mvc *sql = query->sql;
    4525       45376 :         sql_rel *rel = *R, *or = rel; /* the order by relation */
    4526       45376 :         list *exps = new_exp_list(sql->sa);
    4527             : 
    4528       45376 :         if (!orderby->data.lval) { /* by all */
    4529           2 :                 if (is_sql_orderby(f)) {
    4530           2 :                         assert(is_project(rel->op));
    4531           6 :                         for(node *n = rel->exps->h; n; n = n->next) {
    4532           4 :                                 sql_exp *e = n->data;
    4533           4 :                                 append(exps, exp_ref(sql, e));
    4534             :                         }
    4535             :                         return exps;
    4536             :                 }
    4537             :                 return NULL;
    4538             :         }
    4539             : 
    4540       45374 :         dnode *o = orderby->data.lval->h;
    4541       45374 :         dlist *selection = NULL;
    4542             : 
    4543       45374 :         if (is_sql_orderby(f)) {
    4544       36510 :                 assert(is_project(rel->op));
    4545       36510 :                 rel = rel->l;
    4546             :         }
    4547             : 
    4548      159764 :         for (; o; o = o->next) {
    4549      114437 :                 symbol *order = o->data.sym;
    4550             : 
    4551      114437 :                 if (order->token == SQL_COLUMN || order->token == SQL_IDENT) {
    4552      114437 :                         symbol *col = order->data.lval->h->data.sym;
    4553      114437 :                         int direction = order->data.lval->h->next->data.i_val;
    4554      114437 :                         sql_exp *e = NULL;
    4555             : 
    4556      114437 :                         assert(order->data.lval->h->next->type == type_int);
    4557      114437 :                         if ((selection = simple_selection(col)) != NULL) {
    4558           7 :                                 dnode *o = selection->h;
    4559           7 :                                 order = o->data.sym;
    4560           7 :                                 if (order->data.lval->h->type == type_symbol)
    4561           6 :                                         col = order->data.lval->h->data.sym;
    4562             :                                 /* remove optional name from selection */
    4563           7 :                                 order->data.lval->h->next = NULL;
    4564             :                         }
    4565             : 
    4566      114437 :                         if (col->token == SQL_COLUMN || col->token == SQL_IDENT || col->token == SQL_ATOM) {
    4567      114215 :                                 exp_kind ek = {type_value, card_column, FALSE};
    4568             : 
    4569      114215 :                                 e = rel_value_exp2(query, &rel, col, f, ek);
    4570             : 
    4571      114215 :                                 if (e && e->card <= CARD_ATOM) {
    4572        9364 :                                         sql_subtype *tpe = exp_subtype(e);
    4573             :                                         /* integer atom on the stack */
    4574        9364 :                                         if (!is_sql_window(f) && e->type == e_atom &&
    4575        9256 :                                             tpe->type->eclass == EC_NUM) {
    4576        9247 :                                                 atom *a = e->l;
    4577        9247 :                                                 int nr = (int)atom_get_int(a);
    4578             : 
    4579        9247 :                                                 e = exps_get_exp(rel->exps, nr);
    4580        9247 :                                                 if (!e)
    4581           3 :                                                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: the order by column number (%d) is not in the number of projections range (%d)", nr, list_length(rel->exps));
    4582        9244 :                                                 e = exp_ref(sql, e);
    4583             :                                         }
    4584       38129 :                                 } else if (e && exp_card(e) > rel->card) {
    4585           0 :                                         if (exp_name(e) && !has_label(e))
    4586           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(e));
    4587           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    4588             :                                 }
    4589      114212 :                                 if (e && !exp_name(e))
    4590          23 :                                         exp_label(sql->sa, e, ++sql->label);
    4591       47490 :                                 if (e && rel && is_project(rel->op)) {
    4592       39202 :                                         sql_exp *found = exps_find_exp(rel->exps, e);
    4593             : 
    4594       39202 :                                         if (!found) {
    4595          33 :                                                 if (needs_distinct)
    4596           0 :                                                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
    4597          33 :                                                 if (!is_freevar(e))
    4598          16 :                                                         append(rel->exps, e);
    4599             :                                         } else {
    4600             :                                                 e = found;
    4601             :                                         }
    4602       39202 :                                         if (!is_freevar(e))
    4603       39185 :                                                 e = exp_ref(sql, e);
    4604             :                                 }
    4605             :                         }
    4606             : 
    4607      114434 :                         if (rel && !e && sql->session->status != -ERR_AMBIGUOUS) {
    4608             :                                 /* reset error */
    4609       66939 :                                 sql->session->status = 0;
    4610       66939 :                                 sql->errstr[0] = '\0';
    4611             : 
    4612       66939 :                                 e = rel_order_by_column_exp(query, &rel, col, needs_distinct, sql_sel | sql_orderby | (f & sql_group_totals) | (f & sql_window));
    4613             :                         }
    4614       66944 :                         if (!e)
    4615             :                                 return NULL;
    4616      114391 :                         if (!exp_subtype(e))
    4617           1 :                                 return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for order by column");
    4618      114390 :                         set_direction(e, direction);
    4619      114390 :                         list_append(exps, e);
    4620             :                 } else {
    4621           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: order not of type SQL_COLUMN");
    4622             :                 }
    4623             :         }
    4624       45327 :         if (is_sql_orderby(f) && or != rel)
    4625       36470 :                 or->l = rel;
    4626       45327 :         if (is_sql_window(f))
    4627        8857 :                 *R = rel;
    4628             :         return exps;
    4629             : }
    4630             : 
    4631             : static int
    4632         814 : generate_window_bound(tokens sql_token, bool first_half)
    4633             : {
    4634         814 :         switch (sql_token) {
    4635         408 :                 case SQL_PRECEDING:
    4636         408 :                         return first_half ? BOUND_FIRST_HALF_PRECEDING : BOUND_SECOND_HALF_PRECEDING;
    4637         284 :                 case SQL_FOLLOWING:
    4638         284 :                         return first_half ? BOUND_FIRST_HALF_FOLLOWING : BOUND_SECOND_HALF_FOLLOWING;
    4639         122 :                 case SQL_CURRENT_ROW:
    4640         122 :                         return first_half ? CURRENT_ROW_PRECEDING : CURRENT_ROW_FOLLOWING;
    4641             :                 default:
    4642           0 :                         assert(0);
    4643             :         }
    4644             :         return 0;
    4645             : }
    4646             : 
    4647             : /* window functions */
    4648             : static sql_exp*
    4649         407 : generate_window_bound_call(mvc *sql, sql_exp **estart, sql_exp **eend, sql_exp *pe, sql_exp *e,
    4650             :                                                    sql_exp *start, sql_exp *fend, int frame_type, int excl, tokens t1, tokens t2)
    4651             : {
    4652         407 :         list *rargs1 = sa_list(sql->sa), *rargs2 = sa_list(sql->sa), *targs1 = sa_list(sql->sa), *targs2 = sa_list(sql->sa);
    4653         407 :         sql_subfunc *dc1, *dc2;
    4654         407 :         sql_subtype *it = sql_bind_localtype("int");
    4655             : 
    4656         407 :         if (pe) {
    4657         186 :                 append(targs1, exp_subtype(pe));
    4658         186 :                 append(targs2, exp_subtype(pe));
    4659         186 :                 append(rargs1, exp_copy(sql, pe));
    4660         186 :                 append(rargs2, exp_copy(sql, pe));
    4661             :         }
    4662         407 :         append(rargs1, exp_copy(sql, e));
    4663         407 :         append(rargs2, exp_copy(sql, e));
    4664         407 :         append(targs1, exp_subtype(e));
    4665         407 :         append(targs2, exp_subtype(e));
    4666         407 :         append(targs1, it);
    4667         407 :         append(targs2, it);
    4668         407 :         append(targs1, it);
    4669         407 :         append(targs2, it);
    4670         407 :         append(targs1, it);
    4671         407 :         append(targs2, it);
    4672         407 :         append(targs1, exp_subtype(start));
    4673         407 :         append(targs2, exp_subtype(fend));
    4674             : 
    4675         407 :         dc1 = sql_bind_func_(sql, "sys", "window_bound", targs1, F_ANALYTIC, true, false);
    4676         407 :         dc2 = sql_bind_func_(sql, "sys", "window_bound", targs2, F_ANALYTIC, true, false);
    4677         407 :         if (!dc1 || !dc2)
    4678           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: function 'window_bound' not found");
    4679         407 :         append(rargs1, exp_atom_int(sql->sa, frame_type));
    4680         407 :         append(rargs2, exp_atom_int(sql->sa, frame_type));
    4681         407 :         append(rargs1, exp_atom_int(sql->sa, generate_window_bound(t1, true)));
    4682         407 :         append(rargs2, exp_atom_int(sql->sa, generate_window_bound(t2, false)));
    4683         407 :         append(rargs1, exp_atom_int(sql->sa, excl));
    4684         407 :         append(rargs2, exp_atom_int(sql->sa, excl));
    4685         407 :         append(rargs1, start);
    4686         407 :         append(rargs2, fend);
    4687             : 
    4688         407 :         *estart = exp_op(sql->sa, rargs1, dc1);
    4689         407 :         *eend = exp_op(sql->sa, rargs2, dc2);
    4690         407 :         return e; /* return something to say there were no errors */
    4691             : }
    4692             : 
    4693             : #define EC_NUMERIC(e) (e==EC_NUM||EC_INTERVAL(e)||e==EC_DEC||e==EC_FLT)
    4694             : 
    4695             : static sql_exp*
    4696         601 : calculate_window_bound(sql_query *query, sql_rel *p, tokens token, symbol *bound, sql_exp *ie, int frame_type, int f)
    4697             : {
    4698         601 :         mvc *sql = query->sql;
    4699         601 :         sql_subtype *bt, *bound_tp = sql_bind_localtype("lng"), *iet = exp_subtype(ie);
    4700         601 :         sql_exp *res = NULL;
    4701             : 
    4702         792 :         if ((bound->token == SQL_PRECEDING || bound->token == SQL_FOLLOWING || bound->token == SQL_CURRENT_ROW) && bound->type == type_int) {
    4703         191 :                 atom *a = NULL;
    4704         191 :                 bt = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : iet;
    4705             : 
    4706         191 :                 if ((bound->data.i_val == UNBOUNDED_PRECEDING_BOUND || bound->data.i_val == UNBOUNDED_FOLLOWING_BOUND)) {
    4707          69 :                         a = atom_max_value(sql->sa, EC_NUMERIC(bt->type->eclass) ? bt : bound_tp);
    4708         122 :                 } else if (bound->data.i_val == CURRENT_ROW_BOUND) {
    4709         124 :                         a = atom_zero_value(sql->sa, EC_NUMERIC(bt->type->eclass) ? bt : bound_tp);
    4710             :                 } else {
    4711           0 :                         assert(0);
    4712             :                 }
    4713         191 :                 res = exp_atom(sql->sa, a);
    4714             :         } else { /* arbitrary expression case */
    4715         410 :                 exp_kind ek = {type_value, card_column, FALSE};
    4716         410 :                 const char *bound_desc = (token == SQL_PRECEDING) ? "PRECEDING" : "FOLLOWING";
    4717             : 
    4718         410 :                 assert(token == SQL_PRECEDING || token == SQL_FOLLOWING);
    4719         410 :                 if (!(res = rel_value_exp2(query, &p, bound, f, ek)))
    4720           3 :                         return NULL;
    4721         410 :                 if (!(bt = exp_subtype(res))) { /* frame bound is a parameter */
    4722           3 :                         sql_subtype *t = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : iet;
    4723           3 :                         if (rel_set_type_param(sql, t, p, res, 0) < 0) /* workaround */
    4724             :                                 return NULL;
    4725           3 :                         bt = exp_subtype(res);
    4726             :                 }
    4727         410 :                 if (exp_is_null_no_value_opt(res))
    4728           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s offset must not be NULL", bound_desc);
    4729         409 :                 if ((frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) && bt->type->eclass != EC_NUM && !(res = exp_check_type(sql, bound_tp, p, res, type_equal)))
    4730             :                         return NULL;
    4731         409 :                 if (frame_type == FRAME_RANGE) {
    4732          70 :                         sql_class iet_class = iet->type->eclass;
    4733             : 
    4734          70 :                         if (!EC_NUMERIC(iet_class) && !EC_TEMP(iet_class))
    4735           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Ranges with arbitrary expressions are available to numeric, interval and temporal types only");
    4736          12 :                         if (EC_NUMERIC(iet_class) && !(res = exp_check_type(sql, iet, p, res, type_equal)))
    4737             :                                 return NULL;
    4738          69 :                         if ((iet_class == EC_TIME || iet_class == EC_TIME_TZ) && bt->type->eclass != EC_SEC) {
    4739           1 :                                 (void) sql_error(sql, 02, SQLSTATE(42000) "For %s input the %s boundary must be an interval type up to the day", subtype2string2(sql->ta, iet), bound_desc);
    4740           1 :                                 sa_reset(sql->ta);
    4741           1 :                                 return NULL;
    4742             :                         }
    4743          68 :                         if (EC_TEMP(iet->type->eclass) && !EC_INTERVAL(bt->type->eclass)) {
    4744           0 :                                 (void) sql_error(sql, 02, SQLSTATE(42000) "For %s input the %s boundary must be an interval type", subtype2string2(sql->ta, iet), bound_desc);
    4745           0 :                                 sa_reset(sql->ta);
    4746           0 :                                 return NULL;
    4747             :                         }
    4748             :                 }
    4749             :         }
    4750             :         return res;
    4751             : }
    4752             : 
    4753             : static dlist*
    4754          16 : get_window_clauses(mvc *sql, char* ident, symbol **partition_by_clause, symbol **order_by_clause, symbol **frame_clause)
    4755             : {
    4756          16 :         dlist *window_specification = NULL;
    4757          16 :         char *window_ident;
    4758          16 :         int pos;
    4759             : 
    4760          16 :         if (mvc_highwater(sql))
    4761           0 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    4762             : 
    4763          16 :         if ((window_specification = frame_get_window_def(sql, ident, &pos)) == NULL)
    4764           1 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: window '%s' not found", ident);
    4765             : 
    4766             :         /* avoid infinite lookups */
    4767          15 :         if (frame_check_var_visited(sql, pos))
    4768           1 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cyclic references to window '%s' found", ident);
    4769          14 :         frame_set_var_visited(sql, pos);
    4770             : 
    4771          14 :         if (window_specification->h->next->data.sym) {
    4772           2 :                 if (*partition_by_clause)
    4773           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of PARTITION BY clause from window '%s'", ident);
    4774           2 :                 *partition_by_clause = window_specification->h->next->data.sym;
    4775             :         }
    4776          14 :         if (window_specification->h->next->next->data.sym) {
    4777           4 :                 if (*order_by_clause)
    4778           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of ORDER BY clause from window '%s'", ident);
    4779           3 :                 *order_by_clause = window_specification->h->next->next->data.sym;
    4780             :         }
    4781          13 :         if (window_specification->h->next->next->next->data.sym) {
    4782           0 :                 if (*frame_clause)
    4783           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of frame clause from window '%s'", ident);
    4784           0 :                 *frame_clause = window_specification->h->next->next->next->data.sym;
    4785             :         }
    4786             : 
    4787          13 :         window_ident = window_specification->h->data.sval;
    4788          13 :         if (window_ident && !get_window_clauses(sql, window_ident, partition_by_clause, order_by_clause, frame_clause))
    4789             :                 return NULL; /* the error was already set */
    4790             : 
    4791             :         return window_specification; /* return something to say there were no errors */
    4792             : }
    4793             : 
    4794             : /*
    4795             :  * select x, y, rank_op() over (partition by x order by y) as, ...
    4796             :                 aggr_op(z) over (partition by y order by x) as, ...
    4797             :  * from table [x,y,z,w,v]
    4798             :  *
    4799             :  * project and order by over x,y / y,x
    4800             :  * a = project( table ) [ x, y, z, w, v ], [ x, y]
    4801             :  * b = project( table ) [ x, y, z, w, v ], [ y, x]
    4802             :  *
    4803             :  * project with order dependent operators, ie combined prev/current value
    4804             :  * aa = project (a) [ x, y, r = rank_op(diff(x) (marks a new partition), rediff(diff(x), y) (marks diff value with in partition)), z, w, v ]
    4805             :  * project(aa) [ aa.x, aa.y, aa.r ] -- only keep current output list
    4806             :  * bb = project (b) [ x, y, a = aggr_op(z, diff(y), rediff(diff(y), x)), z, w, v ]
    4807             :  * project(bb) [ bb.x, bb.y, bb.a ]  -- only keep current output list
    4808             :  */
    4809             : static sql_exp *
    4810       17947 : rel_rankop(sql_query *query, sql_rel **rel, symbol *se, int f)
    4811             : {
    4812       17947 :         mvc *sql = query->sql;
    4813       17947 :         node *n;
    4814       17947 :         dlist *l = se->data.lval, *window_specification = NULL;
    4815       17947 :         symbol *window_function = l->h->data.sym, *partition_by_clause = NULL, *order_by_clause = NULL, *frame_clause = NULL;
    4816       17947 :         char *aname = NULL, *sname = NULL, *window_ident = NULL;
    4817       17947 :         sql_subfunc *wf = NULL;
    4818       17947 :         sql_exp *in = NULL, *pe = NULL, *oe = NULL, *call = NULL, *start = NULL, *eend = NULL, *fstart = NULL, *fend = NULL, *ie = NULL;
    4819       17947 :         sql_rel *p;
    4820       17947 :         list *gbe = NULL, *obe = NULL, *args = NULL, *types = NULL, *fargs = NULL;
    4821       17947 :         dnode *dn = window_function->data.lval->h, *dargs = NULL;
    4822       17947 :         int distinct = 0, frame_type, pos, nf = f, nfargs = 0;
    4823       17947 :         bool is_nth_value, supports_frames, found = false;
    4824             : 
    4825       17947 :         frame_clear_visited_flag(sql); /* clear visited flags before iterating */
    4826             : 
    4827       17947 :         if (l->h->next->type == type_list) {
    4828       17931 :                 window_specification = l->h->next->data.lval;
    4829          16 :         } else if (l->h->next->type == type_string) {
    4830          16 :                 const char* window_alias = l->h->next->data.sval;
    4831          16 :                 if ((window_specification = frame_get_window_def(sql, window_alias, &pos)) == NULL)
    4832           1 :                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: window '%s' not found", window_alias);
    4833          15 :                 frame_set_var_visited(sql, pos);
    4834             :         } else {
    4835           0 :                 assert(0);
    4836             :         }
    4837             : 
    4838       17946 :         window_ident = window_specification->h->data.sval;
    4839       17946 :         partition_by_clause = window_specification->h->next->data.sym;
    4840       17946 :         order_by_clause = window_specification->h->next->next->data.sym;
    4841       17946 :         frame_clause = window_specification->h->next->next->next->data.sym;
    4842             : 
    4843       17946 :         if (window_ident && !get_window_clauses(sql, window_ident, &partition_by_clause, &order_by_clause, &frame_clause))
    4844             :                 return NULL;
    4845             : 
    4846       17943 :         frame_type = frame_clause ? frame_clause->data.lval->h->next->next->data.i_val : FRAME_RANGE;
    4847       17943 :         aname = qname_schema_object(dn->data.lval);
    4848       17943 :         sname = qname_schema(dn->data.lval);
    4849             : 
    4850       17943 :         is_nth_value = !strcmp(aname, "nth_value");
    4851       17943 :         bool is_value = is_nth_value || !strcmp(aname, "first_value") || !strcmp(aname, "last_value");
    4852       17943 :         supports_frames = window_function->token != SQL_RANK || is_value;
    4853             : 
    4854       17943 :         if (is_sql_update_set(f) || is_sql_psm(f) || is_sql_values(f) || is_sql_join(f) || is_sql_where(f) || is_sql_groupby(f) || is_sql_having(f) || is_psm_call(f) || is_sql_from(f)) {
    4855          13 :                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4856          13 :                 const char *clause = is_sql_update_set(f)||is_sql_psm(f)?"in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses (use subquery)":is_sql_values(f)?"on an unique value":
    4857           8 :                                                          is_sql_join(f)?"in JOIN conditions":is_sql_where(f)?"in WHERE clause":is_sql_groupby(f)?"in GROUP BY clause":
    4858           4 :                                                          is_psm_call(f)?"in CALL":is_sql_from(f)?"in functions in FROM":"in HAVING clause";
    4859          13 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: window function '%s' not allowed %s", toUpperCopy(uaname, aname), aname, clause);
    4860       17930 :         } else if (is_sql_aggr(f)) {
    4861           2 :                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4862           2 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: window functions not allowed inside aggregation functions", toUpperCopy(uaname, aname));
    4863       17928 :         } else if (is_sql_window(f)) {
    4864           6 :                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4865           6 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: window functions cannot be nested", toUpperCopy(uaname, aname));
    4866             :         }
    4867       17922 :         if (window_function->token == SQL_UNOP || window_function->token == SQL_OP) {
    4868        3246 :                 window_function->token = SQL_NOP;
    4869        3246 :                 dn->next->next->data.lval = dlist_append_symbol(sql->sa, dlist_create( sql->sa ), dn->next->next->data.sym); /* make a list */
    4870             :         }
    4871       17922 :         if (window_function->token == SQL_BINOP) {
    4872        5149 :                 window_function->token = SQL_NOP;
    4873        5149 :                 dn->next->next->data.lval = dlist_append_symbol(sql->sa, dlist_append_symbol(sql->sa, dlist_create( sql->sa ), dn->next->next->data.sym), dn->next->next->next->data.sym); /* make a list */
    4874        5149 :                 dn->next->next->next = dn->next->next->next->next; /* skip second arg */
    4875             :         }
    4876       17922 :         if (window_function->token == SQL_AGGR)
    4877         106 :                 dn->next->next->data.lval = dlist_append_symbol(sql->sa, dlist_create( sql->sa ), dn->next->next->data.sym); /* make a list */
    4878       17922 :         if (window_function->token == SQL_NOP)
    4879        8397 :                 window_function->token = SQL_AGGR;
    4880       17922 :         if (window_function->token != SQL_RANK && window_function->token != SQL_AGGR) {
    4881           0 :                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4882           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: window function '%s' unknown", toUpperCopy(uaname, aname));
    4883             :         }
    4884             : 
    4885             :         /* window operations are only allowed in the projection */
    4886       17922 :         if (!is_sql_sel(f))
    4887           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "OVER: only possible within the selection");
    4888             : 
    4889       17922 :         p = *rel;
    4890             :         /* Partition By */
    4891       17922 :         if (partition_by_clause) {
    4892        8208 :                 gbe = rel_partition_groupings(query, &p, partition_by_clause, NULL /* cannot use (selection) column references, as this result is a selection column */, nf | sql_window);
    4893        8208 :                 if (!gbe)
    4894             :                         return NULL;
    4895       16431 :                 for (n = gbe->h ; n ; n = n->next) {
    4896        8231 :                         sql_exp *en = n->data;
    4897             : 
    4898        8231 :                         set_ascending(en);
    4899        8231 :                         set_nulls_first(en);
    4900             :                 }
    4901             :         }
    4902             : 
    4903             :         /* Order By */
    4904       17914 :         if (order_by_clause) {
    4905        8864 :                 obe = rel_order_by(query, &p, order_by_clause, 0, sql_window);
    4906        8864 :                 if (!obe)
    4907             :                         return NULL;
    4908             :         }
    4909             : 
    4910       17907 :         fargs = sa_list(sql->sa);
    4911       17907 :         if (window_function->token == SQL_RANK) { /* rank function call */
    4912        9414 :                 dlist *dl = dn->next->next->data.lval;
    4913        9414 :                 bool is_lag = !strcmp(aname, "lag"), is_lead = !strcmp(aname, "lead"),
    4914        9414 :                          extra_input = !strcmp(aname, "ntile") || !strcmp(aname, "rank") || !strcmp(aname, "dense_rank") || !strcmp(aname, "row_number") || !strcmp(aname, "percent_rank") || !strcmp(aname, "cume_dist");
    4915             : 
    4916        9414 :                 distinct = dn->next->data.i_val;
    4917        9414 :                 if (extra_input) { /* pass an input column for analytic functions that don't require it */
    4918        9230 :                         sql_subfunc *star = sql_bind_func(sql, "sys", "star", NULL, NULL, F_FUNC, true, true);
    4919        9230 :                         in = exp_op(sql->sa, NULL, star);
    4920        9230 :                         append(fargs, in);
    4921             :                 }
    4922        9414 :                 if (dl)
    4923         593 :                         for (dargs = dl->h ; dargs ; dargs = dargs->next) {
    4924         339 :                                 exp_kind ek = {type_value, card_column, FALSE};
    4925         339 :                                 sql_subtype *empty = sql_bind_localtype("void"), *bte = sql_bind_localtype("bte");
    4926             : 
    4927         339 :                                 in = rel_value_exp2(query, &p, dargs->data.sym, f | sql_window | sql_farg, ek);
    4928         339 :                                 if (!in)
    4929           0 :                                         return NULL;
    4930         339 :                                 if (!exp_subtype(in)) { /* we also do not expect parameters here */
    4931           0 :                                         char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4932           0 :                                         return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to window functions", toUpperCopy(uaname, aname));
    4933             :                                 }
    4934         339 :                                 if (!exp_name(in))
    4935         151 :                                         exp_label(sql->sa, in, ++sql->label);
    4936             : 
    4937             :                                 /* corner case, if the argument is null convert it into something countable such as bte */
    4938         339 :                                 if (subtype_cmp(exp_subtype(in), empty) == 0)
    4939          20 :                                         in = exp_convert(sql, in, empty, bte);
    4940         339 :                                 if ((is_lag || is_lead) && nfargs == 2) { /* lag and lead 3rd arg must have same type as 1st arg */
    4941          10 :                                         sql_exp *first = (sql_exp*) fargs->h->data;
    4942          10 :                                         if (!(in = exp_check_type(sql, exp_subtype(first), p, in, type_equal)))
    4943             :                                                 return NULL;
    4944             :                                 }
    4945         329 :                                 if (!in)
    4946             :                                         return NULL;
    4947             : 
    4948         339 :                                 append(fargs, in);
    4949         339 :                                 in = exp_ref_save(sql, in);
    4950         339 :                                 nfargs++;
    4951             :                         }
    4952             :         } else { /* aggregation function call */
    4953        8493 :                 distinct = dn->next->data.i_val;
    4954       22022 :                 for (dargs = dn->next->next->data.lval->h ; dargs && dargs->data.sym ; dargs = dargs->next) {
    4955       13537 :                         exp_kind ek = {type_value, card_column, FALSE};
    4956       13537 :                         sql_subtype *empty = sql_bind_localtype("void"), *bte = sql_bind_localtype("bte");
    4957             : 
    4958       13537 :                         in = rel_value_exp2(query, &p, dargs->data.sym, f | sql_window | sql_farg, ek);
    4959       13537 :                         if (!in)
    4960           8 :                                 return NULL;
    4961       13530 :                         if (!exp_subtype(in)) { /* we also do not expect parameters here */
    4962           1 :                                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4963           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to window functions", toUpperCopy(uaname, aname));
    4964             :                         }
    4965       13529 :                         if (!exp_name(in))
    4966       10112 :                                 exp_label(sql->sa, in, ++sql->label);
    4967             : 
    4968             :                         /* corner case, if the argument is null convert it into something countable such as bte */
    4969       13529 :                         if (subtype_cmp(exp_subtype(in), empty) == 0)
    4970          46 :                                 in = exp_convert(sql, in, empty, bte);
    4971       13529 :                         if (!in)
    4972             :                                 return NULL;
    4973             : 
    4974       13529 :                         append(fargs, in);
    4975       13529 :                         in = exp_ref_save(sql, in);
    4976       13529 :                         nfargs++;
    4977             : 
    4978       13529 :                         if (!strcmp(aname, "count"))
    4979          86 :                                 append(fargs, exp_atom_bool(sql->sa, 1)); /* ignore nills */
    4980             :                 }
    4981             : 
    4982        8485 :                 if (!nfargs) { /* count(*) */
    4983         109 :                         if (window_function->token == SQL_AGGR && strcmp(aname, "count") != 0) {
    4984           2 :                                 char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
    4985           2 :                                 return sql_error(sql, 02, SQLSTATE(42000) "%s: unable to perform '%s(*)'", toUpperCopy(uaname, aname), aname);
    4986             :                         }
    4987         107 :                         sql_subfunc *star = sql_bind_func(sql, "sys", "star", NULL, NULL, F_FUNC, true, true);
    4988         107 :                         in = exp_op(sql->sa, NULL, star);
    4989         107 :                         append(fargs, in);
    4990         107 :                         append(fargs, exp_atom_bool(sql->sa, 0)); /* don't ignore nills */
    4991             :                 }
    4992             :         }
    4993             : 
    4994       17897 :         if (distinct)
    4995           4 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: DISTINCT clause is not implemented for window functions");
    4996             : 
    4997             :         /* diff for partitions */
    4998       17893 :         if (gbe) {
    4999        8191 :                 sql_subtype *bt = sql_bind_localtype("bit");
    5000             : 
    5001       16412 :                 for( n = gbe->h; n; n = n->next) {
    5002        8222 :                         sql_subfunc *df;
    5003        8222 :                         sql_exp *e = n->data;
    5004             : 
    5005        8222 :                         if (!exp_subtype(e))
    5006           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters not allowed at PARTITION BY clause from window functions");
    5007             : 
    5008        8221 :                         e = exp_copy(sql, e);
    5009        8221 :                         args = sa_list(sql->sa);
    5010        8221 :                         if (pe) {
    5011          31 :                                 df = sql_bind_func(sql, "sys", "diff", bt, exp_subtype(e), F_ANALYTIC, true, true);
    5012          31 :                                 append(args, pe);
    5013             :                         } else {
    5014        8190 :                                 df = sql_bind_func(sql, "sys", "diff", exp_subtype(e), NULL, F_ANALYTIC, true, true);
    5015             :                         }
    5016        8221 :                         if (!df)
    5017           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: function 'diff' not found");
    5018        8221 :                         append(args, e);
    5019        8221 :                         pe = exp_op(sql->sa, args, df);
    5020             :                 }
    5021             :         } else {
    5022        9702 :                 pe = exp_atom_bool(sql->sa, 0);
    5023             :         }
    5024             : 
    5025             :         /* diff for orderby */
    5026       17892 :         if (obe) {
    5027        8855 :                 sql_subtype *bt = sql_bind_localtype("bit");
    5028             : 
    5029       17756 :                 for( n = obe->h; n; n = n->next) {
    5030        8901 :                         sql_subfunc *df;
    5031        8901 :                         sql_exp *e = n->data;
    5032             : 
    5033        8901 :                         if (!exp_subtype(e))
    5034           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters not allowed at ORDER BY clause from window functions");
    5035             : 
    5036        8901 :                         e = exp_copy(sql, e);
    5037        8901 :                         args = sa_list(sql->sa);
    5038        8901 :                         if (oe) {
    5039          46 :                                 df = sql_bind_func(sql, "sys", "diff", bt, exp_subtype(e), F_ANALYTIC, true, true);
    5040          46 :                                 append(args, oe);
    5041             :                         } else {
    5042        8855 :                                 df = sql_bind_func(sql, "sys", "diff", exp_subtype(e), NULL, F_ANALYTIC, true, true);
    5043             :                         }
    5044        8901 :                         if (!df)
    5045           0 :                                 return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: function 'diff' not found");
    5046        8901 :                         append(args, e);
    5047        8901 :                         oe = exp_op(sql->sa, args, df);
    5048             :                 }
    5049             :         } else {
    5050        9037 :                 oe = exp_atom_bool(sql->sa, 0);
    5051             :         }
    5052             : 
    5053       17892 :         if (frame_clause || supports_frames) {
    5054        8596 :                 if (frame_type == FRAME_RANGE)
    5055        8285 :                         ie = obe ? (sql_exp*) obe->t->data : in;
    5056             :                 else
    5057         311 :                         ie = obe ? oe : in;
    5058             :         }
    5059       17892 :         assert(oe && pe);
    5060             : 
    5061       17892 :         types = exp_types(sql->sa, fargs);
    5062       17892 :         wf = bind_func_(sql, sname, aname, types, F_ANALYTIC, false, &found, false);
    5063       17892 :         if (wf && !list_empty(fargs) && !(fargs = check_arguments_and_find_largest_any_type(sql, NULL, fargs, wf, 0, false)))
    5064             :                 wf = NULL;
    5065       17887 :         if (!wf) {
    5066           5 :                 char *arg_list = nfargs ? nary_function_arg_types_2str(sql, types, nfargs) : NULL;
    5067          10 :                 return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s window function %s%s%s'%s'(%s)",
    5068           5 :                                                  found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", aname, arg_list ? arg_list : "");
    5069             :         }
    5070             : 
    5071             :         /* Frame */
    5072       17887 :         if (frame_clause) {
    5073         410 :                 dnode *d = frame_clause->data.lval->h;
    5074         410 :                 symbol *wstart = d->data.sym, *wend = d->next->data.sym, *rstart = wstart->data.lval->h->data.sym,
    5075         410 :                            *rend = wend->data.lval->h->data.sym;
    5076         410 :                 int excl = d->next->next->next->data.i_val;
    5077         410 :                 bool shortcut = false;
    5078             : 
    5079         410 :                 if (!supports_frames)
    5080           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "OVER: frame extend only possible with aggregation and first_value, last_value and nth_value functions");
    5081         406 :                 if (excl != EXCLUDE_NONE)
    5082           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "Only EXCLUDE NO OTHERS exclusion is currently implemented");
    5083         406 :                 if (list_empty(obe) && frame_type == FRAME_GROUPS)
    5084           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "GROUPS frame requires an order by expression");
    5085         404 :                 if (wstart->token == SQL_FOLLOWING && wend->token == SQL_PRECEDING)
    5086           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "FOLLOWING offset must come after PRECEDING offset");
    5087         403 :                 if (wstart->token == SQL_CURRENT_ROW && wend->token == SQL_PRECEDING)
    5088           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "CURRENT ROW offset must come after PRECEDING offset");
    5089         402 :                 if (wstart->token == SQL_FOLLOWING && wend->token == SQL_CURRENT_ROW)
    5090           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "FOLLOWING offset must come after CURRENT ROW offset");
    5091         401 :                 if (wstart->token != SQL_CURRENT_ROW && wend->token != SQL_CURRENT_ROW && wstart->token == wend->token && frame_type != FRAME_ROWS)
    5092           4 :                         return sql_error(sql, 02, SQLSTATE(42000) "Non-centered windows are only supported in row frames");
    5093         367 :                 if (frame_type == FRAME_RANGE) {
    5094          97 :                         if (((wstart->token == SQL_PRECEDING || wstart->token == SQL_FOLLOWING) && rstart->token != SQL_PRECEDING && rstart->token != SQL_CURRENT_ROW && rstart->token != SQL_FOLLOWING) ||
    5095          59 :                                 ((wend->token == SQL_PRECEDING || wend->token == SQL_FOLLOWING) && rend->token != SQL_PRECEDING && rend->token != SQL_CURRENT_ROW && rend->token != SQL_FOLLOWING)) {
    5096          40 :                                 if (list_empty(obe))
    5097           2 :                                         return sql_error(sql, 02, SQLSTATE(42000) "RANGE frame with PRECEDING/FOLLOWING offset requires an order by expression");
    5098          38 :                                 if (list_length(obe) > 1)
    5099           0 :                                         return sql_error(sql, 02, SQLSTATE(42000) "RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column");
    5100             :                         }
    5101             :                 }
    5102             : 
    5103         395 :                 if (list_empty(obe) && frame_type == FRAME_RANGE) { /* window functions are weird */
    5104             :                         frame_type = FRAME_ALL;
    5105             :                         shortcut = true;
    5106         383 :                 } else if (!is_value && (rstart->token == SQL_PRECEDING || rstart->token == SQL_CURRENT_ROW || rstart->token == SQL_FOLLOWING) && rstart->type == type_int &&
    5107         150 :                         (rend->token == SQL_PRECEDING || rend->token == SQL_CURRENT_ROW || rend->token == SQL_FOLLOWING) && rend->type == type_int) {
    5108             :                          /* special cases, don't calculate bounds */
    5109         146 :                         if (frame_type != FRAME_ROWS && rstart->data.i_val == UNBOUNDED_PRECEDING_BOUND && rend->data.i_val == CURRENT_ROW_BOUND) {
    5110             :                                 frame_type = FRAME_UNBOUNDED_TILL_CURRENT_ROW;
    5111             :                                 shortcut = true;
    5112          21 :                         } else if (frame_type != FRAME_ROWS && rstart->data.i_val == CURRENT_ROW_BOUND && rend->data.i_val == UNBOUNDED_FOLLOWING_BOUND) {
    5113             :                                 frame_type = FRAME_CURRENT_ROW_TILL_UNBOUNDED;
    5114             :                                 shortcut = true;
    5115          86 :                         } else if (rstart->data.i_val == UNBOUNDED_PRECEDING_BOUND && rend->data.i_val == UNBOUNDED_FOLLOWING_BOUND) {
    5116             :                                 frame_type = FRAME_ALL;
    5117             :                                 shortcut = true;
    5118          76 :                         } else if (rstart->data.i_val == CURRENT_ROW_BOUND && rend->data.i_val == CURRENT_ROW_BOUND) {
    5119         395 :                                 frame_type = FRAME_CURRENT_ROW;
    5120         395 :                                 shortcut = true;
    5121             :                         }
    5122             :                 }
    5123         395 :                 if (!shortcut) {
    5124         302 :                         if (!(fstart = calculate_window_bound(query, p, wstart->token, rstart, ie, frame_type, f | sql_window)))
    5125             :                                 return NULL;
    5126         299 :                         if (!(fend = calculate_window_bound(query, p, wend->token, rend, ie, frame_type, f | sql_window)))
    5127             :                                 return NULL;
    5128         471 :                         if (!generate_window_bound_call(sql, &start, &eend, gbe ? pe : NULL, ie, fstart, fend, frame_type, excl,
    5129             :                                                                                         wstart->token, wend->token))
    5130             :                                 return NULL;
    5131             :                 }
    5132       17477 :         } else if (supports_frames) { /* for analytic functions with no frame clause, we use the standard default values */
    5133        8183 :                 if (is_value) {
    5134         108 :                         sql_subtype *bound_tp = sql_bind_localtype("lng"), *bt = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : exp_subtype(ie);
    5135         108 :                         unsigned char sclass = bt->type->eclass;
    5136             : 
    5137         135 :                         fstart = exp_atom(sql->sa, atom_max_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp));
    5138         108 :                         fend = order_by_clause ? exp_atom(sql->sa, atom_zero_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp)) :
    5139          33 :                                                                          exp_atom(sql->sa, atom_max_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp));
    5140             : 
    5141         157 :                         if (generate_window_bound_call(sql, &start, &eend, gbe ? pe : NULL, ie, fstart, fend, frame_type, EXCLUDE_NONE, SQL_PRECEDING, SQL_FOLLOWING) == NULL)
    5142             :                                 return NULL;
    5143             :                 } else {
    5144        8075 :                         frame_type = list_empty(obe) ? FRAME_ALL : FRAME_UNBOUNDED_TILL_CURRENT_ROW;
    5145             :                 }
    5146             :         }
    5147             : 
    5148       17869 :         args = sa_list(sql->sa);
    5149       41217 :         for (node *n = fargs->h ; n ; n = n->next)
    5150       23348 :                 list_append(args, n->data);
    5151       17869 :         list_append(args, pe);
    5152       17869 :         list_append(args, oe);
    5153       17869 :         if (supports_frames) {
    5154        8575 :                 list_append(args, exp_atom_int(sql->sa, frame_type));
    5155        8575 :                 list_append(args, start ? start : exp_atom_oid(sql->sa, 1));
    5156        8575 :                 list_append(args, eend ? eend : exp_atom_oid(sql->sa, 1));
    5157             :         }
    5158       17869 :         call = exp_rank_op(sql->sa, list_empty(args) ? NULL : args, gbe, obe, wf);
    5159       17869 :         *rel = p;
    5160       17869 :         return call;
    5161             : }
    5162             : 
    5163             : sql_exp *
    5164     5742096 : rel_value_exp2(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
    5165             : {
    5166     5742096 :         mvc *sql = query->sql;
    5167     5742096 :         if (!se)
    5168             :                 return NULL;
    5169             : 
    5170     5742096 :         if (mvc_highwater(sql))
    5171          19 :                 return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    5172             : 
    5173     5742080 :         if (rel && *rel && (*rel)->card == CARD_AGGR) { /* group by expression case, handle it before */
    5174      105569 :                 sql_exp *exp = NULL;
    5175      105569 :                 if (!is_sql_aggr(f) && !is_sql_window(f))
    5176      105111 :                         exp = frame_get_groupby_expression(sql, se);
    5177      105569 :                 if (sql->errstr[0] != '\0')
    5178             :                         return NULL;
    5179      105569 :                 if (exp) {
    5180          78 :                         sql_exp *res = exp_ref(sql, exp);
    5181          78 :                         res->card = (*rel)->card;
    5182          78 :                         if (se->token == SQL_AGGR) {
    5183           0 :                                 dlist *l = se->data.lval;
    5184           0 :                                 int distinct = l->h->next->data.i_val;
    5185           0 :                                 if (distinct)
    5186           0 :                                         set_distinct(res);
    5187             :                         }
    5188          78 :                         if (!query_has_outer(query) && is_groupby((*rel)->op))
    5189          74 :                                 res = rel_groupby_add_aggr(sql, *rel, res);
    5190          78 :                         return res;
    5191             :                 }
    5192             :         }
    5193             : 
    5194     5742002 :         switch (se->token) {
    5195        1826 :         case SQL_OP:
    5196        1826 :                 return rel_op(query, rel, se, f, ek);
    5197       77585 :         case SQL_UNOP:
    5198       77585 :                 return rel_unop(query, rel, se, f, ek);
    5199      373833 :         case SQL_BINOP:
    5200      373833 :                 return rel_binop(query, rel, se, f, ek);
    5201       84769 :         case SQL_NOP:
    5202       84769 :                 return rel_nop(query, rel, se, f, ek);
    5203       18840 :         case SQL_AGGR:
    5204       18840 :                 return rel_aggr(query, rel, se, f);
    5205       17947 :         case SQL_WINDOW:
    5206       17947 :                 return rel_rankop(query, rel, se, f);
    5207     2314187 :         case SQL_IDENT:
    5208             :         case SQL_COLUMN:
    5209     2314187 :                 return rel_column_ref(query, rel, se, f );
    5210        3007 :         case SQL_NAME: {
    5211        3007 :                 dlist *l = se->data.lval;
    5212        3007 :                 const char *sname = qname_schema(l);
    5213        3007 :                 const char *vname = qname_schema_object(l);
    5214        3007 :                 return rel_exp_variable_on_scope(sql, sname, vname);
    5215             :         }
    5216       48002 :         case SQL_VALUES:
    5217             :         case SQL_WITH:
    5218             :         case SQL_SELECT: {
    5219       48002 :                 sql_rel *r = NULL;
    5220             : 
    5221       48002 :                 if (is_psm_call(f) || is_sql_merge(f))
    5222           8 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: subqueries not supported inside %s", is_psm_call(f) ? "CALL" : "MERGE", is_psm_call(f) ? "CALL statements" : "MERGE conditions");
    5223       47998 :                 if (rel && *rel)
    5224       33975 :                         query_push_outer(query, *rel, f);
    5225       47998 :                 if (se->token == SQL_WITH) {
    5226          30 :                         r = rel_with_query(query, se);
    5227       47968 :                 } else if (se->token == SQL_VALUES) {
    5228         213 :                         r = rel_values(query, se, NULL);
    5229             :                 } else {
    5230       47755 :                         assert(se->token == SQL_SELECT);
    5231       47755 :                         exp_kind nek = ek;
    5232       47755 :                         nek.aggr = is_sql_aggr(f);
    5233       47755 :                         if (is_sql_no_subquery(f))
    5234           2 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery not allowed");
    5235             : 
    5236       47753 :                         r = rel_subquery(query, se, nek);
    5237       47753 :                         if (r)
    5238       47653 :                                 exps_label(sql, r->exps);
    5239             :                 }
    5240       47996 :                 if (rel && *rel) {
    5241       33973 :                         *rel = query_pop_outer(query);
    5242       33973 :                         if (is_sql_join(f) && is_groupby((*rel)->op)) {
    5243           0 :                                 return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
    5244       33973 :                         } else if (is_sql_where(f) && is_groupby((*rel)->op)) {
    5245           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
    5246       33973 :                         } else if ((is_sql_update_set(f) || is_sql_psm(f)) && is_groupby((*rel)->op)) {
    5247           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
    5248             :                         }
    5249             :                 }
    5250       47996 :                 if (!r)
    5251             :                         return NULL;
    5252       47893 :                 if (ek.type == type_value && ek.card <= card_set && is_project(r->op) && list_length(r->exps) > 1)
    5253          16 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
    5254       47877 :                 if (ek.type == type_relation && is_project(r->op) && list_length(r->exps) != ek.type)
    5255           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery has too %s columns", list_length(r->exps) < ek.type ? "few" : "many");
    5256       47877 :                 if (ek.type == type_value && list_length(r->exps) == 1 && !is_sql_psm(f)) /* for now don't rename multi attribute results */
    5257       35720 :                         r = rel_zero_or_one(sql, r, ek);
    5258       47877 :                 return exp_rel(sql, r);
    5259             :         }
    5260         215 :         case SQL_TABLE: {
    5261             :                 /* turn a subquery into a tabular result */
    5262         215 :                 *rel = rel_selects(query, se->data.sym);
    5263         215 :                 if (*rel)
    5264         213 :                         return lastexp(*rel);
    5265             :                 return NULL;
    5266             :         }
    5267        1612 :         case SQL_PARAMETER: {
    5268        1612 :                 assert(se->type == type_int);
    5269        1612 :                 sql_arg *a = sql_bind_paramnr(sql, se->data.i_val);
    5270        1612 :                 if (sql->emode != m_prepare) {
    5271           1 :                         if (a && a->name && a->name[0])
    5272           1 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: named placeholder ('%s') but named values list is missing", a->name);
    5273             :                         else
    5274           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters ('?') not allowed in normal queries, use PREPARE");
    5275             :                 }
    5276        1611 :                 return exp_atom_ref(sql->sa, se->data.i_val, a?&a->type:NULL);
    5277             :         }
    5278      105249 :         case SQL_NULL:
    5279      105249 :                 return exp_null(sql->sa, sql_bind_localtype("void"));
    5280        1584 :         case SQL_NEXT:
    5281        1584 :                 return rel_next_value_for(sql, se);
    5282      169014 :         case SQL_CAST:
    5283      169014 :                 return rel_cast(query, rel, se, f);
    5284      104459 :         case SQL_CASE:
    5285             :         case SQL_COALESCE:
    5286             :         case SQL_NULLIF:
    5287      104459 :                 return rel_case_exp(query, rel, se, f);
    5288           1 :         case SQL_RANK:
    5289           1 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: window function %s requires an OVER clause", qname_schema_object(se->data.lval->h->data.lval));
    5290          25 :         case SQL_XMLELEMENT:
    5291             :         case SQL_XMLFOREST:
    5292             :         case SQL_XMLCOMMENT:
    5293             :         case SQL_XMLATTRIBUTE:
    5294             :         case SQL_XMLCONCAT:
    5295             :         case SQL_XMLDOCUMENT:
    5296             :         case SQL_XMLPI:
    5297             :         case SQL_XMLTEXT:
    5298          25 :                 return rel_xml(query, rel, se, f, ek);
    5299     2419847 :         default:
    5300     2419847 :                 return rel_logical_value_exp(query, rel, se, f, ek);
    5301             :         }
    5302             : }
    5303             : 
    5304             : static int exps_has_rank(list *exps);
    5305             : 
    5306             : static int
    5307             : exp_has_rank(sql_exp *e)
    5308             : {
    5309             :         switch(e->type) {
    5310             :         case e_convert:
    5311             :                 return exp_has_rank(e->l);
    5312             :         case e_func:
    5313             :                 if (e->r)
    5314             :                         return 1;
    5315             :                 /* fall through */
    5316             :         case e_aggr:
    5317             :                 return exps_has_rank(e->l);
    5318             :         case e_cmp:
    5319             :                 if (e->flag == cmp_or || e->flag == cmp_filter)
    5320             :                         return exps_has_rank(e->l) || exps_has_rank(e->r);
    5321             :                 if (e->flag == cmp_in || e->flag == cmp_notin)
    5322             :                         return exp_has_rank(e->l) || exps_has_rank(e->r);
    5323             :                 return exp_has_rank(e->l) || exp_has_rank(e->r) || (e->f && exp_has_rank(e->f));
    5324             :         default:
    5325             :                 return 0;
    5326             :         }
    5327             : }
    5328             : 
    5329             : /* TODO create exps_has (list, fptr ) */
    5330             : static int
    5331             : exps_has_rank(list *exps)
    5332             : {
    5333             :         if (!exps || list_empty(exps))
    5334             :                 return 0;
    5335             :         for(node *n = exps->h; n; n=n->next){
    5336             :                 sql_exp *e = n->data;
    5337             : 
    5338             :                 if (exp_has_rank(e))
    5339             :                         return 1;
    5340             :         }
    5341             :         return 0;
    5342             : }
    5343             : 
    5344             : sql_exp *
    5345     4421501 : rel_value_exp(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
    5346             : {
    5347     4421501 :         if (!se)
    5348             :                 return NULL;
    5349             : 
    5350     4421501 :         if (mvc_highwater(query->sql))
    5351           0 :                 return sql_error(query->sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
    5352             : 
    5353     4421503 :         sql_exp *e = rel_value_exp2(query, rel, se, f, ek);
    5354     4421491 :         if (e && (se->token == SQL_SELECT || se->token == SQL_TABLE) && !exp_is_rel(e)) {
    5355           0 :                 assert(*rel);
    5356           0 :                 return rel_lastexp(query->sql, *rel);
    5357             :         }
    5358             :         return e;
    5359             : }
    5360             : 
    5361             : static sql_exp *
    5362     1303564 : column_exp(sql_query *query, sql_rel **rel, symbol *column_e, int f)
    5363             : {
    5364     1303564 :         dlist *l = column_e->data.lval;
    5365     1303564 :         exp_kind ek = {type_value, card_column, FALSE};
    5366     1303564 :         sql_exp *ve;
    5367             : 
    5368     1303564 :         if (f == sql_sel && rel && *rel && (*rel)->card < CARD_AGGR)
    5369       82514 :                 ek.card = card_value;
    5370     1303564 :         ve = rel_value_exp(query, rel, l->h->data.sym, f, ek);
    5371     1303556 :         if (!ve)
    5372             :                 return NULL;
    5373             :         /* AS name */
    5374     1302449 :         if (ve && l->h->next->data.sval)
    5375      492690 :                 exp_setname(query->sql, ve, NULL, l->h->next->data.sval);
    5376             :         return ve;
    5377             : }
    5378             : 
    5379             : static int
    5380      806576 : exp_is_not_intern(sql_exp *e)
    5381             : {
    5382      806576 :         return is_intern(e)?-1:0;
    5383             : }
    5384             : 
    5385             : static void
    5386      122241 : rel_remove_internal_exp(sql_rel *rel)
    5387             : {
    5388      122241 :         if (rel->exps) {
    5389      122241 :                 list *n_exps = list_select(rel->exps, rel, (fcmp)&exp_is_not_intern, (fdup)NULL);
    5390             : 
    5391      122241 :                 rel->exps = n_exps;
    5392             :         }
    5393      122241 : }
    5394             : 
    5395             : static inline int
    5396          16 : exp_key(sql_exp *e)
    5397             : {
    5398          16 :         if (e->alias.name)
    5399          16 :                 return hash_key(e->alias.name);
    5400             :         return 0;
    5401             : }
    5402             : 
    5403             : static list *
    5404           5 : group_merge_exps(mvc *sql, list *gexps, list *exps)
    5405             : {
    5406           5 :         int nexps = list_length(gexps) + list_length(exps);
    5407             : 
    5408           5 :         sql_hash *ht = hash_new(sql->ta, nexps, (fkeyvalue)&exp_key);
    5409             : 
    5410           9 :         for (node *n = gexps->h; n ; n = n->next) { /* first add grouping expressions */
    5411           4 :                 sql_exp *e = n->data;
    5412           4 :                 int key = ht->key(e);
    5413             : 
    5414           4 :                 hash_add(ht, key, e);
    5415             :         }
    5416             : 
    5417          17 :         for (node *n = exps->h; n ; n = n->next) { /* then test if the new grouping expressions are already there */
    5418          12 :                 sql_exp *e = n->data;
    5419          12 :                 int key = ht->key(e);
    5420          12 :                 sql_hash_e *he = ht->buckets[key&(ht->size-1)];
    5421          12 :                 bool duplicates = false;
    5422             : 
    5423          16 :                 for (; he && !duplicates; he = he->chain) {
    5424           4 :                         sql_exp *f = he->value;
    5425             : 
    5426           4 :                         if (!exp_equal(e, f))
    5427           4 :                                 duplicates = true;
    5428             :                 }
    5429          12 :                 hash_add(ht, key, e);
    5430          12 :                 if (!duplicates) {
    5431           8 :                         list_append(gexps, e);
    5432           8 :                         n->data = exp_ref(sql, e);
    5433             :                 }
    5434             :         }
    5435           5 :         return gexps;
    5436             : }
    5437             : 
    5438             : static list *
    5439       57924 : rel_table_exp(sql_query *query, sql_rel **rel, symbol *column_e, bool single_exp )
    5440             : {
    5441       57924 :         mvc *sql = query->sql;
    5442       57924 :         if (column_e->token == SQL_TABLE && column_e->data.lval->h->type == type_symbol) {
    5443           0 :                 sql_rel *r;
    5444             : 
    5445           0 :                 if (!is_project((*rel)->op))
    5446             :                         return NULL;
    5447           0 :                 r = rel_named_table_function(query, (*rel)->l, column_e, 0, NULL);
    5448           0 :                 if (!r)
    5449             :                         return NULL;
    5450           0 :                 *rel = r;
    5451           0 :                 return sa_list(sql->sa);
    5452       57924 :         } else if (column_e->token == SQL_TABLE) {
    5453       56817 :                 char *tname = column_e->data.lval->h->data.sval;
    5454       56817 :                 list *exps = NULL;
    5455       56817 :                 sql_rel *project = *rel, *groupby = NULL;
    5456             : 
    5457             :                 /* if there's a group by relation in the tree, skip it for the '*' case and use the underlying projection */
    5458       56817 :                 if (project) {
    5459       66153 :                         while (is_groupby(project->op) || is_select(project->op)) {
    5460        9336 :                                 if (is_groupby(project->op))
    5461           5 :                                         groupby = project;
    5462        9336 :                                 if (project->l)
    5463        9336 :                                         project = project->l;
    5464             :                         }
    5465             :                         assert(project);
    5466             :                 }
    5467             : 
    5468       56817 :                 if (project->op == op_project && project->l && project == *rel && !tname && !rel_is_ref(project) && !need_distinct(project) && single_exp) {
    5469         410 :                         sql_rel *l = project->l;
    5470         410 :                         if (!l || !is_project(l->op) || list_length(project->exps) == list_length(l->exps)) {
    5471         403 :                                 rel_remove_internal_exp(*rel);
    5472         403 :                                 exps = project->exps;
    5473         403 :                                 *rel = project->l;
    5474             :                         }
    5475             :                 }
    5476       56817 :                 if ((exps || (exps = rel_table_projections(sql, project, tname, 0)) != NULL) && !list_empty(exps)) {
    5477       56813 :                         if (!(exps = check_distinct_exp_names(sql, exps)))
    5478           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Duplicate column names in table%s%s%s projection list", tname ? " '" : "", tname ? tname : "", tname ? "'" : "");
    5479       56813 :                         if (groupby) {
    5480           5 :                                 groupby->exps = group_merge_exps(sql, groupby->exps, exps);
    5481           9 :                                 for (node *n = groupby->exps->h ; n ; n = n->next) {
    5482           8 :                                         sql_exp *e = n->data;
    5483             : 
    5484           8 :                                         if (e->card > groupby->card) {
    5485           4 :                                                 if (exp_name(e) && !has_label(e))
    5486           4 :                                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(e));
    5487           0 :                                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    5488             :                                         }
    5489             :                                 }
    5490             :                         }
    5491       56809 :                         return exps;
    5492             :                 }
    5493           4 :                 if (!tname)
    5494           2 :                         return sql_error(sql, 02, SQLSTATE(42000) "Table expression without table name");
    5495           2 :                 return sql_error(sql, 02, SQLSTATE(42000) "Column expression Table '%s' unknown", tname);
    5496             :         }
    5497             :         return NULL;
    5498             : }
    5499             : 
    5500             : sql_exp *
    5501     1360381 : rel_column_exp(sql_query *query, sql_rel **rel, symbol *column_e, int f)
    5502             : {
    5503     1360381 :         if (column_e->token == SQL_COLUMN || column_e->token == SQL_IDENT)
    5504     1303564 :                 return column_exp(query, rel, column_e, f);
    5505             :         return NULL;
    5506             : }
    5507             : 
    5508             : static sql_rel*
    5509      368249 : rel_where_groupby_nodes(sql_query *query, sql_rel *rel, SelectNode *sn, int *group_totals)
    5510             : {
    5511      368249 :         mvc *sql = query->sql;
    5512             : 
    5513      368249 :         if (sn->where) {
    5514      144409 :                 rel = rel_logical_exp(query, rel, sn->where, sql_where);
    5515      144409 :                 if (!rel) {
    5516          72 :                         if (sql->errstr[0] == 0)
    5517           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "Subquery result missing");
    5518             :                         return NULL;
    5519             :                 }
    5520             :         }
    5521      368177 :         query_processed(query);
    5522             : 
    5523      368176 :         if (rel && sn->groupby) {
    5524        9770 :                 list *gbe = NULL, *sets = NULL;
    5525        9770 :                 int all = 0;
    5526        9770 :                 if (sn->groupby->data.lval == NULL) { /* ALL */
    5527             :                         all = 1;
    5528             :                 } else {
    5529       33104 :                         for (dnode *o = sn->groupby->data.lval->h; o ; o = o->next) {
    5530       23461 :                                 symbol *grouping = o->data.sym;
    5531       23461 :                                 if (grouping->token == SQL_ROLLUP || grouping->token == SQL_CUBE || grouping->token == SQL_GROUPING_SETS) {
    5532         119 :                                         *group_totals |= sql_group_totals;
    5533         119 :                                         break;
    5534             :                                 }
    5535             :                         }
    5536        9762 :                         gbe = rel_groupings(query, &rel, sn->groupby, sn->selection, sql_sel | sql_groupby | *group_totals, false, &sets);
    5537        9762 :                         if (!gbe)
    5538          19 :                                 return NULL;
    5539             :                 }
    5540        9751 :                 rel = rel_groupby(sql, rel, gbe);
    5541        9751 :                 if (rel && all)
    5542           8 :                         rel->flag = 2;
    5543        9751 :                 if (sets && list_length(sets) > 1) { /* if there is only one combination, there is no reason to generate unions */
    5544         114 :                         prop *p = prop_create(sql->sa, PROP_GROUPINGS, rel->p);
    5545         114 :                         p->value.pval = sets;
    5546         114 :                         rel->p = p;
    5547             :                 }
    5548             :         }
    5549             : 
    5550      368157 :         if (rel && sn->having) {
    5551             :                 /* having implies group by, ie if not supplied do a group by */
    5552        1764 :                 if (rel->op != op_groupby)
    5553         128 :                         rel = rel_groupby(sql, rel, NULL);
    5554             :         }
    5555      368157 :         query_processed(query);
    5556      368157 :         return rel;
    5557             : }
    5558             : 
    5559             : static sql_rel*
    5560      367026 : rel_having_limits_nodes(sql_query *query, sql_rel *rel, SelectNode *sn, exp_kind ek, int group_totals)
    5561             : {
    5562      367026 :         mvc *sql = query->sql;
    5563      367026 :         sql_rel *inner = NULL;
    5564      367026 :         int single_value = 1;
    5565             : 
    5566      367026 :         if (is_project(rel->op) && rel->l) {
    5567      367026 :                 inner = rel->l;
    5568      367026 :                 single_value = 0;
    5569             :         }
    5570             : 
    5571      367026 :         if (sn->having) {
    5572        1752 :                 if (inner && is_groupby(inner->op))
    5573        1752 :                         set_processed(inner);
    5574        1752 :                 if (!(inner = rel_logical_exp(query, inner, sn->having, sql_having | group_totals)))
    5575             :                         return NULL;
    5576        1713 :                 if (inner->exps && exps_card(inner->exps) > CARD_AGGR)
    5577           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cannot compare sets with values, probably an aggregate function missing");
    5578        1713 :                 if (!single_value)
    5579        1713 :                         rel->l = inner;
    5580             :         }
    5581             : 
    5582      366987 :         if (rel && sn->distinct)
    5583        1027 :                 rel = rel_distinct(rel);
    5584             : 
    5585      366987 :         if (rel && sn->orderby) {
    5586       36512 :                 list *obe = NULL;
    5587       36512 :                 sql_rel *sel = NULL, *l = rel->l;
    5588             : 
    5589             :                 /* project( select ) */
    5590       36512 :                 if (sn->having && is_select(l->op)) {
    5591          52 :                         sel = l;
    5592          52 :                         rel->l = l->l;
    5593             :                 }
    5594       36512 :                 rel = rel_orderby(sql, rel);
    5595       36512 :                 set_processed(rel);
    5596       36512 :                 obe = rel_order_by(query, &rel, sn->orderby, sn->distinct, sql_orderby | group_totals);
    5597       36512 :                 if (!obe)
    5598             :                         return NULL;
    5599       36472 :                 rel->r = obe;
    5600       36472 :                 if (sel) {
    5601          51 :                         sql_rel *o = rel, *p = o->l;
    5602          51 :                         p->l = sel;
    5603             :                 }
    5604             :         }
    5605      366947 :         if (!rel)
    5606             :                 return NULL;
    5607             : 
    5608      366947 :         if (sn->limit || sn->offset) {
    5609       16498 :                 sql_subtype *lng = sql_bind_localtype("lng");
    5610       16499 :                 list *exps = new_exp_list(sql->sa);
    5611             : 
    5612       16499 :                 if (sn->limit) {
    5613       16469 :                         sql_exp *l = rel_value_exp(query, NULL, sn->limit, 0, ek);
    5614             : 
    5615       16468 :                         if (!l || !(l=exp_check_type(sql, lng, NULL, l, type_equal)))
    5616           0 :                                 return NULL;
    5617       16468 :                         if ((ek.card != card_relation && sn->limit) &&
    5618             :                                 (ek.card == card_value && sn->limit)) {
    5619          11 :                                 sql_subfunc *zero_or_one = sql_bind_func(sql, "sys", "zero_or_one", exp_subtype(l), NULL, F_AGGR, true, true);
    5620          11 :                                 l = exp_aggr1(sql->sa, l, zero_or_one, 0, 0, CARD_ATOM, has_nil(l));
    5621             :                         }
    5622       16468 :                         list_append(exps, l);
    5623             :                 } else
    5624          30 :                         list_append(exps, exp_atom(sql->sa, atom_general(sql->sa, lng, NULL, 0)));
    5625       16498 :                 if (sn->offset) {
    5626          97 :                         sql_exp *o = rel_value_exp( query, NULL, sn->offset, 0, ek);
    5627          97 :                         if (!o || !(o=exp_check_type(sql, lng, NULL, o, type_equal)))
    5628           0 :                                 return NULL;
    5629          97 :                         list_append(exps, o);
    5630             :                 }
    5631       16498 :                 rel = rel_topn(sql->sa, rel, exps);
    5632             :         }
    5633             : 
    5634      366947 :         if (sn->sample || sn->seed) {
    5635          17 :                 list *exps = new_exp_list(sql->sa);
    5636             : 
    5637          24 :                 if (sn->sample) {
    5638          23 :                         sql_exp *s = rel_value_exp(query, NULL, sn->sample, 0, ek);
    5639          23 :                         if (!s)
    5640             :                                 return NULL;
    5641          23 :                         if (!exp_subtype(s) && rel_set_type_param(sql, sql_bind_localtype("lng"), NULL, s, 0) < 0)
    5642             :                                 return NULL;
    5643          23 :                         list_append(exps, s);
    5644             :                 } else {
    5645           1 :                         assert(sn->seed);
    5646           1 :                         return sql_error(sql, 02, SQLSTATE(42000) "SEED: cannot have SEED without SAMPLE");
    5647             :                 }
    5648          23 :                 if (sn->seed) {
    5649          12 :                         sql_exp *e = rel_value_exp(query, NULL, sn->seed, 0, ek);
    5650          12 :                         if (!e || !(e=exp_check_type(sql, sql_bind_localtype("int"), NULL, e, type_equal)))
    5651           0 :                                 return NULL;
    5652          12 :                         list_append(exps, e);
    5653             :                 }
    5654          23 :                 rel = rel_sample(sql->sa, rel, exps);
    5655             :         }
    5656             : 
    5657             :         /* after parsing the current query, set the group by relation as processed */
    5658      366953 :         if (!sn->having && inner && is_groupby(inner->op))
    5659       28374 :                 set_processed(inner);
    5660      366953 :         if (rel)
    5661      366953 :                 set_processed(rel);
    5662             :         return rel;
    5663             : }
    5664             : 
    5665             : static sql_rel *
    5666          60 : join_on_column_name(sql_query *query, sql_rel *rel, sql_rel *t1, sql_rel *t2, int op, int l_nil, int r_nil)
    5667             : {
    5668          60 :         mvc *sql = query->sql;
    5669          60 :         int found = 0, full = (op == op_full), right = (op == op_right);
    5670          60 :         list *exps = rel_projections(sql, t1, NULL, 1, 0);
    5671          60 :         list *r_exps = rel_projections(sql, t2, NULL, 1, 0);
    5672          60 :         list *outexps = new_exp_list(sql->sa);
    5673             : 
    5674          60 :         if (!exps || !r_exps)
    5675             :                 return NULL;
    5676         236 :         for (node *n = exps->h; n; n = n->next) {
    5677         179 :                 sql_exp *le = n->data;
    5678         179 :                 int multi = 0;
    5679         179 :                 const char *rname = exp_relname(le), *name = exp_name(le);
    5680         179 :                 sql_exp *re = exps_bind_column(r_exps, name, NULL, &multi, 0);
    5681             : 
    5682         179 :                 if (re) {
    5683         136 :                         if (multi)
    5684           3 :                                 return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "NATURAL JOIN: common column name '%s' appears more than once in right table", rname);
    5685         134 :                         multi = 0;
    5686         134 :                         le = exps_bind_column(exps, name, NULL, &multi, 0);
    5687         134 :                         if (multi)
    5688           0 :                                 return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "NATURAL JOIN: common column name '%s' appears more than once in left table", rname);
    5689             : 
    5690         134 :                         found = 1;
    5691         134 :                         if (!(rel = rel_compare_exp(query, rel, le, re, "=", TRUE, 0, 0, 0, 0)))
    5692             :                                 return NULL;
    5693         133 :                         list_remove_data(r_exps, NULL, re);
    5694         133 :                         if (full) {
    5695          12 :                                 sql_exp *cond = rel_unop_(sql, rel, le, "sys", "isnull", card_value);
    5696          12 :                                 if (!cond)
    5697             :                                         return NULL;
    5698          12 :                                 set_has_no_nil(cond);
    5699          12 :                                 if (rel_convert_types(sql, NULL, NULL, &le, &re, 1, type_equal_no_any) < 0)
    5700             :                                         return NULL;
    5701          12 :                                 if (!(le = rel_nop_(sql, rel, cond, re, le, NULL, "sys", "ifthenelse", card_value)))
    5702             :                                         return NULL;
    5703         121 :                         } else if (right) {
    5704           3 :                                 le = re;
    5705             :                         }
    5706         133 :                         exp_setname(sql, le, rname, name);
    5707         133 :                         set_not_unique(le);
    5708         133 :                         append(outexps, le);
    5709             :                 } else {
    5710          43 :                         if (l_nil)
    5711           5 :                                 set_has_nil(le);
    5712          43 :                         set_not_unique(le);
    5713          43 :                         append(outexps, le);
    5714             :                 }
    5715             :         }
    5716          57 :         if (!found)
    5717           2 :                 return sql_error(sql, 02, SQLSTATE(42000) "JOIN: no columns of tables '%s' and '%s' match", rel_name(t1)?rel_name(t1):"", rel_name(t2)?rel_name(t2):"");
    5718          86 :         for (node *n = r_exps->h; n; n = n->next) {
    5719          31 :                 sql_exp *re = n->data;
    5720          31 :                 if (r_nil)
    5721           3 :                         set_has_nil(re);
    5722          31 :                 set_not_unique(re);
    5723          31 :                 append(outexps, re);
    5724             :         }
    5725          55 :         rel = rel_project(sql->sa, rel, outexps);
    5726          55 :         return rel;
    5727             : }
    5728             : 
    5729             : static sql_rel *
    5730      368253 : rel_select_exp(sql_query *query, sql_rel *rel, SelectNode *sn, exp_kind ek)
    5731             : {
    5732      368253 :         mvc *sql = query->sql;
    5733      368253 :         sql_rel *inner = NULL;
    5734      368253 :         int group_totals = 0;
    5735      368253 :         list *pexps = NULL;
    5736             : 
    5737      368253 :         assert(sn->s.token == SQL_SELECT);
    5738      368253 :         if (!sn->selection)
    5739           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: the selection or from part is missing");
    5740             : 
    5741      368253 :         if (!rel)
    5742       72552 :                 rel = rel_project_exp(sql, exp_atom_bool(sql->sa, 1));
    5743      368250 :         rel = rel_where_groupby_nodes(query, rel, sn, &group_totals);
    5744      368248 :         if (sql->session->status) /* rel might be NULL as input, so we have to check for the session status for errors */
    5745             :                 return NULL;
    5746             : 
    5747      368157 :         inner = rel;
    5748      368157 :         pexps = sa_list(sql->sa);
    5749     1727410 :         for (dnode *n = sn->selection->h; n; n = n->next) {
    5750             :                 /* Here we could get real column expressions
    5751             :                  * (including single atoms) but also table results.
    5752             :                  * Therefore we try both rel_column_exp
    5753             :                  * and rel_table_exp.
    5754             :                  */
    5755     1360376 :                 list *te = NULL;
    5756     2720694 :                 sql_exp *ce = rel_column_exp(query, &inner, n->data.sym, sql_sel | group_totals | (ek.aggr?sql_aggr:0));
    5757             : 
    5758     1360374 :                 if (ce) {
    5759     1302450 :                         if (inner && inner->flag && is_groupby(inner->op)) {
    5760          62 :                                 int found = 0;
    5761          62 :                                 list *gbe = inner->r;
    5762             :                                 /* flag == 2 just add to group by/ aggrs and ref-to pexps*/
    5763             :                                 /* flag == 1 find group by exp referencing this column nr */
    5764          62 :                                 if (inner->flag == 2) {
    5765          25 :                                         if (ce->card > CARD_AGGR) {
    5766           9 :                                                 if (!gbe)
    5767           8 :                                                         inner->r = gbe = sa_list(sql->sa);
    5768           9 :                                                 append(gbe, ce);
    5769           9 :                                                 ce = exp_ref(sql, ce);
    5770           9 :                                                 ce->card = CARD_AGGR;
    5771           9 :                                                 list_append(inner->exps, ce);
    5772           9 :                                                 ce = exp_ref(sql, ce);
    5773           9 :                                                 found = 1;
    5774             :                                         }
    5775             :                                 } else {
    5776          81 :                                         for(node *n = gbe->h; n && !found; n = n->next) {
    5777          44 :                                                 sql_exp *e = n->data;
    5778          44 :                                                 if (is_atom(e->type) && !e->alias.name) {
    5779          29 :                                                         atom *a = e->l;
    5780          29 :                                                         int nr = (int)atom_get_int(a);
    5781          29 :                                                         if (nr == (list_length(pexps) + 1)) {
    5782          27 :                                                                 n->data = ce;
    5783          27 :                                                                 ce = exp_ref(sql, ce);
    5784          27 :                                                                 ce->card = CARD_AGGR;
    5785          27 :                                                                 list_append(inner->exps, ce);
    5786          27 :                                                                 ce = exp_ref(sql, ce);
    5787          27 :                                                                 found = 1;
    5788             :                                                         }
    5789             :                                                 }
    5790             :                                         }
    5791             :                                 }
    5792             :                         }
    5793     1302450 :                         pexps = append(pexps, ce);
    5794     1302448 :                         rel = inner;
    5795     1302448 :                         continue;
    5796             :                 } else {
    5797       62927 :                         te = rel_table_exp(query, &rel, n->data.sym, !list_length(pexps) && !n->next);
    5798             :                 }
    5799       57924 :                 if (!ce && !te) {
    5800        1115 :                         if (sql->errstr[0])
    5801             :                                 return NULL;
    5802           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery result missing");
    5803             :                 }
    5804             :                 /* here we should merge the column expressions we
    5805             :                  * obtained so far with the table expression, ie
    5806             :                  * t1.* or a subquery.
    5807             :                  */
    5808       56809 :                 pexps = list_merge(pexps, te, (fdup)NULL);
    5809             :         }
    5810      367034 :         if (rel && is_groupby(rel->op) && rel->flag) {
    5811          34 :                 list *gbe = rel->r;
    5812          34 :                 if (!list_empty(gbe)) {
    5813          68 :                         for (node *n=gbe->h; n; n = n->next) {
    5814          37 :                                 sql_exp *e = n->data;
    5815          37 :                                 if (rel->flag == 1 && is_atom(e->type) && !e->alias.name) {
    5816           1 :                                         atom *a = e->l;
    5817           1 :                                         int nr = (int)atom_get_int(a);
    5818           1 :                                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: GROUP BY position %d is not in select list", nr);
    5819             :                                 }
    5820          36 :                                 if (exp_has_aggr(rel, e))
    5821           2 :                                         return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions are not allowed in GROUP BY");
    5822             :                         }
    5823             :                 }
    5824             :         }
    5825      367031 :         if (rel && is_groupby(rel->op) && (!sn->groupby || rel->flag) && !is_processed(rel)) {
    5826       42002 :                 for (node *n=pexps->h; n; n = n->next) {
    5827       21522 :                         sql_exp *ce = n->data;
    5828       21522 :                         if (rel->card < ce->card && !exp_is_aggr(rel, ce)) {
    5829           0 :                                 if (exp_name(ce) && !has_label(ce))
    5830           0 :                                         return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column '%s' in query results without an aggregate function", exp_name(ce));
    5831           0 :                                 return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
    5832             :                         }
    5833             :                 }
    5834       20480 :                 set_processed(rel);
    5835             :         }
    5836      367031 :         rel = rel_project(sql->sa, rel, pexps);
    5837             : 
    5838      367026 :         rel = rel_having_limits_nodes(query, rel, sn, ek, group_totals);
    5839      367026 :         return rel;
    5840             : }
    5841             : 
    5842             : static sql_rel*
    5843      121790 : rel_unique_names(mvc *sql, sql_rel *rel)
    5844             : {
    5845      121790 :         list *l;
    5846             : 
    5847      121790 :         if (!is_project(rel->op))
    5848             :                 return rel;
    5849      121790 :         l = sa_list(sql->sa);
    5850      925914 :         for (node *n = rel->exps->h; n; n = n->next) {
    5851      804124 :                 sql_exp *e = n->data;
    5852      804124 :                 const char *name = exp_name(e);
    5853             : 
    5854             :                 /* If there are two identical expression names, there will be ambiguity */
    5855      804124 :                 if (!name || exps_bind_column(l, name, NULL, NULL, 0))
    5856       55459 :                         exp_label(sql->sa, e, ++sql->label);
    5857      804124 :                 append(l,e);
    5858             :         }
    5859      121790 :         rel->exps = l;
    5860      121790 :         return rel;
    5861             : }
    5862             : 
    5863             : static sql_rel *
    5864      368545 : rel_query(sql_query *query, symbol *sq, exp_kind ek)
    5865             : {
    5866      368545 :         mvc *sql = query->sql;
    5867      368545 :         sql_rel *res = NULL;
    5868      368545 :         SelectNode *sn = NULL;
    5869             : 
    5870      368545 :         if (sq->token != SQL_SELECT)
    5871          22 :                 return table_ref(query, sq, 0, NULL);
    5872             : 
    5873             :         /* select ... into is currently not handled here ! */
    5874      368523 :         sn = (SelectNode *) sq;
    5875      368523 :         if (sn->into)
    5876             :                 return NULL;
    5877             : 
    5878      368523 :         if (ek.card != card_relation && sn->orderby)
    5879           0 :                 return sql_error(sql, 01, SQLSTATE(42000) "SELECT: ORDER BY only allowed on outermost SELECT");
    5880             : 
    5881      368523 :         if (sn->window) {
    5882          20 :                 dlist *wl = sn->window->data.lval;
    5883          51 :                 for (dnode *n = wl->h; n ; n = n->next) {
    5884          32 :                         dlist *wd = n->data.sym->data.lval;
    5885          32 :                         const char *name = wd->h->data.sval;
    5886          32 :                         dlist *wdef = wd->h->next->data.lval;
    5887          32 :                         if (frame_get_window_def(sql, name, NULL)) {
    5888           1 :                                 return sql_error(sql, 01, SQLSTATE(42000) "SELECT: Redefinition of window '%s'", name);
    5889          31 :                         } else if (!frame_push_window_def(sql, name, wdef)) {
    5890           0 :                                 return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
    5891             :                         }
    5892             :                 }
    5893             :         }
    5894             : 
    5895      368522 :         if (sn->from) {
    5896      295971 :                 dlist *fl = sn->from->data.lval;
    5897      295971 :                 sql_rel *fnd = NULL;
    5898      295971 :                 list *refs = new_exp_list(sql->sa); /* Keep list of relation names in order to test for duplicates */
    5899             : 
    5900      733597 :                 for (dnode *n = fl->h; n ; n = n->next) {
    5901      437896 :                         int lateral = check_is_lateral(n->data.sym);
    5902             : 
    5903             :                         /* just used current expression */
    5904      437896 :                         if (lateral && res)
    5905          11 :                                 query_push_outer(query, res, sql_from);
    5906      437896 :                         fnd = table_ref(query, n->data.sym, lateral, refs);
    5907      437896 :                         if (lateral && res)
    5908          11 :                                 res = query_pop_outer(query);
    5909      437896 :                         if (!fnd)
    5910             :                                 break;
    5911      437626 :                         if (res) {
    5912      141911 :                                 res = rel_crossproduct(sql->sa, res, fnd, op_join);
    5913      141911 :                                 if (lateral)
    5914          11 :                                         set_dependent(res);
    5915             :                         } else {
    5916             :                                 res = fnd;
    5917             :                         }
    5918             :                 }
    5919      295971 :                 if (!fnd) {
    5920         270 :                         if (res)
    5921          14 :                                 rel_destroy(res);
    5922         270 :                         return NULL;
    5923             :                 }
    5924       72551 :         } else if (!query_has_outer(query) || !res) {/* only on top level query */
    5925       72552 :                 return rel_select_exp(query, NULL, sn, ek);
    5926             :         }
    5927             : 
    5928      295701 :         sql_rel *rel = NULL;
    5929      295701 :         if (res)
    5930      295701 :                 rel = rel_select_exp(query, res, sn, ek);
    5931      295701 :         if (!rel && res)
    5932        1047 :                 rel_destroy(res);
    5933             :         return rel;
    5934             : }
    5935             : 
    5936             : /* NOTE: does NOT "set" query but instead generate set ops (union, except, intersect) */
    5937             : static sql_rel *
    5938          23 : rel_setquery_corresponding(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer, bool n_ary_op)
    5939             : {
    5940          23 :         mvc *sql = query->sql;
    5941          23 :         const char *opname = op==SQL_EXCEPT?"EXCEPT":op==SQL_INTERSECT?"INTERSECT":outer?"OUTER UNION":"UNION";
    5942          23 :         list *lexps = sa_list(query->sql->sa), *rexps = sa_list(query->sql->sa);
    5943          23 :         if (!lexps || !rexps)
    5944             :                 return NULL;
    5945          23 :         assert(cols);
    5946          23 :         if (dlist_length(cols)) {
    5947          22 :                 for (dnode *dn = cols->h; dn; dn = dn ->next) {
    5948          13 :                         char *nm = dn->data.sym->data.lval->h->data.sval;
    5949          13 :                         sql_exp *ls, *rs;
    5950             : 
    5951          13 :                         if (!(ls = rel_bind_column(sql, l, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    5952             :                                 return NULL;
    5953          13 :                         if (!(rs = rel_bind_column(sql, r, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    5954             :                                 return NULL;
    5955          13 :                         if ((!outer && (!ls || !rs)) || (outer && !ls && !rs))
    5956           2 :                                 return sql_error(sql, 02, SQLSTATE(42000) "%s: tables '%s' and '%s' do not have a matching column '%s'", opname, rel_name(l)?rel_name(l):"", rel_name(r)?rel_name(r):"", nm);
    5957          11 :                         if (outer && !ls)
    5958           4 :                                 ls = exp_null(sql->sa, exp_subtype(rs));
    5959          11 :                         if (outer && !rs)
    5960           4 :                                 rs = exp_null(sql->sa, exp_subtype(ls));
    5961          11 :                         append(lexps, ls);
    5962          11 :                         append(rexps, rs);
    5963             :                 }
    5964             :         } else {
    5965          12 :                 int found = 0;
    5966          12 :                 list *exps = rel_projections(sql, l, NULL, 1, 0), *r_exps = rel_projections(sql, r, NULL, 1, 0);
    5967          12 :                 if (!exps || !r_exps)
    5968             :                         return NULL;
    5969             :                 /* find cols which exist on both sides */
    5970          35 :                 for (node *n = exps->h; n; n = n->next) {
    5971          23 :                         sql_exp *le = n->data;
    5972          23 :                         int multi = 0;
    5973          23 :                         const char *rname = exp_relname(le), *name = exp_name(le);
    5974          23 :                         sql_exp *re = exps_bind_column(r_exps, name, NULL, &multi, 0);
    5975          23 :                         if (re) {
    5976          13 :                                 if (multi)
    5977           0 :                                         return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "%s: common column name '%s' appears more than once in right table", opname, rname);
    5978          13 :                                 multi = 0;
    5979          13 :                                 le = exps_bind_column(exps, name, NULL, &multi, 0);
    5980          13 :                                 if (multi)
    5981           0 :                                         return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "%s: common column name '%s' appears more than once in left table", opname, rname);
    5982             : 
    5983          13 :                                 found = 1;
    5984          13 :                                 append(lexps, le);
    5985          13 :                                 append(rexps, re);
    5986          13 :                                 list_remove_data(r_exps, NULL, re);
    5987          10 :                         } else if (outer) {
    5988           3 :                                 append(lexps, le);
    5989           3 :                                 re = exp_null(sql->sa, exp_subtype(le));
    5990           3 :                                 append(rexps, re); /* nils */
    5991             :                         }
    5992             :                 }
    5993          12 :                 if (!found)
    5994           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "%s: no columns of tables '%s' and '%s' match", opname, rel_name(l)?rel_name(l):"", rel_name(r)?rel_name(r):"");
    5995          12 :                 if (outer) {
    5996           7 :                         for (node *n = r_exps->h; n; n = n->next) {
    5997           4 :                                 sql_exp *re = n->data, *le;
    5998           4 :                                 append(rexps, re);
    5999           4 :                                 le = exp_null(sql->sa, exp_subtype(re));
    6000           4 :                                 append(lexps, le); /* nils */
    6001             :                         }
    6002             :                 }
    6003             :         }
    6004          21 :         return n_ary_op ?
    6005          21 :                 rel_setop_n_ary_check_types(sql, l, r, lexps, rexps, (operator_type)op) :
    6006           2 :                 rel_setop_check_types(sql, l, r, lexps, rexps, (operator_type)op);
    6007             : }
    6008             : 
    6009             : static sql_rel *
    6010        2481 : rel_setquery_(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer)
    6011             : {
    6012        2481 :         mvc *sql = query->sql;
    6013        2481 :         sql_rel *rel;
    6014             : 
    6015        2481 :         if (outer && !cols)
    6016           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "UNION: OUTER needs to be combined with CORRESPONDING [ BY ( column list ) ]");
    6017        2481 :         if (!cols) {
    6018        2479 :                 list *ls, *rs;
    6019             : 
    6020        2479 :                 l = rel_unique_names(sql, l);
    6021        2479 :                 r = rel_unique_names(sql, r);
    6022        2479 :                 ls = rel_projections(sql, l, NULL, 0, 1);
    6023        2479 :                 rs = rel_projections(sql, r, NULL, 0, 1);
    6024        2479 :                 rel = rel_setop_check_types(sql, l, r, ls, rs, (operator_type)op);
    6025             :         } else {
    6026           2 :                 rel = rel_setquery_corresponding(query, l, r, cols, op, outer, false);
    6027             :         }
    6028        2481 :         if (rel) {
    6029        2478 :                 rel_setop_set_exps(sql, rel, rel_projections(sql, rel, NULL, 0, 1), false);
    6030        2478 :                 set_processed(rel);
    6031             :         }
    6032             :         return rel;
    6033             : }
    6034             : 
    6035             : /* Generate n-ary set operator */
    6036             : static sql_rel *
    6037       58437 : rel_setquery_n_ary_(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer)
    6038             : {
    6039             :         /* even though this is for a general n-ary operators in this phase of the query
    6040             :          * processing we gonna have only two operands (so technically it's binary). In
    6041             :          * general this op supports arbitrary number of operands.
    6042             :          */
    6043             :         // TODO: for now we support only multi-union
    6044       58437 :         assert(op == op_munion);
    6045             : 
    6046       58437 :         mvc *sql = query->sql;
    6047       58437 :         sql_rel *rel;
    6048             : 
    6049       58437 :         if (outer && !cols)
    6050           0 :                         return sql_error(sql, 02, SQLSTATE(42000) "UNION: OUTER needs to be combined with CORRESPONDING [ BY ( column list ) ]");
    6051       58437 :         if (!cols) {
    6052             :                 // TODO: make rel_setop_n_ary_check_types to accept a list of rels
    6053             :                 // and a list of lists of exps
    6054       58416 :                 list *ls, *rs;
    6055             : 
    6056       58416 :                 l = rel_unique_names(sql, l);
    6057       58416 :                 r = rel_unique_names(sql, r);
    6058       58416 :                 ls = rel_projections(sql, l, NULL, 0, 1);
    6059       58416 :                 rs = rel_projections(sql, r, NULL, 0, 1);
    6060       58416 :                 rel = rel_setop_n_ary_check_types(sql, l, r, ls, rs, (operator_type)op);
    6061             :         } else {
    6062          21 :                 rel = rel_setquery_corresponding(query, l, r, cols, op, outer, true);
    6063             :         }
    6064             : 
    6065       58437 :         if (rel) {
    6066       58431 :                 rel_setop_n_ary_set_exps(sql, rel, rel_projections(sql, rel, NULL, 0, 1), false);
    6067       58431 :                 set_processed(rel);
    6068             :         }
    6069             : 
    6070             :         return rel;
    6071             : 
    6072             : }
    6073             : 
    6074             : static sql_rel *
    6075       60923 : rel_setquery(sql_query *query, symbol *q)
    6076             : {
    6077       60923 :         mvc *sql = query->sql;
    6078       60923 :         sql_rel *res = NULL;
    6079       60923 :         dnode *n = q->data.lval->h;
    6080       60923 :         symbol *tab_ref1 = n->data.sym;
    6081       60923 :         int distinct = n->next->data.i_val;
    6082       60923 :         dlist *corresponding = n->next->next->data.lval;
    6083       60923 :         symbol *tab_ref2 = n->next->next->next->data.sym;
    6084       60923 :         sql_rel *t1, *t2;
    6085             : 
    6086       60923 :         assert(n->next->type == type_int);
    6087       60923 :         t1 = table_ref(query, tab_ref1, 0, NULL);
    6088       60923 :         if (!t1)
    6089             :                 return NULL;
    6090       60921 :         t2 = table_ref(query, tab_ref2, 0, NULL);
    6091       60921 :         if (!t2)
    6092             :                 return NULL;
    6093             : 
    6094       60919 :         rel_remove_internal_exp(t1);
    6095       60919 :         rel_remove_internal_exp(t2);
    6096       60919 :         if (!corresponding && list_length(t1->exps) != list_length(t2->exps)) {
    6097           1 :                 int t1nrcols = list_length(t1->exps);
    6098           1 :                 int t2nrcols = list_length(t2->exps);
    6099           1 :                 const char *op = "UNION";
    6100           1 :                 if (q->token == SQL_EXCEPT)
    6101             :                         op = "EXCEPT";
    6102           0 :                 else if (q->token == SQL_INTERSECT)
    6103           0 :                         op = "INTERSECT";
    6104           1 :                 rel_destroy(t1);
    6105           1 :                 rel_destroy(t2);
    6106           1 :                 return sql_error(sql, 02, SQLSTATE(42000) "%s: column counts (%d and %d) do not match", op, t1nrcols, t2nrcols);
    6107             :         }
    6108       60918 :         if ( q->token == SQL_UNION) {
    6109       58437 :                 int outer = n->next->next->next->next->data.i_val;
    6110             :                 /* For EXCEPT/INTERSECT the group by is always done within the implementation */
    6111             :                 /* TODO add those later in an optimizer ! */
    6112       58437 :                 if (t1 && distinct)
    6113        2006 :                         t1 = rel_distinct(t1);
    6114       58437 :                 if (t2 && distinct)
    6115        2006 :                         t2 = rel_distinct(t2);
    6116             :                 // TODO: this has to be fixed
    6117             :                 /*res = rel_setquery_(query, t1, t2, corresponding, op_union, outer);*/
    6118       58437 :                 res = rel_setquery_n_ary_(query, t1, t2, corresponding, op_munion, outer);
    6119        2481 :         } else if ( q->token == SQL_EXCEPT)
    6120        2023 :                 res = rel_setquery_(query, t1, t2, corresponding, op_except, 0);
    6121         458 :         else if ( q->token == SQL_INTERSECT)
    6122         458 :                 res = rel_setquery_(query, t1, t2, corresponding, op_inter, 0);
    6123       60918 :         if (res) {
    6124       60909 :                 set_processed(res);
    6125       60909 :                 if (distinct)
    6126        4361 :                         res = rel_distinct(res);
    6127             :         }
    6128             :         return res;
    6129             : }
    6130             : 
    6131             : static sql_rel *
    6132       58671 : rel_joinquery_(sql_query *query, symbol *tab1, int natural, jt jointype, symbol *tab2, symbol *js, list *refs)
    6133             : {
    6134       58671 :         mvc *sql = query->sql;
    6135       58671 :         operator_type op = op_join;
    6136       58671 :         sql_rel *t1 = NULL, *t2 = NULL, *inner, *rel = NULL;
    6137       58671 :         int l_nil = 0, r_nil = 0, lateral = 0;
    6138             : 
    6139       58671 :         switch(jointype) {
    6140             :         case jt_inner:
    6141             :         case jt_cross: op = op_join;
    6142             :                 break;
    6143             :         case jt_left: op = op_left;
    6144             :                 r_nil = 1;
    6145             :                 break;
    6146             :         case jt_right: op = op_right;
    6147             :                 l_nil = 1;
    6148             :                 break;
    6149             :         case jt_full: op = op_full;
    6150             :                 l_nil = 1;
    6151             :                 r_nil = 1;
    6152             :                 break;
    6153             :         }
    6154             : 
    6155             :         /* a dependent join cannot depend on the right side, so disable lateral check for right and full joins */
    6156       58671 :         lateral = (op == op_join || op == op_left) && check_is_lateral(tab2);
    6157       58671 :         t1 = table_ref(query, tab1, 0, refs);
    6158       58671 :         if (t1) {
    6159       58666 :                 if (!lateral) {
    6160       58631 :                         t2 = table_ref(query, tab2, 0, refs);
    6161             :                 } else {
    6162          35 :                         query_processed(query);
    6163          35 :                         query_push_outer(query, t1, sql_from);
    6164          35 :                         t2 = table_ref(query, tab2, 0, refs);
    6165          35 :                         t1 = query_pop_outer(query);
    6166             :                 }
    6167             :         }
    6168       58671 :         if (!t1 || !t2)
    6169             :                 return NULL;
    6170             : 
    6171       58648 :         query_processed(query);
    6172       58648 :         if (strcmp(rel_name(t1), rel_name(t2)) == 0) {
    6173           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: ERROR:  table name '%s' specified more than once", rel_name(t1));
    6174             :         }
    6175       58648 :         inner = rel = rel_crossproduct(sql->sa, t1, t2, op);
    6176       58648 :         if (!rel)
    6177             :                 return NULL;
    6178       58648 :         if (lateral)
    6179          34 :                 set_dependent(rel);
    6180             : 
    6181       58648 :         assert(jointype != jt_cross || (!natural && !js)); /* there are no natural cross joins, or cross joins with conditions */
    6182       58648 :         if (js && natural)
    6183           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cannot have a NATURAL JOIN with a join specification (ON or USING)");
    6184       58648 :         if (jointype != jt_cross && !js && !natural)
    6185           0 :                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: must have NATURAL JOIN or a JOIN with a join specification (ON or USING)");
    6186             : 
    6187       58648 :         if (js && js->token != SQL_USING) {  /* On sql_logical_exp */
    6188       58477 :                 rel = rel_logical_exp(query, rel, js, sql_where | sql_join);
    6189         171 :         } else if (js) {        /* using */
    6190          20 :                 char rname[16], *rnme;
    6191          20 :                 dnode *n = js->data.lval->h;
    6192          20 :                 list *outexps = new_exp_list(sql->sa), *exps;
    6193          20 :                 node *m;
    6194             : 
    6195          20 :                 rnme = sa_strdup(sql->sa, number2name(rname, sizeof(rname), ++sql->label));
    6196          46 :                 for (; n; n = n->next) {
    6197          26 :                         char *nm = n->data.sval;
    6198          26 :                         sql_exp *cond, *ls, *rs;
    6199             : 
    6200          26 :                         if (!(ls = rel_bind_column(sql, t1, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    6201           0 :                                 return NULL;
    6202          26 :                         if (!(rs = rel_bind_column(sql, t2, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
    6203             :                                 return NULL;
    6204          26 :                         if (!ls || !rs)
    6205           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "JOIN: tables '%s' and '%s' do not have a matching column '%s'", rel_name(t1)?rel_name(t1):"", rel_name(t2)?rel_name(t2):"", nm);
    6206          26 :                         if (!(rel = rel_compare_exp(query, rel, ls, rs, "=", TRUE, 0, 0, 0, 0)))
    6207             :                                 return NULL;
    6208          26 :                         if (op != op_join) {
    6209          12 :                                 if (!(cond = rel_unop_(sql, rel, ls, "sys", "isnull", card_value)))
    6210             :                                         return NULL;
    6211          12 :                                 set_has_no_nil(cond);
    6212          12 :                                 if (rel_convert_types(sql, t1, t2, &ls, &rs, 1, type_equal) < 0)
    6213             :                                         return NULL;
    6214          12 :                                 if (!(ls = rel_nop_(sql, rel, cond, rs, ls, NULL, "sys", "ifthenelse", card_value)))
    6215             :                                         return NULL;
    6216             :                         }
    6217          26 :                         exp_setname(sql, ls, rnme, nm);
    6218          26 :                         append(outexps, ls);
    6219          26 :                         if (!rel)
    6220             :                                 return NULL;
    6221             :                 }
    6222          20 :                 exps = rel_projections(sql, t1, NULL, 1, 1);
    6223         199 :                 for (m = exps->h; m; m = m->next) {
    6224         179 :                         const char *nm = exp_name(m->data);
    6225         179 :                         int fnd = 0;
    6226             : 
    6227         429 :                         for (n = js->data.lval->h; n; n = n->next) {
    6228         276 :                                 if (strcmp(nm, n->data.sval) == 0) {
    6229             :                                         fnd = 1;
    6230             :                                         break;
    6231             :                                 }
    6232             :                         }
    6233         179 :                         if (!fnd) {
    6234         153 :                                 sql_exp *ls = m->data;
    6235         153 :                                 if (l_nil)
    6236          18 :                                         set_has_nil(ls);
    6237         153 :                                 set_not_unique(ls);
    6238         153 :                                 append(outexps, ls);
    6239             :                         }
    6240             :                 }
    6241          20 :                 exps = rel_projections(sql, t2, NULL, 1, 1);
    6242         100 :                 for (m = exps->h; m; m = m->next) {
    6243          80 :                         const char *nm = exp_name(m->data);
    6244          80 :                         int fnd = 0;
    6245             : 
    6246         230 :                         for (n = js->data.lval->h; n; n = n->next) {
    6247         176 :                                 if (strcmp(nm, n->data.sval) == 0) {
    6248             :                                         fnd = 1;
    6249             :                                         break;
    6250             :                                 }
    6251             :                         }
    6252          80 :                         if (!fnd) {
    6253          54 :                                 sql_exp *rs = m->data;
    6254          54 :                                 if (r_nil)
    6255          14 :                                         set_has_nil(rs);
    6256          54 :                                 set_not_unique(rs);
    6257          54 :                                 append(outexps, rs);
    6258             :                         }
    6259             :                 }
    6260          20 :                 rel = rel_project(sql->sa, rel, outexps);
    6261         151 :         } else if (jointype != jt_cross) {              /* ! js -> natural join */
    6262          60 :                 rel = join_on_column_name(query, rel, t1, t2, op, l_nil, r_nil);
    6263             :         }
    6264       58648 :         if (!rel)
    6265             :                 return NULL;
    6266       58630 :         if (inner && is_outerjoin(inner->op))
    6267       21647 :                 set_processed(inner);
    6268       58630 :         set_processed(rel);
    6269       58630 :         query_processed(query);
    6270       58630 :         return rel;
    6271             : }
    6272             : 
    6273             : static sql_rel *
    6274       58671 : rel_joinquery(sql_query *query, symbol *q, list *refs)
    6275             : {
    6276       58671 :         dnode *n = q->data.lval->h;
    6277       58671 :         symbol *tab_ref1 = n->data.sym;
    6278       58671 :         int natural = n->next->data.i_val;
    6279       58671 :         jt jointype = (jt) n->next->next->data.i_val;
    6280       58671 :         symbol *tab_ref2 = n->next->next->next->data.sym;
    6281       58671 :         symbol *joinspec = n->next->next->next->next->data.sym;
    6282             : 
    6283       58671 :         assert(n->next->type == type_int);
    6284       58671 :         assert(n->next->next->type == type_int);
    6285       58671 :         return rel_joinquery_(query, tab_ref1, natural, jointype, tab_ref2, joinspec, refs);
    6286             : }
    6287             : 
    6288             : sql_rel *
    6289      368545 : rel_subquery(sql_query *query, symbol *sq, exp_kind ek)
    6290             : {
    6291      368545 :         mvc *sql = query->sql;
    6292             : 
    6293      368545 :         query_processed(query);
    6294      368546 :         if (!stack_push_frame(sql, NULL))
    6295           0 :                 return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
    6296      368544 :         sql_rel *rel = rel_query(query, sq, ek);
    6297      368544 :         stack_pop_frame(sql);
    6298      368545 :         if (!query_has_outer(query))
    6299      332662 :                 query_processed(query);
    6300      368544 :         if (rel && ek.type == type_relation && ek.card < card_set && rel->card >= CARD_AGGR)
    6301          15 :                 return rel_zero_or_one(sql, rel, ek);
    6302             :         return rel;
    6303             : }
    6304             : 
    6305             : sql_rel *
    6306      237808 : rel_selects(sql_query *query, symbol *s)
    6307             : {
    6308      237808 :         mvc *sql = query->sql;
    6309      237808 :         sql_rel *ret = NULL;
    6310             : 
    6311      237808 :         switch (s->token) {
    6312        5663 :         case SQL_WITH:
    6313        5663 :                 ret = rel_with_query(query, s);
    6314        5663 :                 sql->type = Q_TABLE;
    6315        5663 :                 break;
    6316        2177 :         case SQL_VALUES:
    6317        2177 :                 ret = rel_values(query, s, NULL);
    6318        2177 :                 sql->type = Q_TABLE;
    6319        2177 :                 break;
    6320      210851 :         case SQL_SELECT: {
    6321      210851 :                 exp_kind ek = {type_value, card_relation, TRUE};
    6322      210851 :                 SelectNode *sn = (SelectNode *) s;
    6323             : 
    6324      210851 :                 if (sn->into) {
    6325           1 :                         sql->type = Q_SCHEMA;
    6326           1 :                         ret = rel_select_with_into(query, s);
    6327             :                 } else {
    6328      210850 :                         ret = rel_subquery(query, s, ek);
    6329      210849 :                         sql->type = Q_TABLE;
    6330             :                 }
    6331      210850 :         }       break;
    6332           0 :         case SQL_JOIN:
    6333           0 :                 ret = rel_joinquery(query, s, NULL);
    6334           0 :                 sql->type = Q_TABLE;
    6335           0 :                 break;
    6336       19117 :         case SQL_UNION:
    6337             :         case SQL_EXCEPT:
    6338             :         case SQL_INTERSECT:
    6339       19117 :                 ret = rel_setquery(query, s);
    6340       19117 :                 sql->type = Q_TABLE;
    6341       19117 :                 break;
    6342             :         default:
    6343             :                 return NULL;
    6344             :         }
    6345      237807 :         if (!ret && sql->errstr[0] == 0)
    6346           0 :                 (void) sql_error(sql, 02, SQLSTATE(42000) "relational query without result");
    6347             :         return ret;
    6348             : }
    6349             : 
    6350             : sql_rel *
    6351       79016 : schema_selects(sql_query *query, sql_schema *schema, symbol *s)
    6352             : {
    6353       79016 :         mvc *sql = query->sql;
    6354       79016 :         sql_rel *res;
    6355       79016 :         sql_schema *os = cur_schema(sql);
    6356             : 
    6357       79016 :         sql->session->schema = schema;
    6358       79016 :         res = rel_selects(query, s);
    6359       79016 :         sql->session->schema = os;
    6360       79016 :         return res;
    6361             : }
    6362             : 
    6363             : sql_rel *
    6364          26 : rel_loader_function(sql_query *query, symbol* fcall, list *fexps, sql_subfunc **loader_function)
    6365             : {
    6366          26 :         mvc *sql = query->sql;
    6367          26 :         sql_rel *sq = NULL;
    6368          26 :         dnode *l = fcall->data.lval->h;
    6369          26 :         char *sname = qname_schema(l->data.lval);
    6370          26 :         char *fname = qname_schema_object(l->data.lval);
    6371             : 
    6372          26 :         list *tl = sa_list(sql->sa);
    6373          26 :         list *exps = sa_list(sql->sa);
    6374          26 :         if (l->next)
    6375          26 :                 l = l->next; /* skip distinct */
    6376          26 :         if (l->next) { /* table call with subquery */
    6377          22 :                 if (l->next->type == type_symbol || l->next->type == type_list) {
    6378          22 :                         int count = 0;
    6379          22 :                         symbol *subquery = NULL;
    6380          22 :                         dnode *n = NULL;
    6381             : 
    6382          22 :                         if (l->next->type == type_symbol)
    6383             :                                 n = l->next;
    6384             :                         else
    6385           1 :                                 n = l->next->data.lval->h;
    6386             : 
    6387          66 :                         for (dnode *m = n; m; m = m->next) {
    6388          44 :                                 if (m->type == type_symbol && m->data.sym->token == SQL_SELECT)
    6389          44 :                                         subquery = m->data.sym;
    6390          44 :                                 count++;
    6391             :                         }
    6392          22 :                         if (subquery && count > 1)
    6393           0 :                                 return sql_error(sql, 02, SQLSTATE(42000) "SELECT: The input for the loader function '%s' must be either a single sub query, or a list of values", fname);
    6394             : 
    6395          22 :                         if (subquery) {
    6396           0 :                                 exp_kind ek = { type_value, card_relation, TRUE };
    6397           0 :                                 if (!(sq = rel_subquery(query, subquery, ek)))
    6398           0 :                                         return NULL;
    6399             :                         } else {
    6400          22 :                                 exp_kind ek = { type_value, card_column, TRUE };
    6401          22 :                                 list *exps = sa_list(sql->sa);
    6402          88 :                                 for ( ; n; n = n->next) {
    6403          44 :                                         sql_exp *e = rel_value_exp(query, NULL, n->data.sym, sql_sel | sql_from, ek);
    6404             : 
    6405          44 :                                         if (!e)
    6406           0 :                                                 return NULL;
    6407          44 :                                         append(exps, e);
    6408             :                                 }
    6409          22 :                                 sq = rel_project(sql->sa, NULL, exps);
    6410             :                         }
    6411             :                 }
    6412          22 :                 if (!sq)
    6413           0 :                         return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: no such loader function %s%s%s'%s'", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
    6414          66 :                 for (node *en = sq->exps->h; en; en = en->next) {
    6415          44 :                         sql_exp *e = en->data;
    6416             : 
    6417          44 :                         append(exps, e = exp_ref(sql, e));
    6418          44 :                         append(tl, exp_subtype(e));
    6419             :                 }
    6420             :         }
    6421             : 
    6422          26 :         sql_exp *e = NULL;
    6423          26 :         if (!(e = find_table_function(sql, sname, fname, exps, tl, F_LOADER)))
    6424             :                 return NULL;
    6425          25 :         sql_subfunc *sf = e->f;
    6426          25 :         if (sq) {
    6427          66 :                 for (node *n = sq->exps->h, *m = sf->func->ops->h ; n && m ; n = n->next, m = m->next) {
    6428          44 :                         sql_exp *e = (sql_exp*) n->data;
    6429          44 :                         sql_arg *a = (sql_arg*) m->data;
    6430          44 :                         if (!exp_subtype(e) && rel_set_type_param(sql, &(a->type), sq, e, 0) < 0)
    6431             :                                 return NULL;
    6432             :                 }
    6433             :         }
    6434             : 
    6435          25 :         if (loader_function)
    6436          25 :                 *loader_function = sf;
    6437             : 
    6438          28 :         return rel_table_func(sql->sa, sq, e, fexps, (sq)?TABLE_FROM_RELATION:TABLE_PROD_FUNC);
    6439             : }

Generated by: LCOV version 1.14