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 56719 : rel_table_projections( mvc *sql, sql_rel *rel, char *tname, int level )
38 : {
39 57230 : list *exps;
40 :
41 57230 : if (mvc_highwater(sql))
42 1 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
43 :
44 57230 : if (!rel)
45 : return NULL;
46 :
47 57230 : if (!tname)
48 41554 : return _rel_projections(sql, rel, NULL, 1, 0, 1);
49 :
50 15676 : switch(rel->op) {
51 519 : case op_join:
52 : case op_left:
53 : case op_right:
54 : case op_full:
55 519 : exps = rel_table_projections( sql, rel->l, tname, level+1);
56 519 : if (exps)
57 : return exps;
58 13 : return rel_table_projections( sql, rel->r, tname, level+1);
59 498 : case op_semi:
60 : case op_anti:
61 : case op_select:
62 498 : 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 14659 : if (is_basetable(rel->op) && !rel->exps)
84 14101 : return rel_base_project_all(sql, rel, tname);
85 558 : if (rel->exps) {
86 558 : int rename = 0;
87 558 : node *en;
88 :
89 : /* first check alias */
90 558 : 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 558 : exps = new_exp_list(sql->sa);
107 4912 : for (en = rel->exps->h; en; en = en->next) {
108 4354 : sql_exp *e = en->data;
109 4354 : if (is_basecol(e) && exp_relname(e) && strcmp(exp_relname(e), tname) == 0) {
110 4214 : if (rename)
111 0 : append(exps, exp_alias_ref(sql, e));
112 : else {
113 4214 : sql_exp *ne = exp_ref(sql, e);
114 4214 : exp_setname(sql, ne, tname, exp_name(e));
115 4214 : append(exps, ne);
116 : }
117 : }
118 4354 : 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 558 : 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 36189 : rel_orderby(mvc *sql, sql_rel *l)
157 : {
158 36189 : sql_rel *rel = rel_create(sql->sa);
159 36189 : if (!rel)
160 : return NULL;
161 :
162 36189 : assert(l->op == op_project && !l->r);
163 36189 : rel->l = l;
164 36189 : rel->r = NULL;
165 36189 : rel->op = op_project;
166 36189 : rel->exps = rel_projections(sql, l, NULL, 1, 0);
167 36189 : rel->card = l->card;
168 36189 : rel->nrcols = l->nrcols;
169 36189 : 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 201553 : rel_table_optname(mvc *sql, sql_rel *sq, symbol *optname, list *refs)
178 : {
179 201553 : sql_rel *osq = sq;
180 201553 : node *ne;
181 :
182 201553 : if (optname && optname->token == SQL_NAME) {
183 17856 : dlist *columnrefs = NULL;
184 17856 : char *tname = optname->data.lval->h->data.sval;
185 17856 : list *l = sa_list(sql->sa);
186 :
187 17856 : columnrefs = optname->data.lval->h->next->data.lval;
188 17856 : 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 101 : sq = rel_project(sql->sa, sq, rel_projections(sql, sq, NULL, 1, 0));
190 101 : osq = sq;
191 : }
192 17856 : 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 4979 : if (columnrefs && sq->exps) {
195 4979 : dnode *d = columnrefs->h;
196 :
197 4979 : ne = sq->exps->h;
198 4979 : list_hash_clear(sq->exps);
199 20562 : for (; d && ne; d = d->next, ne = ne->next) {
200 10605 : sql_exp *e = ne->data;
201 :
202 10605 : 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 10604 : exp_setname(sql, e, tname, d->data.sval );
205 10604 : if (!is_intern(e))
206 10604 : set_basecol(e);
207 10604 : append(l, e);
208 : }
209 : }
210 17849 : if (!columnrefs && sq->exps) {
211 12871 : ne = sq->exps->h;
212 12871 : list_hash_clear(sq->exps);
213 126050 : for (; ne; ne = ne->next) {
214 100308 : sql_exp *e = ne->data;
215 100308 : char *name = NULL;
216 :
217 100308 : if (!is_intern(e)) {
218 100308 : if (!exp_name(e))
219 108 : name = make_label(sql->sa, ++sql->label);
220 100308 : noninternexp_setname(sql, e, tname, name);
221 100308 : set_basecol(e);
222 : }
223 : }
224 : }
225 17849 : if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
226 17799 : 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 17793 : assert(tname);
229 17793 : list_append(refs, tname);
230 : }
231 : } else {
232 183697 : 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 58293 : sq = rel_project(sql->sa, sq, rel_projections(sql, sq, NULL, 1, 1));
234 58293 : osq = sq;
235 : }
236 2311516 : for (ne = osq->exps->h; ne; ne = ne->next) {
237 2127819 : sql_exp *e = ne->data;
238 :
239 2127819 : if (!is_intern(e))
240 2001854 : set_basecol(e);
241 : }
242 : }
243 : return osq;
244 : }
245 :
246 : static sql_rel *
247 97098 : rel_subquery_optname(sql_query *query, symbol *ast, list *refs)
248 : {
249 97098 : mvc *sql = query->sql;
250 97098 : SelectNode *sn = (SelectNode *) ast;
251 97098 : exp_kind ek = {type_value, card_relation, TRUE};
252 97098 : sql_rel *sq = rel_subquery(query, ast, ek);
253 :
254 97098 : assert(ast->token == SQL_SELECT);
255 97098 : if (!sq)
256 : return NULL;
257 :
258 97082 : return rel_table_optname(sql, sq, sn->name, refs);
259 : }
260 :
261 : sql_rel *
262 6904 : rel_with_query(sql_query *query, symbol *q )
263 : {
264 6904 : mvc *sql = query->sql;
265 6904 : dnode *d = q->data.lval->h;
266 6904 : symbol *next = d->next->data.sym;
267 6904 : sql_rel *rel;
268 :
269 6904 : 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 19586 : for (d = d->data.lval->h; d; d = d->next) {
273 12688 : symbol *sym = d->data.sym;
274 12688 : dnode *dn = sym->data.lval->h->next;
275 12688 : char *rname = qname_schema_object(dn->data.lval);
276 12688 : sql_rel *nrel;
277 :
278 12688 : 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 12687 : nrel = rel_semantic(query, sym);
283 12687 : if (!nrel) {
284 5 : stack_pop_frame(sql);
285 5 : return NULL;
286 : }
287 12682 : 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 12682 : 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 12682 : assert(is_project(nrel->op));
300 12682 : if (is_project(nrel->op) && nrel->exps) {
301 12682 : node *ne = nrel->exps->h;
302 :
303 56246 : for (; ne; ne = ne->next) {
304 43564 : sql_exp *e = ne->data;
305 43564 : char *name = NULL;
306 :
307 43564 : if (!is_intern(e)) {
308 43564 : if (!exp_name(e))
309 13 : name = make_label(sql->sa, ++sql->label);
310 43564 : noninternexp_setname(sql, e, rname, name);
311 43564 : set_basecol(e);
312 : }
313 : }
314 12682 : list_hash_clear(nrel->exps);
315 : }
316 : }
317 6898 : rel = rel_semantic(query, next);
318 6898 : stack_pop_frame(sql);
319 6898 : return rel;
320 : }
321 :
322 : static sql_rel *
323 59344 : query_exp_optname(sql_query *query, symbol *q, list *refs)
324 : {
325 59344 : mvc *sql = query->sql;
326 59344 : switch (q->token) {
327 939 : case SQL_WITH:
328 : {
329 939 : sql_rel *tq = rel_with_query(query, q);
330 :
331 939 : if (!tq)
332 : return NULL;
333 939 : if (q->data.lval->t->type == type_symbol)
334 939 : return rel_table_optname(sql, tq, q->data.lval->t->data.sym, refs);
335 : return tq;
336 : }
337 58405 : case SQL_JOIN:
338 : {
339 58405 : sql_rel *tq = rel_joinquery(query, q, refs);
340 :
341 58405 : if (!tq)
342 : return NULL;
343 58368 : 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 112765 : bind_func_(mvc *sql, char *sname, char *fname, list *ops, sql_ftype type, bool private, bool *found, bool exact)
353 : {
354 112765 : sql_subfunc *sf = NULL;
355 :
356 112989 : if (sql->forward && strcmp(fname, sql->forward->base.name) == 0 &&
357 224 : 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 112765 : sf = sql_bind_func_(sql, sname, fname, ops, type, private, exact);
361 112765 : if (found)
362 112294 : *found |= sf != NULL;
363 112765 : if (sf && execute_priv(sql, sf->func))
364 : return sf;
365 : return NULL;
366 : }
367 :
368 : static sql_subfunc *
369 614486 : 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 614486 : list *tl = sa_list(sql->sa);
372 614486 : assert(nr >= 1 && nr <= 2);
373 614486 : append(tl, t1);
374 614486 : if (nr == 2)
375 520487 : append(tl, t2);
376 614486 : sql_subfunc *sf = NULL;
377 :
378 614486 : if (sql->forward) {
379 131035 : if (execute_priv(sql, sql->forward) &&
380 131035 : strcmp(fname, sql->forward->base.name) == 0 &&
381 229 : ((!t1 && list_length(sql->forward->ops) == 0) ||
382 231 : (!t2 && list_length(sql->forward->ops) == 1 && arg_subtype_cmp(sql->forward->ops->h->data, t1) == 0) ||
383 227 : (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 614484 : sf = sql_bind_func_(sql, sname, fname, tl, type, private, exact);
390 614484 : if (found)
391 614484 : *found |= sf != NULL;
392 614484 : if (sf && execute_priv(sql, sf->func))
393 : return sf;
394 : return NULL;
395 : }
396 :
397 : static sql_subfunc *
398 633695 : find_func(mvc *sql, char *sname, char *fname, int len, sql_ftype type, bool private, sql_subfunc *prev, bool *found)
399 : {
400 633695 : sql_subfunc *sf = NULL;
401 :
402 633695 : 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 633695 : sf = sql_find_func(sql, sname, fname, len, type, private, prev);
405 633695 : if (found)
406 0 : *found |= sf != NULL;
407 633695 : if (sf && execute_priv(sql, sf->func))
408 : return sf;
409 : return NULL;
410 : }
411 :
412 : static sql_exp *
413 691434 : exp_fix_scale(mvc *sql, sql_subtype *ct, sql_exp *e)
414 : {
415 691434 : sql_subtype *et = exp_subtype(e);
416 :
417 691434 : if (ct->type->scale == SCALE_FIX && et->type->scale == SCALE_FIX) {
418 82330 : int scale_diff = ((int) ct->scale - (int) et->scale);
419 :
420 82330 : 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 9452 : rel_get_count(sql_rel *rel)
435 : {
436 30639 : if (!rel)
437 : return 0;
438 30635 : prop *p = NULL;
439 30635 : if (rel->p && (p = find_prop(rel->p, PROP_COUNT)) != NULL)
440 2907 : return p->value.lval;
441 27728 : 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 27560 : } else if(rel->l) {
452 24917 : 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 734375 : 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 734375 : list *nexps = new_exp_list(sql->sa);
464 734376 : sql_subtype *atp = NULL, super, *res = !list_empty(sf->res) ? sf->res->h->data: NULL;
465 734376 : unsigned int digits = 0, scale = 0;
466 :
467 : /* find largest any type argument */
468 2168588 : for (node *n = exps->h, *m = sf->func->ops->h; n && m; n = n->next, m = m->next) {
469 1434213 : sql_arg *a = m->data;
470 1434213 : sql_exp *e = n->data;
471 1434213 : sql_subtype *t = exp_subtype(e);
472 :
473 1434212 : if (a->type.type->eclass == EC_ANY) {
474 264146 : if (t && atp) {
475 114003 : supertype(&super, t, atp);
476 114003 : atp = &super;
477 150143 : } else if (t) {
478 : atp = t;
479 : }
480 : }
481 1434209 : 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 734375 : if (!atp && !list_empty(exps))
489 584234 : atp = exp_subtype(exps->h->data);
490 :
491 734376 : if ((atp && atp->type->localtype == TYPE_void) || !atp) /* NULL */
492 9364 : atp = sql_bind_localtype("str");
493 :
494 734376 : node *n, *m;
495 2168587 : for (n = exps->h, m = sf->func->ops->h; n && m; n = n->next, m = m->next) {
496 1434212 : sql_arg *a = m->data;
497 1434212 : sql_exp *e = n->data;
498 1434212 : sql_subtype *ntp = &a->type, *t = exp_subtype(e);
499 :
500 1434211 : 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 1434173 : } else if (a->type.type->eclass == EC_ANY && atp) {
505 264143 : ntp = sql_create_subtype(sql->sa, atp->type, atp->digits, atp->scale);
506 1170030 : } else if (t && ntp->digits == 0 && EC_VARCHAR(a->type.type->eclass)) {
507 508667 : ntp = sql_create_subtype(sql->sa, a->type.type, type_digits_to_char_digits(t), 0);
508 661363 : } else if (t && ntp->digits > 0 && a->type.type->eclass == EC_NUM && t->type->eclass == EC_NUM) {
509 357657 : ntp = sql_create_subtype(sql->sa, a->type.type, t->digits, 0);
510 303706 : } 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 303706 : } else if (t && ntp->scale == 0 && ntp->type->eclass == EC_DEC) {
516 4859 : ntp = sql_create_subtype(sql->sa, a->type.type, t->type->eclass == EC_NUM?bits2digits(t->digits):t->digits, t->scale);
517 298847 : } else if (t->type == ntp->type) {
518 296757 : ntp = t;
519 : }
520 1434212 : if (!(e = exp_check_type(sql, ntp, rel, e, type_equal)))
521 : return NULL;
522 1434211 : if (sf->func->fix_scale == SCALE_FIX) {
523 521013 : ntp = sql_create_subtype(sql->sa, a->type.type->localtype?a->type.type:t?t->type:atp->type, digits, scale);
524 521013 : e = exp_fix_scale(sql, ntp, e);
525 913198 : } else if (sf->func->fix_scale == SCALE_EQ) {
526 170421 : e = exp_fix_scale(sql, &a->type, e);
527 : }
528 1434211 : 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 1434211 : append(nexps, e);
533 : }
534 : /* handle any extra arguments for rel_dump/analytic funcs */
535 734594 : for ( ; n; n = n->next)
536 218 : append(nexps, n->data);
537 734376 : if (sf->func->fix_scale == SCALE_FIX || IS_ANALYTIC(sf->func)) {
538 269166 : exps_scale_fix(sf, nexps, atp);
539 465210 : } else if (sf->func->fix_scale == MAX_BITS) {
540 111230 : exps_max_bits(sf, nexps);
541 353980 : } else if (sf->func->fix_scale == SCALE_MUL) {
542 25105 : exps_sum_scales(sf, nexps);
543 328875 : } else if (!internal && sf->func->fix_scale == SCALE_DIV) {
544 2591 : if (!exps_scale_algebra(sql, sf, rel, nexps))
545 : return NULL;
546 326284 : } else if (sf->func->fix_scale == DIGITS_ADD) {
547 180536 : exps_digits_add(sf, nexps);
548 145748 : } else if (sf->func->fix_scale == INOUT) {
549 18965 : exps_inout(sf, nexps);
550 126783 : } else if (is_sum_aggr(sf->func))
551 9116 : exps_largest_int(sf, nexps, rel_get_count(rel));
552 :
553 : /* dirty hack */
554 734374 : if (sf->func->type != F_PROC && sf->func->type != F_UNION && sf->func->type != F_LOADER && res) {
555 729768 : 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 30 : nary_function_arg_types_2str(mvc *sql, list* types, int N)
563 : {
564 30 : char *arg_list = NULL;
565 30 : int i = 0;
566 :
567 111 : for (node *n = types->h; n && i < N; n = n->next) {
568 81 : sql_subtype *t = (sql_subtype *) n->data;
569 81 : char *tpe = t ? sql_subtype_string(sql->ta, t) : "?";
570 :
571 81 : if (arg_list) {
572 51 : arg_list = sa_message(sql->ta, "%s, %s", arg_list, tpe);
573 : } else {
574 : arg_list = tpe;
575 : }
576 81 : i++;
577 : }
578 30 : 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 10796 : find_table_function(mvc *sql, char *sname, char *fname, list *exps, list *tl, sql_ftype type)
662 : {
663 10796 : bool found = false;
664 10796 : sql_subfunc *f = NULL;
665 :
666 10796 : assert(type == F_UNION || type == F_LOADER);
667 10796 : if ((f = bind_func_(sql, sname, fname, tl, type, false, &found, false))) {
668 10776 : list *nexps = exps;
669 10776 : if (list_empty(tl) || f->func->vararg || (nexps = check_arguments_and_find_largest_any_type(sql, NULL, exps, f, 1, false)))
670 10776 : 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 10807 : rel_named_table_function(sql_query *query, sql_rel *rel, symbol *ast, int lateral, list *refs)
681 : {
682 10807 : mvc *sql = query->sql;
683 10807 : list *exps = NULL, *tl;
684 10807 : node *m;
685 10807 : exp_kind ek = {type_value, card_relation, TRUE};
686 10807 : sql_rel *sq = NULL, *outer = NULL;
687 10807 : sql_exp *e = NULL;
688 10807 : sql_subfunc *sf = NULL;
689 10807 : symbol *sym = ast->data.lval->h->data.sym, *subquery = NULL;
690 10807 : dnode *l = sym->data.lval->h, *n;
691 10807 : char *tname = NULL;
692 10807 : char *fname = qname_schema_object(l->data.lval);
693 10807 : char *sname = qname_schema(l->data.lval);
694 :
695 10807 : tl = sa_list(sql->sa);
696 10807 : exps = sa_list(sql->sa);
697 10807 : if (l->next)
698 10807 : l = l->next; /* skip distinct */
699 10807 : if (l->next) { /* table call with subquery */
700 1004 : int is_value = 1;
701 1004 : if (l->next->type == type_symbol || l->next->type == type_list) {
702 1004 : exp_kind iek = {type_value, card_set, TRUE};
703 1004 : int count = 0;
704 :
705 1004 : if (l->next->type == type_symbol)
706 : n = l->next;
707 : else
708 671 : n = l->next->data.lval->h;
709 :
710 3600 : for (dnode *m = n; m; m = m->next) {
711 2596 : if (m->type == type_symbol && m->data.sym->token == SQL_SELECT)
712 2596 : subquery = m->data.sym;
713 2596 : count++;
714 : }
715 1004 : if (subquery && count > 1)
716 14 : 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 999 : if (subquery) {
720 23 : if (!(sq = rel_subquery(query, subquery, ek)))
721 : return NULL;
722 : is_value = 0;
723 : } else {
724 3530 : for ( ; n; n = n->next) {
725 2558 : sql_exp *e = rel_value_exp(query, &outer, n->data.sym, sql_sel | sql_from, iek);
726 :
727 2558 : if (!e)
728 : return NULL;
729 2554 : append(exps, e);
730 2554 : is_value &= exp_is_atom(e);
731 : }
732 972 : if (!is_value || (lateral && outer))
733 11 : sq = rel_project(sql->sa, NULL, exps);
734 11 : 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 995 : 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 995 : if (!is_value) {
744 34 : if (list_length(exps))
745 11 : exps = sa_list(sql->sa);
746 133 : for (node *en = sq->exps->h; en; en = en->next) {
747 99 : sql_exp *e = en->data;
748 :
749 99 : if (!e->alias.label)
750 23 : exp_label(sql->sa, e, ++sql->label);
751 99 : sql_exp *ne = exp_ref(sql, e);
752 : /* allow for table functions with table input */
753 99 : ne->card = CARD_ATOM;
754 99 : exp_setname(sql, ne, tname, exp_name(e));
755 99 : append(exps, ne);
756 99 : append(tl, exp_subtype(e));
757 : }
758 : } else {
759 3493 : for (node *en = exps->h; en; en = en->next)
760 2532 : append(tl, exp_subtype(en->data));
761 : }
762 : }
763 :
764 10798 : rel = NULL;
765 10798 : if (ast->data.lval->t->type == type_symbol && ast->data.lval->t->data.sym)
766 1182 : tname = ast->data.lval->t->data.sym->data.lval->h->data.sval;
767 : else
768 9616 : tname = make_label(sql->sa, ++sql->label);
769 :
770 10798 : 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 20568 : } else if (!(e = find_table_function(sql, sname, fname, list_empty(exps) ? NULL : exps, tl, F_UNION)))
775 : return NULL;
776 :
777 10746 : if (!rel) {
778 10746 : rel = sq;
779 :
780 : /* column or table function */
781 10746 : sf = e->f;
782 10746 : 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 10746 : if (sq) {
786 133 : for (node *n = sq->exps->h, *m = sf->func->ops->h ; n && m ; n = n->next, m = m->next) {
787 99 : sql_exp *e = (sql_exp*) n->data;
788 99 : sql_arg *a = (sql_arg*) m->data;
789 99 : 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 10746 : exps = new_exp_list(sql->sa);
796 106673 : for (m = sf->func->res->h; m; m = m->next) {
797 95927 : sql_arg *a = m->data;
798 95927 : sql_exp *e = exp_column(sql->sa, tname, a->name, &a->type, CARD_MULTI, 1, 0, 0);
799 95927 : e->alias.label = -(sql->nid++);
800 :
801 95927 : set_basecol(e);
802 95927 : append(exps, e);
803 : }
804 21458 : rel = rel_table_func(sql->sa, rel, e, exps, (sq)?TABLE_FROM_RELATION:TABLE_PROD_FUNC);
805 : }
806 10760 : 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 20 : rel = rel_table_optname(sql, rel, ast->data.lval->t->data.sym, refs);
808 10740 : } else if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
809 10740 : 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 10740 : list_append(refs, tname);
812 : }
813 : return rel;
814 : }
815 :
816 : static sql_exp *
817 1817 : rel_op_(mvc *sql, char *sname, char *fname, exp_kind ek)
818 : {
819 1817 : bool found = false;
820 1817 : sql_subfunc *f = NULL;
821 1817 : 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 1817 : if ((f = bind_func_(sql, sname, fname, NULL, type, false, &found, true))) {
825 1800 : if (check_card(ek.card, f))
826 1800 : return exp_op(sql->sa, NULL, f);
827 0 : found = false;
828 : }
829 34 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s operator %s%s%s'%s'()",
830 17 : found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
831 : }
832 :
833 : static sql_exp*
834 4082 : exp_tuples_set_supertype(mvc *sql, list *tuple_values, sql_exp *tuples)
835 : {
836 4082 : assert(is_values(tuples));
837 4082 : list *vals = exp_get_values(tuples);
838 4082 : if (!vals || !vals->h)
839 : return NULL;
840 :
841 4082 : int tuple_width = list_length(tuple_values), i;
842 4082 : sql_subtype *types = SA_NEW_ARRAY(sql->sa, sql_subtype, tuple_width);
843 4082 : bool *has_type = SA_NEW_ARRAY(sql->sa, bool, tuple_width);
844 4082 : node *n;
845 :
846 4082 : memset(has_type, 0, sizeof(bool)*tuple_width);
847 13290 : for(n = tuple_values->h, i = 0; n; n = n->next, i++) {
848 9208 : sql_exp *e = n->data;
849 9208 : if (exp_subtype(e)) {
850 9206 : types[i] = *exp_subtype(e);
851 9206 : has_type[i] = 1;
852 : }
853 : }
854 :
855 8166 : for (node *m = vals->h; m; m = m->next) {
856 4084 : sql_exp *tuple = m->data;
857 4084 : 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 4081 : sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, tuple);
881 :
882 13287 : for(n = tuple_relation->exps->h, i = 0; n; n = n->next, i++) {
883 9206 : sql_subtype *tpe;
884 9206 : sql_exp *e = n->data;
885 :
886 9206 : 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 9206 : tpe = exp_subtype(e);
893 9206 : if (!tpe)
894 : return NULL;
895 9206 : if (has_type[i] && tpe) {
896 9204 : 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 8166 : for (node *m = vals->h; m; m = m->next) {
906 4084 : sql_exp *tuple = m->data;
907 4084 : 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 4081 : sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, tuple);
922 :
923 4081 : list *nexps = sa_list(sql->sa);
924 13287 : for(n = tuple_relation->exps->h, i = 0; n; n = n->next, i++) {
925 9206 : sql_exp *e = n->data;
926 :
927 9206 : e = exp_check_type(sql, types+i, NULL, e, type_equal);
928 9206 : if (!e)
929 : return NULL;
930 9206 : append(nexps, e);
931 : }
932 4081 : tuple_relation->exps = nexps;
933 : }
934 : }
935 : return tuples;
936 : }
937 :
938 : static int
939 9208 : rel_binop_check_types(mvc *sql, sql_rel *rel, sql_exp *ls, sql_exp *rs, int upcast)
940 : {
941 9208 : sql_subtype *t1 = exp_subtype(ls), *t2 = exp_subtype(rs);
942 :
943 9208 : 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 9208 : 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 4082 : tuples_check_types(mvc *sql, list *tuple_values, sql_exp *tuples)
958 : {
959 4082 : list *tuples_list = exp_get_values(tuples);
960 4082 : sql_exp *first_tuple = tuples_list->h->data;
961 4082 : list *nvalues = sa_list(sql->sa);
962 4082 : 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 4081 : sql_rel *tuple_relation = exp_rel_get_rel(sql->sa, first_tuple);
977 :
978 4081 : assert(list_length(tuple_values) == list_length(tuple_relation->exps));
979 13287 : for (node *n = tuple_values->h, *m = tuple_relation->exps->h; n && m; n = n->next, m = m->next) {
980 9206 : sql_exp *le = n->data, *re = m->data;
981 :
982 9206 : if (rel_binop_check_types(sql, NULL, le, re, 0) < 0)
983 : return NULL;
984 9206 : if ((le = exp_check_type(sql, exp_subtype(re), NULL, le, type_equal)) == NULL)
985 : return NULL;
986 9206 : append(nvalues, le);
987 : }
988 : return nvalues;
989 : }
990 : return tuple_values;
991 : }
992 :
993 : static sql_rel *
994 3697 : rel_values(sql_query *query, symbol *tableref, list *refs)
995 : {
996 3697 : mvc *sql = query->sql;
997 3697 : sql_rel *r = NULL;
998 3697 : dlist *rowlist = tableref->data.lval->h->data.lval;
999 3697 : symbol *optname = tableref->data.lval->t->type == type_symbol ? tableref->data.lval->t->data.sym : NULL;
1000 3697 : node *m;
1001 3697 : list *exps = sa_list(sql->sa);
1002 3697 : exp_kind ek = {type_value, card_value, TRUE};
1003 :
1004 14843 : for (dnode *o = rowlist->h; o; o = o->next) {
1005 11155 : dlist *values = o->data.lval;
1006 :
1007 11155 : 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 11152 : dnode *n;
1011 :
1012 11152 : if (list_empty(exps)) {
1013 10559 : for (n = values->h; n; n = n->next) {
1014 6862 : sql_exp *vals = exp_values(sql->sa, sa_list(sql->sa));
1015 :
1016 6862 : exp_label(sql->sa, vals, ++sql->label);
1017 6862 : list_append(exps, vals);
1018 : }
1019 : }
1020 34153 : for (n = values->h, m = exps->h; n && m; n = n->next, m = m->next) {
1021 23007 : sql_exp *vals = m->data;
1022 23007 : list *vals_list = vals->f;
1023 23007 : sql_exp *e = rel_value_exp(query, NULL, n->data.sym, sql_sel | sql_values, ek);
1024 23007 : if (!e)
1025 : return NULL;
1026 23001 : list_append(vals_list, e);
1027 : }
1028 : }
1029 : }
1030 :
1031 : /* loop to check types and cardinality */
1032 3688 : unsigned int card = exps->h && list_length(((sql_exp*)exps->h->data)->f) > 1 ? CARD_MULTI : CARD_ATOM;
1033 10534 : for (m = exps->h; m; m = m->next) {
1034 6849 : sql_exp *e = m->data;
1035 :
1036 6849 : if (!(e = exp_values_set_supertype(sql, e, NULL)))
1037 : return NULL;
1038 6846 : e->card = card;
1039 6846 : m->data = e;
1040 : }
1041 :
1042 3685 : r = rel_project(sql->sa, NULL, exps);
1043 3685 : r->nrcols = list_length(exps);
1044 3685 : r->card = card;
1045 3685 : return rel_table_optname(sql, r, optname, refs);
1046 : }
1047 :
1048 : static int
1049 493868 : check_is_lateral(symbol *tableref)
1050 : {
1051 493868 : if (tableref->token == SQL_NAME || tableref->token == SQL_TABLE ||
1052 : tableref->token == SQL_VALUES) {
1053 442771 : if (dlist_length(tableref->data.lval) == 3)
1054 441969 : return tableref->data.lval->h->next->data.i_val;
1055 : return 0;
1056 : } else if (tableref->token == SQL_WITH) {
1057 937 : 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 3574 : SelectNode *sn = (SelectNode *) tableref;
1062 3574 : return sn->lateral;
1063 : } else if (tableref->token == SQL_EXCEPT || tableref->token == SQL_INTERSECT ||
1064 : tableref->token == SQL_UNION) {
1065 10636 : if (dlist_length(tableref->data.lval) == 6)
1066 8980 : 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 673992 : table_ref(sql_query *query, symbol *tableref, int lateral, list *refs)
1094 : {
1095 673992 : mvc *sql = query->sql;
1096 673992 : char *tname = NULL;
1097 673992 : sql_table *t = NULL;
1098 673992 : sql_rel *res = NULL;
1099 :
1100 673992 : if (tableref->token == SQL_NAME) {
1101 463962 : dlist *name = tableref->data.lval->h->data.lval;
1102 463962 : sql_rel *temp_table = NULL;
1103 463962 : char *sname = qname_schema(name);
1104 463967 : int allowed = 1;
1105 :
1106 463967 : tname = qname_schema_object(name);
1107 :
1108 463965 : if (dlist_length(name) > 2)
1109 4 : return sql_error(sql, 02, SQLSTATE(3F000) "SELECT: only a schema and table name expected");
1110 :
1111 463965 : if (!sname)
1112 112309 : temp_table = stack_find_rel_view(sql, tname);
1113 112308 : if (!temp_table)
1114 447194 : t = find_table_or_view_on_scope(sql, NULL, sname, tname, "SELECT", false);
1115 463962 : if (!t && !temp_table)
1116 : return NULL;
1117 463863 : if (!temp_table && !table_privs(sql, t, PRIV_SELECT))
1118 463854 : allowed = 0;
1119 :
1120 463854 : if (tableref->data.lval->t->type == type_symbol && tableref->data.lval->t->data.sym) /* AS */
1121 271179 : tname = tableref->data.lval->t->data.sym->data.lval->h->data.sval;
1122 463854 : if (temp_table && !t) {
1123 16770 : node *n;
1124 16770 : int needed = !is_simple_project(temp_table->op);
1125 :
1126 16770 : 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 59982 : for (n = temp_table->exps->h; n && !needed; n = n->next) {
1131 43212 : sql_exp *e = n->data;
1132 :
1133 43212 : if (!exp_relname(e) || strcmp(exp_relname(e), tname) != 0)
1134 : needed = 1;
1135 : }
1136 :
1137 16770 : if (needed) {
1138 6792 : list *exps = rel_projections(sql, temp_table, NULL, 1, 1);
1139 :
1140 6792 : temp_table = rel_project(sql->sa, temp_table, exps);
1141 24367 : for (n = exps->h; n; n = n->next) {
1142 17575 : sql_exp *e = n->data;
1143 :
1144 17575 : noninternexp_setname(sql, e, tname, NULL);
1145 17575 : set_basecol(e);
1146 : }
1147 6792 : list_hash_clear(exps);
1148 : }
1149 : }
1150 16770 : 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 16770 : 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 447084 : } else if (isView(t)) {
1156 : /* instantiate base view */
1157 69217 : node *n,*m;
1158 69217 : sql_rel *rel;
1159 :
1160 69217 : if (sql->emode == m_deps) {
1161 24276 : rel = rel_basetable(sql, t, tname);
1162 24276 : if (!allowed)
1163 0 : rel_base_disallow(rel);
1164 : } else {
1165 : /* when recreating a view, the view itself can't be found */
1166 44941 : 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 44940 : rel = rel_parse(sql, t->s, t->query, m_instantiate);
1169 44940 : if (rel && sql->emode == m_deps)
1170 0 : rel = rel_unnest(sql, rel);
1171 : }
1172 :
1173 69214 : if (!rel)
1174 2 : return NULL;
1175 : /* Rename columns of the rel_parse relation */
1176 69214 : if (sql->emode != m_deps) {
1177 44938 : assert(is_project(rel->op));
1178 44938 : set_processed(rel);
1179 44938 : 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 44938 : rel = rel_project(sql->sa, rel, rel_projections(sql, rel, NULL, 0, 0));
1182 44938 : set_processed(rel);
1183 : }
1184 406073 : for (n = ol_first_node(t->columns), m = rel->exps->h; n && m; n = n->next, m = m->next) {
1185 361135 : sql_column *c = n->data;
1186 361135 : sql_exp *e = m->data;
1187 :
1188 361135 : exp_setname(sql, e, tname, c->base.name);
1189 361135 : set_basecol(e);
1190 : }
1191 44938 : list_hash_clear(rel->exps);
1192 : }
1193 69214 : 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 69198 : return rel;
1196 : }
1197 377867 : 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 377853 : res = rel_basetable(sql, t, tname);
1201 377871 : 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 377840 : 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 377832 : } else if (refs) { /* if this relation is under a FROM clause, check for duplicate names */
1209 377827 : 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 377820 : assert(tname);
1212 377820 : list_append(refs, tname);
1213 : }
1214 377833 : return res;
1215 : } else if (tableref->token == SQL_VALUES) {
1216 1329 : return rel_values(query, tableref, refs);
1217 : } else if (tableref->token == SQL_TABLE) {
1218 10807 : return rel_named_table_function(query, NULL, tableref, lateral, refs);
1219 : } else if (tableref->token == SQL_SELECT) {
1220 97098 : 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 41452 : sql_rel *tq = rel_setquery(query, tableref);
1224 :
1225 41452 : if (!tq)
1226 : return NULL;
1227 : /* look for lateral joins */
1228 41450 : symbol *optname = tableref->data.lval->t->type == type_symbol ? tableref->data.lval->t->data.sym : NULL;
1229 41450 : return rel_table_optname(sql, tq, optname, refs);
1230 : } else {
1231 59344 : return query_exp_optname(query, tableref, refs);
1232 : }
1233 : }
1234 :
1235 : static sql_exp *
1236 120249 : rel_exp_variable_on_scope(mvc *sql, const char *sname, const char *vname)
1237 : {
1238 120249 : sql_subtype *tpe = NULL;
1239 120249 : sql_var *var = NULL;
1240 120249 : sql_arg *a = NULL;
1241 120249 : int level = 1;
1242 :
1243 120249 : if (find_variable_on_scope(sql, sname, vname, &var, &a, &tpe, &level, "SELECT")) {
1244 119375 : if (var) /* if variable is known from the stack or a global var */
1245 37193 : 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 87140 : if (a) /* if variable is a parameter */
1247 87140 : 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 9232 : exps_get_exp(list *exps, int nth)
1254 : {
1255 9232 : node *n = NULL;
1256 9232 : int i = 0;
1257 :
1258 9232 : if (exps)
1259 27154 : for (n=exps->h, i=1; n && i<nth; n=n->next, i++)
1260 : ;
1261 9232 : if (n && i == nth)
1262 9230 : return n->data;
1263 : return NULL;
1264 : }
1265 :
1266 : static sql_rel *
1267 27394 : rel_find_groupby(sql_rel *groupby)
1268 : {
1269 27394 : if (groupby && !is_processed(groupby) && !is_base(groupby->op)) {
1270 36986 : while(!is_processed(groupby) && !is_base(groupby->op)) {
1271 29242 : if (is_groupby(groupby->op) || !groupby->l)
1272 : break;
1273 : if (groupby->l)
1274 : groupby = groupby->l;
1275 : }
1276 27328 : if (groupby && is_groupby(groupby->op))
1277 19584 : return groupby;
1278 : }
1279 : return NULL;
1280 : }
1281 :
1282 : static int
1283 169 : is_groupby_col(sql_rel *gb, sql_exp *e)
1284 : {
1285 169 : gb = rel_find_groupby(gb);
1286 :
1287 169 : if (gb) {
1288 99 : if (exp_relname(e)) {
1289 90 : if (exp_name(e) && exps_bind_column2(gb->r, exp_relname(e), exp_name(e), NULL))
1290 : return 1;
1291 : } else {
1292 9 : 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 4676 : set_dependent_( sql_rel *r)
1301 : {
1302 4676 : if (is_select(r->op))
1303 3568 : r = r->l;
1304 4676 : if (r && is_join(r->op))
1305 1159 : set_dependent(r);
1306 4676 : }
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 51 : bool group_by_pk_project_uk_cond(mvc* sql, sql_rel* inner, sql_exp* exp,const char* sname, const char* tname) {
1317 51 : sql_table* t = find_table_or_view_on_scope(sql, NULL, sname, tname, "SELECT", false);
1318 51 : bool allow = false;
1319 51 : 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 51 : return allow;
1370 :
1371 : }
1372 :
1373 : static sql_exp *
1374 2325878 : rel_column_ref(sql_query *query, sql_rel **rel, symbol *column_r, int f)
1375 : {
1376 2325878 : mvc *sql = query->sql;
1377 2325878 : sql_exp *exp = NULL;
1378 2325878 : dlist *l = NULL;
1379 2325878 : sql_rel *inner = rel?*rel:NULL, *outer = NULL;
1380 2325878 : int used_lower_after_processed = 0;
1381 :
1382 2325878 : assert((column_r->token == SQL_COLUMN || column_r->token == SQL_IDENT) && column_r->type == type_list);
1383 2325878 : l = column_r->data.lval;
1384 :
1385 2325878 : if (dlist_length(l) == 1) {
1386 1099747 : const char *name = l->h->data.sval;
1387 :
1388 1099747 : if (!exp && inner)
1389 1005823 : if (!(exp = rel_bind_column(sql, inner, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
1390 : return NULL;
1391 1099733 : if (!exp && inner && ((is_sql_aggr(f) && (is_groupby(inner->op) || is_select(inner->op))) ||
1392 23614 : (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 225 : while (gp && is_select(gp->op))
1396 20 : gp = gp->l;
1397 205 : 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 1099733 : if (!exp && query && query_has_outer(query)) {
1401 376 : int i;
1402 :
1403 485 : for (i=query_has_outer(query)-1; i>= 0 && !exp && (outer = query_fetch_outer(query,i)); i--) {
1404 398 : if (!(exp = rel_bind_column(sql, outer, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
1405 : return NULL;
1406 123 : if (!exp && is_groupby(outer->op)) {
1407 14 : if (!(exp = rel_bind_column(sql, outer->l, name, f, 0)) && sql->session->status == -ERR_AMBIGUOUS)
1408 : return NULL;
1409 : else
1410 14 : used_lower_after_processed = is_processed(outer);
1411 : }
1412 398 : if (exp && is_simple_project(outer->op) && !rel_find_exp(outer, exp))
1413 0 : exp = rel_project_add_exp(sql, outer, exp);
1414 289 : if (exp)
1415 : break;
1416 : }
1417 376 : if (exp && exp->card != CARD_AGGR && is_groupby(outer->op) && !is_sql_aggr(f) && rel_find_exp(outer->l, exp))
1418 3 : 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 373 : 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 373 : if (exp && outer && !is_sql_aggr(f) && !is_sql_aggr(query_fetch_outer_state(query, i))) {
1422 211 : 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 373 : if (exp) {
1430 286 : int of = query_fetch_outer_state(query, i);
1431 286 : if (is_groupby(outer->op) && !is_sql_aggr(f)) {
1432 21 : exp = rel_groupby_add_aggr(sql, outer, exp);
1433 21 : exp->card = CARD_ATOM;
1434 265 : } else if (is_groupby(outer->op) && is_sql_aggr(f) && exps_any_match(outer->exps, exp))
1435 31 : exp = exp_ref(sql, exp);
1436 : else
1437 234 : exp->card = CARD_ATOM;
1438 286 : set_freevar(exp, i);
1439 : /*
1440 : if (exp->alias.label == exp->nid)
1441 : exp->alias.label = -(sql->nid++);
1442 : */
1443 286 : if (!is_sql_where(of) && !is_sql_aggr(of) && !is_sql_aggr(f) && !outer->grouped)
1444 88 : set_outer(outer);
1445 : }
1446 373 : if (exp && outer && (is_select(outer->op) || is_join(outer->op)))
1447 30 : set_dependent_(outer);
1448 : }
1449 :
1450 : /* some views are just in the stack, like before and after updates views */
1451 1099730 : 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 1099728 : if (!exp) /* If no column was found, try a variable or parameter */
1466 117254 : exp = rel_exp_variable_on_scope(sql, NULL, name);
1467 :
1468 117254 : if (!exp) {
1469 874 : if (inner && !is_sql_aggr(f) && is_groupby(inner->op) && inner->l && (exp = rel_bind_column(sql, inner->l, name, f, 0)))
1470 49 : 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 1098854 : if (!exp)
1474 825 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: identifier '%s' unknown", name);
1475 1098854 : 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 1098854 : if (exp && inner && is_groupby(inner->op) && !is_sql_aggr(f) && !is_freevar(exp) && !inner->flag)
1478 24844 : exp = rel_groupby_add_aggr(sql, inner, exp);
1479 1226131 : } else if (dlist_length(l) == 2 || dlist_length(l) == 3) {
1480 1226131 : const char *sname = NULL;
1481 1226131 : const char *tname = l->h->data.sval;
1482 1226131 : const char *cname = l->h->next->data.sval;
1483 1226131 : 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 1226131 : if (!exp && rel && inner)
1490 1226020 : if (!(exp = rel_bind_column3(sql, inner, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
1491 : return NULL;
1492 1226130 : 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 38 : while (gp && is_select(gp->op))
1496 0 : gp = gp->l;
1497 38 : 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 1226130 : if (!exp && query && query_has_outer(query)) {
1501 11447 : int i;
1502 :
1503 11599 : for (i=query_has_outer(query)-1; i>= 0 && !exp && (outer = query_fetch_outer(query,i)); i--) {
1504 11589 : if (!(exp = rel_bind_column3(sql, outer, sname, tname, cname, f | sql_outer)) && sql->session->status == -ERR_AMBIGUOUS)
1505 : return NULL;
1506 210 : if (!exp && is_groupby(outer->op)) {
1507 70 : if (!(exp = rel_bind_column3(sql, outer->l, sname, tname, cname, f)) && sql->session->status == -ERR_AMBIGUOUS)
1508 : return NULL;
1509 : else
1510 70 : used_lower_after_processed = is_processed(outer);
1511 : }
1512 11589 : if (exp && is_simple_project(outer->op) && !rel_find_exp(outer, exp))
1513 0 : exp = rel_project_add_exp(sql, outer, exp);
1514 11437 : if (exp)
1515 : break;
1516 : }
1517 11447 : if (exp && exp->card != CARD_AGGR && is_groupby(outer->op) && !is_sql_aggr(f) && rel_find_exp(outer->l, exp))
1518 5 : 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 11442 : 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 11442 : if (exp && outer && !is_sql_aggr(f)) {
1522 11254 : 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 11442 : if (exp) {
1530 11432 : int of = query_fetch_outer_state(query, i);
1531 11432 : if (is_groupby(outer->op) && !is_sql_aggr(f)) {
1532 36 : exp = rel_groupby_add_aggr(sql, outer, exp);
1533 36 : exp->card = CARD_ATOM;
1534 11396 : } else if (is_groupby(outer->op) && is_sql_aggr(f) && exps_any_match(outer->exps, exp))
1535 34 : exp = exp_ref(sql, exp);
1536 : else
1537 11362 : exp->card = CARD_ATOM;
1538 11432 : set_freevar(exp, i);
1539 : /*
1540 : if (exp->alias.label == exp->nid)
1541 : exp->alias.label = -(sql->nid++);
1542 : */
1543 11432 : if (!is_sql_where(of) && !is_sql_aggr(of) && !is_sql_aggr(f) && !outer->grouped)
1544 9927 : set_outer(outer);
1545 : }
1546 11442 : if (exp && outer && (is_select(outer->op) || is_join(outer->op)))
1547 4646 : set_dependent_(outer);
1548 : }
1549 :
1550 : /* some views are just in the stack, like before and after updates views */
1551 1226125 : 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 1226105 : if (!exp) { /* If no column was found, try a global variable */
1566 65952 : sql_var *var = NULL;
1567 65952 : sql_subtype *tpe = NULL;
1568 65952 : int level = 0;
1569 65952 : sql_arg *a = NULL;
1570 :
1571 65952 : 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 65952 : if (!exp) {
1577 65942 : if (inner && !is_sql_aggr(f) && is_groupby(inner->op) && inner->l && (exp = rel_bind_column3(sql, inner->l, sname, tname, cname, f))) {
1578 51 : 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 50 : 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 65891 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42S22) "SELECT: no such column '%s.%s'", tname, cname);
1593 1160184 : 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 1160184 : if (exp && inner && is_groupby(inner->op) && !is_sql_aggr(f) && !is_freevar(exp))
1596 5624 : 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 2259038 : if (exp && !exp_is_atom(exp) && rel && !outer) {
1601 2130935 : if (query->last_exp && query->last_rel == *rel && !is_sql_aggr(query->last_state) && is_sql_aggr(f)) {
1602 51 : if (!is_groupby(query->last_rel->op) || list_empty(query->last_rel->r) || !exps_find_exp(query->last_rel->r, query->last_exp)) {
1603 32 : if (exp_relname(query->last_exp) && exp_name(query->last_exp) && !has_label(query->last_exp))
1604 32 : 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 2130903 : query->prev = query->last_exp;
1609 2130903 : query->last_exp = exp;
1610 2130903 : query->last_state = f;
1611 2130903 : query->last_rel = *rel;
1612 : }
1613 : return exp;
1614 : }
1615 :
1616 : int
1617 971919 : 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 971919 : sql_exp *ls = *L;
1620 971919 : sql_exp *rs = *R;
1621 971919 : sql_subtype *lt = exp_subtype(ls);
1622 971919 : sql_subtype *rt = exp_subtype(rs);
1623 :
1624 971919 : 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 971917 : if (rt && (!lt || !lt->type))
1629 7 : return rel_set_type_param(sql, rt, ll, ls, 0);
1630 971910 : if (lt && (!rt || !rt->type))
1631 648 : return rel_set_type_param(sql, lt, rr, rs, 0);
1632 :
1633 971262 : if (rt && lt) {
1634 971262 : sql_subtype *i = lt;
1635 971262 : sql_subtype *r = rt;
1636 :
1637 971262 : if (subtype_cmp(lt, rt) != 0 || (tpe == type_equal_no_any && (lt->type->localtype==0 || rt->type->localtype==0))) {
1638 267227 : sql_subtype super;
1639 :
1640 267227 : cmp_supertype(&super, r, i);
1641 267227 : if (scale_fixing) {
1642 : /* convert ls to super type */
1643 267227 : ls = exp_check_type(sql, &super, ll, ls, tpe);
1644 : /* convert rs to super type */
1645 267227 : 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 971262 : *L = ls;
1656 971262 : *R = rs;
1657 971262 : if (!ls || !rs)
1658 : return -1;
1659 : return 0;
1660 : }
1661 : return -1;
1662 : }
1663 :
1664 : static sql_rel *
1665 108032 : push_select_exp(mvc *sql, sql_rel *rel, sql_exp *e, sql_exp *ls, int f)
1666 : {
1667 108032 : if (is_outerjoin(rel->op)) {
1668 1168 : if ((is_left(rel->op) || is_full(rel->op)) && rel_find_exp(rel->l, ls)) {
1669 33 : rel_join_add_exp(sql->sa, rel, e);
1670 33 : return rel;
1671 1135 : } 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 1130 : if (is_left(rel->op) && rel_find_exp(rel->r, ls)) {
1676 1104 : rel->r = rel_push_select(sql, rel->r, ls, e, f);
1677 1104 : 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 106879 : return rel_push_select(sql, rel, ls, e, f);
1685 : }
1686 :
1687 : static sql_rel *
1688 203841 : push_join_exp(mvc *sql, sql_rel *rel, sql_exp *e, sql_exp *L, sql_exp *R, sql_exp *R2, int f)
1689 : {
1690 203841 : sql_rel *r;
1691 203841 : if (/*is_semi(rel->op) ||*/ (is_outerjoin(rel->op) && !is_processed((rel)))) {
1692 21889 : rel_join_add_exp(sql->sa, rel, e);
1693 21889 : return rel;
1694 : }
1695 : /* push join into the given relation */
1696 181952 : 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 3363 : rel_select_push_filter_exp_down(mvc *sql, sql_rel *rel, sql_exp *e, list *l, list *r, int ff)
1704 : {
1705 3363 : sql_exp *ll, *rr;
1706 3363 : if (exps_card(r) <= CARD_ATOM && (exps_are_atoms(r) || exps_have_freevar(sql, r) || exps_have_freevar(sql, l))) {
1707 3267 : if (exps_card(l) == exps_card(r) || rel->processed) /* bin compare op */
1708 98 : return rel_select(sql->sa, rel, e);
1709 3169 : if ((ll = exps_find_one_multi_exp(l)))
1710 3169 : 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 3362 : rel_filter(mvc *sql, sql_rel *rel, list *l, list *r, char *sname, char *filter_op, int anti, int ff)
1721 : {
1722 3362 : node *n;
1723 3362 : sql_exp *e = NULL;
1724 3362 : sql_subfunc *f = NULL;
1725 3362 : list *tl = sa_list(sql->sa);
1726 3362 : bool found = false;
1727 :
1728 6724 : for (n = l->h; n; n = n->next){
1729 3362 : sql_exp *e = n->data;
1730 :
1731 3362 : list_append(tl, exp_subtype(e));
1732 : }
1733 13371 : for (n = r->h; n; n = n->next){
1734 10009 : sql_exp *e = n->data;
1735 :
1736 10009 : list_append(tl, exp_subtype(e));
1737 : }
1738 : /* find filter function */
1739 3362 : f = bind_func_(sql, sname, filter_op, tl, F_FILT, false, &found, false);
1740 3362 : if (f) {
1741 3360 : node *n,*m = f->func->ops->h;
1742 3360 : list *nexps = sa_list(sql->sa);
1743 :
1744 6720 : for(n=l->h; m && n; m = m->next, n = n->next) {
1745 3360 : sql_arg *a = m->data;
1746 3360 : sql_exp *e = n->data;
1747 :
1748 3360 : e = exp_check_type(sql, &a->type, rel, e, type_equal);
1749 3360 : if (!e)
1750 : return NULL;
1751 3360 : list_append(nexps, e);
1752 : }
1753 3360 : l = nexps;
1754 3360 : nexps = sa_list(sql->sa);
1755 13361 : for(n=r->h; m && n; m = m->next, n = n->next) {
1756 10001 : sql_arg *a = m->data;
1757 10001 : sql_exp *e = n->data;
1758 :
1759 10001 : e = exp_check_type(sql, &a->type, rel, e, type_equal);
1760 10001 : if (!e)
1761 : return NULL;
1762 10001 : list_append(nexps, e);
1763 : }
1764 : r = nexps;
1765 : }
1766 3362 : 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 3360 : e = exp_filter(sql->sa, l, r, f, anti);
1770 :
1771 3360 : 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 6702 : for (node *n=l->h; n; n = n->next) {
1775 3351 : sql_exp *ls = n->data;
1776 :
1777 3351 : 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 13325 : for (node *n=r->h; n; n = n->next) {
1784 9974 : sql_exp *rs = n->data;
1785 :
1786 9974 : 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 3351 : return rel_select_push_filter_exp_down(sql, rel, e, l, r, ff);
1793 : }
1794 :
1795 : static sql_rel *
1796 3302 : 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 3302 : list *l = sa_list(sql->sa);
1799 3302 : list *r = sa_list(sql->sa);
1800 :
1801 3302 : list_append(l, ls);
1802 3302 : list_append(r, r1);
1803 3302 : if (r2)
1804 3302 : list_append(r, r2);
1805 3302 : if (r3)
1806 3302 : list_append(r, r3);
1807 3302 : return rel_filter(sql, rel, l, r, "sys", filter_op, anti, f);
1808 : }
1809 :
1810 : static sql_rel *
1811 376431 : 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 376431 : if (!is_join(rel->op) && !is_select(rel->op))
1814 85338 : return rel_select(sql->sa, rel, e);
1815 378936 : if ((rs->card <= CARD_ATOM || (rs2 && ls->card <= CARD_ATOM)) &&
1816 175686 : (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 87309 : if (ls->card == rs->card || (rs2 && (ls->card == rs2->card || rs->card == rs2->card)) || rel->processed) /* bin compare op */
1819 984 : return rel_select(sql->sa, rel, e);
1820 :
1821 86325 : return push_select_exp(sql, rel, e, ls, f);
1822 : } else { /* join */
1823 203784 : return push_join_exp(sql, rel, e, ls, rs, rs2, f);
1824 : }
1825 : return rel;
1826 : }
1827 :
1828 : static sql_rel *
1829 349831 : 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 349831 : mvc *sql = query->sql;
1832 349831 : sql_exp *e = NULL;
1833 :
1834 349831 : if (quantifier || exp_is_rel(ls) || exp_is_rel(rs) || (rs2 && exp_is_rel(rs2))) {
1835 3129 : 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 3122 : assert(!symmetric);
1841 3122 : if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
1842 : return NULL;
1843 3122 : e = exp_compare_func(sql, ls, rs, compare_func((comp_type)type, anti), quantifier);
1844 : }
1845 3129 : return rel_select(sql->sa, rel, e);
1846 346702 : } else if (!rs2) {
1847 343755 : assert(!symmetric);
1848 343755 : if (ls->card < rs->card) {
1849 12610 : sql_exp *swap = ls;
1850 12610 : ls = rs;
1851 12610 : rs = swap;
1852 12610 : type = (int)swap_compare((comp_type)type);
1853 : }
1854 343755 : if (rel_convert_types(sql, rel, rel, &ls, &rs, 1, type_equal_no_any) < 0)
1855 : return NULL;
1856 343752 : e = exp_compare(sql->sa, ls, rs, type);
1857 343752 : 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 346699 : if (anti)
1867 847 : set_anti(e);
1868 :
1869 346699 : 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 346699 : 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 346699 : return rel_select_push_compare_exp_down(sql, rel, e, ls, rs, rs2, f);
1880 : }
1881 :
1882 : static sql_rel *
1883 346877 : 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 346877 : mvc *sql = query->sql;
1886 346877 : comp_type type = cmp_equal;
1887 :
1888 346877 : if (!ls || !rs)
1889 : return NULL;
1890 :
1891 346877 : 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 346877 : type = compare_str2type(compare_op);
1915 346877 : assert(type != cmp_filter);
1916 346877 : return rel_compare_exp_(query, rel, ls, rs, NULL, type, need_not, quantifier, f, 0, is_semantics);
1917 : }
1918 :
1919 : static sql_rel *
1920 346822 : 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 346822 : mvc *sql = query->sql;
1923 346822 : sql_exp *rs = NULL, *ls;
1924 346822 : comp_type cmp_type = compare_str2type(compare_op);
1925 346822 : exp_kind ek = {type_value, card_column, FALSE};
1926 346822 : int need_not = 0;
1927 :
1928 346822 : if ((quantifier == 1 && cmp_type == cmp_equal) ||
1929 346801 : (quantifier == 2 && cmp_type == cmp_notequal)) {
1930 45 : dnode *n = sc->data.lval->h;
1931 45 : dlist *dl = dlist_create(sql->sa);
1932 : /* map into IN/NOT IN */
1933 45 : sc->token = cmp_type==cmp_equal?SQL_IN:SQL_NOT_IN;
1934 45 : n->next->type = type_list;
1935 45 : n->next->data.lval = dl;
1936 45 : n->next->next->next = NULL; /* remove quantifier */
1937 45 : dl->h = n->next->next;
1938 45 : n->next->next = NULL; /* (remove comparison) moved righthand side */
1939 45 : return rel_logical_exp(query, rel, sc, f);
1940 : }
1941 : /* <> ANY -> NOT (= ALL) */
1942 346777 : if (quantifier == 1 && cmp_type == cmp_notequal) {
1943 2 : need_not = 1;
1944 2 : quantifier = 2;
1945 2 : cmp_type = cmp_equal;
1946 2 : compare_op = "=";
1947 : }
1948 :
1949 346777 : if ((lo->token == SQL_SELECT || lo->token == SQL_UNION || lo->token == SQL_EXCEPT || lo->token == SQL_INTERSECT || lo->token == SQL_VALUES) &&
1950 34 : (ro->token != SQL_SELECT && ro->token != SQL_UNION && ro->token != SQL_EXCEPT && ro->token != SQL_INTERSECT && ro->token != SQL_VALUES)) {
1951 26 : symbol *tmp = lo; /* swap subquery to the right hand side */
1952 :
1953 26 : lo = ro;
1954 26 : ro = tmp;
1955 :
1956 26 : if (compare_op[0] == '>')
1957 15 : compare_op[0] = '<';
1958 11 : else if (compare_op[0] == '<' && compare_op[1] != '>')
1959 1 : compare_op[0] = '>';
1960 26 : cmp_type = swap_compare(cmp_type);
1961 : }
1962 :
1963 346777 : ls = rel_value_exp(query, &rel, lo, f|sql_farg, ek);
1964 346777 : if (!ls)
1965 : return NULL;
1966 346732 : if (ls && rel && exp_has_freevar(sql, ls) && is_sql_sel(f))
1967 0 : ls = rel_project_add_exp(sql, rel, ls);
1968 346732 : if (quantifier)
1969 31 : ek.card = card_set;
1970 :
1971 346732 : rs = rel_value_exp(query, &rel, ro, f|sql_farg, ek);
1972 346732 : if (!rs)
1973 : return NULL;
1974 346717 : 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 346717 : 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 346717 : 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 78524 : _rel_nop(mvc *sql, char *sname, char *fname, list *tl, sql_rel *rel, list *exps, exp_kind ek)
1989 : {
1990 78524 : bool found = false;
1991 78524 : int table_func = (ek.card == card_relation);
1992 78524 : 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 78524 : sql_subfunc *f = bind_func_(sql, sname, fname, tl, type, false, &found, false);
1996 78524 : if (f && !(exps = check_arguments_and_find_largest_any_type(sql, rel, exps, f, table_func, false)))
1997 : f = NULL;
1998 :
1999 78508 : if (f)
2000 78508 : 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 1980 : exp_exist(sql_query *query, sql_rel *rel, sql_exp *le, int exists)
2008 : {
2009 1980 : mvc *sql = query->sql;
2010 1980 : sql_subfunc *exists_func = NULL;
2011 1980 : sql_subtype *t;
2012 1980 : sql_exp *res;
2013 :
2014 1980 : if (!exp_name(le))
2015 748 : exp_label(sql->sa, le, ++sql->label);
2016 1980 : if (exp_is_rel(le)) { /* for the subquery case, propagate to the inner query */
2017 1980 : sql_rel *r = exp_rel_get_rel(sql->sa, le);
2018 1980 : if (is_project(r->op) && !list_empty(r->exps)) {
2019 5728 : for (node *n = r->exps->h; n; n = n->next)
2020 3748 : if (!exp_subtype(n->data) && rel_set_type_param(sql, sql_bind_localtype("bit"), r, n->data, 0) < 0) /* workaround */
2021 : return NULL;
2022 1980 : 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 1980 : t = exp_subtype(le);
2027 :
2028 2028 : 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 1980 : res = exp_unop(sql->sa, le, exists_func);
2031 1980 : set_has_no_nil(res);
2032 1980 : return res;
2033 : }
2034 :
2035 : static sql_exp *
2036 1013 : rel_exists_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f)
2037 : {
2038 1013 : exp_kind ek = {type_value, card_exists, FALSE};
2039 1013 : sql_exp *le, *e;
2040 :
2041 1013 : le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
2042 1013 : if (!le)
2043 : return NULL;
2044 1012 : if (!(e = exp_exist(query, rel ? *rel : NULL, le, sc->token == SQL_EXISTS)))
2045 : return NULL;
2046 : /* only freevar should have CARD_AGGR */
2047 1012 : e->card = CARD_ATOM;
2048 1012 : return e;
2049 : }
2050 :
2051 : static sql_rel *
2052 974 : rel_exists_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
2053 : {
2054 974 : exp_kind ek = {type_value, card_exists, TRUE};
2055 974 : mvc *sql = query->sql;
2056 974 : sql_rel *sq = NULL;
2057 :
2058 974 : 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 973 : if (rel) {
2061 973 : query_processed(query);
2062 973 : query_push_outer(query, rel, f);
2063 : }
2064 973 : sq = rel_subquery(query, sc->data.sym, ek);
2065 973 : if (rel)
2066 973 : rel = query_pop_outer(query);
2067 973 : assert(!is_sql_sel(f));
2068 973 : if (sq) {
2069 968 : sql_exp *e = exp_rel(sql, sq);
2070 968 : if (!(e = exp_exist(query, rel, e, sc->token == SQL_EXISTS)))
2071 : return NULL;
2072 : /* only freevar should have CARD_AGGR */
2073 968 : e->card = CARD_ATOM;
2074 968 : rel = rel_select_add_exp(sql->sa, rel, e);
2075 968 : return rel;
2076 : }
2077 : return NULL;
2078 : }
2079 :
2080 : static int
2081 6875 : is_project_true(sql_rel *r)
2082 : {
2083 6875 : if (r && !r->l && list_length(r->exps) == 1) {
2084 58 : sql_exp *e = r->exps->h->data;
2085 58 : if (exp_is_atom(e) && exp_is_true(e))
2086 : return 1;
2087 : }
2088 : return 0;
2089 : }
2090 :
2091 : static sql_exp *
2092 61909 : rel_in_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f)
2093 : {
2094 61909 : mvc *sql = query->sql;
2095 61909 : exp_kind ek = {type_value, card_column, TRUE};
2096 61909 : dlist *dl = sc->data.lval;
2097 61909 : symbol *lo = NULL;
2098 61909 : dnode *n = dl->h->next, *dn = NULL;
2099 61909 : sql_exp *le = NULL, *re, *e = NULL;
2100 61909 : list *ll = sa_list(sql->sa);
2101 61909 : int is_tuple = 0, add_select = 0;
2102 :
2103 : /* complex case */
2104 61909 : if (dl->h->type == type_list) { /* (a,b..) in (.. ) */
2105 4084 : dn = dl->h->data.lval->h;
2106 4084 : lo = dn->data.sym;
2107 4084 : dn = dn->next;
2108 : } else {
2109 57825 : lo = dl->h->data.sym;
2110 : }
2111 195977 : for( ; lo; lo = dn?dn->data.sym:NULL, dn = dn?dn->next:NULL ) {
2112 67037 : le = rel_value_exp(query, rel, lo, f|sql_farg, ek);
2113 67037 : if (!le)
2114 : return NULL;
2115 67034 : append(ll, le);
2116 : }
2117 61906 : if (list_length(ll) == 1) {
2118 57822 : le = ll->h->data;
2119 57822 : ek.card = card_set;
2120 : } else {
2121 4084 : le = exp_values(sql->sa, ll);
2122 4084 : exp_label(sql->sa, le, ++sql->label);
2123 4084 : ek.type = list_length(ll);
2124 4084 : 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 61906 : if (n->type == type_list) {
2133 61906 : sql_exp *values;
2134 61906 : list *vals = sa_list(sql->sa);
2135 :
2136 61906 : n = dl->h->next;
2137 61906 : n = n->data.lval->h;
2138 :
2139 307608 : for (; n; n = n->next) {
2140 245727 : 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 245724 : assert(n->type == type_symbol);
2153 245724 : re = rel_value_exp(query, rel, n->data.sym, f|sql_farg, ek);
2154 : }
2155 245727 : if (!re)
2156 : return NULL;
2157 245704 : 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 8167 : if (is_tuple && exp_is_rel(re)) {
2160 4083 : sql_rel *r = exp_rel_get_rel(sql->sa, re);
2161 :
2162 4083 : if (!r)
2163 0 : return sql_error(sql, 02, SQLSTATE(42000) "Subquery missing");
2164 4083 : if (r->nrcols != ek.type)
2165 3 : return sql_error(sql, 02, SQLSTATE(42000) "Subquery has too %s columns", (r->nrcols < ek.type) ? "few" : "many");
2166 4081 : re = exp_rel_label(sql, re);
2167 241621 : } else if (exp_is_rel(re)) {
2168 6876 : sql_rel *r = exp_rel_get_rel(sql->sa, re);
2169 6876 : add_select = 1;
2170 6876 : if (rel && *rel && is_join((*rel)->op))
2171 2922 : set_dependent((*rel));
2172 6876 : if (is_project(r->op) && is_project_true(r->l) && list_length(r->exps) == 1)
2173 56 : re = r->exps->h->data;
2174 234745 : } 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 245702 : append(vals, re);
2178 : }
2179 :
2180 61881 : 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 61881 : values = exp_values(sql->sa, vals);
2184 61881 : exp_label(sql->sa, values, ++sql->label);
2185 61881 : if (is_tuple) {
2186 4082 : if (!(values = exp_tuples_set_supertype(sql, exp_get_values(le), values)))
2187 : return NULL;
2188 4082 : 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 57799 : sql_subtype super, *le_tpe = exp_subtype(le), *values_tpe = NULL;
2192 :
2193 299416 : for (node *m = vals->h; m; m = m->next) { /* first get values supertype */
2194 241617 : sql_exp *e = m->data;
2195 241617 : sql_subtype *tpe = exp_subtype(e);
2196 :
2197 241617 : if (values_tpe && tpe) {
2198 183815 : cmp_supertype(&super, values_tpe, tpe);
2199 183815 : *values_tpe = super;
2200 57802 : } else if (!values_tpe && tpe) {
2201 57795 : super = *tpe;
2202 57795 : values_tpe = &super;
2203 : }
2204 : }
2205 57799 : if (!le_tpe)
2206 2 : le_tpe = values_tpe;
2207 57799 : if (!values_tpe)
2208 4 : values_tpe = le_tpe;
2209 57799 : 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 57798 : 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 57798 : if ((is_sql_where(f) || is_sql_having(f)) && !is_sql_farg(f) && !exp_has_rel(le) && exps_are_atoms(vals)) {
2215 23901 : if (list_length(vals) == 1) { /* use cmp_equal instead of cmp_in for 1 expression */
2216 113 : sql_exp *first = vals->h->data;
2217 113 : if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &le, &first, 1, type_equal_no_any) < 0)
2218 0 : return NULL;
2219 138 : 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 120403 : for (node *n = vals->h ; n ; n = n->next)
2222 96615 : if ((n->data = exp_check_type(sql, &super, rel ? *rel : NULL, n->data, type_equal)) == NULL)
2223 : return NULL;
2224 23788 : if ((le = exp_check_type(sql, &super, rel ? *rel : NULL, le, type_equal)) == NULL)
2225 : return NULL;
2226 32352 : e = exp_in(sql->sa, le, vals, (sc->token == SQL_IN) ? cmp_in : cmp_notin);
2227 : }
2228 : }
2229 23901 : if (!e) { /* after computing supertype, check types for each IN value */
2230 178785 : for (node *n = vals->h ; n ; n = n->next)
2231 144888 : if ((n->data = exp_check_type(sql, &super, rel ? *rel : NULL, n->data, type_equal)) == NULL)
2232 : return NULL;
2233 33897 : values->tpe = *exp_subtype(vals->h->data);
2234 33897 : if (!(le = exp_check_type(sql, &super, rel ? *rel : NULL, le, type_equal)))
2235 : return NULL;
2236 : }
2237 : }
2238 57798 : if (!e) {
2239 37979 : if (add_select && rel && *rel && !is_project((*rel)->op) && !is_select((*rel)->op) && !is_base((*rel)->op))
2240 2921 : *rel = rel_select(sql->sa, *rel, NULL);
2241 37979 : if ((rel && *rel) || exp_has_rel(le) || exp_has_rel(values))
2242 32441 : e = exp_in_func(sql, le, values, (sc->token == SQL_IN), is_tuple);
2243 : else
2244 5538 : 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 32424 : rel_in_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
2252 : {
2253 32424 : mvc *sql = query->sql;
2254 32424 : sql_exp *e = rel_in_value_exp(query, &rel, sc, f);
2255 :
2256 32424 : assert(!is_sql_sel(f));
2257 32424 : if (!e || !rel)
2258 : return NULL;
2259 :
2260 32407 : if (e->type == e_cmp) { /* it's a exp_in or cmp_equal of simple expressions, push down early on if possible */
2261 23899 : sql_exp *ls = e->l;
2262 23899 : bool rlist = (e->flag == cmp_in || e->flag == cmp_notin);
2263 23899 : unsigned int rcard = rlist ? exps_card(e->r) : exp_card(e->r);
2264 23899 : int r_is_atoms = rlist ? exps_are_atoms(e->r) : exp_is_atom(e->r);
2265 23899 : int r_has_freevar = rlist ? exps_have_freevar(sql, e->r) : exp_has_freevar(sql, e->r);
2266 :
2267 23899 : if (rcard <= CARD_ATOM && (r_is_atoms || r_has_freevar || exp_has_freevar(sql, ls))) {
2268 23899 : if ((exp_card(ls) == rcard) || rel->processed) /* bin compare op */
2269 5361 : return rel_select(sql->sa, rel, e);
2270 :
2271 18538 : 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 8508 : if (is_outerjoin(rel->op))
2279 13 : return rel_select(sql->sa, rel, e);
2280 8495 : return rel_select_add_exp(sql->sa, rel, e);
2281 : }
2282 :
2283 : static bool
2284 52407 : not_symbol_can_be_propagated(mvc *sql, symbol *sc)
2285 : {
2286 52407 : 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 36369 : default:
2307 36369 : 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 16033 : negate_symbol_tree(mvc *sql, symbol *sc)
2314 : {
2315 16033 : switch (sc->token) {
2316 1447 : case SQL_IN:
2317 1447 : sc->token = SQL_NOT_IN;
2318 1447 : break;
2319 14 : case SQL_NOT_IN:
2320 14 : sc->token = SQL_IN;
2321 14 : 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 16 : case SQL_BETWEEN:
2335 16 : sc->token = SQL_NOT_BETWEEN;
2336 16 : 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 7646 : case SQL_COMPARE: {
2359 7646 : dnode *cmp_n = sc->data.lval->h;
2360 7646 : comp_type neg_cmp_type = negate_compare(compare_str2type(cmp_n->next->data.sval)); /* negate the comparator */
2361 7646 : if (cmp_n->next->next->next) {
2362 13 : switch(cmp_n->next->next->next->data.i_val)
2363 : {
2364 5 : case 0: /* negating ANY/ALL */
2365 5 : cmp_n->next->next->next->data.i_val = 1;
2366 5 : break;
2367 5 : case 1: /* negating ANY/ALL */
2368 5 : cmp_n->next->next->next->data.i_val = 0;
2369 5 : 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 7646 : cmp_n->next->data.sval = sa_strdup(sql->sa, compare_func(neg_cmp_type, 0));
2379 7646 : } 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 16033 : return sc;
2390 : }
2391 :
2392 : static int
2393 3110 : exp_between_check_types(sql_subtype *res, sql_subtype *t1, sql_subtype *t2, sql_subtype *t3)
2394 : {
2395 3110 : bool type_found = false;
2396 3110 : sql_subtype super;
2397 :
2398 3110 : if (t1 && t2) {
2399 3104 : cmp_supertype(&super, t2, t1);
2400 3104 : 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 3110 : if (t3) {
2409 3107 : if (type_found)
2410 3106 : 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 3109 : *res = super;
2418 3109 : return 0;
2419 : }
2420 :
2421 : static bool
2422 116126 : exp_is_null_no_value_opt(sql_exp *e)
2423 : {
2424 116126 : if (!e)
2425 : return false;
2426 120026 : while (is_convert(e->type))
2427 3900 : e = e->l;
2428 232233 : return e->type == e_atom && e->l && atom_null(e->l);
2429 : }
2430 :
2431 : sql_exp *
2432 2625407 : rel_logical_value_exp(sql_query *query, sql_rel **rel, symbol *sc, int f, exp_kind ek)
2433 : {
2434 2625483 : mvc *sql = query->sql;
2435 :
2436 2625483 : if (!sc)
2437 : return NULL;
2438 :
2439 2625483 : if (mvc_highwater(sql))
2440 167 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
2441 :
2442 2625866 : switch (sc->token) {
2443 51306 : case SQL_OR:
2444 : case SQL_AND:
2445 : {
2446 51306 : symbol *lo = sc->data.lval->h->data.sym;
2447 51306 : symbol *ro = sc->data.lval->h->next->data.sym;
2448 51306 : sql_exp *ls, *rs;
2449 :
2450 51306 : if (!(ls = rel_value_exp(query, rel, lo, f|sql_farg, ek)))
2451 : return NULL;
2452 51306 : if (!(rs = rel_value_exp(query, rel, ro, f|sql_farg, ek)))
2453 : return NULL;
2454 90550 : 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 115826 : case SQL_COMPARE:
2495 : {
2496 115826 : dnode *n = sc->data.lval->h;
2497 115826 : symbol *lo = n->data.sym;
2498 115826 : symbol *ro = n->next->next->data.sym;
2499 115826 : char *compare_op = n->next->data.sval;
2500 115826 : int quantifier = 0, need_not = 0;
2501 115826 : sql_exp *rs = NULL, *ls;
2502 115826 : comp_type cmp_type = compare_str2type(compare_op);
2503 115826 : bool is_not_distinct_from = false;
2504 115826 : 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 115826 : if (n->next->next->next)
2511 166 : quantifier = n->next->next->next->data.i_val + 1;
2512 166 : assert(quantifier == 0 || quantifier == 1 || quantifier == 2 || quantifier == 3 || quantifier == 4);
2513 :
2514 : /* [NOT] DISTINCT FROM */
2515 115826 : if (quantifier == 3) {
2516 : is_not_distinct_from = true;
2517 : quantifier = 0;
2518 : }
2519 115812 : else if (quantifier == 4) {
2520 14 : is_distinct_from = true;
2521 14 : quantifier = 0;
2522 : }
2523 :
2524 115826 : if ((quantifier == 1 && cmp_type == cmp_equal) ||
2525 115782 : (quantifier == 2 && cmp_type == cmp_notequal)) {
2526 69 : dlist *dl = dlist_create(sql->sa);
2527 : /* map into IN/NOT IN */
2528 69 : sc->token = cmp_type==cmp_equal?SQL_IN:SQL_NOT_IN;
2529 69 : n->next->type = type_list;
2530 69 : n->next->data.lval = dl;
2531 69 : n->next->next->next = NULL; /* remove quantifier */
2532 69 : dl->h = n->next->next;
2533 69 : n->next->next = NULL; /* (remove comparison) moved righthand side */
2534 69 : return rel_logical_value_exp(query, rel, sc, f, ek);
2535 : }
2536 : /* <> ANY -> NOT (= ALL) */
2537 115757 : if (quantifier == 1 && cmp_type == cmp_notequal) {
2538 8 : need_not = 1;
2539 8 : quantifier = 2;
2540 8 : cmp_type = cmp_equal;
2541 8 : compare_op = "=";
2542 : }
2543 :
2544 115757 : ls = rel_value_exp(query, rel, lo, f|sql_farg, ek);
2545 115757 : if (!ls)
2546 : return NULL;
2547 115745 : if (quantifier)
2548 69 : ek.card = card_set;
2549 :
2550 115745 : rs = rel_value_exp(query, rel, ro, f|sql_farg, ek);
2551 115745 : if (!rs)
2552 : return NULL;
2553 :
2554 115736 : if (is_distinct_from || is_not_distinct_from) {
2555 28 : if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &ls, &rs, 1, type_equal_no_any) < 0)
2556 : return NULL;
2557 42 : sql_exp* e = exp_compare(sql->sa, ls, rs, is_not_distinct_from?cmp_equal:cmp_notequal);
2558 28 : set_semantics(e);
2559 28 : return e;
2560 : }
2561 :
2562 115708 : if (rs->type == e_atom)
2563 104517 : quantifier = 0;
2564 :
2565 115708 : if (!exp_is_rel(ls) && !exp_is_rel(rs) && ls->card < rs->card) {
2566 13 : sql_exp *swap = ls; /* has to swap parameters like in the rel_logical_exp case */
2567 13 : ls = rs;
2568 13 : rs = swap;
2569 13 : cmp_type = swap_compare(cmp_type);
2570 : }
2571 :
2572 115708 : if (rel_convert_types(sql, rel ? *rel : NULL, rel ? *rel : NULL, &ls, &rs, 1, type_equal_no_any) < 0)
2573 : return NULL;
2574 115705 : 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 115698 : return exp_compare_func(sql, ls, rs, compare_func(cmp_type, need_not), quantifier);
2578 : }
2579 : /* Set Member ship */
2580 29485 : case SQL_IN:
2581 : case SQL_NOT_IN:
2582 29485 : return rel_in_value_exp(query, rel, sc, f);
2583 1013 : case SQL_EXISTS:
2584 : case SQL_NOT_EXISTS:
2585 1013 : 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 163 : case SQL_BETWEEN:
2623 : case SQL_NOT_BETWEEN:
2624 : {
2625 163 : symbol *lo = sc->data.lval->h->data.sym;
2626 163 : int symmetric = sc->data.lval->h->next->data.i_val;
2627 163 : symbol *ro1 = sc->data.lval->h->next->next->data.sym;
2628 163 : symbol *ro2 = sc->data.lval->h->next->next->next->data.sym;
2629 163 : sql_exp *le, *re1, *re2;
2630 163 : sql_subtype super;
2631 :
2632 163 : assert(sc->data.lval->h->next->type == type_int);
2633 :
2634 163 : if (!(le = rel_value_exp(query, rel, lo, f|sql_farg, ek)))
2635 : return NULL;
2636 162 : if (!(re1 = rel_value_exp(query, rel, ro1, f|sql_farg, ek)))
2637 : return NULL;
2638 159 : if (!(re2 = rel_value_exp(query, rel, ro2, f|sql_farg, ek)))
2639 : return NULL;
2640 :
2641 154 : 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 154 : if ((le = exp_check_type(sql, &super, rel ? *rel:NULL, le, type_equal)) == NULL ||
2645 154 : (re1 = exp_check_type(sql, &super, rel ? *rel:NULL, re1, type_equal)) == NULL ||
2646 154 : (re2 = exp_check_type(sql, &super, rel ? *rel:NULL, re2, type_equal)) == NULL)
2647 0 : return NULL;
2648 :
2649 154 : le = exp_compare2(sql->sa, le, re1, re2, 3, symmetric);
2650 154 : if (sc->token == SQL_NOT_BETWEEN)
2651 55 : set_anti(le);
2652 : return le;
2653 : }
2654 16206 : case SQL_IS_NULL:
2655 : case SQL_IS_NOT_NULL:
2656 : /* is (NOT) NULL */
2657 : {
2658 16206 : sql_exp *le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
2659 :
2660 16206 : if (!le)
2661 : return NULL;
2662 20437 : le = rel_unop_(sql, rel ? *rel : NULL, le, "sys", sc->token == SQL_IS_NULL ? "isnull" : "isnotnull", card_value);
2663 16203 : if (!le)
2664 : return NULL;
2665 16203 : set_has_no_nil(le);
2666 16203 : return le;
2667 : }
2668 18804 : case SQL_NOT: {
2669 18804 : if (not_symbol_can_be_propagated(sql, sc->data.sym)) {
2670 76 : sc->data.sym = negate_symbol_tree(sql, sc->data.sym);
2671 76 : return rel_logical_value_exp(query, rel, sc->data.sym, f, ek);
2672 : }
2673 18728 : sql_exp *le = rel_value_exp(query, rel, sc->data.sym, f|sql_farg, ek);
2674 :
2675 18728 : if (!le)
2676 : return NULL;
2677 18727 : return rel_unop_(sql, rel ? *rel : NULL, le, "sys", "not", card_value);
2678 : }
2679 : case SQL_ATOM: {
2680 2371915 : AtomNode *an = (AtomNode *) sc;
2681 2371915 : assert(an && an->a);
2682 2371915 : return exp_atom(sql->sa, an->a);
2683 : }
2684 20308 : case SQL_IDENT:
2685 : case SQL_COLUMN:
2686 20308 : return rel_column_ref(query, rel, sc, f);
2687 172 : case SQL_UNION:
2688 : case SQL_EXCEPT:
2689 : case SQL_INTERSECT: {
2690 172 : sql_rel *sq;
2691 :
2692 172 : if (is_psm_call(f) || is_sql_merge(f))
2693 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");
2694 171 : if (rel && *rel)
2695 116 : query_push_outer(query, *rel, f);
2696 171 : sq = rel_setquery(query, sc);
2697 171 : if (rel && *rel) {
2698 116 : *rel = query_pop_outer(query);
2699 116 : 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 116 : } 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 116 : } 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 171 : if (!sq)
2708 : return NULL;
2709 169 : if (ek.type == type_value && ek.card <= card_set && is_project(sq->op) && list_length(sq->exps) > 1)
2710 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
2711 169 : 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 259 : 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 90 : ( is_sql_where(f) && rel && (!*rel || is_basetable((*rel)->op) || is_simple_project((*rel)->op) || is_joinop((*rel)->op)))))
2715 90 : sq = rel_zero_or_one(sql, sq, ek);
2716 169 : 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 628206 : rel_logical_exp(sql_query *query, sql_rel *rel, symbol *sc, int f)
2737 : {
2738 628206 : mvc *sql = query->sql;
2739 628206 : exp_kind ek = {type_value, card_column, TRUE};
2740 :
2741 628206 : if (!sc)
2742 : return NULL;
2743 :
2744 628206 : if (mvc_highwater(sql))
2745 0 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
2746 :
2747 628206 : switch (sc->token) {
2748 18965 : case SQL_OR:
2749 : {
2750 18965 : list *exps = NULL, *lexps = NULL, *rexps = NULL;
2751 18965 : symbol *lo = sc->data.lval->h->data.sym;
2752 18965 : symbol *ro = sc->data.lval->h->next->data.sym;
2753 18965 : sql_rel *lr, *rr;
2754 :
2755 18965 : if (!rel)
2756 : return NULL;
2757 :
2758 18965 : lr = rel;
2759 18965 : rr = rel_dup(lr);
2760 :
2761 18965 : if (is_outerjoin(rel->op) && !is_processed(rel)) {
2762 42 : exps = rel->exps;
2763 :
2764 42 : lr = rel_select_copy(sql->sa, lr, sa_list(sql->sa));
2765 42 : lr = rel_logical_exp(query, lr, lo, f | sql_or);
2766 42 : if (!lr)
2767 : return NULL;
2768 41 : query_processed(query);
2769 41 : rr = rel_select_copy(sql->sa, rr, sa_list(sql->sa));
2770 41 : rr = rel_logical_exp(query, rr, ro, f | sql_or);
2771 41 : if (!rr)
2772 : return NULL;
2773 40 : if (lr->l == rr->l) {
2774 40 : lexps = lr->exps;
2775 40 : lr = lr->l;
2776 40 : rexps = rr->exps;
2777 40 : rr = rr->l;
2778 : }
2779 40 : rel = NULL;
2780 : } else {
2781 18923 : lr = rel_logical_exp(query, lr, lo, f | sql_or);
2782 18923 : if (!lr)
2783 : return NULL;
2784 18921 : rr = rel_logical_exp(query, rr, ro, f | sql_or);
2785 : }
2786 :
2787 18961 : if (!lr || !rr)
2788 : return NULL;
2789 18961 : return rel_or(sql, rel, lr, rr, exps, lexps, rexps);
2790 : }
2791 190601 : case SQL_AND:
2792 : {
2793 190601 : symbol *lo = sc->data.lval->h->data.sym;
2794 190601 : symbol *ro = sc->data.lval->h->next->data.sym;
2795 190601 : rel = rel_logical_exp(query, rel, lo, f);
2796 190601 : if (!rel)
2797 : return NULL;
2798 190594 : 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 346822 : case SQL_COMPARE:
2833 : {
2834 346822 : dnode *n = sc->data.lval->h;
2835 346822 : symbol *lo = n->data.sym;
2836 346822 : symbol *ro = n->next->next->data.sym;
2837 346822 : char *compare_op = n->next->data.sval;
2838 346822 : int quantifier = 0;
2839 346822 : int is_semantics = 0;
2840 :
2841 346822 : if (n->next->next->next)
2842 86 : quantifier = n->next->next->next->data.i_val + 1;
2843 86 : assert(quantifier == 0 || quantifier == 1 || quantifier == 2 || quantifier == 3 || quantifier == 4);
2844 :
2845 346822 : if (quantifier >= 3) {
2846 10 : if (quantifier == 4)
2847 6 : compare_op = "<>";
2848 : quantifier = 0;
2849 : is_semantics = 1;
2850 : }
2851 346822 : return rel_compare(query, rel, sc, lo, ro, compare_op, f, ek, quantifier, is_semantics);
2852 : }
2853 : /* Set Member ship */
2854 32424 : case SQL_IN:
2855 : case SQL_NOT_IN:
2856 32424 : return rel_in_exp(query, rel, sc, f);
2857 974 : case SQL_EXISTS:
2858 : case SQL_NOT_EXISTS:
2859 974 : return rel_exists_exp(query, rel , sc, f);
2860 3305 : case SQL_LIKE:
2861 : case SQL_NOT_LIKE:
2862 : {
2863 3305 : symbol *lo = sc->data.lval->h->data.sym;
2864 3305 : symbol *ro = sc->data.lval->h->next->data.sym;
2865 3305 : int insensitive = sc->data.lval->h->next->next->data.i_val;
2866 3305 : int anti = (sc->token == SQL_NOT_LIKE) != (sc->data.lval->h->next->next->next->data.i_val != 0);
2867 3305 : sql_subtype *st = sql_bind_localtype("str");
2868 3305 : sql_exp *le = rel_value_exp(query, &rel, lo, f|sql_farg, ek), *re, *ee = NULL, *ie = exp_atom_bool(sql->sa, insensitive);
2869 :
2870 3305 : if (!le)
2871 : return NULL;
2872 :
2873 3303 : if (!exp_subtype(le))
2874 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameter not allowed on "
2875 : "left hand side of LIKE operator");
2876 :
2877 : /* Do we need to escape ? */
2878 3303 : if (dlist_length(ro->data.lval) == 2) {
2879 82 : char *escape = ro->data.lval->h->next->data.sval;
2880 82 : ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, escape)));
2881 : } else {
2882 3221 : ee = exp_atom(sql->sa, atom_string(sql->sa, st, sa_strdup(sql->sa, "")));
2883 : }
2884 3303 : ro = ro->data.lval->h->data.sym;
2885 3303 : re = rel_value_exp(query, &rel, ro, f|sql_farg, ek);
2886 3303 : if (!re)
2887 : return NULL;
2888 3302 : if ((re = exp_check_type(sql, st, rel, re, type_equal)) == NULL)
2889 0 : return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
2890 3302 : if ((le = exp_check_type(sql, st, rel, le, type_equal)) == NULL)
2891 0 : return sql_error(sql, 02, SQLSTATE(42000) "LIKE: wrong type, should be string");
2892 3302 : return rel_filter_exp_(sql, rel, le, re, ee, ie, "like", anti, f);
2893 : }
2894 2960 : case SQL_BETWEEN:
2895 : case SQL_NOT_BETWEEN:
2896 : {
2897 2960 : symbol *lo = sc->data.lval->h->data.sym;
2898 2960 : int symmetric = sc->data.lval->h->next->data.i_val;
2899 2960 : symbol *ro1 = sc->data.lval->h->next->next->data.sym;
2900 2960 : symbol *ro2 = sc->data.lval->h->next->next->next->data.sym;
2901 2960 : sql_exp *le, *re1, *re2;
2902 2960 : sql_subtype super;
2903 :
2904 2960 : assert(sc->data.lval->h->next->type == type_int);
2905 :
2906 2960 : if (!(le = rel_value_exp(query, &rel, lo, f|sql_farg, ek)))
2907 : return NULL;
2908 2958 : if (!(re1 = rel_value_exp(query, &rel, ro1, f|sql_farg, ek)))
2909 : return NULL;
2910 2956 : if (!(re2 = rel_value_exp(query, &rel, ro2, f|sql_farg, ek)))
2911 : return NULL;
2912 :
2913 2956 : if (exp_between_check_types(&super, exp_subtype(le), exp_subtype(re1), exp_subtype(re2)) < 0)
2914 1 : return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
2915 :
2916 2955 : if ((le = exp_check_type(sql, &super, rel, le, type_equal)) == NULL ||
2917 2955 : (re1 = exp_check_type(sql, &super, rel, re1, type_equal)) == NULL ||
2918 2955 : (re2 = exp_check_type(sql, &super, rel, re2, type_equal)) == NULL)
2919 1 : return NULL;
2920 :
2921 2954 : return rel_compare_exp_(query, rel, le, re1, re2, 3, sc->token == SQL_NOT_BETWEEN ? 1 : 0, 0, f, symmetric, 0);
2922 : }
2923 10490 : case SQL_IS_NULL:
2924 : case SQL_IS_NOT_NULL:
2925 : /* is (NOT) NULL */
2926 : {
2927 10490 : sql_exp *le = rel_value_exp(query, &rel, sc->data.sym, f|sql_farg, ek);
2928 10490 : sql_subtype *t;
2929 :
2930 10490 : if (!le)
2931 : return NULL;
2932 10486 : if (!(t = exp_subtype(le)))
2933 1 : return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for IS%s NULL operator", sc->token == SQL_IS_NOT_NULL ? " NOT" : "");
2934 10485 : le = exp_compare(sql->sa, le, exp_atom(sql->sa, atom_general(sql->sa, t, NULL, 0)), cmp_equal);
2935 10485 : if (sc->token == SQL_IS_NOT_NULL)
2936 2532 : set_anti(le);
2937 10485 : set_has_no_nil(le);
2938 10485 : set_semantics(le);
2939 10485 : return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
2940 : }
2941 19962 : case SQL_NOT: {
2942 19962 : if (not_symbol_can_be_propagated(sql, sc->data.sym)) {
2943 2321 : sc->data.sym = negate_symbol_tree(sql, sc->data.sym);
2944 2321 : return rel_logical_exp(query, rel, sc->data.sym, f);
2945 : }
2946 17641 : sql_exp *le = rel_value_exp(query, &rel, sc->data.sym, f|sql_farg, ek);
2947 17641 : sql_subtype bt;
2948 :
2949 17641 : sql_find_subtype(&bt, "boolean", 0, 0);
2950 17641 : if (!le || !(le = exp_check_type(sql, &bt, rel, le, type_equal)))
2951 1 : return NULL;
2952 17640 : le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 0), cmp_equal);
2953 17640 : return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
2954 : }
2955 618 : case SQL_ATOM: {
2956 : /* TRUE or FALSE */
2957 618 : sql_rel *or = rel;
2958 618 : AtomNode *an = (AtomNode *) sc;
2959 618 : sql_exp *e = exp_atom(sql->sa, an->a);
2960 :
2961 618 : if (e) {
2962 618 : sql_subtype bt;
2963 :
2964 618 : sql_find_subtype(&bt, "boolean", 0, 0);
2965 618 : e = exp_check_type(sql, &bt, rel, e, type_equal);
2966 : }
2967 618 : if (!e || or != rel)
2968 1 : return NULL;
2969 617 : e = exp_compare(sql->sa, e, exp_atom_bool(sql->sa, 1), cmp_equal);
2970 617 : return rel_select_push_compare_exp_down(sql, rel, e, e->l, e->r, NULL, f);
2971 : }
2972 706 : case SQL_IDENT:
2973 : case SQL_COLUMN: {
2974 706 : sql_rel *or = rel;
2975 706 : sql_exp *e = rel_column_ref(query, &rel, sc, f);
2976 :
2977 706 : if (e) {
2978 703 : sql_subtype bt;
2979 :
2980 703 : sql_find_subtype(&bt, "boolean", 0, 0);
2981 703 : e = exp_check_type(sql, &bt, rel, e, type_equal);
2982 : }
2983 703 : if (!e || or != rel)
2984 3 : return NULL;
2985 703 : e = exp_compare(sql->sa, e, exp_atom_bool(sql->sa, 1), cmp_equal);
2986 703 : return rel_select_push_compare_exp_down(sql, rel, e, e->l, e->r, NULL, f);
2987 : }
2988 8 : case SQL_UNION:
2989 : case SQL_EXCEPT:
2990 : case SQL_INTERSECT: {
2991 8 : sql_rel *sq;
2992 :
2993 8 : if (is_psm_call(f) || is_sql_merge(f))
2994 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");
2995 7 : if (rel)
2996 7 : query_push_outer(query, rel, f);
2997 7 : sq = rel_setquery(query, sc);
2998 7 : if (rel) {
2999 7 : rel = query_pop_outer(query);
3000 7 : if (is_sql_join(f) && is_groupby(rel->op)) {
3001 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
3002 7 : } else if (is_sql_where(f) && is_groupby(rel->op)) {
3003 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
3004 7 : } else if ((is_sql_update_set(f) || is_sql_psm(f)) && is_groupby(rel->op)) {
3005 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
3006 : }
3007 : }
3008 7 : if (!sq)
3009 : return NULL;
3010 7 : assert(ek.type == type_value); /* I don't expect IN tuple matching calls to land here */
3011 7 : if (is_sql_where(f) && is_groupby(rel->op))
3012 0 : assert(0);
3013 7 : if (ek.card <= card_set && is_project(sq->op) && list_length(sq->exps) > 1)
3014 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
3015 7 : if (!rel)
3016 : return sq;
3017 7 : sq = rel_zero_or_one(sql, sq, ek);
3018 7 : if (is_sql_where(f) || is_sql_having(f)) {
3019 7 : sql_exp *le = exp_rel(sql, sq);
3020 7 : sql_subtype bt;
3021 :
3022 7 : sql_find_subtype(&bt, "boolean", 0, 0);
3023 7 : le = exp_check_type(sql, &bt, rel, le, type_equal);
3024 7 : if (!le)
3025 : return NULL;
3026 7 : le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 1), cmp_equal);
3027 7 : return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, NULL, f);
3028 : } else {
3029 0 : sq = rel_crossproduct(sql->sa, rel, sq, (f==sql_sel || is_single(sq))?op_left:op_join);
3030 0 : set_processed(sq);
3031 : }
3032 0 : return sq;
3033 : }
3034 0 : case SQL_DEFAULT:
3035 0 : return sql_error(sql, 02, SQLSTATE(42000) "DEFAULT keyword not allowed outside insert and update statements");
3036 311 : default: {
3037 311 : sql_exp *le = rel_value_exp(query, &rel, sc, f|sql_farg, ek);
3038 311 : sql_subtype bt;
3039 :
3040 311 : if (!le)
3041 : return NULL;
3042 292 : if (le && (!is_compare(le->type) || le->flag > cmp_filter)) {
3043 279 : sql_find_subtype(&bt, "boolean", 0, 0);
3044 279 : if (!(le = exp_check_type(sql, &bt, rel, le, type_equal)))
3045 : return NULL;
3046 279 : le = exp_compare(sql->sa, le, exp_atom_bool(sql->sa, 1), cmp_equal);
3047 : }
3048 292 : if (le->flag == cmp_filter)
3049 12 : return rel_select_push_filter_exp_down(sql, rel, le, le->l, le->r, f);
3050 : else
3051 280 : return rel_select_push_compare_exp_down(sql, rel, le, le->l, le->r, le->f, f);
3052 : }
3053 : }
3054 : /* never reached, as all switch cases have a `return` */
3055 : }
3056 :
3057 : static sql_exp * _rel_aggr(sql_query *query, sql_rel **rel, int distinct, char *sname, char *aname, dnode *arguments, int f);
3058 : static sql_exp *rel_aggr(sql_query *query, sql_rel **rel, symbol *se, int f);
3059 :
3060 : static sql_exp *
3061 1817 : rel_op(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek )
3062 : {
3063 1817 : mvc *sql = query->sql;
3064 1817 : dnode *l = se->data.lval->h;
3065 1817 : char *fname = qname_schema_object(l->data.lval);
3066 1817 : char *sname = qname_schema(l->data.lval);
3067 :
3068 1817 : if (find_func(sql, sname, fname, 0, F_AGGR, false, NULL, NULL))
3069 0 : return _rel_aggr(query, rel, 0, sname, fname, NULL, f);
3070 1817 : sql->session->status = 0; /* if the function was not found clean the error */
3071 1817 : sql->errstr[0] = '\0';
3072 1817 : return rel_op_(sql, sname, fname, ek);
3073 : }
3074 :
3075 : sql_exp *
3076 93999 : rel_unop_(mvc *sql, sql_rel *rel, sql_exp *e, char *sname, char *fname, int card)
3077 : {
3078 93999 : bool found = false;
3079 93999 : sql_subtype *t = exp_subtype(e);
3080 93999 : sql_ftype type = (card == card_loader)?F_LOADER:((card == card_none)?F_PROC:
3081 : ((card == card_relation)?F_UNION:F_FUNC));
3082 :
3083 93999 : sql_subfunc *f = bind_func(sql, sname, fname, t, NULL, 1, type, false, &found, false);
3084 93999 : if (f && !f->func->vararg) {
3085 93929 : sql_arg *a = f->func->ops->h->data;
3086 93929 : t = &a->type;
3087 : }
3088 93999 : if (f && t && type_has_tz(t) && f->func->fix_scale == SCALE_FIX) {
3089 : /* set timezone (using msec (.3)) */
3090 0 : sql_subtype *intsec = sql_bind_subtype(sql->sa, "sec_interval", 10 /*hour to second */, 3);
3091 0 : atom *a = atom_int(sql->sa, intsec, sql->timezone);
3092 0 : sql_exp *tz = exp_atom(sql->sa, a);
3093 :
3094 0 : e = rel_binop_(sql, rel, e, tz, "sys", "sql_add", card, true);
3095 0 : if (!e)
3096 : return NULL;
3097 : }
3098 93977 : if (f) {
3099 93930 : if (check_card(card, f)) {
3100 93930 : list *args = list_append(sa_list(sql->sa), e);
3101 93930 : if (!f->func->vararg)
3102 187858 : args = check_arguments_and_find_largest_any_type(sql, rel, args, f, card == card_relation && e->card > CARD_ATOM, false);
3103 93930 : if (args)
3104 93930 : return exp_op(sql->sa, args, f);
3105 : }
3106 0 : found = false; /* reset found */
3107 0 : f = NULL;
3108 : }
3109 : /* reset error */
3110 69 : sql->session->status = 0;
3111 69 : sql->errstr[0] = '\0';
3112 206 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s unary operator %s%s%s'%s'(%s)",
3113 137 : found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname, t ? t->type->base.name : "?");
3114 : }
3115 :
3116 : static sql_exp *
3117 76952 : rel_unop(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
3118 : {
3119 76952 : mvc *sql = query->sql;
3120 76952 : dnode *l = se->data.lval->h;
3121 76952 : char *fname = qname_schema_object(l->data.lval);
3122 76952 : char *sname = qname_schema(l->data.lval);
3123 76952 : exp_kind iek = {type_value, card_column, FALSE};
3124 76952 : sql_exp *e = NULL;
3125 :
3126 76952 : if (find_func(sql, sname, fname, 1, F_AGGR, false, NULL, NULL))
3127 18496 : return rel_aggr(query, rel, se, f);
3128 :
3129 58456 : sql->session->status = 0; /* if the function was not found clean the error */
3130 58456 : sql->errstr[0] = '\0';
3131 58456 : if (!(e = rel_value_exp(query, rel, l->next->next->data.sym, f|sql_farg, iek)))
3132 : return NULL;
3133 58447 : return rel_unop_(sql, rel ? *rel : NULL, e, sname, fname, ek.card);
3134 : }
3135 :
3136 : sql_exp *
3137 520487 : rel_binop_(mvc *sql, sql_rel *rel, sql_exp *l, sql_exp *r, char *sname, char *fname, int card, bool exact)
3138 : {
3139 520487 : sql_subtype *t1 = exp_subtype(l), *t2 = exp_subtype(r);
3140 520487 : sql_ftype type = (card == card_loader)?F_LOADER:((card == card_none)?F_PROC:((card == card_relation)?F_UNION:F_FUNC));
3141 520487 : bool found = false;
3142 :
3143 520487 : if (card == card_loader)
3144 0 : card = card_none;
3145 :
3146 520487 : if (is_commutative(sname, fname) && l->card < r->card) { /* move constants to the right if possible */
3147 : sql_subtype *tmp = t1;
3148 520487 : t1 = t2;
3149 520487 : t2 = tmp;
3150 : sql_exp *res = l;
3151 520487 : l = r;
3152 520487 : r = res;
3153 : }
3154 : /* swap complex types (intervals) to left side of +, * */
3155 520487 : if (t1 && t2 && is_commutative(sname, fname)) {
3156 120849 : if ((EC_INTERVAL(t1->type->eclass) && EC_TEMP(t2->type->eclass)) ||
3157 120847 : ((!EC_TEMP(t1->type->eclass) && !EC_INTERVAL(t1->type->eclass)) && EC_INTERVAL(t2->type->eclass))) {
3158 : sql_subtype *tmp = t1;
3159 520487 : t1 = t2;
3160 520487 : t2 = tmp;
3161 : sql_exp *res = l;
3162 520487 : l = r;
3163 520487 : r = res;
3164 : }
3165 : }
3166 :
3167 520487 : sql_subfunc *f = bind_func(sql, sname, fname, t1, t2, 2, type, false, &found, exact);
3168 520487 : if (f && check_card(card,f)) {
3169 520324 : t1 = exp_subtype(l);
3170 520324 : t2 = exp_subtype(r);
3171 520324 : list *args = list_append(list_append(sa_list(sql->sa), l), r);
3172 520324 : if (!f->func->vararg)
3173 520323 : args = check_arguments_and_find_largest_any_type(sql, rel, args, f, 0, false);
3174 520324 : if (args)
3175 520322 : return exp_op(sql->sa, args, f);
3176 : return NULL;
3177 : }
3178 :
3179 163 : if (!exp_subtype(l) || !exp_subtype(r))
3180 0 : return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) on both sides of an expression");
3181 163 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s binary operator %s%s%s'%s'(%s,%s)",
3182 163 : found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname,
3183 163 : exp_subtype(l)->type->base.name, exp_subtype(r)->type->base.name);
3184 : }
3185 :
3186 : static sql_exp *
3187 372353 : rel_binop(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
3188 : {
3189 372353 : mvc *sql = query->sql;
3190 372353 : dnode *dl = se->data.lval->h;
3191 372353 : sql_exp *l, *r;
3192 372353 : char *fname = qname_schema_object(dl->data.lval);
3193 372353 : char *sname = qname_schema(dl->data.lval);
3194 372353 : exp_kind iek = {type_value, card_column, FALSE};
3195 :
3196 372353 : if (find_func(sql, sname, fname, 2, F_AGGR, false, NULL, NULL))
3197 4173 : return rel_aggr(query, rel, se, f);
3198 :
3199 368180 : sql->session->status = 0; /* if the function was not found clean the error */
3200 368180 : sql->errstr[0] = '\0';
3201 368180 : if (!(l = rel_value_exp(query, rel, dl->next->next->data.sym, f|sql_farg, iek)))
3202 : return NULL;
3203 368153 : if (!(r = rel_value_exp(query, rel, dl->next->next->next->data.sym, f|sql_farg, iek)))
3204 : return NULL;
3205 368117 : return rel_binop_(sql, rel ? *rel : NULL, l, r, sname, fname, ek.card, false);
3206 : }
3207 :
3208 : sql_exp *
3209 471 : 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)
3210 : {
3211 471 : list *tl = sa_list(sql->sa);
3212 471 : sql_subfunc *f = NULL;
3213 471 : sql_ftype type = (card == card_none)?F_PROC:((card == card_relation)?F_UNION:F_FUNC);
3214 :
3215 : /* rel_nop_ should only be called for functions available to everyone, ie defined at sql_types! */
3216 471 : (void) rel;
3217 471 : append(tl, exp_subtype(a1));
3218 471 : append(tl, exp_subtype(a2));
3219 471 : append(tl, exp_subtype(a3));
3220 471 : if (a4)
3221 371 : append(tl, exp_subtype(a4));
3222 :
3223 471 : if (!(f = bind_func_(sql, sname, fname, tl, type, false, NULL, true)))
3224 : return NULL;
3225 471 : if (!a4)
3226 100 : return exp_op3(sql->sa, a1,a2,a3,f);
3227 371 : return exp_op4(sql->sa, a1,a2,a3,a4,f);
3228 : }
3229 :
3230 : static sql_func *
3231 3 : inplace_func(mvc *sql)
3232 : {
3233 3 : sql_func *f = SA_NEW(sql->sa, sql_func);
3234 :
3235 3 : *f = (sql_func) {
3236 : .mod = "",
3237 : .imp = "",
3238 : .type = F_PROC,
3239 : .lang = FUNC_LANG_INT,
3240 : .query = NULL,
3241 3 : .ops = sql->params,
3242 : .res = NULL,
3243 : };
3244 3 : base_init(sql->sa, &f->base, 0, true, NULL);
3245 3 : f->base.new = 1;
3246 3 : f->base.id = -1;
3247 3 : f->base.name = "-1";
3248 3 : f->instantiated = TRUE;
3249 3 : return f;
3250 : }
3251 :
3252 : static list *
3253 3 : reorder_args(mvc *sql, list *exps, list *names, list *params)
3254 : {
3255 3 : list *nexps = sa_list(sql->sa);
3256 8 : for(node *n = params->h; n; n = n->next) {
3257 5 : sql_arg *a = n->data;
3258 5 : int found =0;
3259 7 : for(node *m = names->h, *o = exps->h; m && o; m = m->next, o = o->next) {
3260 7 : if (strcmp(m->data, a->name) == 0) {
3261 5 : append(nexps, o->data);
3262 5 : found = 1;
3263 5 : break;
3264 : }
3265 : }
3266 5 : if (!found)
3267 : return NULL;
3268 : }
3269 : return nexps;
3270 : }
3271 :
3272 : static sql_exp *
3273 84436 : rel_nop(sql_query *query, sql_rel **rel, symbol *se, int fs, exp_kind ek)
3274 : {
3275 84436 : mvc *sql = query->sql;
3276 84436 : int nr_args = 0, err = 0;
3277 84436 : dnode *l = se->data.lval->h;
3278 84436 : dnode *ops = l->next->next->data.lval?l->next->next->data.lval->h:NULL;
3279 84436 : list *exps = sa_list(sql->sa), *tl = sa_list(sql->sa);
3280 84436 : exp_kind iek = {type_value, card_column, FALSE};
3281 84436 : char buf[ERRSIZE];
3282 84436 : int split = (l->type == type_int && l->data.i_val == -1);
3283 84436 : list *names = NULL;
3284 :
3285 3 : if (split)
3286 3 : names = sa_list(sql->sa);
3287 347296 : for (; ops; ops = ops->next, nr_args++) {
3288 262860 : if (!err) { /* we need the nr_args count at the end, but if an error is found, stop calling rel_value_exp */
3289 262838 : sql_exp *e = rel_value_exp(query, rel, ops->data.sym, fs|sql_farg, iek);
3290 262838 : if (!e) {
3291 6 : err = sql->session->status;
3292 6 : strcpy(buf, sql->errstr);
3293 6 : continue;
3294 : }
3295 262832 : if (split) {
3296 5 : ops = ops->next;
3297 5 : append(names, ops->data.sval);
3298 : }
3299 262832 : append(exps, e);
3300 262832 : append(tl, exp_subtype(e));
3301 : }
3302 : }
3303 84436 : if (l->type == type_int) {
3304 : /* exec nr (ops)*/
3305 5909 : int nr = l->data.i_val;
3306 5909 : cq *q = NULL;
3307 :
3308 5909 : if (err)
3309 : return NULL;
3310 5908 : if (nr == -1 || (q = qc_find(sql->qc, nr))) {
3311 5906 : list *nexps = new_exp_list(sql->sa);
3312 5906 : sql_func *f = q?q->f:inplace_func(sql);
3313 5906 : list *ops = q?f->ops:sql->params;
3314 :
3315 5906 : tl = sa_list(sql->sa);
3316 5906 : if (list_length(ops) != list_length(exps))
3317 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));
3318 5903 : if (split) {
3319 3 : exps = reorder_args(sql, exps, names, ops);
3320 3 : if (!exps)
3321 0 : return sql_error(sql, 02, SQLSTATE(42000) "EXEC called with wrong arguments");
3322 : }
3323 5903 : if (exps->h && ops) {
3324 21927 : for (node *n = exps->h, *m = ops->h; n && m; n = n->next, m = m->next) {
3325 16115 : sql_arg *a = m->data;
3326 16115 : sql_exp *e = n->data;
3327 16115 : sql_subtype *ntp = &a->type;
3328 :
3329 16115 : if (ntp && ntp->type)
3330 16115 : e = exp_check_type(sql, ntp, NULL, e, type_equal);
3331 : else
3332 0 : a->type = *exp_subtype(e);
3333 16115 : if (!e) {
3334 1 : err = sql->session->status;
3335 1 : strcpy(buf, sql->errstr);
3336 1 : break;
3337 : }
3338 16114 : append(nexps, e);
3339 16114 : append(tl, exp_subtype(e));
3340 : }
3341 : }
3342 :
3343 5903 : if (err)
3344 : return NULL;
3345 5902 : if (q)
3346 5899 : sql->type = q->type;
3347 5992 : return exp_op(sql->sa, list_empty(nexps) ? NULL : nexps, sql_dup_subfunc(sql->sa, f, tl, NULL));
3348 : } else {
3349 2 : return sql_error(sql, 02, SQLSTATE(42000) "EXEC: PREPARED Statement missing '%d'", nr);
3350 : }
3351 : }
3352 78527 : char *fname = qname_schema_object(l->data.lval);
3353 78527 : char *sname = qname_schema(l->data.lval);
3354 :
3355 78527 : if (!sname && strcmp(fname, "field") == 0) { /* map into join */
3356 2 : if (err)
3357 2 : return NULL;
3358 1 : if (list_length(exps) < 2)
3359 1 : return sql_error(sql, 02, SQLSTATE(42000) "Field function called with not enough arguments");
3360 0 : sql_exp *le = exps->h->data;
3361 0 : set_freevar(le, 1);
3362 0 : list_remove_data(exps, NULL, le);
3363 0 : sql_exp *re = exp_values(sql->sa, exps);
3364 0 : exp_label(sql->sa, re, ++sql->label);
3365 0 : sql_rel *r = rel_project(sql->sa, NULL, append(sa_list(sql->sa), re));
3366 0 : sql_exp *id = NULL;
3367 0 : rel_add_identity(sql, r, &id);
3368 0 : re = exp_ref(sql, re);
3369 0 : id = exp_ref(sql, id);
3370 0 : if (r) {
3371 0 : r->nrcols = list_length(exps);
3372 0 : sql_exp *e = exp_compare(sql->sa, le, re, cmp_equal);
3373 0 : r = rel_select(sql->sa, r, e);
3374 0 : r = rel_project(sql->sa, r, append(sa_list(sql->sa), exp_convert(sql, id, exp_subtype(id), sql_bind_localtype("int"))));
3375 0 : re = exp_rel(sql, r);
3376 0 : return re;
3377 : }
3378 : }
3379 : /* first try aggregate */
3380 78525 : 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 */
3381 : /* reset error */
3382 2 : sql->session->status = 0;
3383 2 : sql->errstr[0] = '\0';
3384 2 : return _rel_aggr(query, rel, l->next->data.i_val, sname, fname, l->next->next->data.lval->h, fs);
3385 : }
3386 78523 : if (err) {
3387 2 : sql->session->status = err;
3388 2 : strcpy(sql->errstr, buf);
3389 2 : return NULL;
3390 : }
3391 78521 : sql->session->status = 0; /* if the function was not found clean the error */
3392 78521 : sql->errstr[0] = '\0';
3393 78521 : return _rel_nop(sql, sname, fname, tl, rel ? *rel : NULL, exps, ek);
3394 : }
3395 :
3396 : typedef struct aggr_input {
3397 : sql_query *query;
3398 : int groupby;
3399 : char *err;
3400 : } aggr_input;
3401 :
3402 : static sql_exp *
3403 246 : exp_valid(visitor *v, sql_rel *rel, sql_exp *e, int depth)
3404 : {
3405 246 : aggr_input *ai = v->data;
3406 246 : (void)rel; (void)depth;
3407 :
3408 246 : int vf = is_freevar(e);
3409 246 : if (!v->changes && vf && vf < ai->groupby) { /* check need with outer query */
3410 14 : sql_rel *sq = query_fetch_outer(ai->query, vf-1);
3411 :
3412 : /* problem freevar have cardinality CARD_ATOM */
3413 14 : if (sq->card <= CARD_AGGR && exp_card(e) != CARD_AGGR && is_alias(e->type)) {
3414 4 : if (!exps_bind_column(sq->exps, e->l, e->r, NULL, 0)) {
3415 1 : v->changes = 1;
3416 1 : ai->err = SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query";
3417 : }
3418 : }
3419 232 : } else if (!v->changes && vf && vf == ai->groupby) { /* check if input is already aggregated */
3420 157 : sql_rel *sq = query_fetch_outer(ai->query, vf-1);
3421 157 : sql_exp *a = NULL;
3422 :
3423 157 : if (sq->card <= CARD_AGGR && is_alias(e->type)) {
3424 117 : if ((a = exps_bind_column(sq->exps, e->l, e->r, NULL, 0)) && is_aggr(a->type)) { /* aggregate */
3425 8 : v->changes = 1;
3426 8 : ai->err = SQLSTATE(42000) "SELECT: aggregate function calls cannot be nested";
3427 : }
3428 : }
3429 : }
3430 246 : return e;
3431 : }
3432 :
3433 : static char *
3434 154 : exps_valid(sql_query *query, list *exps, int groupby)
3435 : {
3436 154 : aggr_input ai = { .query = query, .groupby = groupby };
3437 154 : visitor v = { .sql = query->sql, .data = &ai };
3438 :
3439 154 : exps_exp_visitor_topdown(&v, NULL, exps, 0, &exp_valid, true);
3440 154 : if (v.changes)
3441 9 : return ai.err;
3442 : return NULL;
3443 : }
3444 :
3445 : static sql_exp *
3446 41453 : _rel_aggr(sql_query *query, sql_rel **rel, int distinct, char *sname, char *aname, dnode *args, int f)
3447 : {
3448 41453 : mvc *sql = query->sql;
3449 41453 : exp_kind ek = {type_value, card_column, FALSE};
3450 41453 : sql_subfunc *a = NULL;
3451 41453 : int no_nil = 0, group = 0, all_aggr = query_has_outer(query), i;
3452 41453 : unsigned int all_freevar = 0;
3453 41453 : sql_rel *groupby = rel ? *rel : NULL, *sel = NULL, *gr, *og = NULL, *res = groupby;
3454 41453 : sql_rel *subquery = NULL;
3455 41453 : list *exps = NULL, *ungrouped_cols = NULL;
3456 41453 : bool is_grouping = !strcmp(aname, "grouping"), has_args = false, found = false, used_rel = false;
3457 :
3458 41453 : if (!all_aggr) {
3459 27585 : if (!groupby) {
3460 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3461 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: missing group by", toUpperCopy(uaname, aname));
3462 27584 : } else if (is_sql_groupby(f)) {
3463 6 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3464 6 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate function '%s' not allowed in GROUP BY clause", toUpperCopy(uaname, aname), aname);
3465 27578 : } else if (is_sql_values(f)) {
3466 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3467 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed on an unique value", toUpperCopy(uaname, aname));
3468 27577 : } 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 */
3469 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3470 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in JOIN conditions", toUpperCopy(uaname, aname));
3471 27575 : } else if (is_sql_where(f)) {
3472 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3473 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
3474 27574 : } else if (is_sql_update_set(f) || is_sql_psm(f)) {
3475 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3476 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE, RETURNING clauses (use subquery)", toUpperCopy(uaname, aname));
3477 27574 : } else if (is_sql_aggr(f)) {
3478 3 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3479 3 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
3480 27571 : } else if (is_psm_call(f)) {
3481 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3482 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed inside CALL", toUpperCopy(uaname, aname));
3483 27571 : } else if (is_sql_from(f)) {
3484 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3485 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in functions in FROM", toUpperCopy(uaname, aname));
3486 : }
3487 : }
3488 :
3489 41439 : exps = sa_list(sql->sa);
3490 41439 : if (args && args->data.sym) {
3491 22772 : bool arguments_correlated = true, all_const = true;
3492 :
3493 22772 : all_freevar = all_aggr?1:0;
3494 49742 : for (i = 0; args && args->data.sym; args = args->next, i++) {
3495 27024 : int base = (!groupby || !is_project(groupby->op) || is_base(groupby->op) || is_processed(groupby));
3496 19448 : sql_rel *gl = base?groupby:groupby->l, *ogl = gl; /* handle case of subqueries without correlation */
3497 27024 : sql_exp *e = rel_value_exp(query, &gl, args->data.sym, (f | sql_aggr)& ~sql_farg, ek);
3498 27024 : bool found_one_freevar = false;
3499 :
3500 27024 : if (!e)
3501 54 : return NULL;
3502 26974 : used_rel |= (rel_has_exp(gl, e, true) == 0);
3503 26974 : has_args = true;
3504 26974 : if (gl && gl != ogl) {
3505 3 : if (gl->grouped) {
3506 3 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3507 3 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
3508 : }
3509 0 : if (!base)
3510 0 : groupby->l = subquery = gl;
3511 : else
3512 : groupby = subquery = gl;
3513 : }
3514 26971 : sql_subtype *t = exp_subtype(e);
3515 26971 : if (!t) { /* we also do not expect parameters here */
3516 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3517 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to aggregate functions", toUpperCopy(uaname, aname));
3518 : }
3519 26970 : if (!t->type->localtype) {
3520 47 : if (e->type == e_atom && !e->f) {
3521 44 : t = sql_bind_localtype("bte");
3522 44 : e->tpe = *t;
3523 44 : if (e->l)
3524 44 : e->l = atom_set_type(sql->sa, e->l, t);
3525 : }
3526 : }
3527 :
3528 26970 : 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)));
3529 26970 : exp_only_freevar(query, e, &arguments_correlated, &found_one_freevar, &ungrouped_cols);
3530 26970 : 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 */
3531 26970 : all_const &= is_atom(e->type);
3532 26970 : list_append(exps, e);
3533 : }
3534 22718 : if (all_const)
3535 196 : all_freevar = 0;
3536 : }
3537 41385 : if (!all_freevar) {
3538 41217 : if (is_sql_groupby(f)) {
3539 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3540 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate function '%s' not allowed in GROUP BY clause", toUpperCopy(uaname, aname), aname);
3541 41217 : } else if (is_sql_from(f)) {
3542 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3543 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in functions in FROM", toUpperCopy(uaname, aname));
3544 41216 : } else if (is_sql_aggr(f) && groupby->grouped) {
3545 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3546 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
3547 41214 : } else if (is_sql_values(f)) {
3548 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3549 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed on an unique value", toUpperCopy(uaname, aname));
3550 41214 : } 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 */
3551 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3552 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in JOIN conditions", toUpperCopy(uaname, aname));
3553 41214 : } else if (is_sql_where(f)) {
3554 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3555 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
3556 41213 : } else if (!all_aggr && !list_empty(ungrouped_cols)) {
3557 65 : for (node *n = ungrouped_cols->h ; n ; n = n->next) {
3558 36 : sql_rel *outer;
3559 36 : sql_exp *e = (sql_exp*) n->data;
3560 :
3561 36 : if ((outer = query_fetch_outer(query, is_freevar(e)-1))) {
3562 36 : int of = query_fetch_outer_state(query, is_freevar(e)-1);
3563 36 : if (outer->grouped) {
3564 10 : bool err = false, was_processed = false;
3565 :
3566 10 : if (is_processed(outer)) {
3567 2 : was_processed = true;
3568 2 : reset_processed(outer);
3569 : }
3570 10 : if (!is_groupby_col(outer, e))
3571 2 : err = true;
3572 10 : if (was_processed)
3573 2 : set_processed(outer);
3574 10 : if (err) {
3575 2 : if (exp_name(e) && exp_relname(e) && !has_label(e))
3576 2 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column \"%s.%s\" from outer query", exp_relname(e), exp_name(e));
3577 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
3578 : }
3579 26 : } else if (!used_rel && is_sql_where(of)) {
3580 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3581 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions not allowed in WHERE clause", toUpperCopy(uaname, aname));
3582 24 : } else if (!is_sql_aggr(of)) {
3583 21 : set_outer(outer);
3584 : }
3585 : }
3586 : }
3587 : }
3588 : }
3589 :
3590 41377 : if (all_freevar) { /* case 2, ie use outer */
3591 168 : int card;
3592 168 : sql_exp *exp = NULL;
3593 : /* find proper groupby relation */
3594 343 : for (node *n = exps->h; n; n = n->next) {
3595 175 : sql_exp *e = n->data;
3596 :
3597 175 : int vf = exp_freevar_offset(sql, e);
3598 175 : if (vf > (int)all_freevar)
3599 19 : all_freevar = vf;
3600 175 : exp = e;
3601 : }
3602 168 : if (query_has_outer(query) >= all_freevar) {
3603 168 : int sql_state = query_fetch_outer_state(query,all_freevar-1);
3604 168 : res = groupby = query_fetch_outer(query, all_freevar-1);
3605 168 : card = query_outer_used_card(query, all_freevar-1);
3606 : /* given groupby validate all input expressions */
3607 168 : char *err;
3608 168 : if (groupby && !is_groupby(groupby->op)) {
3609 57 : sql_exp *p = query_outer_last_used(query, all_freevar-1);
3610 57 : if (p && !is_aggr(p->type) && !is_groupby_col(groupby, p)) {
3611 14 : if (p->type == e_column)
3612 14 : 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);
3613 0 : if (exp_name(p) && exp_relname(p) && !has_label(p))
3614 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));
3615 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
3616 : }
3617 : }
3618 154 : if ((err = exps_valid(query, exps, all_freevar)) != NULL) {
3619 9 : strcpy(sql->errstr, err);
3620 9 : sql->session->status = -ERR_GROUPBY;
3621 9 : return NULL;
3622 : }
3623 145 : if (exp && !is_groupby_col(res, exp)) {
3624 101 : if (is_sql_groupby(sql_state))
3625 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate function '%s' not allowed in GROUP BY clause", aname);
3626 101 : if (is_sql_aggr(sql_state) && groupby->grouped) {
3627 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3628 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: aggregate functions cannot be nested", toUpperCopy(uaname, aname));
3629 : }
3630 99 : if (is_sql_values(sql_state))
3631 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed on an unique value");
3632 99 : if (is_sql_update_set(sql_state) || is_sql_psm(f))
3633 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
3634 99 : if (is_sql_join(sql_state))
3635 3 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
3636 96 : if (is_sql_where(sql_state))
3637 2 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
3638 94 : if (is_psm_call(sql_state))
3639 0 : return sql_error(sql, 05, SQLSTATE(42000) "CALL: aggregate functions not allowed inside CALL");
3640 94 : if (is_sql_from(sql_state))
3641 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in functions in FROM");
3642 94 : if (card > CARD_AGGR) { /* used an expression before on the non grouped relation */
3643 0 : sql_exp *lu = query_outer_last_used(query, all_freevar-1);
3644 0 : if (lu->type == e_column)
3645 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);
3646 0 : if (exp_name(lu) && exp_relname(lu) && !has_label(lu))
3647 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));
3648 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
3649 : }
3650 94 : if (is_outer(groupby))
3651 2 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
3652 : }
3653 : } else {
3654 : all_freevar = 0;
3655 : }
3656 41209 : } else if (!subquery && groupby && is_outer(groupby) && !is_groupby(groupby->op))
3657 1 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: subquery uses ungrouped column from outer query");
3658 :
3659 : /* find having select */
3660 41344 : if (!subquery && groupby && !is_processed(groupby) && is_sql_having(f)) {
3661 80 : og = groupby;
3662 80 : while(!is_processed(groupby) && !is_base(groupby->op)) {
3663 47 : if (is_select(groupby->op) || !groupby->l)
3664 : break;
3665 : if (groupby->l)
3666 : groupby = groupby->l;
3667 : }
3668 51 : if (groupby && is_select(groupby->op) && !is_processed(groupby)) {
3669 18 : group = 1;
3670 18 : sel = groupby;
3671 : /* At the end we switch back to the old projection relation og.
3672 : * During the partitioning and ordering we add the expressions to the intermediate relations. */
3673 : }
3674 18 : if (!sel)
3675 : groupby = og;
3676 18 : if (sel && sel->l)
3677 18 : groupby = sel->l;
3678 : }
3679 :
3680 : /* find groupby */
3681 41344 : if (!subquery && groupby && !is_processed(groupby) && !is_base(groupby->op)) {
3682 27225 : og = groupby;
3683 27225 : groupby = rel_find_groupby(groupby);
3684 27225 : if (groupby)
3685 : group = 1;
3686 : else
3687 : groupby = og;
3688 : }
3689 :
3690 7740 : if (!groupby && exps_card(exps) > CARD_ATOM) {
3691 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3692 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: missing group by", toUpperCopy(uaname, aname));
3693 : }
3694 :
3695 41344 : if (!subquery && groupby && groupby->op != op_groupby) { /* implicit groupby */
3696 20152 : if (!all_freevar && query->last_exp && !is_sql_aggr(query->last_state)) {
3697 9 : if (exp_relname(query->last_exp) && exp_name(query->last_exp) && !has_label(query->last_exp))
3698 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));
3699 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
3700 : }
3701 20143 : res = groupby = rel_groupby(sql, groupby, NULL);
3702 : }
3703 41335 : if (subquery) {
3704 0 : assert(!all_freevar);
3705 0 : res = groupby;
3706 0 : if (is_sql_sel(f) && is_left(subquery->op) && !is_groupby(groupby->op)) {
3707 0 : res = groupby = rel_groupby(sql, groupby, NULL);
3708 0 : exps_set_freevar(sql, exps, groupby); /* mark free variables */
3709 0 : } else if (!is_groupby(groupby->op)) {
3710 0 : res = groupby = rel_groupby(sql, groupby, NULL);
3711 : }
3712 0 : assert(!is_base(groupby->op));
3713 : }
3714 41335 : if ((!exps || exps_card(exps) > CARD_ATOM) && (!res || !groupby))
3715 : return NULL;
3716 :
3717 41335 : if (all_freevar) {
3718 136 : query_update_outer(query, res, all_freevar-1);
3719 41199 : } else if (rel) {
3720 41199 : *rel = res;
3721 41199 : if (query->last_rel != res) {
3722 37291 : query->last_rel = res;
3723 37291 : query->last_state |= sql_aggr;
3724 : }
3725 : }
3726 :
3727 41335 : if (!has_args) { /* count(*) case */
3728 18663 : sql_exp *e;
3729 :
3730 18663 : if (strcmp(aname, "count") != 0) {
3731 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3732 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: unable to perform '%s(*)'", toUpperCopy(uaname, aname), aname);
3733 : }
3734 18661 : a = sql_bind_func(sql, "sys", aname, sql_bind_localtype("void"), NULL, F_AGGR, true, true);
3735 18661 : e = exp_aggr(sql->sa, NULL, a, distinct, 0, groupby?groupby->card:CARD_ATOM, 0);
3736 :
3737 18661 : if (!groupby)
3738 : return e;
3739 18661 : if (all_freevar)
3740 0 : query_outer_used_exp(query, all_freevar-1, e, sql_aggr);
3741 18661 : e = rel_groupby_add_aggr(sql, groupby, e);
3742 18661 : if (!group && !all_freevar)
3743 : return e;
3744 3194 : if (all_freevar) {
3745 0 : assert(!is_simple_project(res->op));
3746 0 : e->card = CARD_ATOM;
3747 0 : set_freevar(e, all_freevar-1);
3748 0 : return e;
3749 : }
3750 : return e;
3751 : }
3752 :
3753 : /* use cnt as nils shouldn't be counted */
3754 22672 : no_nil = 1;
3755 :
3756 22672 : gr = groupby;
3757 22672 : if (gr && gr->op == op_project && gr->l)
3758 : gr = gr->l;
3759 :
3760 22672 : if (is_grouping) {
3761 109 : sql_subtype *tpe;
3762 109 : list *l = (list*) groupby->r;
3763 :
3764 109 : if (list_length(l) <= 7)
3765 107 : tpe = sql_bind_localtype("bte");
3766 2 : else if (list_length(l) <= 15)
3767 2 : tpe = sql_bind_localtype("sht");
3768 0 : else if (list_length(l) <= 31)
3769 0 : tpe = sql_bind_localtype("int");
3770 0 : else if (list_length(l) <= 63)
3771 0 : tpe = sql_bind_localtype("lng");
3772 : #ifdef HAVE_HGE
3773 0 : else if (list_length(l) <= 127)
3774 0 : tpe = sql_bind_localtype("hge");
3775 : #endif
3776 : else
3777 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: GROUPING the number of grouping columns is larger"
3778 : " than the maximum number of representable bits from this server (%d > %d)", list_length(l),
3779 : #ifdef HAVE_HGE
3780 : 127
3781 : #else
3782 : 63
3783 : #endif
3784 : );
3785 109 : a = sql_bind_func_result(sql, sname, aname, F_AGGR, true, tpe, 1, exp_subtype(exps->h->data));
3786 : } else
3787 22563 : a = sql_bind_func_(sql, sname, aname, exp_types(sql->sa, exps), F_AGGR, false, false);
3788 :
3789 22672 : if (a) {
3790 22667 : found = true;
3791 22667 : if (!execute_priv(sql, a->func))
3792 0 : a = NULL;
3793 22667 : if (!is_grouping && a && !(exps = check_arguments_and_find_largest_any_type(sql, rel ? *rel : NULL, exps, a, 0, false)))
3794 0 : a = NULL;
3795 : }
3796 :
3797 22672 : if (a) {
3798 22667 : bool hasnil = have_nil(exps) || (strcmp(aname, "count") != 0 && (!groupby || list_empty(groupby->r))); /* for global case, the aggregate may return NULL */
3799 22667 : sql_exp *e = exp_aggr(sql->sa, exps, a, distinct, no_nil, groupby?groupby->card:CARD_ATOM, hasnil);
3800 :
3801 22667 : if (!groupby)
3802 : return e;
3803 22667 : if (all_freevar)
3804 136 : query_outer_aggregated(query, all_freevar-1, e);
3805 22667 : e = rel_groupby_add_aggr(sql, groupby, e);
3806 22667 : if (!group && !all_freevar)
3807 : return e;
3808 16355 : if (all_freevar) {
3809 136 : rel_bind_vars(sql, groupby->l, exps);
3810 136 : assert(!is_simple_project(res->op));
3811 136 : e->card = CARD_ATOM;
3812 136 : set_freevar(e, all_freevar-1);
3813 136 : return e;
3814 : }
3815 : return e;
3816 : }
3817 5 : const char *type = "unknown";
3818 5 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
3819 :
3820 5 : if (!list_empty(exps)) {
3821 5 : sql_exp *e = exps->h->data;
3822 5 : type = exp_subtype(e)->type->base.name;
3823 : }
3824 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",
3825 : sname ? "'":"", sname ? sname : "", sname ? "'.":"", aname, type);
3826 : }
3827 :
3828 : static sql_exp *
3829 41451 : rel_aggr(sql_query *query, sql_rel **rel, symbol *se, int f)
3830 : {
3831 41451 : dlist *l = se->data.lval;
3832 41451 : dnode *d = l->h->next->next;
3833 41451 : int distinct = l->h->next->data.i_val;
3834 41451 : char *aname = qname_schema_object(l->h->data.lval);
3835 41451 : char *sname = qname_schema(l->h->data.lval);
3836 :
3837 41451 : return _rel_aggr(query, rel, distinct, sname, aname, d, f);
3838 : }
3839 :
3840 : static sql_exp *
3841 100249 : rel_case(sql_query *query, sql_rel **rel, symbol *opt_cond, dlist *when_search_list, symbol *opt_else, int f)
3842 : {
3843 100249 : mvc *sql = query->sql;
3844 100249 : sql_subtype *tpe = NULL;
3845 100249 : list *conds = new_exp_list(sql->sa), *results = new_exp_list(sql->sa);
3846 100249 : sql_subtype *restype = NULL, *condtype = NULL, ctype, rtype, bt;
3847 100249 : sql_exp *res = NULL, *opt_cond_exp = NULL;
3848 100249 : exp_kind ek = {type_value, card_column, FALSE};
3849 :
3850 100249 : if (opt_cond) {
3851 9404 : if (!(opt_cond_exp = rel_value_exp(query, rel, opt_cond, f, ek)))
3852 : return NULL;
3853 9403 : condtype = exp_subtype(opt_cond_exp);
3854 : }
3855 :
3856 247391 : for (dnode *dn = when_search_list->h; dn; dn = dn->next) {
3857 147152 : sql_exp *cond = NULL, *result = NULL;
3858 147152 : dlist *when = dn->data.sym->data.lval;
3859 :
3860 147152 : if (opt_cond)
3861 45444 : cond = rel_value_exp(query, rel, when->h->data.sym, f, ek);
3862 : else
3863 101708 : cond = rel_logical_value_exp(query, rel, when->h->data.sym, f, ek);
3864 147152 : if (!cond)
3865 : return NULL;
3866 147146 : append(conds, cond);
3867 147146 : tpe = exp_subtype(cond);
3868 147146 : if (tpe && condtype) {
3869 56301 : result_datatype(&ctype, condtype, tpe);
3870 56301 : condtype = &ctype;
3871 90845 : } else if (tpe) {
3872 90843 : condtype = tpe;
3873 : }
3874 :
3875 147146 : if (!(result = rel_value_exp(query, rel, when->h->next->data.sym, f, ek)))
3876 : return NULL;
3877 147143 : append(results, result);
3878 147143 : tpe = exp_subtype(result);
3879 147143 : if (tpe && restype) {
3880 46901 : result_datatype(&rtype, restype, tpe);
3881 46901 : restype = &rtype;
3882 100242 : } else if (tpe) {
3883 100236 : restype = tpe;
3884 : }
3885 : }
3886 100239 : if (opt_else) {
3887 97677 : if (!(res = rel_value_exp(query, rel, opt_else, f, ek)))
3888 : return NULL;
3889 :
3890 97677 : tpe = exp_subtype(res);
3891 97677 : if (tpe && restype) {
3892 97672 : result_datatype(&rtype, restype, tpe);
3893 97672 : restype = &rtype;
3894 5 : } else if (tpe) {
3895 : restype = tpe;
3896 : }
3897 :
3898 97675 : if (!restype)
3899 2 : return sql_error(sql, 02, SQLSTATE(42000) "Result type missing");
3900 97675 : if (restype->type->localtype == TYPE_void) /* NULL */
3901 0 : restype = sql_bind_localtype("str");
3902 :
3903 97675 : if (!(res = exp_check_type(sql, restype, rel ? *rel : NULL, res, type_equal)))
3904 : return NULL;
3905 : } else {
3906 2562 : if (!restype)
3907 0 : return sql_error(sql, 02, SQLSTATE(42000) "Result type missing");
3908 2562 : if (restype->type->localtype == TYPE_void) /* NULL */
3909 7 : restype = sql_bind_localtype("str");
3910 2562 : res = exp_null(sql->sa, restype);
3911 : }
3912 :
3913 100237 : if (!condtype)
3914 0 : return sql_error(sql, 02, SQLSTATE(42000) "Condition type missing");
3915 100237 : if (condtype->type->localtype == TYPE_void) /* NULL */
3916 0 : condtype = sql_bind_localtype("str");
3917 100237 : if (opt_cond_exp && !(opt_cond_exp = exp_check_type(sql, condtype, rel ? *rel : NULL, opt_cond_exp, type_equal)))
3918 : return NULL;
3919 100237 : sql_find_subtype(&bt, "boolean", 0, 0);
3920 100237 : list *args = sa_list(sql->sa);
3921 100237 : if (opt_cond_exp)
3922 9397 : append(args, opt_cond_exp);
3923 247373 : for (node *n = conds->h, *m = results->h; n && m; n = n->next, m = m->next) {
3924 147137 : sql_exp *cond = n->data;
3925 147137 : sql_exp *result = m->data;
3926 :
3927 147137 : if (!(result = exp_check_type(sql, restype, rel ? *rel : NULL, result, type_equal)))
3928 : return NULL;
3929 :
3930 147137 : if (!(cond = exp_check_type(sql, condtype, rel ? *rel : NULL, cond, type_equal)))
3931 : return NULL;
3932 147136 : if (!opt_cond_exp && !(cond = exp_check_type(sql, &bt, rel ? *rel : NULL, cond, type_equal)))
3933 : return NULL;
3934 147136 : append(args, cond);
3935 147136 : append(args, result);
3936 : }
3937 100236 : assert(res);
3938 100236 : list_append(args, res);
3939 100236 : list *types = sa_list(sql->sa);
3940 100236 : types = append(append(types, restype), restype);
3941 191076 : sql_subfunc *case_func = find_func(sql, NULL, opt_cond_exp?"casewhen":"case", list_length(types), F_FUNC, true, NULL, NULL);
3942 100236 : res = exp_op(sql->sa, args, case_func);
3943 100236 : ((sql_subfunc*)res->f)->res->h->data = sql_create_subtype(sql->sa, restype->type, restype->digits, restype->scale);
3944 100236 : return res;
3945 : }
3946 :
3947 : static sql_exp *
3948 3825 : rel_complex_case(sql_query *query, sql_rel **rel, dlist *case_args, int f, str func)
3949 : {
3950 3825 : exp_kind ek = {type_value, card_column, FALSE};
3951 3825 : list *args = sa_list(query->sql->sa);
3952 3825 : sql_subtype *restype = NULL, rtype;
3953 3825 : sql_exp *res;
3954 :
3955 : /* generate nested func calls */
3956 11931 : for(dnode *dn = case_args->h; dn; dn = dn->next) {
3957 8119 : sql_exp *a = rel_value_exp(query, rel, dn->data.sym, f, ek);
3958 8119 : if (!a)
3959 : return NULL;
3960 8106 : append(args, a);
3961 : /* all arguments should have the same type */
3962 8106 : sql_subtype *tpe = exp_subtype(a);
3963 8106 : if (tpe && restype) {
3964 4283 : result_datatype(&rtype, restype, tpe);
3965 4283 : restype = &rtype;
3966 3823 : } else if (tpe) {
3967 3823 : restype = tpe;
3968 : }
3969 : }
3970 3812 : if (!restype)
3971 0 : return sql_error(query->sql, 02, SQLSTATE(42000) "Result type missing");
3972 3812 : if (restype->type->localtype == TYPE_void) /* NULL */
3973 0 : restype = sql_bind_localtype("str");
3974 3812 : list *nargs = sa_list(query->sql->sa);
3975 11903 : for (node *m = args->h; m; m = m->next) {
3976 8091 : sql_exp *result = m->data;
3977 :
3978 8091 : if (!(result = exp_check_type(query->sql, restype, rel ? *rel : NULL, result, type_equal)))
3979 : return NULL;
3980 8091 : append(nargs, result);
3981 : }
3982 3812 : list *types = append(append(sa_list(query->sql->sa), restype), restype);
3983 3812 : sql_subfunc *fnc = find_func(query->sql, NULL, func, list_length(types), F_FUNC, true, NULL, NULL);
3984 3812 : res = exp_op(query->sql->sa, nargs, fnc);
3985 3812 : ((sql_subfunc*)res->f)->res->h->data = sql_create_subtype(query->sql->sa, restype->type, restype->digits, restype->scale);
3986 3812 : return res;
3987 : }
3988 :
3989 : static sql_exp *
3990 104074 : rel_case_exp(sql_query *query, sql_rel **rel, symbol *se, int f)
3991 : {
3992 104074 : dlist *l = se->data.lval;
3993 :
3994 104074 : if (se->token == SQL_COALESCE) {
3995 3674 : return rel_complex_case(query, rel, l, f | sql_farg, "coalesce");
3996 100400 : } else if (se->token == SQL_NULLIF) {
3997 151 : return rel_complex_case(query, rel, l, f | sql_farg, "nullif");
3998 100249 : } else if (l->h->type == type_list) {
3999 90845 : dlist *when_search_list = l->h->data.lval;
4000 90845 : symbol *opt_else = l->h->next->data.sym;
4001 :
4002 90845 : return rel_case(query, rel, NULL, when_search_list, opt_else, f | sql_farg);
4003 : } else {
4004 9404 : symbol *scalar_exp = l->h->data.sym;
4005 9404 : dlist *when_value_list = l->h->next->data.lval;
4006 9404 : symbol *opt_else = l->h->next->next->data.sym;
4007 :
4008 9404 : return rel_case(query, rel, scalar_exp, when_value_list, opt_else, f | sql_farg);
4009 : }
4010 : }
4011 :
4012 : #define E_ATOM_STRING(e) ((atom*)(e)->l)->data.val.sval
4013 :
4014 : static sql_exp *
4015 168263 : rel_cast(sql_query *query, sql_rel **rel, symbol *se, int f)
4016 : {
4017 168263 : mvc *sql = query->sql;
4018 168263 : dlist *dl = se->data.lval;
4019 168263 : symbol *s = dl->h->data.sym;
4020 168263 : sql_subtype *tpe = &dl->h->next->data.typeval;
4021 168263 : exp_kind ek = {type_value, card_column, FALSE};
4022 168263 : sql_exp *e = rel_value_exp(query, rel, s, f|sql_farg, ek);
4023 :
4024 168263 : if (!e)
4025 : return NULL;
4026 :
4027 : /* strings may need to be truncated */
4028 168249 : if (EC_VARCHAR(tpe->type->eclass) && tpe->digits > 0) {
4029 82222 : sql_subtype *et = exp_subtype(e);
4030 : /* truncate only if the number of digits are smaller or from clob */
4031 82222 : if (et && EC_VARCHAR(et->type->eclass) && (tpe->digits < et->digits || et->digits == 0)) {
4032 2858 : sql_subfunc *c = sql_bind_func(sql, "sys", "truncate", et, sql_bind_localtype("int"), F_FUNC, true, true);
4033 2858 : if (c)
4034 2858 : e = exp_binop(sql->sa, e, exp_atom_int(sql->sa, tpe->digits), c);
4035 : }
4036 : }
4037 :
4038 168249 : if (e->type == e_atom && tpe->type->eclass == EC_DEC) {
4039 86 : sql_subtype *et = exp_subtype(e);
4040 86 : if (et->type->eclass == EC_NUM) {
4041 42 : unsigned int min_precision = atom_num_digits(e->l);
4042 42 : if (min_precision > tpe->digits)
4043 0 : return sql_error(sql, 02, SQLSTATE(42000) "Precision (%d) should be at least (%d)", tpe->digits, min_precision);
4044 42 : tpe = sql_bind_subtype(sql->sa, "decimal", min_precision, et->scale);
4045 44 : } else if (EC_VARCHAR(et->type->eclass)) {
4046 12 : char *s = E_ATOM_STRING(e);
4047 12 : unsigned int min_precision = 0, min_scale = 0;
4048 12 : bool dot_seen = false;
4049 61 : for (size_t i = 0; i < strlen(s); i++) {
4050 49 : if (isdigit(s[i])) {
4051 41 : min_precision++;
4052 41 : if (dot_seen)
4053 14 : min_scale++;
4054 8 : } else if (s[i] == '.') {
4055 7 : dot_seen = true;
4056 : }
4057 : }
4058 12 : tpe = sql_bind_subtype(sql->sa, "decimal", min_precision, min_scale);
4059 : }
4060 : }
4061 :
4062 : if (e)
4063 168249 : e = exp_check_type(sql, tpe, rel ? *rel : NULL, e, type_cast);
4064 :
4065 168249 : if (e && e->type == e_convert)
4066 47718 : exp_label(sql->sa, e, ++sql->label);
4067 :
4068 : return e;
4069 : }
4070 :
4071 : static sql_exp *
4072 1584 : rel_next_value_for( mvc *sql, symbol *se )
4073 : {
4074 1584 : char *sname = qname_schema(se->data.lval);
4075 1584 : char *seqname = qname_schema_object(se->data.lval);
4076 1584 : sql_sequence *seq = NULL;
4077 1584 : sql_subtype t;
4078 1584 : sql_subfunc *f;
4079 :
4080 1584 : if (!stack_find_rel_view(sql, seqname)) {
4081 1388 : if (!(seq = find_sequence_on_scope(sql, sname, seqname, "NEXT VALUE FOR")))
4082 : return NULL;
4083 1386 : if (!mvc_schema_privs(sql, seq->s))
4084 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);
4085 : }
4086 1582 : sql_find_subtype(&t, "varchar", 0, 0);
4087 1582 : f = sql_bind_func(sql, "sys", "next_value_for", &t, &t, F_FUNC, true, true);
4088 1582 : assert(f);
4089 : /* sequence found in the stack. use session's schema? */
4090 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);
4091 : }
4092 :
4093 : /* some users like to use aliases already in the groupby */
4094 : static sql_exp *
4095 153 : rel_selection_ref(sql_query *query, sql_rel **rel, char *name, dlist *selection)
4096 : {
4097 153 : allocator *sa = query->sql->sa;
4098 153 : dlist *nl;
4099 153 : exp_kind ek = {type_value, card_column, FALSE};
4100 153 : sql_exp *res = NULL;
4101 153 : symbol *nsym;
4102 :
4103 153 : if (!selection)
4104 : return NULL;
4105 :
4106 643 : for (dnode *n = selection->h; n; n = n->next) {
4107 : /* we only look for columns */
4108 493 : tokens to = n->data.sym->token;
4109 493 : if (to == SQL_COLUMN || to == SQL_IDENT) {
4110 491 : dlist *l = n->data.sym->data.lval;
4111 : /* AS name */
4112 491 : if (l->h->next->data.sval && strcmp(l->h->next->data.sval, name) == 0) {
4113 134 : sql_exp *ve = rel_value_exp(query, rel, l->h->data.sym, sql_sel|sql_groupby, ek);
4114 134 : if (ve) {
4115 133 : if (res)
4116 1 : return sql_error(query->sql, ERR_AMBIGUOUS, SQLSTATE(42000) "SELECT: identifier '%s' ambiguous", name);
4117 132 : res = ve;
4118 :
4119 132 : nl = dlist_create(sa);
4120 132 : exp_setname(query->sql, ve, NULL, name);
4121 : /* now we should rewrite the selection such that it uses the new group by column */
4122 132 : dlist_append_string(sa, nl, sa_strdup(sa, name));
4123 132 : nsym = symbol_create_list(sa, to, nl);
4124 132 : nl = dlist_create(sa);
4125 132 : dlist_append_symbol(sa, nl, nsym);
4126 : /* no alias */
4127 132 : dlist_append_symbol(sa, nl, NULL);
4128 132 : n->data.sym = symbol_create_list(sa, to, nl);
4129 : }
4130 : }
4131 : }
4132 : }
4133 : return res;
4134 : }
4135 :
4136 : static char*
4137 168 : symbol_get_identifier(symbol *sym)
4138 : {
4139 168 : dlist *syml;
4140 :
4141 168 : if (sym->token != SQL_COLUMN && sym->token != SQL_IDENT)
4142 : return NULL;
4143 159 : syml = sym->data.lval;
4144 159 : if (dlist_length(syml) > 1)
4145 : return NULL;
4146 :
4147 153 : return syml->h->data.sval;
4148 : }
4149 :
4150 : static sql_exp*
4151 23394 : rel_group_column(sql_query *query, sql_rel **rel, symbol *grp, dlist *selection, list *exps, int f)
4152 : {
4153 23394 : sql_query *lquery = query_create(query->sql);
4154 23394 : mvc *sql = query->sql;
4155 23394 : exp_kind ek = {type_value, card_value, TRUE};
4156 23394 : sql_exp *e = rel_value_exp2(lquery, rel, grp, f, ek);
4157 :
4158 23394 : if (e && exp_is_atom(e)) {
4159 34 : sql_subtype *tpe = exp_subtype(e);
4160 34 : if (!is_atom(e->type) ||!tpe || tpe->type->eclass != EC_NUM) {
4161 2 : if (!tpe)
4162 2 : return sql_error(sql, 02, SQLSTATE(42000) "Cannot have a parameter (?) for group by column");
4163 3 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: non-integer constant in GROUP BY");
4164 : }
4165 : }
4166 :
4167 164 : if (!e) {
4168 164 : char buf[ERRSIZE], *name;
4169 164 : int status = sql->session->status;
4170 164 : strcpy(buf, sql->errstr);
4171 : /* reset error */
4172 164 : sql->session->status = 0;
4173 164 : sql->errstr[0] = '\0';
4174 :
4175 164 : if ((name = symbol_get_identifier(grp))) {
4176 151 : e = rel_selection_ref(query, rel, name, selection);
4177 151 : if (!e) { /* attempt to find in the existing list of group by expressions */
4178 29 : for (node *n = exps->h ; n && !e ; n = n->next) {
4179 9 : sql_exp *ge = (sql_exp *) n->data;
4180 9 : const char *gen = exp_name(ge);
4181 :
4182 9 : if (gen && strcmp(name, gen) == 0)
4183 5 : e = exp_ref(sql, ge);
4184 : }
4185 : }
4186 : }
4187 33 : if (!e && query_has_outer(query)) {
4188 : /* reset error */
4189 19 : sql->session->status = 0;
4190 19 : sql->errstr[0] = '\0';
4191 19 : e = rel_value_exp2(query, rel, grp, f, ek);
4192 : }
4193 28 : if (!e) {
4194 9 : if (sql->errstr[0] == 0) {
4195 7 : sql->session->status = status;
4196 7 : strcpy(sql->errstr, buf);
4197 : }
4198 9 : return NULL;
4199 : }
4200 : }
4201 23380 : if (!exp_subtype(e))
4202 0 : return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for group by column");
4203 : return e;
4204 : }
4205 :
4206 : static list*
4207 44 : list_power_set(allocator *sa, list* input) /* cube */
4208 : {
4209 44 : list *res = sa_list(sa);
4210 : /* N stores total number of subsets */
4211 44 : int N = (int) pow(2, input->cnt);
4212 :
4213 : /* generate each subset one by one */
4214 266 : for (int i = 0; i < N; i++) {
4215 222 : list *ll = sa_list(sa);
4216 222 : int j = 0; /* check every bit of i */
4217 844 : for (node *n = input->h ; n ; n = n->next) {
4218 : /* if j'th bit of i is set, then append */
4219 622 : if (i & (1 << j))
4220 311 : list_prepend(ll, n->data);
4221 622 : j++;
4222 : }
4223 222 : list_prepend(res, ll);
4224 : }
4225 44 : return res;
4226 : }
4227 :
4228 : static list*
4229 61 : list_rollup(allocator *sa, list* input)
4230 : {
4231 61 : list *res = sa_list(sa);
4232 :
4233 188 : for (int counter = input->cnt; counter > 0; counter--) {
4234 127 : list *ll = sa_list(sa);
4235 127 : int j = 0;
4236 376 : for (node *n = input->h; n && j < counter; j++, n = n->next)
4237 249 : list_append(ll, n->data);
4238 127 : list_append(res, ll);
4239 : }
4240 61 : list_append(res, sa_list(sa)); /* global aggregate case */
4241 61 : return res;
4242 : }
4243 :
4244 : static int
4245 320 : list_equal(list* list1, list* list2)
4246 : {
4247 375 : for (node *n = list1->h; n ; n = n->next) {
4248 328 : sql_exp *e = (sql_exp*) n->data;
4249 328 : if (!exps_find_exp(list2, e))
4250 : return 1;
4251 : }
4252 78 : for (node *n = list2->h; n ; n = n->next) {
4253 47 : sql_exp *e = (sql_exp*) n->data;
4254 47 : if (!exps_find_exp(list1, e))
4255 : return 1;
4256 : }
4257 : return 0;
4258 : }
4259 :
4260 : static list*
4261 26 : lists_cartesian_product_and_distinct(allocator *sa, list *l1, list *l2)
4262 : {
4263 26 : list *res = sa_list(sa);
4264 :
4265 : /* for each list of l2, merge into each list of l1 while removing duplicates */
4266 116 : for (node *n = l1->h ; n ; n = n->next) {
4267 90 : list *sub_list = (list*) n->data;
4268 :
4269 279 : for (node *m = l2->h ; m ; m = m->next) {
4270 189 : list *other = (list*) m->data;
4271 189 : list_append(res, list_distinct(list_merge(list_dup(sub_list, (fdup) NULL), other, (fdup) NULL), (fcmp) list_equal, (fdup) NULL));
4272 : }
4273 : }
4274 26 : return res;
4275 : }
4276 :
4277 : static list*
4278 9652 : rel_groupings(sql_query *query, sql_rel **rel, symbol *groupby, dlist *selection, int f, bool grouping_sets, list **sets)
4279 : {
4280 9652 : mvc *sql = query->sql;
4281 9652 : list *exps = new_exp_list(sql->sa);
4282 :
4283 9652 : if (mvc_highwater(sql))
4284 0 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
4285 :
4286 32958 : for (dnode *o = groupby->data.lval->h; o; o = o->next) {
4287 23321 : symbol *grouping = o->data.sym;
4288 23321 : list *next_set = NULL;
4289 :
4290 23321 : if (grouping->token == SQL_GROUPING_SETS) { /* call recursively, and merge the generated sets */
4291 39 : list *other = rel_groupings(query, rel, grouping, selection, f, true, &next_set);
4292 39 : if (!other)
4293 15 : return NULL;
4294 39 : exps = list_distinct(list_merge(exps, other, (fdup) NULL), (fcmp) exp_equal, (fdup) NULL);
4295 : } else {
4296 23282 : dlist *dl = grouping->data.lval;
4297 23282 : if (dl) {
4298 23256 : list *set_cols = new_exp_list(sql->sa); /* columns and combination of columns to be used for the next set */
4299 :
4300 46606 : for (dnode *oo = dl->h; oo; oo = oo->next) {
4301 23364 : symbol *grp = oo->data.sym;
4302 23364 : list *next_tuple = new_exp_list(sql->sa); /* next tuple of columns */
4303 :
4304 23364 : if (grp->token == SQL_COLUMN_GROUP) { /* set of columns */
4305 71 : assert(is_sql_group_totals(f));
4306 172 : for (dnode *ooo = grp->data.lval->h; ooo; ooo = ooo->next) {
4307 101 : symbol *elm = ooo->data.sym;
4308 101 : sql_exp *e = rel_group_column(query, rel, elm, selection, exps, f);
4309 101 : if (!e)
4310 : return NULL;
4311 101 : assert(e->type == e_column);
4312 101 : list_append(next_tuple, e);
4313 101 : list_append(exps, e);
4314 : }
4315 : } else { /* single column or expression */
4316 23293 : sql_exp *e = rel_group_column(query, rel, grp, selection, exps, f);
4317 23293 : if (!e)
4318 : return NULL;
4319 23279 : if (e->type != e_column && !exp_is_atom(e)) { /* store group by expressions in the stack */
4320 124 : if (is_sql_group_totals(f))
4321 0 : return sql_error(sql, 02, SQLSTATE(42000) "GROUP BY: grouping expressions not possible with ROLLUP, CUBE and GROUPING SETS");
4322 124 : if (!exp_has_rel(e) && !frame_push_groupby_expression(sql, grp, e))
4323 : return NULL;
4324 : }
4325 23279 : list_append(next_tuple, e);
4326 23279 : list_append(exps, e);
4327 : }
4328 23350 : list_append(set_cols, next_tuple);
4329 : }
4330 23242 : if (is_sql_group_totals(f)) {
4331 178 : if (grouping->token == SQL_ROLLUP)
4332 61 : next_set = list_rollup(sql->sa, set_cols);
4333 117 : else if (grouping->token == SQL_CUBE)
4334 44 : next_set = list_power_set(sql->sa, set_cols);
4335 : else /* the list of sets is not used in the "GROUP BY a, b, ..." case */
4336 73 : next_set = list_append(new_exp_list(sql->sa), set_cols);
4337 : }
4338 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 */
4339 17 : next_set = list_append(new_exp_list(sql->sa), new_exp_list(sql->sa));
4340 : }
4341 23307 : if (is_sql_group_totals(f)) { /* if there are no sets, set the found one, otherwise calculate cartesian product and merge the distinct ones */
4342 235 : if (!next_set)
4343 1 : return sql_error(sql, 02, SQLSTATE(42000) "GROUP BY: GROUPING SETS is empty");
4344 234 : if (!*sets)
4345 157 : *sets = next_set;
4346 : else
4347 77 : *sets = grouping_sets ? list_merge(*sets, next_set, (fdup) NULL) : lists_cartesian_product_and_distinct(sql->sa, *sets, next_set);
4348 : }
4349 : }
4350 : return exps;
4351 : }
4352 :
4353 : static list*
4354 8145 : rel_partition_groupings(sql_query *query, sql_rel **rel, symbol *partitionby, dlist *selection, int f)
4355 : {
4356 8145 : mvc *sql = query->sql;
4357 8145 : dnode *o = partitionby->data.lval->h;
4358 8145 : list *exps = new_exp_list(sql->sa);
4359 :
4360 24463 : for (; o; o = o->next) {
4361 8179 : symbol *grp = o->data.sym;
4362 8179 : exp_kind ek = {type_value, card_value, TRUE};
4363 8179 : sql_exp *e = rel_value_exp2(query, rel, grp, f, ek);
4364 :
4365 8179 : if (!e) {
4366 4 : int status = sql->session->status;
4367 4 : char buf[ERRSIZE], *name;
4368 :
4369 : /* reset error */
4370 4 : sql->session->status = 0;
4371 4 : strcpy(buf, sql->errstr);
4372 4 : sql->errstr[0] = '\0';
4373 :
4374 4 : if ((name = symbol_get_identifier(grp))) {
4375 2 : e = rel_selection_ref(query, rel, name, selection);
4376 2 : if (!e) { /* attempt to find in the existing list of partition by expressions */
4377 3 : for (node *n = exps->h ; n ; n = n->next) {
4378 1 : sql_exp *ge = (sql_exp *) n->data;
4379 1 : const char *gen = exp_name(ge);
4380 :
4381 1 : if (gen && strcmp(name, gen) == 0) {
4382 0 : e = exp_ref(sql, ge);
4383 0 : break;
4384 : }
4385 : }
4386 : }
4387 : }
4388 4 : if (!e) {
4389 4 : if (sql->errstr[0] == 0) {
4390 4 : sql->session->status = status;
4391 4 : strcpy(sql->errstr, buf);
4392 : }
4393 4 : return NULL;
4394 : }
4395 : }
4396 :
4397 8175 : if (exp_has_rel(e))
4398 2 : return sql_error(sql, 02, SQLSTATE(42000) "PARTITION BY: subqueries not allowed in PARTITION BY clause");
4399 :
4400 8173 : if (e->type != e_column) { /* store group by expressions in the stack */
4401 31 : if (!frame_push_groupby_expression(sql, grp, e))
4402 : return NULL;
4403 : }
4404 :
4405 8173 : if (e->card > CARD_AGGR)
4406 8082 : e->card = CARD_AGGR;
4407 8173 : append(exps, e);
4408 : }
4409 : return exps;
4410 : }
4411 :
4412 : /* find selection expressions matching the order by column expression */
4413 : /* complex columns only */
4414 : static sql_exp *
4415 66606 : rel_order_by_column_exp(sql_query *query, sql_rel **R, symbol *column_r, int needs_distinct, int f)
4416 : {
4417 66606 : mvc *sql = query->sql;
4418 66606 : sql_rel *r = *R, *p = NULL;
4419 66606 : sql_exp *e = NULL, *found = NULL;
4420 66606 : exp_kind ek = {type_value, card_column, FALSE};
4421 :
4422 66606 : if (!r)
4423 : return e;
4424 :
4425 66606 : if (is_simple_project(r->op) && r->l && is_processed(r)) {
4426 66561 : p = r;
4427 66561 : r = r->l;
4428 : }
4429 :
4430 66606 : e = rel_value_exp(query, &r, column_r, f, ek);
4431 :
4432 66606 : if (r && !p)
4433 45 : *R = r;
4434 66561 : else if (r)
4435 66561 : p->l = r;
4436 66606 : if (e && p) {
4437 66536 : if (is_project(p->op) && (found = exps_any_match(p->exps, e))) { /* if one of the projections matches, return a reference to it */
4438 59144 : e = exp_ref(sql, found);
4439 : } else {
4440 7392 : if (needs_distinct)
4441 2 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
4442 7390 : e = rel_project_add_exp(sql, p, e);
4443 7390 : if (r) {
4444 120435 : for (node *n = p->exps->h ; n ; n = n->next) {
4445 113045 : sql_exp *ee = n->data;
4446 :
4447 113045 : if (ee->card > r->card) {
4448 0 : if (exp_name(ee) && !has_label(ee))
4449 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(ee));
4450 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
4451 : }
4452 : }
4453 : }
4454 : }
4455 66534 : return e;
4456 : }
4457 70 : if (e && r && is_project(r->op)) {
4458 18 : sql_exp *found = exps_find_exp(r->exps, e);
4459 :
4460 18 : if (!found) {
4461 4 : if (needs_distinct)
4462 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
4463 4 : if (!is_simple_project(r->op) && !is_groupby(r->op))
4464 1 : *R = r = rel_project(sql->sa, r, rel_projections(sql, r, NULL, 1, 0));
4465 4 : append(r->exps, e);
4466 : } else {
4467 : e = found;
4468 : }
4469 18 : e = exp_ref(sql, e);
4470 : }
4471 : return e;
4472 : }
4473 :
4474 : static dlist *
4475 113800 : simple_selection(symbol *sq)
4476 : {
4477 113800 : if (sq->token == SQL_SELECT) {
4478 3 : SelectNode *sn;
4479 3 : sn = (SelectNode *) sq;
4480 :
4481 3 : if (!sn->from && !sn->where && !sn->distinct && !sn->window && dlist_length(sn->selection) == 1)
4482 2 : return sn->selection;
4483 : }
4484 : return NULL;
4485 : }
4486 :
4487 : static list *
4488 44990 : rel_order_by(sql_query *query, sql_rel **R, symbol *orderby, int needs_distinct, int f)
4489 : {
4490 44990 : mvc *sql = query->sql;
4491 44990 : sql_rel *rel = *R, *or = rel; /* the order by relation */
4492 44990 : list *exps = new_exp_list(sql->sa);
4493 :
4494 44990 : if (!orderby->data.lval) { /* by all */
4495 2 : if (is_sql_orderby(f)) {
4496 2 : assert(is_project(rel->op));
4497 6 : for(node *n = rel->exps->h; n; n = n->next) {
4498 4 : sql_exp *e = n->data;
4499 4 : append(exps, exp_ref(sql, e));
4500 : }
4501 : return exps;
4502 : }
4503 : return NULL;
4504 : }
4505 :
4506 44988 : dnode *o = orderby->data.lval->h;
4507 44988 : dlist *selection = NULL;
4508 :
4509 44988 : if (is_sql_orderby(f)) {
4510 36187 : assert(is_project(rel->op));
4511 36187 : rel = rel->l;
4512 : }
4513 :
4514 158748 : for (; o; o = o->next) {
4515 113800 : symbol *order = o->data.sym;
4516 :
4517 113800 : if (order->token == SQL_COLUMN || order->token == SQL_IDENT) {
4518 113800 : symbol *col = order->data.lval->h->data.sym;
4519 113800 : int direction = order->data.lval->h->next->data.i_val;
4520 113800 : sql_exp *e = NULL;
4521 :
4522 113800 : assert(order->data.lval->h->next->type == type_int);
4523 113800 : if ((selection = simple_selection(col)) != NULL) {
4524 2 : dnode *o = selection->h;
4525 2 : order = o->data.sym;
4526 2 : if (order->data.lval->h->type == type_symbol)
4527 1 : col = order->data.lval->h->data.sym;
4528 : /* remove optional name from selection */
4529 2 : order->data.lval->h->next = NULL;
4530 : }
4531 :
4532 113800 : if (col->token == SQL_COLUMN || col->token == SQL_IDENT || col->token == SQL_ATOM) {
4533 113603 : exp_kind ek = {type_value, card_column, FALSE};
4534 :
4535 113603 : e = rel_value_exp2(query, &rel, col, f, ek);
4536 :
4537 113603 : if (e && e->card <= CARD_ATOM) {
4538 9337 : sql_subtype *tpe = exp_subtype(e);
4539 : /* integer atom on the stack */
4540 9337 : if (!is_sql_window(f) && e->type == e_atom &&
4541 9240 : tpe->type->eclass == EC_NUM) {
4542 9232 : atom *a = e->l;
4543 9232 : int nr = (int)atom_get_int(a);
4544 :
4545 9232 : e = exps_get_exp(rel->exps, nr);
4546 9232 : if (!e)
4547 2 : 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));
4548 9230 : e = exp_ref(sql, e);
4549 : }
4550 37852 : } else if (e && exp_card(e) > rel->card) {
4551 0 : if (exp_name(e) && !has_label(e))
4552 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));
4553 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
4554 : }
4555 113601 : if (e && !exp_name(e))
4556 20 : exp_label(sql->sa, e, ++sql->label);
4557 47187 : if (e && rel && is_project(rel->op)) {
4558 38937 : sql_exp *found = exps_find_exp(rel->exps, e);
4559 :
4560 38937 : if (!found) {
4561 28 : if (needs_distinct)
4562 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: with DISTINCT ORDER BY expressions must appear in select list");
4563 28 : if (!is_freevar(e))
4564 13 : append(rel->exps, e);
4565 : } else {
4566 : e = found;
4567 : }
4568 38937 : if (!is_freevar(e))
4569 38922 : e = exp_ref(sql, e);
4570 : }
4571 : }
4572 :
4573 113798 : if (rel && !e && sql->session->status != -ERR_AMBIGUOUS) {
4574 : /* reset error */
4575 66606 : sql->session->status = 0;
4576 66606 : sql->errstr[0] = '\0';
4577 :
4578 66606 : e = rel_order_by_column_exp(query, &rel, col, needs_distinct, sql_sel | sql_orderby | (f & sql_group_totals) | (f & sql_window));
4579 : }
4580 66611 : if (!e)
4581 : return NULL;
4582 113761 : if (!exp_subtype(e))
4583 1 : return sql_error(sql, 01, SQLSTATE(42000) "Cannot have a parameter (?) for order by column");
4584 113760 : set_direction(e, direction);
4585 113760 : list_append(exps, e);
4586 : } else {
4587 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: order not of type SQL_COLUMN");
4588 : }
4589 : }
4590 44948 : if (is_sql_orderby(f) && or != rel)
4591 36152 : or->l = rel;
4592 44948 : if (is_sql_window(f))
4593 8796 : *R = rel;
4594 : return exps;
4595 : }
4596 :
4597 : static int
4598 784 : generate_window_bound(tokens sql_token, bool first_half)
4599 : {
4600 784 : switch (sql_token) {
4601 393 : case SQL_PRECEDING:
4602 393 : return first_half ? BOUND_FIRST_HALF_PRECEDING : BOUND_SECOND_HALF_PRECEDING;
4603 284 : case SQL_FOLLOWING:
4604 284 : return first_half ? BOUND_FIRST_HALF_FOLLOWING : BOUND_SECOND_HALF_FOLLOWING;
4605 107 : case SQL_CURRENT_ROW:
4606 107 : return first_half ? CURRENT_ROW_PRECEDING : CURRENT_ROW_FOLLOWING;
4607 : default:
4608 0 : assert(0);
4609 : }
4610 : return 0;
4611 : }
4612 :
4613 : /* window functions */
4614 : static sql_exp*
4615 392 : generate_window_bound_call(mvc *sql, sql_exp **estart, sql_exp **eend, sql_exp *pe, sql_exp *e,
4616 : sql_exp *start, sql_exp *fend, int frame_type, int excl, tokens t1, tokens t2)
4617 : {
4618 392 : list *rargs1 = sa_list(sql->sa), *rargs2 = sa_list(sql->sa), *targs1 = sa_list(sql->sa), *targs2 = sa_list(sql->sa);
4619 392 : sql_subfunc *dc1, *dc2;
4620 392 : sql_subtype *it = sql_bind_localtype("int");
4621 :
4622 392 : if (pe) {
4623 173 : append(targs1, exp_subtype(pe));
4624 173 : append(targs2, exp_subtype(pe));
4625 173 : append(rargs1, exp_copy(sql, pe));
4626 173 : append(rargs2, exp_copy(sql, pe));
4627 : }
4628 392 : append(rargs1, exp_copy(sql, e));
4629 392 : append(rargs2, exp_copy(sql, e));
4630 392 : append(targs1, exp_subtype(e));
4631 392 : append(targs2, exp_subtype(e));
4632 392 : append(targs1, it);
4633 392 : append(targs2, it);
4634 392 : append(targs1, it);
4635 392 : append(targs2, it);
4636 392 : append(targs1, it);
4637 392 : append(targs2, it);
4638 392 : append(targs1, exp_subtype(start));
4639 392 : append(targs2, exp_subtype(fend));
4640 :
4641 392 : dc1 = sql_bind_func_(sql, "sys", "window_bound", targs1, F_ANALYTIC, true, false);
4642 392 : dc2 = sql_bind_func_(sql, "sys", "window_bound", targs2, F_ANALYTIC, true, false);
4643 392 : if (!dc1 || !dc2)
4644 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: function 'window_bound' not found");
4645 392 : append(rargs1, exp_atom_int(sql->sa, frame_type));
4646 392 : append(rargs2, exp_atom_int(sql->sa, frame_type));
4647 392 : append(rargs1, exp_atom_int(sql->sa, generate_window_bound(t1, true)));
4648 392 : append(rargs2, exp_atom_int(sql->sa, generate_window_bound(t2, false)));
4649 392 : append(rargs1, exp_atom_int(sql->sa, excl));
4650 392 : append(rargs2, exp_atom_int(sql->sa, excl));
4651 392 : append(rargs1, start);
4652 392 : append(rargs2, fend);
4653 :
4654 392 : *estart = exp_op(sql->sa, rargs1, dc1);
4655 392 : *eend = exp_op(sql->sa, rargs2, dc2);
4656 392 : return e; /* return something to say there were no errors */
4657 : }
4658 :
4659 : #define EC_NUMERIC(e) (e==EC_NUM||EC_INTERVAL(e)||e==EC_DEC||e==EC_FLT)
4660 :
4661 : static sql_exp*
4662 571 : calculate_window_bound(sql_query *query, sql_rel *p, tokens token, symbol *bound, sql_exp *ie, int frame_type, int f)
4663 : {
4664 571 : mvc *sql = query->sql;
4665 571 : sql_subtype *bt, *bound_tp = sql_bind_localtype("lng"), *iet = exp_subtype(ie);
4666 571 : sql_exp *res = NULL;
4667 :
4668 732 : if ((bound->token == SQL_PRECEDING || bound->token == SQL_FOLLOWING || bound->token == SQL_CURRENT_ROW) && bound->type == type_int) {
4669 161 : atom *a = NULL;
4670 161 : bt = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : iet;
4671 :
4672 161 : if ((bound->data.i_val == UNBOUNDED_PRECEDING_BOUND || bound->data.i_val == UNBOUNDED_FOLLOWING_BOUND)) {
4673 54 : a = atom_max_value(sql->sa, EC_NUMERIC(bt->type->eclass) ? bt : bound_tp);
4674 107 : } else if (bound->data.i_val == CURRENT_ROW_BOUND) {
4675 109 : a = atom_zero_value(sql->sa, EC_NUMERIC(bt->type->eclass) ? bt : bound_tp);
4676 : } else {
4677 0 : assert(0);
4678 : }
4679 161 : res = exp_atom(sql->sa, a);
4680 : } else { /* arbitrary expression case */
4681 410 : exp_kind ek = {type_value, card_column, FALSE};
4682 410 : const char *bound_desc = (token == SQL_PRECEDING) ? "PRECEDING" : "FOLLOWING";
4683 :
4684 410 : assert(token == SQL_PRECEDING || token == SQL_FOLLOWING);
4685 410 : if (!(res = rel_value_exp2(query, &p, bound, f, ek)))
4686 3 : return NULL;
4687 410 : if (!(bt = exp_subtype(res))) { /* frame bound is a parameter */
4688 3 : sql_subtype *t = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : iet;
4689 3 : if (rel_set_type_param(sql, t, p, res, 0) < 0) /* workaround */
4690 : return NULL;
4691 3 : bt = exp_subtype(res);
4692 : }
4693 410 : if (exp_is_null_no_value_opt(res))
4694 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s offset must not be NULL", bound_desc);
4695 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)))
4696 : return NULL;
4697 409 : if (frame_type == FRAME_RANGE) {
4698 70 : sql_class iet_class = iet->type->eclass;
4699 :
4700 70 : if (!EC_NUMERIC(iet_class) && !EC_TEMP(iet_class))
4701 1 : return sql_error(sql, 02, SQLSTATE(42000) "Ranges with arbitrary expressions are available to numeric, interval and temporal types only");
4702 12 : if (EC_NUMERIC(iet_class) && !(res = exp_check_type(sql, iet, p, res, type_equal)))
4703 : return NULL;
4704 69 : if ((iet_class == EC_TIME || iet_class == EC_TIME_TZ) && bt->type->eclass != EC_SEC) {
4705 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);
4706 1 : sa_reset(sql->ta);
4707 1 : return NULL;
4708 : }
4709 68 : if (EC_TEMP(iet->type->eclass) && !EC_INTERVAL(bt->type->eclass)) {
4710 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);
4711 0 : sa_reset(sql->ta);
4712 0 : return NULL;
4713 : }
4714 : }
4715 : }
4716 : return res;
4717 : }
4718 :
4719 : static dlist*
4720 16 : get_window_clauses(mvc *sql, char* ident, symbol **partition_by_clause, symbol **order_by_clause, symbol **frame_clause)
4721 : {
4722 16 : dlist *window_specification = NULL;
4723 16 : char *window_ident;
4724 16 : int pos;
4725 :
4726 16 : if (mvc_highwater(sql))
4727 0 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
4728 :
4729 16 : if ((window_specification = frame_get_window_def(sql, ident, &pos)) == NULL)
4730 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: window '%s' not found", ident);
4731 :
4732 : /* avoid infinite lookups */
4733 15 : if (frame_check_var_visited(sql, pos))
4734 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cyclic references to window '%s' found", ident);
4735 14 : frame_set_var_visited(sql, pos);
4736 :
4737 14 : if (window_specification->h->next->data.sym) {
4738 2 : if (*partition_by_clause)
4739 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of PARTITION BY clause from window '%s'", ident);
4740 2 : *partition_by_clause = window_specification->h->next->data.sym;
4741 : }
4742 14 : if (window_specification->h->next->next->data.sym) {
4743 4 : if (*order_by_clause)
4744 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of ORDER BY clause from window '%s'", ident);
4745 3 : *order_by_clause = window_specification->h->next->next->data.sym;
4746 : }
4747 13 : if (window_specification->h->next->next->next->data.sym) {
4748 0 : if (*frame_clause)
4749 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: redefinition of frame clause from window '%s'", ident);
4750 0 : *frame_clause = window_specification->h->next->next->next->data.sym;
4751 : }
4752 :
4753 13 : window_ident = window_specification->h->data.sval;
4754 13 : if (window_ident && !get_window_clauses(sql, window_ident, partition_by_clause, order_by_clause, frame_clause))
4755 : return NULL; /* the error was already set */
4756 :
4757 : return window_specification; /* return something to say there were no errors */
4758 : }
4759 :
4760 : /*
4761 : * select x, y, rank_op() over (partition by x order by y) as, ...
4762 : aggr_op(z) over (partition by y order by x) as, ...
4763 : * from table [x,y,z,w,v]
4764 : *
4765 : * project and order by over x,y / y,x
4766 : * a = project( table ) [ x, y, z, w, v ], [ x, y]
4767 : * b = project( table ) [ x, y, z, w, v ], [ y, x]
4768 : *
4769 : * project with order dependent operators, ie combined prev/current value
4770 : * 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 ]
4771 : * project(aa) [ aa.x, aa.y, aa.r ] -- only keep current output list
4772 : * bb = project (b) [ x, y, a = aggr_op(z, diff(y), rediff(diff(y), x)), z, w, v ]
4773 : * project(bb) [ bb.x, bb.y, bb.a ] -- only keep current output list
4774 : */
4775 : static sql_exp *
4776 17803 : rel_rankop(sql_query *query, sql_rel **rel, symbol *se, int f)
4777 : {
4778 17803 : mvc *sql = query->sql;
4779 17803 : node *n;
4780 17803 : dlist *l = se->data.lval, *window_specification = NULL;
4781 17803 : symbol *window_function = l->h->data.sym, *partition_by_clause = NULL, *order_by_clause = NULL, *frame_clause = NULL;
4782 17803 : char *aname = NULL, *sname = NULL, *window_ident = NULL;
4783 17803 : sql_subfunc *wf = NULL;
4784 17803 : sql_exp *in = NULL, *pe = NULL, *oe = NULL, *call = NULL, *start = NULL, *eend = NULL, *fstart = NULL, *fend = NULL, *ie = NULL;
4785 17803 : sql_rel *p;
4786 17803 : list *gbe = NULL, *obe = NULL, *args = NULL, *types = NULL, *fargs = NULL;
4787 17803 : dnode *dn = window_function->data.lval->h, *dargs = NULL;
4788 17803 : int distinct = 0, frame_type, pos, nf = f, nfargs = 0;
4789 17803 : bool is_nth_value, supports_frames, found = false;
4790 :
4791 17803 : frame_clear_visited_flag(sql); /* clear visited flags before iterating */
4792 :
4793 17803 : if (l->h->next->type == type_list) {
4794 17787 : window_specification = l->h->next->data.lval;
4795 16 : } else if (l->h->next->type == type_string) {
4796 16 : const char* window_alias = l->h->next->data.sval;
4797 16 : if ((window_specification = frame_get_window_def(sql, window_alias, &pos)) == NULL)
4798 1 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: window '%s' not found", window_alias);
4799 15 : frame_set_var_visited(sql, pos);
4800 : } else {
4801 0 : assert(0);
4802 : }
4803 :
4804 17802 : window_ident = window_specification->h->data.sval;
4805 17802 : partition_by_clause = window_specification->h->next->data.sym;
4806 17802 : order_by_clause = window_specification->h->next->next->data.sym;
4807 17802 : frame_clause = window_specification->h->next->next->next->data.sym;
4808 :
4809 17802 : if (window_ident && !get_window_clauses(sql, window_ident, &partition_by_clause, &order_by_clause, &frame_clause))
4810 : return NULL;
4811 :
4812 17799 : frame_type = frame_clause ? frame_clause->data.lval->h->next->next->data.i_val : FRAME_RANGE;
4813 17799 : aname = qname_schema_object(dn->data.lval);
4814 17799 : sname = qname_schema(dn->data.lval);
4815 :
4816 17799 : is_nth_value = !strcmp(aname, "nth_value");
4817 17799 : bool is_value = is_nth_value || !strcmp(aname, "first_value") || !strcmp(aname, "last_value");
4818 17799 : supports_frames = window_function->token != SQL_RANK || is_value;
4819 :
4820 17799 : 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)) {
4821 5 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4822 5 : 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":
4823 3 : is_sql_join(f)?"in JOIN conditions":is_sql_where(f)?"in WHERE clause":is_sql_groupby(f)?"in GROUP BY clause":
4824 2 : is_psm_call(f)?"in CALL":is_sql_from(f)?"in functions in FROM":"in HAVING clause";
4825 5 : return sql_error(sql, 02, SQLSTATE(42000) "%s: window function '%s' not allowed %s", toUpperCopy(uaname, aname), aname, clause);
4826 17794 : } else if (is_sql_aggr(f)) {
4827 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4828 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: window functions not allowed inside aggregation functions", toUpperCopy(uaname, aname));
4829 17792 : } else if (is_sql_window(f)) {
4830 6 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4831 6 : return sql_error(sql, 02, SQLSTATE(42000) "%s: window functions cannot be nested", toUpperCopy(uaname, aname));
4832 : }
4833 17786 : if (window_function->token == SQL_UNOP || window_function->token == SQL_OP) {
4834 3189 : window_function->token = SQL_NOP;
4835 3189 : dn->next->next->data.lval = dlist_append_symbol(sql->sa, dlist_create( sql->sa ), dn->next->next->data.sym); /* make a list */
4836 : }
4837 17786 : if (window_function->token == SQL_BINOP) {
4838 5128 : window_function->token = SQL_NOP;
4839 5128 : 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 */
4840 5128 : dn->next->next->next = dn->next->next->next->next; /* skip second arg */
4841 : }
4842 17786 : if (window_function->token == SQL_AGGR)
4843 106 : dn->next->next->data.lval = dlist_append_symbol(sql->sa, dlist_create( sql->sa ), dn->next->next->data.sym); /* make a list */
4844 17786 : if (window_function->token == SQL_NOP)
4845 8319 : window_function->token = SQL_AGGR;
4846 17786 : if (window_function->token != SQL_RANK && window_function->token != SQL_AGGR) {
4847 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4848 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: window function '%s' unknown", toUpperCopy(uaname, aname));
4849 : }
4850 :
4851 : /* window operations are only allowed in the projection */
4852 17786 : if (!is_sql_sel(f))
4853 0 : return sql_error(sql, 02, SQLSTATE(42000) "OVER: only possible within the selection");
4854 :
4855 17786 : p = *rel;
4856 : /* Partition By */
4857 17786 : if (partition_by_clause) {
4858 8145 : 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);
4859 8145 : if (!gbe)
4860 : return NULL;
4861 16309 : for (n = gbe->h ; n ; n = n->next) {
4862 8170 : sql_exp *en = n->data;
4863 :
4864 8170 : set_ascending(en);
4865 8170 : set_nulls_first(en);
4866 : }
4867 : }
4868 :
4869 : /* Order By */
4870 17780 : if (order_by_clause) {
4871 8801 : obe = rel_order_by(query, &p, order_by_clause, 0, sql_window);
4872 8801 : if (!obe)
4873 : return NULL;
4874 : }
4875 :
4876 17775 : fargs = sa_list(sql->sa);
4877 17775 : if (window_function->token == SQL_RANK) { /* rank function call */
4878 9357 : dlist *dl = dn->next->next->data.lval;
4879 9357 : bool is_lag = !strcmp(aname, "lag"), is_lead = !strcmp(aname, "lead"),
4880 9357 : extra_input = !strcmp(aname, "ntile") || !strcmp(aname, "rank") || !strcmp(aname, "dense_rank") || !strcmp(aname, "row_number") || !strcmp(aname, "percent_rank") || !strcmp(aname, "cume_dist");
4881 :
4882 9357 : distinct = dn->next->data.i_val;
4883 9357 : if (extra_input) { /* pass an input column for analytic functions that don't require it */
4884 9173 : sql_subfunc *star = sql_bind_func(sql, "sys", "star", NULL, NULL, F_FUNC, true, true);
4885 9173 : in = exp_op(sql->sa, NULL, star);
4886 9173 : append(fargs, in);
4887 : }
4888 9357 : if (dl)
4889 576 : for (dargs = dl->h ; dargs ; dargs = dargs->next) {
4890 330 : exp_kind ek = {type_value, card_column, FALSE};
4891 330 : sql_subtype *empty = sql_bind_localtype("void"), *bte = sql_bind_localtype("bte");
4892 :
4893 330 : in = rel_value_exp2(query, &p, dargs->data.sym, f | sql_window | sql_farg, ek);
4894 330 : if (!in)
4895 0 : return NULL;
4896 330 : if (!exp_subtype(in)) { /* we also do not expect parameters here */
4897 0 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4898 0 : return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to window functions", toUpperCopy(uaname, aname));
4899 : }
4900 330 : if (!exp_name(in))
4901 148 : exp_label(sql->sa, in, ++sql->label);
4902 :
4903 : /* corner case, if the argument is null convert it into something countable such as bte */
4904 330 : if (subtype_cmp(exp_subtype(in), empty) == 0)
4905 20 : in = exp_convert(sql, in, empty, bte);
4906 330 : if ((is_lag || is_lead) && nfargs == 2) { /* lag and lead 3rd arg must have same type as 1st arg */
4907 10 : sql_exp *first = (sql_exp*) fargs->h->data;
4908 10 : if (!(in = exp_check_type(sql, exp_subtype(first), p, in, type_equal)))
4909 : return NULL;
4910 : }
4911 320 : if (!in)
4912 : return NULL;
4913 :
4914 330 : append(fargs, in);
4915 330 : in = exp_ref_save(sql, in);
4916 330 : nfargs++;
4917 : }
4918 : } else { /* aggregation function call */
4919 8418 : distinct = dn->next->data.i_val;
4920 21853 : for (dargs = dn->next->next->data.lval->h ; dargs && dargs->data.sym ; dargs = dargs->next) {
4921 13441 : exp_kind ek = {type_value, card_column, FALSE};
4922 13441 : sql_subtype *empty = sql_bind_localtype("void"), *bte = sql_bind_localtype("bte");
4923 :
4924 13441 : in = rel_value_exp2(query, &p, dargs->data.sym, f | sql_window | sql_farg, ek);
4925 13441 : if (!in)
4926 6 : return NULL;
4927 13436 : if (!exp_subtype(in)) { /* we also do not expect parameters here */
4928 1 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4929 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: parameters not allowed as arguments to window functions", toUpperCopy(uaname, aname));
4930 : }
4931 13435 : if (!exp_name(in))
4932 10053 : exp_label(sql->sa, in, ++sql->label);
4933 :
4934 : /* corner case, if the argument is null convert it into something countable such as bte */
4935 13435 : if (subtype_cmp(exp_subtype(in), empty) == 0)
4936 46 : in = exp_convert(sql, in, empty, bte);
4937 13435 : if (!in)
4938 : return NULL;
4939 :
4940 13435 : append(fargs, in);
4941 13435 : in = exp_ref_save(sql, in);
4942 13435 : nfargs++;
4943 :
4944 13435 : if (!strcmp(aname, "count"))
4945 84 : append(fargs, exp_atom_bool(sql->sa, 1)); /* ignore nills */
4946 : }
4947 :
4948 8412 : if (!nfargs) { /* count(*) */
4949 109 : if (window_function->token == SQL_AGGR && strcmp(aname, "count") != 0) {
4950 2 : char *uaname = SA_NEW_ARRAY(sql->ta, char, strlen(aname) + 1);
4951 2 : return sql_error(sql, 02, SQLSTATE(42000) "%s: unable to perform '%s(*)'", toUpperCopy(uaname, aname), aname);
4952 : }
4953 107 : sql_subfunc *star = sql_bind_func(sql, "sys", "star", NULL, NULL, F_FUNC, true, true);
4954 107 : in = exp_op(sql->sa, NULL, star);
4955 107 : append(fargs, in);
4956 107 : append(fargs, exp_atom_bool(sql->sa, 0)); /* don't ignore nills */
4957 : }
4958 : }
4959 :
4960 17767 : if (distinct)
4961 4 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: DISTINCT clause is not implemented for window functions");
4962 :
4963 : /* diff for partitions */
4964 17763 : if (gbe) {
4965 8133 : sql_subtype *bt = sql_bind_localtype("bit");
4966 :
4967 16296 : for( n = gbe->h; n; n = n->next) {
4968 8164 : sql_subfunc *df;
4969 8164 : sql_exp *e = n->data;
4970 :
4971 8164 : if (!exp_subtype(e))
4972 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters not allowed at PARTITION BY clause from window functions");
4973 :
4974 8163 : e = exp_copy(sql, e);
4975 8163 : args = sa_list(sql->sa);
4976 8163 : if (pe) {
4977 31 : df = sql_bind_func(sql, "sys", "diff", bt, exp_subtype(e), F_ANALYTIC, true, true);
4978 31 : append(args, pe);
4979 : } else {
4980 8132 : df = sql_bind_func(sql, "sys", "diff", exp_subtype(e), NULL, F_ANALYTIC, true, true);
4981 : }
4982 8163 : if (!df)
4983 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: function 'diff' not found");
4984 8163 : append(args, e);
4985 8163 : pe = exp_op(sql->sa, args, df);
4986 : }
4987 : } else {
4988 9630 : pe = exp_atom_bool(sql->sa, 0);
4989 : }
4990 :
4991 : /* diff for orderby */
4992 17762 : if (obe) {
4993 8795 : sql_subtype *bt = sql_bind_localtype("bit");
4994 :
4995 17636 : for( n = obe->h; n; n = n->next) {
4996 8841 : sql_subfunc *df;
4997 8841 : sql_exp *e = n->data;
4998 :
4999 8841 : if (!exp_subtype(e))
5000 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters not allowed at ORDER BY clause from window functions");
5001 :
5002 8841 : e = exp_copy(sql, e);
5003 8841 : args = sa_list(sql->sa);
5004 8841 : if (oe) {
5005 46 : df = sql_bind_func(sql, "sys", "diff", bt, exp_subtype(e), F_ANALYTIC, true, true);
5006 46 : append(args, oe);
5007 : } else {
5008 8795 : df = sql_bind_func(sql, "sys", "diff", exp_subtype(e), NULL, F_ANALYTIC, true, true);
5009 : }
5010 8841 : if (!df)
5011 0 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: function 'diff' not found");
5012 8841 : append(args, e);
5013 8841 : oe = exp_op(sql->sa, args, df);
5014 : }
5015 : } else {
5016 8967 : oe = exp_atom_bool(sql->sa, 0);
5017 : }
5018 :
5019 17762 : if (frame_clause || supports_frames) {
5020 8523 : if (frame_type == FRAME_RANGE)
5021 8227 : ie = obe ? (sql_exp*) obe->t->data : in;
5022 : else
5023 296 : ie = obe ? oe : in;
5024 : }
5025 17762 : assert(oe && pe);
5026 :
5027 17762 : types = exp_types(sql->sa, fargs);
5028 17762 : wf = bind_func_(sql, sname, aname, types, F_ANALYTIC, false, &found, false);
5029 17762 : if (wf && !list_empty(fargs) && !(fargs = check_arguments_and_find_largest_any_type(sql, NULL, fargs, wf, 0, false)))
5030 : wf = NULL;
5031 17759 : if (!wf) {
5032 3 : char *arg_list = nfargs ? nary_function_arg_types_2str(sql, types, nfargs) : NULL;
5033 6 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: %s window function %s%s%s'%s'(%s)",
5034 3 : found ? "insufficient privileges for" : "no such", sname ? "'":"", sname ? sname : "", sname ? "'.":"", aname, arg_list ? arg_list : "");
5035 : }
5036 :
5037 : /* Frame */
5038 17759 : if (frame_clause) {
5039 395 : dnode *d = frame_clause->data.lval->h;
5040 395 : symbol *wstart = d->data.sym, *wend = d->next->data.sym, *rstart = wstart->data.lval->h->data.sym,
5041 395 : *rend = wend->data.lval->h->data.sym;
5042 395 : int excl = d->next->next->next->data.i_val;
5043 395 : bool shortcut = false;
5044 :
5045 395 : if (!supports_frames)
5046 4 : return sql_error(sql, 02, SQLSTATE(42000) "OVER: frame extend only possible with aggregation and first_value, last_value and nth_value functions");
5047 391 : if (excl != EXCLUDE_NONE)
5048 0 : return sql_error(sql, 02, SQLSTATE(42000) "Only EXCLUDE NO OTHERS exclusion is currently implemented");
5049 391 : if (list_empty(obe) && frame_type == FRAME_GROUPS)
5050 2 : return sql_error(sql, 02, SQLSTATE(42000) "GROUPS frame requires an order by expression");
5051 389 : if (wstart->token == SQL_FOLLOWING && wend->token == SQL_PRECEDING)
5052 1 : return sql_error(sql, 02, SQLSTATE(42000) "FOLLOWING offset must come after PRECEDING offset");
5053 388 : if (wstart->token == SQL_CURRENT_ROW && wend->token == SQL_PRECEDING)
5054 1 : return sql_error(sql, 02, SQLSTATE(42000) "CURRENT ROW offset must come after PRECEDING offset");
5055 387 : if (wstart->token == SQL_FOLLOWING && wend->token == SQL_CURRENT_ROW)
5056 1 : return sql_error(sql, 02, SQLSTATE(42000) "FOLLOWING offset must come after CURRENT ROW offset");
5057 386 : if (wstart->token != SQL_CURRENT_ROW && wend->token != SQL_CURRENT_ROW && wstart->token == wend->token && frame_type != FRAME_ROWS)
5058 4 : return sql_error(sql, 02, SQLSTATE(42000) "Non-centered windows are only supported in row frames");
5059 352 : if (frame_type == FRAME_RANGE) {
5060 97 : if (((wstart->token == SQL_PRECEDING || wstart->token == SQL_FOLLOWING) && rstart->token != SQL_PRECEDING && rstart->token != SQL_CURRENT_ROW && rstart->token != SQL_FOLLOWING) ||
5061 59 : ((wend->token == SQL_PRECEDING || wend->token == SQL_FOLLOWING) && rend->token != SQL_PRECEDING && rend->token != SQL_CURRENT_ROW && rend->token != SQL_FOLLOWING)) {
5062 40 : if (list_empty(obe))
5063 2 : return sql_error(sql, 02, SQLSTATE(42000) "RANGE frame with PRECEDING/FOLLOWING offset requires an order by expression");
5064 38 : if (list_length(obe) > 1)
5065 0 : return sql_error(sql, 02, SQLSTATE(42000) "RANGE with offset PRECEDING/FOLLOWING requires exactly one ORDER BY column");
5066 : }
5067 : }
5068 :
5069 380 : if (list_empty(obe) && frame_type == FRAME_RANGE) { /* window functions are weird */
5070 : frame_type = FRAME_ALL;
5071 : shortcut = true;
5072 368 : } else if (!is_value && (rstart->token == SQL_PRECEDING || rstart->token == SQL_CURRENT_ROW || rstart->token == SQL_FOLLOWING) && rstart->type == type_int &&
5073 135 : (rend->token == SQL_PRECEDING || rend->token == SQL_CURRENT_ROW || rend->token == SQL_FOLLOWING) && rend->type == type_int) {
5074 : /* special cases, don't calculate bounds */
5075 131 : if (frame_type != FRAME_ROWS && rstart->data.i_val == UNBOUNDED_PRECEDING_BOUND && rend->data.i_val == CURRENT_ROW_BOUND) {
5076 : frame_type = FRAME_UNBOUNDED_TILL_CURRENT_ROW;
5077 : shortcut = true;
5078 21 : } else if (frame_type != FRAME_ROWS && rstart->data.i_val == CURRENT_ROW_BOUND && rend->data.i_val == UNBOUNDED_FOLLOWING_BOUND) {
5079 : frame_type = FRAME_CURRENT_ROW_TILL_UNBOUNDED;
5080 : shortcut = true;
5081 71 : } else if (rstart->data.i_val == UNBOUNDED_PRECEDING_BOUND && rend->data.i_val == UNBOUNDED_FOLLOWING_BOUND) {
5082 : frame_type = FRAME_ALL;
5083 : shortcut = true;
5084 61 : } else if (rstart->data.i_val == CURRENT_ROW_BOUND && rend->data.i_val == CURRENT_ROW_BOUND) {
5085 380 : frame_type = FRAME_CURRENT_ROW;
5086 380 : shortcut = true;
5087 : }
5088 : }
5089 380 : if (!shortcut) {
5090 287 : if (!(fstart = calculate_window_bound(query, p, wstart->token, rstart, ie, frame_type, f | sql_window)))
5091 : return NULL;
5092 284 : if (!(fend = calculate_window_bound(query, p, wend->token, rend, ie, frame_type, f | sql_window)))
5093 : return NULL;
5094 454 : if (!generate_window_bound_call(sql, &start, &eend, gbe ? pe : NULL, ie, fstart, fend, frame_type, excl,
5095 : wstart->token, wend->token))
5096 : return NULL;
5097 : }
5098 17364 : } else if (supports_frames) { /* for analytic functions with no frame clause, we use the standard default values */
5099 8125 : if (is_value) {
5100 108 : sql_subtype *bound_tp = sql_bind_localtype("lng"), *bt = (frame_type == FRAME_ROWS || frame_type == FRAME_GROUPS) ? bound_tp : exp_subtype(ie);
5101 108 : unsigned char sclass = bt->type->eclass;
5102 :
5103 135 : fstart = exp_atom(sql->sa, atom_max_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp));
5104 108 : fend = order_by_clause ? exp_atom(sql->sa, atom_zero_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp)) :
5105 33 : exp_atom(sql->sa, atom_max_value(sql->sa, EC_NUMERIC(sclass) ? bt : bound_tp));
5106 :
5107 157 : if (generate_window_bound_call(sql, &start, &eend, gbe ? pe : NULL, ie, fstart, fend, frame_type, EXCLUDE_NONE, SQL_PRECEDING, SQL_FOLLOWING) == NULL)
5108 : return NULL;
5109 : } else {
5110 8017 : frame_type = list_empty(obe) ? FRAME_ALL : FRAME_UNBOUNDED_TILL_CURRENT_ROW;
5111 : }
5112 : }
5113 :
5114 17741 : args = sa_list(sql->sa);
5115 40932 : for (node *n = fargs->h ; n ; n = n->next)
5116 23191 : list_append(args, n->data);
5117 17741 : list_append(args, pe);
5118 17741 : list_append(args, oe);
5119 17741 : if (supports_frames) {
5120 8502 : list_append(args, exp_atom_int(sql->sa, frame_type));
5121 8502 : list_append(args, start ? start : exp_atom_oid(sql->sa, 1));
5122 8502 : list_append(args, eend ? eend : exp_atom_oid(sql->sa, 1));
5123 : }
5124 17741 : call = exp_rank_op(sql->sa, list_empty(args) ? NULL : args, gbe, obe, wf);
5125 17741 : *rel = p;
5126 17741 : return call;
5127 : }
5128 :
5129 : sql_exp *
5130 5818502 : rel_value_exp2(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
5131 : {
5132 5818502 : mvc *sql = query->sql;
5133 5818502 : if (!se)
5134 : return NULL;
5135 :
5136 5818502 : if (mvc_highwater(sql))
5137 7 : return sql_error(sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
5138 :
5139 5818714 : if (rel && *rel && (*rel)->card == CARD_AGGR) { /* group by expression case, handle it before */
5140 104662 : sql_exp *exp = NULL;
5141 104662 : if (!is_sql_aggr(f) && !is_sql_window(f))
5142 104272 : exp = frame_get_groupby_expression(sql, se);
5143 104662 : if (sql->errstr[0] != '\0')
5144 : return NULL;
5145 104662 : if (exp) {
5146 76 : sql_exp *res = exp_ref(sql, exp);
5147 76 : res->card = (*rel)->card;
5148 76 : if (se->token == SQL_AGGR) {
5149 0 : dlist *l = se->data.lval;
5150 0 : int distinct = l->h->next->data.i_val;
5151 0 : if (distinct)
5152 0 : set_distinct(res);
5153 : }
5154 76 : if (!query_has_outer(query) && is_groupby((*rel)->op))
5155 72 : res = rel_groupby_add_aggr(sql, *rel, res);
5156 76 : return res;
5157 : }
5158 : }
5159 :
5160 5818638 : switch (se->token) {
5161 1817 : case SQL_OP:
5162 1817 : return rel_op(query, rel, se, f, ek);
5163 76952 : case SQL_UNOP:
5164 76952 : return rel_unop(query, rel, se, f, ek);
5165 372353 : case SQL_BINOP:
5166 372353 : return rel_binop(query, rel, se, f, ek);
5167 84436 : case SQL_NOP:
5168 84436 : return rel_nop(query, rel, se, f, ek);
5169 18782 : case SQL_AGGR:
5170 18782 : return rel_aggr(query, rel, se, f);
5171 17803 : case SQL_WINDOW:
5172 17803 : return rel_rankop(query, rel, se, f);
5173 2304864 : case SQL_IDENT:
5174 : case SQL_COLUMN:
5175 2304864 : return rel_column_ref(query, rel, se, f );
5176 2995 : case SQL_NAME: {
5177 2995 : dlist *l = se->data.lval;
5178 2995 : const char *sname = qname_schema(l);
5179 2995 : const char *vname = qname_schema_object(l);
5180 2995 : return rel_exp_variable_on_scope(sql, sname, vname);
5181 : }
5182 47268 : case SQL_VALUES:
5183 : case SQL_WITH:
5184 : case SQL_SELECT: {
5185 47268 : sql_rel *r = NULL;
5186 :
5187 47268 : if (is_psm_call(f) || is_sql_merge(f))
5188 6 : 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");
5189 47266 : if (rel && *rel)
5190 33320 : query_push_outer(query, *rel, f);
5191 47266 : if (se->token == SQL_WITH) {
5192 30 : r = rel_with_query(query, se);
5193 47236 : } else if (se->token == SQL_VALUES) {
5194 203 : r = rel_values(query, se, NULL);
5195 : } else {
5196 47033 : assert(se->token == SQL_SELECT);
5197 47033 : exp_kind nek = ek;
5198 47033 : nek.aggr = is_sql_aggr(f);
5199 47033 : if (is_sql_no_subquery(f))
5200 3 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery not allowed");
5201 :
5202 47030 : r = rel_subquery(query, se, nek);
5203 47030 : if (r)
5204 46960 : exps_label(sql, r->exps);
5205 : }
5206 47263 : if (rel && *rel) {
5207 33317 : *rel = query_pop_outer(query);
5208 33317 : if (is_sql_join(f) && is_groupby((*rel)->op)) {
5209 0 : return sql_error(sql, 05, SQLSTATE(42000) "SELECT: aggregate functions not allowed in JOIN conditions");
5210 33317 : } else if (is_sql_where(f) && is_groupby((*rel)->op)) {
5211 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in WHERE clause");
5212 33317 : } else if ((is_sql_update_set(f) || is_sql_psm(f)) && is_groupby((*rel)->op)) {
5213 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions not allowed in SET, WHILE, IF, ELSE, CASE, WHEN, RETURN, ANALYZE clauses");
5214 : }
5215 : }
5216 47263 : if (!r)
5217 : return NULL;
5218 47190 : if (ek.type == type_value && ek.card <= card_set && is_project(r->op) && list_length(r->exps) > 1)
5219 7 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery must return only one column");
5220 47183 : if (ek.type == type_relation && is_project(r->op) && list_length(r->exps) != ek.type)
5221 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery has too %s columns", list_length(r->exps) < ek.type ? "few" : "many");
5222 47183 : if (ek.type == type_value && list_length(r->exps) == 1 && !is_sql_psm(f)) /* for now don't rename multi attribute results */
5223 35092 : r = rel_zero_or_one(sql, r, ek);
5224 47183 : return exp_rel(sql, r);
5225 : }
5226 203 : case SQL_TABLE: {
5227 : /* turn a subquery into a tabular result */
5228 203 : *rel = rel_selects(query, se->data.sym);
5229 203 : if (*rel)
5230 201 : return lastexp(*rel);
5231 : return NULL;
5232 : }
5233 1612 : case SQL_PARAMETER: {
5234 1612 : assert(se->type == type_int);
5235 1612 : sql_arg *a = sql_bind_paramnr(sql, se->data.i_val);
5236 1612 : if (sql->emode != m_prepare) {
5237 1 : if (a && a->name && a->name[0])
5238 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: named placeholder ('%s') but named values list is missing", a->name);
5239 : else
5240 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: parameters ('?') not allowed in normal queries, use PREPARE");
5241 : }
5242 1611 : return exp_atom_ref(sql->sa, se->data.i_val, a?&a->type:NULL);
5243 : }
5244 104780 : case SQL_NULL:
5245 104780 : return exp_null(sql->sa, sql_bind_localtype("void"));
5246 1584 : case SQL_NEXT:
5247 1584 : return rel_next_value_for(sql, se);
5248 168263 : case SQL_CAST:
5249 168263 : return rel_cast(query, rel, se, f);
5250 104074 : case SQL_CASE:
5251 : case SQL_COALESCE:
5252 : case SQL_NULLIF:
5253 104074 : return rel_case_exp(query, rel, se, f);
5254 1 : case SQL_RANK:
5255 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));
5256 25 : case SQL_XMLELEMENT:
5257 : case SQL_XMLFOREST:
5258 : case SQL_XMLCOMMENT:
5259 : case SQL_XMLATTRIBUTE:
5260 : case SQL_XMLCONCAT:
5261 : case SQL_XMLDOCUMENT:
5262 : case SQL_XMLPI:
5263 : case SQL_XMLTEXT:
5264 25 : return rel_xml(query, rel, se, f, ek);
5265 2510826 : default:
5266 2510826 : return rel_logical_value_exp(query, rel, se, f, ek);
5267 : }
5268 : }
5269 :
5270 : static int exps_has_rank(list *exps);
5271 :
5272 : static int
5273 : exp_has_rank(sql_exp *e)
5274 : {
5275 : switch(e->type) {
5276 : case e_convert:
5277 : return exp_has_rank(e->l);
5278 : case e_func:
5279 : if (e->r)
5280 : return 1;
5281 : /* fall through */
5282 : case e_aggr:
5283 : return exps_has_rank(e->l);
5284 : case e_cmp:
5285 : if (e->flag == cmp_or || e->flag == cmp_filter)
5286 : return exps_has_rank(e->l) || exps_has_rank(e->r);
5287 : if (e->flag == cmp_in || e->flag == cmp_notin)
5288 : return exp_has_rank(e->l) || exps_has_rank(e->r);
5289 : return exp_has_rank(e->l) || exp_has_rank(e->r) || (e->f && exp_has_rank(e->f));
5290 : default:
5291 : return 0;
5292 : }
5293 : }
5294 :
5295 : /* TODO create exps_has (list, fptr ) */
5296 : static int
5297 : exps_has_rank(list *exps)
5298 : {
5299 : if (!exps || list_empty(exps))
5300 : return 0;
5301 : for(node *n = exps->h; n; n=n->next){
5302 : sql_exp *e = n->data;
5303 :
5304 : if (exp_has_rank(e))
5305 : return 1;
5306 : }
5307 : return 0;
5308 : }
5309 :
5310 : sql_exp *
5311 4403925 : rel_value_exp(sql_query *query, sql_rel **rel, symbol *se, int f, exp_kind ek)
5312 : {
5313 4403925 : if (!se)
5314 : return NULL;
5315 :
5316 4403925 : if (mvc_highwater(query->sql))
5317 0 : return sql_error(query->sql, 10, SQLSTATE(42000) "Query too complex: running out of stack space");
5318 :
5319 4403994 : sql_exp *e = rel_value_exp2(query, rel, se, f, ek);
5320 4404025 : if (e && (se->token == SQL_SELECT || se->token == SQL_TABLE) && !exp_is_rel(e)) {
5321 0 : assert(*rel);
5322 0 : return rel_lastexp(query->sql, *rel);
5323 : }
5324 : return e;
5325 : }
5326 :
5327 : static sql_exp *
5328 1297952 : column_exp(sql_query *query, sql_rel **rel, symbol *column_e, int f)
5329 : {
5330 1297952 : dlist *l = column_e->data.lval;
5331 1297952 : exp_kind ek = {type_value, card_column, FALSE};
5332 1297952 : sql_exp *ve;
5333 :
5334 1297952 : if (f == sql_sel && rel && *rel && (*rel)->card < CARD_AGGR)
5335 82019 : ek.card = card_value;
5336 1297952 : ve = rel_value_exp(query, rel, l->h->data.sym, f, ek);
5337 1298048 : if (!ve)
5338 : return NULL;
5339 : /* AS name */
5340 1296981 : if (ve && l->h->next->data.sval)
5341 490677 : exp_setname(query->sql, ve, NULL, l->h->next->data.sval);
5342 : return ve;
5343 : }
5344 :
5345 : static int
5346 803597 : exp_is_not_intern(sql_exp *e)
5347 : {
5348 803597 : return is_intern(e)?-1:0;
5349 : }
5350 :
5351 : static void
5352 121764 : rel_remove_internal_exp(sql_rel *rel)
5353 : {
5354 121764 : if (rel->exps) {
5355 121764 : list *n_exps = list_select(rel->exps, rel, (fcmp)&exp_is_not_intern, (fdup)NULL);
5356 :
5357 121764 : rel->exps = n_exps;
5358 : }
5359 121764 : }
5360 :
5361 : static inline int
5362 16 : exp_key(sql_exp *e)
5363 : {
5364 16 : if (e->alias.name)
5365 16 : return hash_key(e->alias.name);
5366 : return 0;
5367 : }
5368 :
5369 : static list *
5370 5 : group_merge_exps(mvc *sql, list *gexps, list *exps)
5371 : {
5372 5 : int nexps = list_length(gexps) + list_length(exps);
5373 :
5374 5 : sql_hash *ht = hash_new(sql->ta, nexps, (fkeyvalue)&exp_key);
5375 :
5376 9 : for (node *n = gexps->h; n ; n = n->next) { /* first add grouping expressions */
5377 4 : sql_exp *e = n->data;
5378 4 : int key = ht->key(e);
5379 :
5380 4 : hash_add(ht, key, e);
5381 : }
5382 :
5383 17 : for (node *n = exps->h; n ; n = n->next) { /* then test if the new grouping expressions are already there */
5384 12 : sql_exp *e = n->data;
5385 12 : int key = ht->key(e);
5386 12 : sql_hash_e *he = ht->buckets[key&(ht->size-1)];
5387 12 : bool duplicates = false;
5388 :
5389 16 : for (; he && !duplicates; he = he->chain) {
5390 4 : sql_exp *f = he->value;
5391 :
5392 4 : if (!exp_equal(e, f))
5393 4 : duplicates = true;
5394 : }
5395 12 : hash_add(ht, key, e);
5396 12 : if (!duplicates) {
5397 8 : list_append(gexps, e);
5398 8 : n->data = exp_ref(sql, e);
5399 : }
5400 : }
5401 5 : return gexps;
5402 : }
5403 :
5404 : static list *
5405 57652 : rel_table_exp(sql_query *query, sql_rel **rel, symbol *column_e, bool single_exp )
5406 : {
5407 57652 : mvc *sql = query->sql;
5408 57652 : if (column_e->token == SQL_TABLE && column_e->data.lval->h->type == type_symbol) {
5409 0 : sql_rel *r;
5410 :
5411 0 : if (!is_project((*rel)->op))
5412 : return NULL;
5413 0 : r = rel_named_table_function(query, (*rel)->l, column_e, 0, NULL);
5414 0 : if (!r)
5415 : return NULL;
5416 0 : *rel = r;
5417 0 : return sa_list(sql->sa);
5418 57652 : } else if (column_e->token == SQL_TABLE) {
5419 56596 : char *tname = column_e->data.lval->h->data.sval;
5420 56596 : list *exps = NULL;
5421 56596 : sql_rel *project = *rel, *groupby = NULL;
5422 :
5423 : /* if there's a group by relation in the tree, skip it for the '*' case and use the underlying projection */
5424 56596 : if (project) {
5425 65912 : while (is_groupby(project->op) || is_select(project->op)) {
5426 9316 : if (is_groupby(project->op))
5427 5 : groupby = project;
5428 9316 : if (project->l)
5429 9316 : project = project->l;
5430 : }
5431 : assert(project);
5432 : }
5433 :
5434 56596 : if (project->op == op_project && project->l && project == *rel && !tname && !rel_is_ref(project) && !need_distinct(project) && single_exp) {
5435 403 : sql_rel *l = project->l;
5436 403 : if (!l || !is_project(l->op) || list_length(project->exps) == list_length(l->exps)) {
5437 396 : rel_remove_internal_exp(*rel);
5438 396 : exps = project->exps;
5439 396 : *rel = project->l;
5440 : }
5441 : }
5442 56596 : if ((exps || (exps = rel_table_projections(sql, project, tname, 0)) != NULL) && !list_empty(exps)) {
5443 56591 : if (!(exps = check_distinct_exp_names(sql, exps)))
5444 0 : return sql_error(sql, 02, SQLSTATE(42000) "Duplicate column names in table%s%s%s projection list", tname ? " '" : "", tname ? tname : "", tname ? "'" : "");
5445 56591 : if (groupby) {
5446 5 : groupby->exps = group_merge_exps(sql, groupby->exps, exps);
5447 10 : for (node *n = groupby->exps->h ; n ; n = n->next) {
5448 8 : sql_exp *e = n->data;
5449 :
5450 8 : if (e->card > groupby->card) {
5451 4 : if (exp_name(e) && !has_label(e))
5452 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));
5453 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
5454 : }
5455 : }
5456 : }
5457 56588 : return exps;
5458 : }
5459 4 : if (!tname)
5460 2 : return sql_error(sql, 02, SQLSTATE(42000) "Table expression without table name");
5461 2 : return sql_error(sql, 02, SQLSTATE(42000) "Column expression Table '%s' unknown", tname);
5462 : }
5463 : return NULL;
5464 : }
5465 :
5466 : sql_exp *
5467 1354541 : rel_column_exp(sql_query *query, sql_rel **rel, symbol *column_e, int f)
5468 : {
5469 1354541 : if (column_e->token == SQL_COLUMN || column_e->token == SQL_IDENT)
5470 1297953 : return column_exp(query, rel, column_e, f);
5471 : return NULL;
5472 : }
5473 :
5474 : static sql_rel*
5475 366051 : rel_where_groupby_nodes(sql_query *query, sql_rel *rel, SelectNode *sn, int *group_totals)
5476 : {
5477 366051 : mvc *sql = query->sql;
5478 :
5479 366051 : if (sn->where) {
5480 143765 : rel = rel_logical_exp(query, rel, sn->where, sql_where);
5481 143765 : if (!rel) {
5482 53 : if (sql->errstr[0] == 0)
5483 0 : return sql_error(sql, 02, SQLSTATE(42000) "Subquery result missing");
5484 : return NULL;
5485 : }
5486 : }
5487 365998 : query_processed(query);
5488 :
5489 365998 : if (rel && sn->groupby) {
5490 9621 : list *gbe = NULL, *sets = NULL;
5491 9621 : int all = 0;
5492 9621 : if (sn->groupby->data.lval == NULL) { /* ALL */
5493 : all = 1;
5494 : } else {
5495 32707 : for (dnode *o = sn->groupby->data.lval->h; o ; o = o->next) {
5496 23213 : symbol *grouping = o->data.sym;
5497 23213 : if (grouping->token == SQL_ROLLUP || grouping->token == SQL_CUBE || grouping->token == SQL_GROUPING_SETS) {
5498 119 : *group_totals |= sql_group_totals;
5499 119 : break;
5500 : }
5501 : }
5502 9613 : gbe = rel_groupings(query, &rel, sn->groupby, sn->selection, sql_sel | sql_groupby | *group_totals, false, &sets);
5503 9613 : if (!gbe)
5504 15 : return NULL;
5505 : }
5506 9606 : rel = rel_groupby(sql, rel, gbe);
5507 9606 : if (rel && all)
5508 8 : rel->flag = 2;
5509 9606 : if (sets && list_length(sets) > 1) { /* if there is only one combination, there is no reason to generate unions */
5510 114 : prop *p = prop_create(sql->sa, PROP_GROUPINGS, rel->p);
5511 114 : p->value.pval = sets;
5512 114 : rel->p = p;
5513 : }
5514 : }
5515 :
5516 365983 : if (rel && sn->having) {
5517 : /* having implies group by, ie if not supplied do a group by */
5518 1733 : if (rel->op != op_groupby)
5519 120 : rel = rel_groupby(sql, rel, NULL);
5520 : }
5521 365983 : query_processed(query);
5522 365986 : return rel;
5523 : }
5524 :
5525 : static sql_rel*
5526 364914 : rel_having_limits_nodes(sql_query *query, sql_rel *rel, SelectNode *sn, exp_kind ek, int group_totals)
5527 : {
5528 364914 : mvc *sql = query->sql;
5529 364914 : sql_rel *inner = NULL;
5530 364914 : int single_value = 1;
5531 :
5532 364914 : if (is_project(rel->op) && rel->l) {
5533 364914 : inner = rel->l;
5534 364914 : single_value = 0;
5535 : }
5536 :
5537 364914 : if (sn->having) {
5538 1722 : if (inner && is_groupby(inner->op))
5539 1722 : set_processed(inner);
5540 1722 : if (!(inner = rel_logical_exp(query, inner, sn->having, sql_having | group_totals)))
5541 : return NULL;
5542 1683 : if (inner->exps && exps_card(inner->exps) > CARD_AGGR)
5543 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cannot compare sets with values, probably an aggregate function missing");
5544 1683 : if (!single_value)
5545 1683 : rel->l = inner;
5546 : }
5547 :
5548 364875 : if (rel && sn->distinct)
5549 1018 : rel = rel_distinct(rel);
5550 :
5551 364875 : if (rel && sn->orderby) {
5552 36189 : list *obe = NULL;
5553 36189 : sql_rel *sel = NULL, *l = rel->l;
5554 :
5555 : /* project( select ) */
5556 36189 : if (sn->having && is_select(l->op)) {
5557 49 : sel = l;
5558 49 : rel->l = l->l;
5559 : }
5560 36189 : rel = rel_orderby(sql, rel);
5561 36189 : set_processed(rel);
5562 36189 : obe = rel_order_by(query, &rel, sn->orderby, sn->distinct, sql_orderby | group_totals);
5563 36189 : if (!obe)
5564 : return NULL;
5565 36154 : rel->r = obe;
5566 36154 : if (sel) {
5567 48 : sql_rel *o = rel, *p = o->l;
5568 48 : p->l = sel;
5569 : }
5570 : }
5571 364840 : if (!rel)
5572 : return NULL;
5573 :
5574 364840 : if (sn->limit || sn->offset) {
5575 16458 : sql_subtype *lng = sql_bind_localtype("lng");
5576 16454 : list *exps = new_exp_list(sql->sa);
5577 :
5578 16454 : if (sn->limit) {
5579 16424 : sql_exp *l = rel_value_exp(query, NULL, sn->limit, 0, ek);
5580 :
5581 16424 : if (!l || !(l=exp_check_type(sql, lng, NULL, l, type_equal)))
5582 0 : return NULL;
5583 16422 : if ((ek.card != card_relation && sn->limit) &&
5584 : (ek.card == card_value && sn->limit)) {
5585 11 : sql_subfunc *zero_or_one = sql_bind_func(sql, "sys", "zero_or_one", exp_subtype(l), NULL, F_AGGR, true, true);
5586 11 : l = exp_aggr1(sql->sa, l, zero_or_one, 0, 0, CARD_ATOM, has_nil(l));
5587 : }
5588 16422 : list_append(exps, l);
5589 : } else
5590 30 : list_append(exps, exp_atom(sql->sa, atom_general(sql->sa, lng, NULL, 0)));
5591 16451 : if (sn->offset) {
5592 96 : sql_exp *o = rel_value_exp( query, NULL, sn->offset, 0, ek);
5593 96 : if (!o || !(o=exp_check_type(sql, lng, NULL, o, type_equal)))
5594 0 : return NULL;
5595 96 : list_append(exps, o);
5596 : }
5597 16451 : rel = rel_topn(sql->sa, rel, exps);
5598 : }
5599 :
5600 364836 : if (sn->sample || sn->seed) {
5601 5 : list *exps = new_exp_list(sql->sa);
5602 :
5603 23 : if (sn->sample) {
5604 22 : sql_exp *s = rel_value_exp(query, NULL, sn->sample, 0, ek);
5605 22 : if (!s)
5606 : return NULL;
5607 22 : if (!exp_subtype(s) && rel_set_type_param(sql, sql_bind_localtype("lng"), NULL, s, 0) < 0)
5608 : return NULL;
5609 22 : list_append(exps, s);
5610 : } else {
5611 1 : assert(sn->seed);
5612 1 : return sql_error(sql, 02, SQLSTATE(42000) "SEED: cannot have SEED without SAMPLE");
5613 : }
5614 22 : if (sn->seed) {
5615 12 : sql_exp *e = rel_value_exp(query, NULL, sn->seed, 0, ek);
5616 12 : if (!e || !(e=exp_check_type(sql, sql_bind_localtype("int"), NULL, e, type_equal)))
5617 0 : return NULL;
5618 12 : list_append(exps, e);
5619 : }
5620 22 : rel = rel_sample(sql->sa, rel, exps);
5621 : }
5622 :
5623 : /* after parsing the current query, set the group by relation as processed */
5624 364853 : if (!sn->having && inner && is_groupby(inner->op))
5625 28020 : set_processed(inner);
5626 364853 : if (rel)
5627 364853 : set_processed(rel);
5628 : return rel;
5629 : }
5630 :
5631 : static sql_rel *
5632 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)
5633 : {
5634 60 : mvc *sql = query->sql;
5635 60 : int found = 0, full = (op == op_full), right = (op == op_right);
5636 60 : list *exps = rel_projections(sql, t1, NULL, 1, 0);
5637 60 : list *r_exps = rel_projections(sql, t2, NULL, 1, 0);
5638 60 : list *outexps = new_exp_list(sql->sa);
5639 :
5640 60 : if (!exps || !r_exps)
5641 : return NULL;
5642 236 : for (node *n = exps->h; n; n = n->next) {
5643 179 : sql_exp *le = n->data;
5644 179 : int multi = 0;
5645 179 : const char *rname = exp_relname(le), *name = exp_name(le);
5646 179 : sql_exp *re = exps_bind_column(r_exps, name, NULL, &multi, 0);
5647 :
5648 179 : if (re) {
5649 136 : if (multi)
5650 3 : return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "NATURAL JOIN: common column name '%s' appears more than once in right table", rname);
5651 134 : multi = 0;
5652 134 : le = exps_bind_column(exps, name, NULL, &multi, 0);
5653 134 : if (multi)
5654 0 : return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "NATURAL JOIN: common column name '%s' appears more than once in left table", rname);
5655 :
5656 134 : found = 1;
5657 134 : if (!(rel = rel_compare_exp(query, rel, le, re, "=", TRUE, 0, 0, 0, 0)))
5658 : return NULL;
5659 133 : list_remove_data(r_exps, NULL, re);
5660 133 : if (full) {
5661 12 : sql_exp *cond = rel_unop_(sql, rel, le, "sys", "isnull", card_value);
5662 12 : if (!cond)
5663 : return NULL;
5664 12 : set_has_no_nil(cond);
5665 12 : if (rel_convert_types(sql, NULL, NULL, &le, &re, 1, type_equal_no_any) < 0)
5666 : return NULL;
5667 12 : if (!(le = rel_nop_(sql, rel, cond, re, le, NULL, "sys", "ifthenelse", card_value)))
5668 : return NULL;
5669 121 : } else if (right) {
5670 3 : le = re;
5671 : }
5672 133 : exp_setname(sql, le, rname, name);
5673 133 : set_not_unique(le);
5674 133 : append(outexps, le);
5675 : } else {
5676 43 : if (l_nil)
5677 5 : set_has_nil(le);
5678 43 : set_not_unique(le);
5679 43 : append(outexps, le);
5680 : }
5681 : }
5682 57 : if (!found)
5683 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):"");
5684 86 : for (node *n = r_exps->h; n; n = n->next) {
5685 31 : sql_exp *re = n->data;
5686 31 : if (r_nil)
5687 3 : set_has_nil(re);
5688 31 : set_not_unique(re);
5689 31 : append(outexps, re);
5690 : }
5691 55 : rel = rel_project(sql->sa, rel, outexps);
5692 55 : return rel;
5693 : }
5694 :
5695 : static sql_rel *
5696 366085 : rel_select_exp(sql_query *query, sql_rel *rel, SelectNode *sn, exp_kind ek)
5697 : {
5698 366085 : mvc *sql = query->sql;
5699 366085 : sql_rel *inner = NULL;
5700 366085 : int group_totals = 0;
5701 366085 : list *pexps = NULL;
5702 :
5703 366085 : assert(sn->s.token == SQL_SELECT);
5704 366085 : if (!sn->selection)
5705 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: the selection or from part is missing");
5706 :
5707 366085 : if (!rel)
5708 72143 : rel = rel_project_exp(sql, exp_atom_bool(sql->sa, 1));
5709 366117 : rel = rel_where_groupby_nodes(query, rel, sn, &group_totals);
5710 366088 : if (sql->session->status) /* rel might be NULL as input, so we have to check for the session status for errors */
5711 : return NULL;
5712 :
5713 366020 : inner = rel;
5714 366020 : pexps = sa_list(sql->sa);
5715 1719545 : for (dnode *n = sn->selection->h; n; n = n->next) {
5716 : /* Here we could get real column expressions
5717 : * (including single atoms) but also table results.
5718 : * Therefore we try both rel_column_exp
5719 : * and rel_table_exp.
5720 : */
5721 1354588 : list *te = NULL;
5722 2709135 : sql_exp *ce = rel_column_exp(query, &inner, n->data.sym, sql_sel | group_totals | (ek.aggr?sql_aggr:0));
5723 :
5724 1354617 : if (ce) {
5725 1296964 : if (inner && inner->flag && is_groupby(inner->op)) {
5726 62 : int found = 0;
5727 62 : list *gbe = inner->r;
5728 : /* flag == 2 just add to group by/ aggrs and ref-to pexps*/
5729 : /* flag == 1 find group by exp referencing this column nr */
5730 62 : if (inner->flag == 2) {
5731 25 : if (ce->card > CARD_AGGR) {
5732 9 : if (!gbe)
5733 8 : inner->r = gbe = sa_list(sql->sa);
5734 9 : append(gbe, ce);
5735 9 : ce = exp_ref(sql, ce);
5736 9 : ce->card = CARD_AGGR;
5737 9 : list_append(inner->exps, ce);
5738 9 : ce = exp_ref(sql, ce);
5739 9 : found = 1;
5740 : }
5741 : } else {
5742 81 : for(node *n = gbe->h; n && !found; n = n->next) {
5743 44 : sql_exp *e = n->data;
5744 44 : if (is_atom(e->type) && !e->alias.name) {
5745 29 : atom *a = e->l;
5746 29 : int nr = (int)atom_get_int(a);
5747 29 : if (nr == (list_length(pexps) + 1)) {
5748 27 : n->data = ce;
5749 27 : ce = exp_ref(sql, ce);
5750 27 : ce->card = CARD_AGGR;
5751 27 : list_append(inner->exps, ce);
5752 27 : ce = exp_ref(sql, ce);
5753 27 : found = 1;
5754 : }
5755 : }
5756 : }
5757 : }
5758 : }
5759 1296964 : pexps = append(pexps, ce);
5760 1296928 : rel = inner;
5761 1296928 : continue;
5762 : } else {
5763 62645 : te = rel_table_exp(query, &rel, n->data.sym, !list_length(pexps) && !n->next);
5764 : }
5765 57652 : if (!ce && !te) {
5766 1064 : if (sql->errstr[0])
5767 : return NULL;
5768 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: subquery result missing");
5769 : }
5770 : /* here we should merge the column expressions we
5771 : * obtained so far with the table expression, ie
5772 : * t1.* or a subquery.
5773 : */
5774 56588 : pexps = list_merge(pexps, te, (fdup)NULL);
5775 : }
5776 364957 : if (rel && is_groupby(rel->op) && rel->flag) {
5777 34 : list *gbe = rel->r;
5778 34 : if (!list_empty(gbe)) {
5779 68 : for (node *n=gbe->h; n; n = n->next) {
5780 37 : sql_exp *e = n->data;
5781 37 : if (rel->flag == 1 && is_atom(e->type) && !e->alias.name) {
5782 1 : atom *a = e->l;
5783 1 : int nr = (int)atom_get_int(a);
5784 1 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: GROUP BY position %d is not in select list", nr);
5785 : }
5786 36 : if (exp_has_aggr(rel, e))
5787 2 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: aggregate functions are not allowed in GROUP BY");
5788 : }
5789 : }
5790 : }
5791 364954 : if (rel && is_groupby(rel->op) && (!sn->groupby || rel->flag) && !is_processed(rel)) {
5792 41490 : for (node *n=pexps->h; n; n = n->next) {
5793 21258 : sql_exp *ce = n->data;
5794 21258 : if (rel->card < ce->card && !exp_is_aggr(rel, ce)) {
5795 0 : if (exp_name(ce) && !has_label(ce))
5796 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));
5797 0 : return sql_error(sql, ERR_GROUPBY, SQLSTATE(42000) "SELECT: cannot use non GROUP BY column in query results without an aggregate function");
5798 : }
5799 : }
5800 20232 : set_processed(rel);
5801 : }
5802 364954 : rel = rel_project(sql->sa, rel, pexps);
5803 :
5804 364975 : rel = rel_having_limits_nodes(query, rel, sn, ek, group_totals);
5805 364975 : return rel;
5806 : }
5807 :
5808 : static sql_rel*
5809 121320 : rel_unique_names(mvc *sql, sql_rel *rel)
5810 : {
5811 121320 : list *l;
5812 :
5813 121320 : if (!is_project(rel->op))
5814 : return rel;
5815 121320 : l = sa_list(sql->sa);
5816 922484 : for (node *n = rel->exps->h; n; n = n->next) {
5817 801164 : sql_exp *e = n->data;
5818 801164 : const char *name = exp_name(e);
5819 :
5820 : /* If there are two identical expression names, there will be ambiguity */
5821 801164 : if (!name || exps_bind_column(l, name, NULL, NULL, 0))
5822 55201 : exp_label(sql->sa, e, ++sql->label);
5823 801164 : append(l,e);
5824 : }
5825 121320 : rel->exps = l;
5826 121320 : return rel;
5827 : }
5828 :
5829 : static sql_rel *
5830 366397 : rel_query(sql_query *query, symbol *sq, exp_kind ek)
5831 : {
5832 366397 : mvc *sql = query->sql;
5833 366397 : sql_rel *res = NULL;
5834 366397 : SelectNode *sn = NULL;
5835 :
5836 366397 : if (sq->token != SQL_SELECT)
5837 20 : return table_ref(query, sq, 0, NULL);
5838 :
5839 : /* select ... into is currently not handled here ! */
5840 366377 : sn = (SelectNode *) sq;
5841 366377 : if (sn->into)
5842 : return NULL;
5843 :
5844 366377 : if (ek.card != card_relation && sn->orderby)
5845 0 : return sql_error(sql, 01, SQLSTATE(42000) "SELECT: ORDER BY only allowed on outermost SELECT");
5846 :
5847 366377 : if (sn->window) {
5848 20 : dlist *wl = sn->window->data.lval;
5849 51 : for (dnode *n = wl->h; n ; n = n->next) {
5850 32 : dlist *wd = n->data.sym->data.lval;
5851 32 : const char *name = wd->h->data.sval;
5852 32 : dlist *wdef = wd->h->next->data.lval;
5853 32 : if (frame_get_window_def(sql, name, NULL)) {
5854 1 : return sql_error(sql, 01, SQLSTATE(42000) "SELECT: Redefinition of window '%s'", name);
5855 31 : } else if (!frame_push_window_def(sql, name, wdef)) {
5856 0 : return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
5857 : }
5858 : }
5859 : }
5860 :
5861 366376 : if (sn->from) {
5862 294203 : dlist *fl = sn->from->data.lval;
5863 294203 : sql_rel *fnd = NULL;
5864 294203 : list *refs = new_exp_list(sql->sa); /* Keep list of relation names in order to test for duplicates */
5865 :
5866 729675 : for (dnode *n = fl->h; n ; n = n->next) {
5867 435730 : int lateral = check_is_lateral(n->data.sym);
5868 :
5869 : /* just used current expression */
5870 435728 : if (lateral && res)
5871 11 : query_push_outer(query, res, sql_from);
5872 435728 : fnd = table_ref(query, n->data.sym, lateral, refs);
5873 435732 : if (lateral && res)
5874 11 : res = query_pop_outer(query);
5875 435732 : if (!fnd)
5876 : break;
5877 435470 : if (res) {
5878 141511 : res = rel_crossproduct(sql->sa, res, fnd, op_join);
5879 141511 : if (lateral)
5880 11 : set_dependent(res);
5881 : } else {
5882 : res = fnd;
5883 : }
5884 : }
5885 294207 : if (!fnd) {
5886 262 : if (res)
5887 14 : rel_destroy(res);
5888 262 : return NULL;
5889 : }
5890 72173 : } else if (!query_has_outer(query) || !res) {/* only on top level query */
5891 72146 : return rel_select_exp(query, NULL, sn, ek);
5892 : }
5893 :
5894 293945 : sql_rel *rel = NULL;
5895 293945 : if (res)
5896 293945 : rel = rel_select_exp(query, res, sn, ek);
5897 293939 : if (!rel && res)
5898 979 : rel_destroy(res);
5899 : return rel;
5900 : }
5901 :
5902 : /* NOTE: does NOT "set" query but instead generate set ops (union, except, intersect) */
5903 : static sql_rel *
5904 23 : rel_setquery_corresponding(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer, bool n_ary_op)
5905 : {
5906 23 : mvc *sql = query->sql;
5907 23 : const char *opname = op==SQL_EXCEPT?"EXCEPT":op==SQL_INTERSECT?"INTERSECT":outer?"OUTER UNION":"UNION";
5908 23 : list *lexps = sa_list(query->sql->sa), *rexps = sa_list(query->sql->sa);
5909 23 : if (!lexps || !rexps)
5910 : return NULL;
5911 23 : assert(cols);
5912 23 : if (dlist_length(cols)) {
5913 22 : for (dnode *dn = cols->h; dn; dn = dn ->next) {
5914 13 : char *nm = dn->data.sym->data.lval->h->data.sval;
5915 13 : sql_exp *ls, *rs;
5916 :
5917 13 : if (!(ls = rel_bind_column(sql, l, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
5918 : return NULL;
5919 13 : if (!(rs = rel_bind_column(sql, r, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
5920 : return NULL;
5921 13 : if ((!outer && (!ls || !rs)) || (outer && !ls && !rs))
5922 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);
5923 11 : if (outer && !ls)
5924 4 : ls = exp_null(sql->sa, exp_subtype(rs));
5925 11 : if (outer && !rs)
5926 4 : rs = exp_null(sql->sa, exp_subtype(ls));
5927 11 : append(lexps, ls);
5928 11 : append(rexps, rs);
5929 : }
5930 : } else {
5931 12 : int found = 0;
5932 12 : list *exps = rel_projections(sql, l, NULL, 1, 0), *r_exps = rel_projections(sql, r, NULL, 1, 0);
5933 12 : if (!exps || !r_exps)
5934 : return NULL;
5935 : /* find cols which exist on both sides */
5936 35 : for (node *n = exps->h; n; n = n->next) {
5937 23 : sql_exp *le = n->data;
5938 23 : int multi = 0;
5939 23 : const char *rname = exp_relname(le), *name = exp_name(le);
5940 23 : sql_exp *re = exps_bind_column(r_exps, name, NULL, &multi, 0);
5941 23 : if (re) {
5942 13 : if (multi)
5943 0 : return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "%s: common column name '%s' appears more than once in right table", opname, rname);
5944 13 : multi = 0;
5945 13 : le = exps_bind_column(exps, name, NULL, &multi, 0);
5946 13 : if (multi)
5947 0 : return sql_error(sql, ERR_AMBIGUOUS, SQLSTATE(42000) "%s: common column name '%s' appears more than once in left table", opname, rname);
5948 :
5949 13 : found = 1;
5950 13 : append(lexps, le);
5951 13 : append(rexps, re);
5952 13 : list_remove_data(r_exps, NULL, re);
5953 10 : } else if (outer) {
5954 3 : append(lexps, le);
5955 3 : re = exp_null(sql->sa, exp_subtype(le));
5956 3 : append(rexps, re); /* nils */
5957 : }
5958 : }
5959 12 : if (!found)
5960 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):"");
5961 12 : if (outer) {
5962 7 : for (node *n = r_exps->h; n; n = n->next) {
5963 4 : sql_exp *re = n->data, *le;
5964 4 : append(rexps, re);
5965 4 : le = exp_null(sql->sa, exp_subtype(re));
5966 4 : append(lexps, le); /* nils */
5967 : }
5968 : }
5969 : }
5970 21 : return n_ary_op ?
5971 21 : rel_setop_n_ary_check_types(sql, l, r, lexps, rexps, (operator_type)op) :
5972 2 : rel_setop_check_types(sql, l, r, lexps, rexps, (operator_type)op);
5973 : }
5974 :
5975 : static sql_rel *
5976 2473 : rel_setquery_(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer)
5977 : {
5978 2473 : mvc *sql = query->sql;
5979 2473 : sql_rel *rel;
5980 :
5981 2473 : if (outer && !cols)
5982 0 : return sql_error(sql, 02, SQLSTATE(42000) "UNION: OUTER needs to be combined with CORRESPONDING [ BY ( column list ) ]");
5983 2473 : if (!cols) {
5984 2471 : list *ls, *rs;
5985 :
5986 2471 : l = rel_unique_names(sql, l);
5987 2471 : r = rel_unique_names(sql, r);
5988 2471 : ls = rel_projections(sql, l, NULL, 0, 1);
5989 2471 : rs = rel_projections(sql, r, NULL, 0, 1);
5990 2471 : rel = rel_setop_check_types(sql, l, r, ls, rs, (operator_type)op);
5991 : } else {
5992 2 : rel = rel_setquery_corresponding(query, l, r, cols, op, outer, false);
5993 : }
5994 2473 : if (rel) {
5995 2470 : rel_setop_set_exps(sql, rel, rel_projections(sql, rel, NULL, 0, 1), false);
5996 2470 : set_processed(rel);
5997 : }
5998 : return rel;
5999 : }
6000 :
6001 : /* Generate n-ary set operator */
6002 : static sql_rel *
6003 58210 : rel_setquery_n_ary_(sql_query *query, sql_rel *l, sql_rel *r, dlist *cols, int op, int outer)
6004 : {
6005 : /* even though this is for a general n-ary operators in this phase of the query
6006 : * processing we gonna have only two operands (so technically it's binary). In
6007 : * general this op supports arbitrary number of operands.
6008 : */
6009 : // TODO: for now we support only multi-union
6010 58210 : assert(op == op_munion);
6011 :
6012 58210 : mvc *sql = query->sql;
6013 58210 : sql_rel *rel;
6014 :
6015 58210 : if (outer && !cols)
6016 0 : return sql_error(sql, 02, SQLSTATE(42000) "UNION: OUTER needs to be combined with CORRESPONDING [ BY ( column list ) ]");
6017 58210 : if (!cols) {
6018 : // TODO: make rel_setop_n_ary_check_types to accept a list of rels
6019 : // and a list of lists of exps
6020 58189 : list *ls, *rs;
6021 :
6022 58189 : l = rel_unique_names(sql, l);
6023 58189 : r = rel_unique_names(sql, r);
6024 58189 : ls = rel_projections(sql, l, NULL, 0, 1);
6025 58189 : rs = rel_projections(sql, r, NULL, 0, 1);
6026 58189 : rel = rel_setop_n_ary_check_types(sql, l, r, ls, rs, (operator_type)op);
6027 : } else {
6028 21 : rel = rel_setquery_corresponding(query, l, r, cols, op, outer, true);
6029 : }
6030 :
6031 58210 : if (rel) {
6032 58204 : rel_setop_n_ary_set_exps(sql, rel, rel_projections(sql, rel, NULL, 0, 1), false);
6033 58204 : set_processed(rel);
6034 : }
6035 :
6036 : return rel;
6037 :
6038 : }
6039 :
6040 : static sql_rel *
6041 60688 : rel_setquery(sql_query *query, symbol *q)
6042 : {
6043 60688 : mvc *sql = query->sql;
6044 60688 : sql_rel *res = NULL;
6045 60688 : dnode *n = q->data.lval->h;
6046 60688 : symbol *tab_ref1 = n->data.sym;
6047 60688 : int distinct = n->next->data.i_val;
6048 60688 : dlist *corresponding = n->next->next->data.lval;
6049 60688 : symbol *tab_ref2 = n->next->next->next->data.sym;
6050 60688 : sql_rel *t1, *t2;
6051 :
6052 60688 : assert(n->next->type == type_int);
6053 60688 : t1 = table_ref(query, tab_ref1, 0, NULL);
6054 60688 : if (!t1)
6055 : return NULL;
6056 60686 : t2 = table_ref(query, tab_ref2, 0, NULL);
6057 60686 : if (!t2)
6058 : return NULL;
6059 :
6060 60684 : rel_remove_internal_exp(t1);
6061 60684 : rel_remove_internal_exp(t2);
6062 60684 : if (!corresponding && list_length(t1->exps) != list_length(t2->exps)) {
6063 1 : int t1nrcols = list_length(t1->exps);
6064 1 : int t2nrcols = list_length(t2->exps);
6065 1 : const char *op = "UNION";
6066 1 : if (q->token == SQL_EXCEPT)
6067 : op = "EXCEPT";
6068 0 : else if (q->token == SQL_INTERSECT)
6069 0 : op = "INTERSECT";
6070 1 : rel_destroy(t1);
6071 1 : rel_destroy(t2);
6072 1 : return sql_error(sql, 02, SQLSTATE(42000) "%s: column counts (%d and %d) do not match", op, t1nrcols, t2nrcols);
6073 : }
6074 60683 : if ( q->token == SQL_UNION) {
6075 58210 : int outer = n->next->next->next->next->data.i_val;
6076 : /* For EXCEPT/INTERSECT the group by is always done within the implementation */
6077 : /* TODO add those later in an optimizer ! */
6078 58210 : if (t1 && distinct)
6079 1998 : t1 = rel_distinct(t1);
6080 58210 : if (t2 && distinct)
6081 1998 : t2 = rel_distinct(t2);
6082 : // TODO: this has to be fixed
6083 : /*res = rel_setquery_(query, t1, t2, corresponding, op_union, outer);*/
6084 58210 : res = rel_setquery_n_ary_(query, t1, t2, corresponding, op_munion, outer);
6085 2473 : } else if ( q->token == SQL_EXCEPT)
6086 2018 : res = rel_setquery_(query, t1, t2, corresponding, op_except, 0);
6087 455 : else if ( q->token == SQL_INTERSECT)
6088 455 : res = rel_setquery_(query, t1, t2, corresponding, op_inter, 0);
6089 60683 : if (res) {
6090 60674 : set_processed(res);
6091 60674 : if (distinct)
6092 4345 : res = rel_distinct(res);
6093 : }
6094 : return res;
6095 : }
6096 :
6097 : static sql_rel *
6098 58405 : rel_joinquery_(sql_query *query, symbol *tab1, int natural, jt jointype, symbol *tab2, symbol *js, list *refs)
6099 : {
6100 58405 : mvc *sql = query->sql;
6101 58405 : operator_type op = op_join;
6102 58405 : sql_rel *t1 = NULL, *t2 = NULL, *inner, *rel = NULL;
6103 58405 : int l_nil = 0, r_nil = 0, lateral = 0;
6104 :
6105 58405 : switch(jointype) {
6106 : case jt_inner:
6107 : case jt_cross: op = op_join;
6108 : break;
6109 : case jt_left: op = op_left;
6110 : r_nil = 1;
6111 : break;
6112 : case jt_right: op = op_right;
6113 : l_nil = 1;
6114 : break;
6115 : case jt_full: op = op_full;
6116 : l_nil = 1;
6117 : r_nil = 1;
6118 : break;
6119 : }
6120 :
6121 : /* a dependent join cannot depend on the right side, so disable lateral check for right and full joins */
6122 58405 : lateral = (op == op_join || op == op_left) && check_is_lateral(tab2);
6123 58405 : t1 = table_ref(query, tab1, 0, refs);
6124 58405 : if (t1) {
6125 58400 : if (!lateral) {
6126 58365 : t2 = table_ref(query, tab2, 0, refs);
6127 : } else {
6128 35 : query_processed(query);
6129 35 : query_push_outer(query, t1, sql_from);
6130 35 : t2 = table_ref(query, tab2, 0, refs);
6131 35 : t1 = query_pop_outer(query);
6132 : }
6133 : }
6134 58405 : if (!t1 || !t2)
6135 : return NULL;
6136 :
6137 58382 : query_processed(query);
6138 58382 : if (strcmp(rel_name(t1), rel_name(t2)) == 0) {
6139 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: ERROR: table name '%s' specified more than once", rel_name(t1));
6140 : }
6141 58382 : inner = rel = rel_crossproduct(sql->sa, t1, t2, op);
6142 58382 : if (!rel)
6143 : return NULL;
6144 58382 : if (lateral)
6145 34 : set_dependent(rel);
6146 :
6147 58382 : assert(jointype != jt_cross || (!natural && !js)); /* there are no natural cross joins, or cross joins with conditions */
6148 58382 : if (js && natural)
6149 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: cannot have a NATURAL JOIN with a join specification (ON or USING)");
6150 58382 : if (jointype != jt_cross && !js && !natural)
6151 0 : return sql_error(sql, 02, SQLSTATE(42000) "SELECT: must have NATURAL JOIN or a JOIN with a join specification (ON or USING)");
6152 :
6153 58382 : if (js && js->token != SQL_USING) { /* On sql_logical_exp */
6154 58211 : rel = rel_logical_exp(query, rel, js, sql_where | sql_join);
6155 171 : } else if (js) { /* using */
6156 20 : char rname[16], *rnme;
6157 20 : dnode *n = js->data.lval->h;
6158 20 : list *outexps = new_exp_list(sql->sa), *exps;
6159 20 : node *m;
6160 :
6161 20 : rnme = sa_strdup(sql->sa, number2name(rname, sizeof(rname), ++sql->label));
6162 46 : for (; n; n = n->next) {
6163 26 : char *nm = n->data.sval;
6164 26 : sql_exp *cond, *ls, *rs;
6165 :
6166 26 : if (!(ls = rel_bind_column(sql, t1, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
6167 0 : return NULL;
6168 26 : if (!(rs = rel_bind_column(sql, t2, nm, sql_where | sql_join, 0)) && sql->session->status == -ERR_AMBIGUOUS)
6169 : return NULL;
6170 26 : if (!ls || !rs)
6171 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);
6172 26 : if (!(rel = rel_compare_exp(query, rel, ls, rs, "=", TRUE, 0, 0, 0, 0)))
6173 : return NULL;
6174 26 : if (op != op_join) {
6175 12 : if (!(cond = rel_unop_(sql, rel, ls, "sys", "isnull", card_value)))
6176 : return NULL;
6177 12 : set_has_no_nil(cond);
6178 12 : if (rel_convert_types(sql, t1, t2, &ls, &rs, 1, type_equal) < 0)
6179 : return NULL;
6180 12 : if (!(ls = rel_nop_(sql, rel, cond, rs, ls, NULL, "sys", "ifthenelse", card_value)))
6181 : return NULL;
6182 : }
6183 26 : exp_setname(sql, ls, rnme, nm);
6184 26 : append(outexps, ls);
6185 26 : if (!rel)
6186 : return NULL;
6187 : }
6188 20 : exps = rel_projections(sql, t1, NULL, 1, 1);
6189 199 : for (m = exps->h; m; m = m->next) {
6190 179 : const char *nm = exp_name(m->data);
6191 179 : int fnd = 0;
6192 :
6193 429 : for (n = js->data.lval->h; n; n = n->next) {
6194 276 : if (strcmp(nm, n->data.sval) == 0) {
6195 : fnd = 1;
6196 : break;
6197 : }
6198 : }
6199 179 : if (!fnd) {
6200 153 : sql_exp *ls = m->data;
6201 153 : if (l_nil)
6202 18 : set_has_nil(ls);
6203 153 : set_not_unique(ls);
6204 153 : append(outexps, ls);
6205 : }
6206 : }
6207 20 : exps = rel_projections(sql, t2, NULL, 1, 1);
6208 100 : for (m = exps->h; m; m = m->next) {
6209 80 : const char *nm = exp_name(m->data);
6210 80 : int fnd = 0;
6211 :
6212 230 : for (n = js->data.lval->h; n; n = n->next) {
6213 176 : if (strcmp(nm, n->data.sval) == 0) {
6214 : fnd = 1;
6215 : break;
6216 : }
6217 : }
6218 80 : if (!fnd) {
6219 54 : sql_exp *rs = m->data;
6220 54 : if (r_nil)
6221 14 : set_has_nil(rs);
6222 54 : set_not_unique(rs);
6223 54 : append(outexps, rs);
6224 : }
6225 : }
6226 20 : rel = rel_project(sql->sa, rel, outexps);
6227 151 : } else if (jointype != jt_cross) { /* ! js -> natural join */
6228 60 : rel = join_on_column_name(query, rel, t1, t2, op, l_nil, r_nil);
6229 : }
6230 58382 : if (!rel)
6231 : return NULL;
6232 58368 : if (inner && is_outerjoin(inner->op))
6233 21543 : set_processed(inner);
6234 58368 : set_processed(rel);
6235 58368 : query_processed(query);
6236 58368 : return rel;
6237 : }
6238 :
6239 : static sql_rel *
6240 58405 : rel_joinquery(sql_query *query, symbol *q, list *refs)
6241 : {
6242 58405 : dnode *n = q->data.lval->h;
6243 58405 : symbol *tab_ref1 = n->data.sym;
6244 58405 : int natural = n->next->data.i_val;
6245 58405 : jt jointype = (jt) n->next->next->data.i_val;
6246 58405 : symbol *tab_ref2 = n->next->next->next->data.sym;
6247 58405 : symbol *joinspec = n->next->next->next->next->data.sym;
6248 :
6249 58405 : assert(n->next->type == type_int);
6250 58405 : assert(n->next->next->type == type_int);
6251 58405 : return rel_joinquery_(query, tab_ref1, natural, jointype, tab_ref2, joinspec, refs);
6252 : }
6253 :
6254 : sql_rel *
6255 366331 : rel_subquery(sql_query *query, symbol *sq, exp_kind ek)
6256 : {
6257 366331 : mvc *sql = query->sql;
6258 :
6259 366331 : query_processed(query);
6260 366327 : if (!stack_push_frame(sql, NULL))
6261 0 : return sql_error(sql, 02, SQLSTATE(HY013) MAL_MALLOC_FAIL);
6262 366422 : sql_rel *rel = rel_query(query, sq, ek);
6263 366320 : stack_pop_frame(sql);
6264 366432 : if (!query_has_outer(query))
6265 331328 : query_processed(query);
6266 366432 : if (rel && ek.type == type_relation && ek.card < card_set && rel->card >= CARD_AGGR)
6267 10 : return rel_zero_or_one(sql, rel, ek);
6268 : return rel;
6269 : }
6270 :
6271 : sql_rel *
6272 236749 : rel_selects(sql_query *query, symbol *s)
6273 : {
6274 236749 : mvc *sql = query->sql;
6275 236749 : sql_rel *ret = NULL;
6276 :
6277 236749 : switch (s->token) {
6278 5639 : case SQL_WITH:
6279 5639 : ret = rel_with_query(query, s);
6280 5639 : sql->type = Q_TABLE;
6281 5639 : break;
6282 2165 : case SQL_VALUES:
6283 2165 : ret = rel_values(query, s, NULL);
6284 2165 : sql->type = Q_TABLE;
6285 2165 : break;
6286 209887 : case SQL_SELECT: {
6287 209887 : exp_kind ek = {type_value, card_relation, TRUE};
6288 209887 : SelectNode *sn = (SelectNode *) s;
6289 :
6290 209887 : if (sn->into) {
6291 1 : sql->type = Q_SCHEMA;
6292 1 : ret = rel_select_with_into(query, s);
6293 : } else {
6294 209886 : ret = rel_subquery(query, s, ek);
6295 209975 : sql->type = Q_TABLE;
6296 : }
6297 209972 : } break;
6298 0 : case SQL_JOIN:
6299 0 : ret = rel_joinquery(query, s, NULL);
6300 0 : sql->type = Q_TABLE;
6301 0 : break;
6302 19058 : case SQL_UNION:
6303 : case SQL_EXCEPT:
6304 : case SQL_INTERSECT:
6305 19058 : ret = rel_setquery(query, s);
6306 19058 : sql->type = Q_TABLE;
6307 19058 : break;
6308 : default:
6309 : return NULL;
6310 : }
6311 236834 : if (!ret && sql->errstr[0] == 0)
6312 0 : (void) sql_error(sql, 02, SQLSTATE(42000) "relational query without result");
6313 : return ret;
6314 : }
6315 :
6316 : sql_rel *
6317 78702 : schema_selects(sql_query *query, sql_schema *schema, symbol *s)
6318 : {
6319 78702 : mvc *sql = query->sql;
6320 78702 : sql_rel *res;
6321 78702 : sql_schema *os = cur_schema(sql);
6322 :
6323 78702 : sql->session->schema = schema;
6324 78702 : res = rel_selects(query, s);
6325 78702 : sql->session->schema = os;
6326 78702 : return res;
6327 : }
6328 :
6329 : sql_rel *
6330 26 : rel_loader_function(sql_query *query, symbol* fcall, list *fexps, sql_subfunc **loader_function)
6331 : {
6332 26 : mvc *sql = query->sql;
6333 26 : sql_rel *sq = NULL;
6334 26 : dnode *l = fcall->data.lval->h;
6335 26 : char *sname = qname_schema(l->data.lval);
6336 26 : char *fname = qname_schema_object(l->data.lval);
6337 :
6338 26 : list *tl = sa_list(sql->sa);
6339 26 : list *exps = sa_list(sql->sa);
6340 26 : if (l->next)
6341 26 : l = l->next; /* skip distinct */
6342 26 : if (l->next) { /* table call with subquery */
6343 22 : if (l->next->type == type_symbol || l->next->type == type_list) {
6344 22 : int count = 0;
6345 22 : symbol *subquery = NULL;
6346 22 : dnode *n = NULL;
6347 :
6348 22 : if (l->next->type == type_symbol)
6349 : n = l->next;
6350 : else
6351 1 : n = l->next->data.lval->h;
6352 :
6353 66 : for (dnode *m = n; m; m = m->next) {
6354 44 : if (m->type == type_symbol && m->data.sym->token == SQL_SELECT)
6355 44 : subquery = m->data.sym;
6356 44 : count++;
6357 : }
6358 22 : if (subquery && count > 1)
6359 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);
6360 :
6361 22 : if (subquery) {
6362 0 : exp_kind ek = { type_value, card_relation, TRUE };
6363 0 : if (!(sq = rel_subquery(query, subquery, ek)))
6364 0 : return NULL;
6365 : } else {
6366 22 : exp_kind ek = { type_value, card_column, TRUE };
6367 22 : list *exps = sa_list(sql->sa);
6368 88 : for ( ; n; n = n->next) {
6369 44 : sql_exp *e = rel_value_exp(query, NULL, n->data.sym, sql_sel | sql_from, ek);
6370 :
6371 44 : if (!e)
6372 0 : return NULL;
6373 44 : append(exps, e);
6374 : }
6375 22 : sq = rel_project(sql->sa, NULL, exps);
6376 : }
6377 : }
6378 22 : if (!sq)
6379 0 : return sql_error(sql, ERR_NOTFOUND, SQLSTATE(42000) "SELECT: no such loader function %s%s%s'%s'", sname ? "'":"", sname ? sname : "", sname ? "'.":"", fname);
6380 66 : for (node *en = sq->exps->h; en; en = en->next) {
6381 44 : sql_exp *e = en->data;
6382 :
6383 44 : append(exps, e = exp_ref(sql, e));
6384 44 : append(tl, exp_subtype(e));
6385 : }
6386 : }
6387 :
6388 26 : sql_exp *e = NULL;
6389 26 : if (!(e = find_table_function(sql, sname, fname, exps, tl, F_LOADER)))
6390 : return NULL;
6391 25 : sql_subfunc *sf = e->f;
6392 25 : if (sq) {
6393 66 : for (node *n = sq->exps->h, *m = sf->func->ops->h ; n && m ; n = n->next, m = m->next) {
6394 44 : sql_exp *e = (sql_exp*) n->data;
6395 44 : sql_arg *a = (sql_arg*) m->data;
6396 44 : if (!exp_subtype(e) && rel_set_type_param(sql, &(a->type), sq, e, 0) < 0)
6397 : return NULL;
6398 : }
6399 : }
6400 :
6401 25 : if (loader_function)
6402 25 : *loader_function = sf;
6403 :
6404 28 : return rel_table_func(sql->sa, sq, e, fexps, (sq)?TABLE_FROM_RELATION:TABLE_PROD_FUNC);
6405 : }
|