Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * var.c
4 : : * Var node manipulation routines
5 : : *
6 : : * Note: for most purposes, PlaceHolderVar is considered a Var too,
7 : : * even if its contained expression is variable-free. Also, CurrentOfExpr
8 : : * is treated as a Var for purposes of determining whether an expression
9 : : * contains variables.
10 : : *
11 : : *
12 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
13 : : * Portions Copyright (c) 1994, Regents of the University of California
14 : : *
15 : : *
16 : : * IDENTIFICATION
17 : : * src/backend/optimizer/util/var.c
18 : : *
19 : : *-------------------------------------------------------------------------
20 : : */
21 : : #include "postgres.h"
22 : :
23 : : #include "access/sysattr.h"
24 : : #include "nodes/nodeFuncs.h"
25 : : #include "optimizer/clauses.h"
26 : : #include "optimizer/optimizer.h"
27 : : #include "optimizer/placeholder.h"
28 : : #include "optimizer/prep.h"
29 : : #include "parser/parsetree.h"
30 : : #include "rewrite/rewriteManip.h"
31 : :
32 : :
33 : : typedef struct
34 : : {
35 : : Relids varnos;
36 : : PlannerInfo *root;
37 : : int sublevels_up;
38 : : } pull_varnos_context;
39 : :
40 : : typedef struct
41 : : {
42 : : Bitmapset *varattnos;
43 : : Index varno;
44 : : } pull_varattnos_context;
45 : :
46 : : typedef struct
47 : : {
48 : : List *vars;
49 : : int sublevels_up;
50 : : } pull_vars_context;
51 : :
52 : : typedef struct
53 : : {
54 : : int var_location;
55 : : int sublevels_up;
56 : : } locate_var_of_level_context;
57 : :
58 : : typedef struct
59 : : {
60 : : List *varlist;
61 : : int flags;
62 : : } pull_var_clause_context;
63 : :
64 : : typedef struct
65 : : {
66 : : PlannerInfo *root; /* could be NULL! */
67 : : Query *query; /* outer Query */
68 : : int sublevels_up;
69 : : bool possible_sublink; /* could aliases include a SubLink? */
70 : : bool inserted_sublink; /* have we inserted a SubLink? */
71 : : } flatten_join_alias_vars_context;
72 : :
73 : : static bool pull_varnos_walker(Node *node,
74 : : pull_varnos_context *context);
75 : : static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context);
76 : : static bool pull_vars_walker(Node *node, pull_vars_context *context);
77 : : static bool contain_var_clause_walker(Node *node, void *context);
78 : : static bool contain_vars_of_level_walker(Node *node, int *sublevels_up);
79 : : static bool contain_vars_returning_old_or_new_walker(Node *node, void *context);
80 : : static bool contain_var_or_representative_walker(Node *node, void *context);
81 : : static bool locate_var_of_level_walker(Node *node,
82 : : locate_var_of_level_context *context);
83 : : static bool pull_var_clause_walker(Node *node,
84 : : pull_var_clause_context *context);
85 : : static Node *flatten_join_alias_vars_mutator(Node *node,
86 : : flatten_join_alias_vars_context *context);
87 : : static Node *flatten_group_exprs_mutator(Node *node,
88 : : flatten_join_alias_vars_context *context);
89 : : static Node *mark_nullable_by_grouping(PlannerInfo *root, Node *newnode,
90 : : Var *oldvar);
91 : : static Node *add_nullingrels_if_needed(PlannerInfo *root, Node *newnode,
92 : : Var *oldvar);
93 : : static bool is_standard_join_alias_expression(Node *newnode, Var *oldvar);
94 : : static void adjust_standard_join_alias_expression(Node *newnode, Var *oldvar);
95 : : static Relids alias_relid_set(Query *query, Relids relids);
96 : :
97 : :
98 : : /*
99 : : * pull_varnos
100 : : * Create a set of all the distinct varnos present in a parsetree.
101 : : * Only varnos that reference level-zero rtable entries are considered.
102 : : *
103 : : * The result includes outer-join relids mentioned in Var.varnullingrels and
104 : : * PlaceHolderVar.phnullingrels fields in the parsetree.
105 : : *
106 : : * "root" can be passed as NULL if it is not necessary to process
107 : : * PlaceHolderVars.
108 : : *
109 : : * NOTE: this is used on not-yet-planned expressions. It may therefore find
110 : : * bare SubLinks, and if so it needs to recurse into them to look for uplevel
111 : : * references to the desired rtable level! But when we find a completed
112 : : * SubPlan, we only need to look at the parameters passed to the subplan.
113 : : */
114 : : Relids
115 : 2776788 : pull_varnos(PlannerInfo *root, Node *node)
116 : : {
117 : : pull_varnos_context context;
118 : :
119 : 2776788 : context.varnos = NULL;
120 : 2776788 : context.root = root;
121 : 2776788 : context.sublevels_up = 0;
122 : :
123 : : /*
124 : : * Must be prepared to start with a Query or a bare expression tree; if
125 : : * it's a Query, we don't want to increment sublevels_up.
126 : : */
127 : 2776788 : query_or_expression_tree_walker(node,
128 : : pull_varnos_walker,
129 : : &context,
130 : : 0);
131 : :
132 : 2776788 : return context.varnos;
133 : : }
134 : :
135 : : /*
136 : : * pull_varnos_of_level
137 : : * Create a set of all the distinct varnos present in a parsetree.
138 : : * Only Vars of the specified level are considered.
139 : : */
140 : : Relids
141 : 8753 : pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
142 : : {
143 : : pull_varnos_context context;
144 : :
145 : 8753 : context.varnos = NULL;
146 : 8753 : context.root = root;
147 : 8753 : context.sublevels_up = levelsup;
148 : :
149 : : /*
150 : : * Must be prepared to start with a Query or a bare expression tree; if
151 : : * it's a Query, we don't want to increment sublevels_up.
152 : : */
153 : 8753 : query_or_expression_tree_walker(node,
154 : : pull_varnos_walker,
155 : : &context,
156 : : 0);
157 : :
158 : 8753 : return context.varnos;
159 : : }
160 : :
161 : : static bool
162 : 4945669 : pull_varnos_walker(Node *node, pull_varnos_context *context)
163 : : {
164 [ + + ]: 4945669 : if (node == NULL)
165 : 187529 : return false;
166 [ + + ]: 4758140 : if (IsA(node, Var))
167 : : {
168 : 2384853 : Var *var = (Var *) node;
169 : :
170 [ + + ]: 2384853 : if (var->varlevelsup == context->sublevels_up)
171 : : {
172 : 2373315 : context->varnos = bms_add_member(context->varnos, var->varno);
173 : 2373315 : context->varnos = bms_add_members(context->varnos,
174 : 2373315 : var->varnullingrels);
175 : : }
176 : 2384853 : return false;
177 : : }
178 [ + + ]: 2373287 : if (IsA(node, CurrentOfExpr))
179 : : {
180 : 680 : CurrentOfExpr *cexpr = (CurrentOfExpr *) node;
181 : :
182 [ + - ]: 680 : if (context->sublevels_up == 0)
183 : 680 : context->varnos = bms_add_member(context->varnos, cexpr->cvarno);
184 : 680 : return false;
185 : : }
186 [ + + ]: 2372607 : if (IsA(node, PlaceHolderVar))
187 : : {
188 : 6429 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
189 : :
190 : : /*
191 : : * If a PlaceHolderVar is not of the target query level, ignore it,
192 : : * instead recursing into its expression to see if it contains any
193 : : * vars that are of the target level. We'll also do that when the
194 : : * caller doesn't pass a "root" pointer. (We probably shouldn't see
195 : : * PlaceHolderVars at all in such cases, but if we do, this is a
196 : : * reasonable behavior.)
197 : : */
198 [ + + ]: 6429 : if (phv->phlevelsup == context->sublevels_up &&
199 [ + - ]: 6409 : context->root != NULL)
200 : : {
201 : : /*
202 : : * Ideally, the PHV's contribution to context->varnos is its
203 : : * ph_eval_at set. However, this code can be invoked before
204 : : * that's been computed. If we cannot find a PlaceHolderInfo,
205 : : * fall back to the conservative assumption that the PHV will be
206 : : * evaluated at its syntactic level (phv->phrels).
207 : : *
208 : : * Another problem is that a PlaceHolderVar can appear in quals or
209 : : * tlists that have been translated for use in a child appendrel.
210 : : * Typically such a PHV is a parameter expression sourced by some
211 : : * other relation, so that the translation from parent appendrel
212 : : * to child doesn't change its phrels, and we should still take
213 : : * ph_eval_at at face value. But in corner cases, the PHV's
214 : : * original phrels can include the parent appendrel itself, in
215 : : * which case the translated PHV will have the child appendrel in
216 : : * phrels, and we must translate ph_eval_at to match.
217 : : */
218 : 6409 : PlaceHolderInfo *phinfo = NULL;
219 : :
220 [ + + ]: 6409 : if (phv->phlevelsup == 0)
221 : : {
222 [ + + ]: 6289 : if (phv->phid < context->root->placeholder_array_size)
223 : 4926 : phinfo = context->root->placeholder_array[phv->phid];
224 : : }
225 [ + + ]: 6409 : if (phinfo == NULL)
226 : : {
227 : : /* No PlaceHolderInfo yet, use phrels */
228 : 1503 : context->varnos = bms_add_members(context->varnos,
229 : 1503 : phv->phrels);
230 : : }
231 [ + + ]: 4906 : else if (bms_equal(phv->phrels, phinfo->ph_var->phrels))
232 : : {
233 : : /* Normal case: use ph_eval_at */
234 : 4606 : context->varnos = bms_add_members(context->varnos,
235 : 4606 : phinfo->ph_eval_at);
236 : : }
237 : : else
238 : : {
239 : : /* Translated PlaceHolderVar: translate ph_eval_at to match */
240 : : Relids newevalat,
241 : : delta;
242 : :
243 : : /* remove what was removed from phv->phrels ... */
244 : 300 : delta = bms_difference(phinfo->ph_var->phrels, phv->phrels);
245 : 300 : newevalat = bms_difference(phinfo->ph_eval_at, delta);
246 : : /* ... then if that was in fact part of ph_eval_at ... */
247 [ + - ]: 300 : if (!bms_equal(newevalat, phinfo->ph_eval_at))
248 : : {
249 : : /* ... add what was added */
250 : 300 : delta = bms_difference(phv->phrels, phinfo->ph_var->phrels);
251 : 300 : newevalat = bms_join(newevalat, delta);
252 : : }
253 : 300 : context->varnos = bms_join(context->varnos,
254 : : newevalat);
255 : : }
256 : :
257 : : /*
258 : : * In all three cases, include phnullingrels in the result. We
259 : : * don't worry about possibly needing to translate it, because
260 : : * appendrels only translate varnos of baserels, not outer joins.
261 : : */
262 : 12818 : context->varnos = bms_add_members(context->varnos,
263 : 6409 : phv->phnullingrels);
264 : 6409 : return false; /* don't recurse into expression */
265 : : }
266 : : }
267 [ + + ]: 2366178 : else if (IsA(node, Query))
268 : : {
269 : : /* Recurse into RTE subquery or not-yet-planned sublink subquery */
270 : : bool result;
271 : :
272 : 5993 : context->sublevels_up++;
273 : 5993 : result = query_tree_walker((Query *) node, pull_varnos_walker,
274 : : context, 0);
275 : 5993 : context->sublevels_up--;
276 : 5993 : return result;
277 : : }
278 : 2360205 : return expression_tree_walker(node, pull_varnos_walker, context);
279 : : }
280 : :
281 : :
282 : : /*
283 : : * pull_varattnos
284 : : * Find all the distinct attribute numbers present in an expression tree,
285 : : * and add them to the initial contents of *varattnos.
286 : : * Only Vars of the given varno and rtable level zero are considered.
287 : : *
288 : : * Attribute numbers are offset by FirstLowInvalidHeapAttributeNumber so that
289 : : * we can include system attributes (e.g., OID) in the bitmap representation.
290 : : *
291 : : * Currently, this does not support unplanned subqueries; that is not needed
292 : : * for current uses. It will handle already-planned SubPlan nodes, though,
293 : : * looking into only the "testexpr" and the "args" list. (The subplan cannot
294 : : * contain any other references to Vars of the current level.)
295 : : */
296 : : void
297 : 1335096 : pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
298 : : {
299 : : pull_varattnos_context context;
300 : :
301 : 1335096 : context.varattnos = *varattnos;
302 : 1335096 : context.varno = varno;
303 : :
304 : 1335096 : (void) pull_varattnos_walker(node, &context);
305 : :
306 : 1335096 : *varattnos = context.varattnos;
307 : 1335096 : }
308 : :
309 : : static bool
310 : 4471121 : pull_varattnos_walker(Node *node, pull_varattnos_context *context)
311 : : {
312 [ + + ]: 4471121 : if (node == NULL)
313 : 57694 : return false;
314 [ + + ]: 4413427 : if (IsA(node, Var))
315 : : {
316 : 2540741 : Var *var = (Var *) node;
317 : :
318 [ + + + - ]: 2540741 : if (var->varno == context->varno && var->varlevelsup == 0)
319 : 2540410 : context->varattnos =
320 : 2540410 : bms_add_member(context->varattnos,
321 : 2540410 : var->varattno - FirstLowInvalidHeapAttributeNumber);
322 : 2540741 : return false;
323 : : }
324 : :
325 : : /* Should not find an unplanned subquery */
326 : : Assert(!IsA(node, Query));
327 : :
328 : 1872686 : return expression_tree_walker(node, pull_varattnos_walker, context);
329 : : }
330 : :
331 : :
332 : : /*
333 : : * pull_vars_of_level
334 : : * Create a list of all Vars (and PlaceHolderVars) referencing the
335 : : * specified query level in the given parsetree.
336 : : *
337 : : * Caution: the Vars are not copied, only linked into the list.
338 : : */
339 : : List *
340 : 7013 : pull_vars_of_level(Node *node, int levelsup)
341 : : {
342 : : pull_vars_context context;
343 : :
344 : 7013 : context.vars = NIL;
345 : 7013 : context.sublevels_up = levelsup;
346 : :
347 : : /*
348 : : * Must be prepared to start with a Query or a bare expression tree; if
349 : : * it's a Query, we don't want to increment sublevels_up.
350 : : */
351 : 7013 : query_or_expression_tree_walker(node,
352 : : pull_vars_walker,
353 : : &context,
354 : : 0);
355 : :
356 : 7013 : return context.vars;
357 : : }
358 : :
359 : : static bool
360 : 128485 : pull_vars_walker(Node *node, pull_vars_context *context)
361 : : {
362 [ + + ]: 128485 : if (node == NULL)
363 : 34085 : return false;
364 [ + + ]: 94400 : if (IsA(node, Var))
365 : : {
366 : 19239 : Var *var = (Var *) node;
367 : :
368 [ + + ]: 19239 : if (var->varlevelsup == context->sublevels_up)
369 : 10029 : context->vars = lappend(context->vars, var);
370 : 19239 : return false;
371 : : }
372 [ + + ]: 75161 : if (IsA(node, PlaceHolderVar))
373 : : {
374 : 308 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
375 : :
376 [ + - ]: 308 : if (phv->phlevelsup == context->sublevels_up)
377 : 308 : context->vars = lappend(context->vars, phv);
378 : : /* we don't want to look into the contained expression */
379 : 308 : return false;
380 : : }
381 [ + + ]: 74853 : if (IsA(node, Query))
382 : : {
383 : : /* Recurse into RTE subquery or not-yet-planned sublink subquery */
384 : : bool result;
385 : :
386 : 585 : context->sublevels_up++;
387 : 585 : result = query_tree_walker((Query *) node, pull_vars_walker,
388 : : context, 0);
389 : 585 : context->sublevels_up--;
390 : 585 : return result;
391 : : }
392 : 74268 : return expression_tree_walker(node, pull_vars_walker, context);
393 : : }
394 : :
395 : :
396 : : /*
397 : : * contain_var_clause
398 : : * Recursively scan a clause to discover whether it contains any Var nodes
399 : : * (of the current query level).
400 : : *
401 : : * Returns true if any varnode found.
402 : : *
403 : : * Does not examine subqueries, therefore must only be used after reduction
404 : : * of sublinks to subplans!
405 : : */
406 : : bool
407 : 10647 : contain_var_clause(Node *node)
408 : : {
409 : 10647 : return contain_var_clause_walker(node, NULL);
410 : : }
411 : :
412 : : static bool
413 : 13657 : contain_var_clause_walker(Node *node, void *context)
414 : : {
415 [ + + ]: 13657 : if (node == NULL)
416 : 80 : return false;
417 [ + + ]: 13577 : if (IsA(node, Var))
418 : : {
419 [ + - ]: 38 : if (((Var *) node)->varlevelsup == 0)
420 : 38 : return true; /* abort the tree traversal and return true */
421 : 0 : return false;
422 : : }
423 [ - + ]: 13539 : if (IsA(node, CurrentOfExpr))
424 : 0 : return true;
425 [ - + ]: 13539 : if (IsA(node, PlaceHolderVar))
426 : : {
427 [ # # ]: 0 : if (((PlaceHolderVar *) node)->phlevelsup == 0)
428 : 0 : return true; /* abort the tree traversal and return true */
429 : : /* else fall through to check the contained expr */
430 : : }
431 : 13539 : return expression_tree_walker(node, contain_var_clause_walker, context);
432 : : }
433 : :
434 : :
435 : : /*
436 : : * contain_vars_of_level
437 : : * Recursively scan a clause to discover whether it contains any Var nodes
438 : : * of the specified query level.
439 : : *
440 : : * Returns true if any such Var found.
441 : : *
442 : : * Will recurse into sublinks. Also, may be invoked directly on a Query.
443 : : */
444 : : bool
445 : 124307 : contain_vars_of_level(Node *node, int levelsup)
446 : : {
447 : 124307 : int sublevels_up = levelsup;
448 : :
449 : 124307 : return query_or_expression_tree_walker(node,
450 : : contain_vars_of_level_walker,
451 : : &sublevels_up,
452 : : 0);
453 : : }
454 : :
455 : : static bool
456 : 497176 : contain_vars_of_level_walker(Node *node, int *sublevels_up)
457 : : {
458 [ + + ]: 497176 : if (node == NULL)
459 : 147761 : return false;
460 [ + + ]: 349415 : if (IsA(node, Var))
461 : : {
462 [ + + ]: 63196 : if (((Var *) node)->varlevelsup == *sublevels_up)
463 : 38983 : return true; /* abort tree traversal and return true */
464 : 24213 : return false;
465 : : }
466 [ + + ]: 286219 : if (IsA(node, CurrentOfExpr))
467 : : {
468 [ + - ]: 152 : if (*sublevels_up == 0)
469 : 152 : return true;
470 : 0 : return false;
471 : : }
472 [ + + ]: 286067 : if (IsA(node, PlaceHolderVar))
473 : : {
474 [ + - ]: 140 : if (((PlaceHolderVar *) node)->phlevelsup == *sublevels_up)
475 : 140 : return true; /* abort the tree traversal and return true */
476 : : /* else fall through to check the contained expr */
477 : : }
478 [ + + ]: 285927 : if (IsA(node, Query))
479 : : {
480 : : /* Recurse into subselects */
481 : : bool result;
482 : :
483 : 580 : (*sublevels_up)++;
484 : 580 : result = query_tree_walker((Query *) node,
485 : : contain_vars_of_level_walker,
486 : : sublevels_up,
487 : : 0);
488 : 580 : (*sublevels_up)--;
489 : 580 : return result;
490 : : }
491 : 285347 : return expression_tree_walker(node,
492 : : contain_vars_of_level_walker,
493 : : sublevels_up);
494 : : }
495 : :
496 : :
497 : : /*
498 : : * contain_vars_returning_old_or_new
499 : : * Recursively scan a clause to discover whether it contains any Var nodes
500 : : * (of the current query level) whose varreturningtype is VAR_RETURNING_OLD
501 : : * or VAR_RETURNING_NEW.
502 : : *
503 : : * Returns true if any found.
504 : : *
505 : : * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten,
506 : : * we still regard this as a clause that returns OLD/NEW values.
507 : : *
508 : : * Does not examine subqueries, therefore must only be used after reduction
509 : : * of sublinks to subplans!
510 : : */
511 : : bool
512 : 209 : contain_vars_returning_old_or_new(Node *node)
513 : : {
514 : 209 : return contain_vars_returning_old_or_new_walker(node, NULL);
515 : : }
516 : :
517 : : static bool
518 : 645 : contain_vars_returning_old_or_new_walker(Node *node, void *context)
519 : : {
520 [ + + ]: 645 : if (node == NULL)
521 : 147 : return false;
522 [ + + ]: 498 : if (IsA(node, Var))
523 : : {
524 [ + - ]: 212 : if (((Var *) node)->varlevelsup == 0 &&
525 [ + + ]: 212 : ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT)
526 : 7 : return true; /* abort the tree traversal and return true */
527 : 205 : return false;
528 : : }
529 [ - + ]: 286 : if (IsA(node, ReturningExpr))
530 : : {
531 [ # # ]: 0 : if (((ReturningExpr *) node)->retlevelsup == 0)
532 : 0 : return true; /* abort the tree traversal and return true */
533 : 0 : return false;
534 : : }
535 : 286 : return expression_tree_walker(node, contain_vars_returning_old_or_new_walker,
536 : : context);
537 : : }
538 : :
539 : :
540 : : /*
541 : : * contain_var_or_representative
542 : : * Recursively scan a clause to discover whether it contains any Var nodes
543 : : * (of the current query level), or CaseTestExpr or Param nodes.
544 : : *
545 : : * Returns true if any such node found.
546 : : *
547 : : * This is like contain_var_clause, but additionally returns true if we find
548 : : * a node that might represent the value of a Var from elsewhere in the query.
549 : : * We don't inquire into whether it actually does represent one; this is used
550 : : * for leakproofness checks in which it's better to report false positives
551 : : * than false negatives.
552 : : *
553 : : * You might think this needs to return true for upper-level Vars too,
554 : : * but at least in current usage it's better to match contain_var_clause.
555 : : * The caller is considering whether to push the clause below an RLS qual, so
556 : : * we need only restrict access to Vars of the relation with the RLS policy.
557 : : *
558 : : * Does not examine subqueries, therefore must only be used after reduction
559 : : * of sublinks to subplans!
560 : : */
561 : : bool
562 : 2245 : contain_var_or_representative(Node *node)
563 : : {
564 : 2245 : return contain_var_or_representative_walker(node, NULL);
565 : : }
566 : :
567 : : static bool
568 : 4541 : contain_var_or_representative_walker(Node *node, void *context)
569 : : {
570 : : /* This part must match contain_var_clause ... */
571 [ - + ]: 4541 : if (node == NULL)
572 : 0 : return false;
573 [ + + ]: 4541 : if (IsA(node, Var))
574 : : {
575 [ + - ]: 2201 : if (((Var *) node)->varlevelsup == 0)
576 : 2201 : return true; /* abort the tree traversal and return true */
577 : 0 : return false;
578 : : }
579 [ - + ]: 2340 : if (IsA(node, CurrentOfExpr))
580 : 0 : return true;
581 [ - + ]: 2340 : if (IsA(node, PlaceHolderVar))
582 : : {
583 [ # # ]: 0 : if (((PlaceHolderVar *) node)->phlevelsup == 0)
584 : 0 : return true; /* abort the tree traversal and return true */
585 : : /* else fall through to check the contained expr */
586 : : }
587 : : /* ... and here's the additional part */
588 [ - + ]: 2340 : if (IsA(node, CaseTestExpr))
589 : 0 : return true;
590 [ - + ]: 2340 : if (IsA(node, Param))
591 : : {
592 : : /* We don't consider PARAM_EXTERN Params dangerous for this purpose */
593 [ # # ]: 0 : if (((Param *) node)->paramkind == PARAM_EXTERN)
594 : 0 : return false;
595 : : else
596 : 0 : return true;
597 : : }
598 : 2340 : return expression_tree_walker(node, contain_var_or_representative_walker,
599 : : context);
600 : : }
601 : :
602 : :
603 : : /*
604 : : * locate_var_of_level
605 : : * Find the parse location of any Var of the specified query level.
606 : : *
607 : : * Returns -1 if no such Var is in the querytree, or if they all have
608 : : * unknown parse location. (The former case is probably caller error,
609 : : * but we don't bother to distinguish it from the latter case.)
610 : : *
611 : : * Will recurse into sublinks. Also, may be invoked directly on a Query.
612 : : *
613 : : * Note: it might seem appropriate to merge this functionality into
614 : : * contain_vars_of_level, but that would complicate that function's API.
615 : : * Currently, the only uses of this function are for error reporting,
616 : : * and so shaving cycles probably isn't very important.
617 : : */
618 : : int
619 : 8 : locate_var_of_level(Node *node, int levelsup)
620 : : {
621 : : locate_var_of_level_context context;
622 : :
623 : 8 : context.var_location = -1; /* in case we find nothing */
624 : 8 : context.sublevels_up = levelsup;
625 : :
626 : 8 : (void) query_or_expression_tree_walker(node,
627 : : locate_var_of_level_walker,
628 : : &context,
629 : : 0);
630 : :
631 : 8 : return context.var_location;
632 : : }
633 : :
634 : : static bool
635 : 20 : locate_var_of_level_walker(Node *node,
636 : : locate_var_of_level_context *context)
637 : : {
638 [ - + ]: 20 : if (node == NULL)
639 : 0 : return false;
640 [ + + ]: 20 : if (IsA(node, Var))
641 : : {
642 : 8 : Var *var = (Var *) node;
643 : :
644 [ + - ]: 8 : if (var->varlevelsup == context->sublevels_up &&
645 [ + - ]: 8 : var->location >= 0)
646 : : {
647 : 8 : context->var_location = var->location;
648 : 8 : return true; /* abort tree traversal and return true */
649 : : }
650 : 0 : return false;
651 : : }
652 [ - + ]: 12 : if (IsA(node, CurrentOfExpr))
653 : : {
654 : : /* since CurrentOfExpr doesn't carry location, nothing we can do */
655 : 0 : return false;
656 : : }
657 : : /* No extra code needed for PlaceHolderVar; just look in contained expr */
658 [ - + ]: 12 : if (IsA(node, Query))
659 : : {
660 : : /* Recurse into subselects */
661 : : bool result;
662 : :
663 : 0 : context->sublevels_up++;
664 : 0 : result = query_tree_walker((Query *) node,
665 : : locate_var_of_level_walker,
666 : : context,
667 : : 0);
668 : 0 : context->sublevels_up--;
669 : 0 : return result;
670 : : }
671 : 12 : return expression_tree_walker(node,
672 : : locate_var_of_level_walker,
673 : : context);
674 : : }
675 : :
676 : :
677 : : /*
678 : : * pull_var_clause
679 : : * Recursively pulls all Var nodes from an expression clause.
680 : : *
681 : : * Aggrefs are handled according to these bits in 'flags':
682 : : * PVC_INCLUDE_AGGREGATES include Aggrefs in output list
683 : : * PVC_RECURSE_AGGREGATES recurse into Aggref arguments
684 : : * neither flag throw error if Aggref found
685 : : * Vars within an Aggref's expression are included in the result only
686 : : * when PVC_RECURSE_AGGREGATES is specified.
687 : : *
688 : : * WindowFuncs are handled according to these bits in 'flags':
689 : : * PVC_INCLUDE_WINDOWFUNCS include WindowFuncs in output list
690 : : * PVC_RECURSE_WINDOWFUNCS recurse into WindowFunc arguments
691 : : * neither flag throw error if WindowFunc found
692 : : * Vars within a WindowFunc's expression are included in the result only
693 : : * when PVC_RECURSE_WINDOWFUNCS is specified.
694 : : *
695 : : * PlaceHolderVars are handled according to these bits in 'flags':
696 : : * PVC_INCLUDE_PLACEHOLDERS include PlaceHolderVars in output list
697 : : * PVC_RECURSE_PLACEHOLDERS recurse into PlaceHolderVar arguments
698 : : * neither flag throw error if PlaceHolderVar found
699 : : * Vars within a PHV's expression are included in the result only
700 : : * when PVC_RECURSE_PLACEHOLDERS is specified.
701 : : *
702 : : * GroupingFuncs are treated exactly like Aggrefs, and so do not need
703 : : * their own flag bits.
704 : : *
705 : : * CurrentOfExpr nodes are ignored in all cases.
706 : : *
707 : : * Upper-level vars (with varlevelsup > 0) should not be seen here,
708 : : * likewise for upper-level Aggrefs and PlaceHolderVars.
709 : : *
710 : : * Returns list of nodes found. Note the nodes themselves are not
711 : : * copied, only referenced.
712 : : *
713 : : * Does not examine subqueries, therefore must only be used after reduction
714 : : * of sublinks to subplans!
715 : : */
716 : : List *
717 : 703910 : pull_var_clause(Node *node, int flags)
718 : : {
719 : : pull_var_clause_context context;
720 : :
721 : : /* Assert that caller has not specified inconsistent flags */
722 : : Assert((flags & (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES))
723 : : != (PVC_INCLUDE_AGGREGATES | PVC_RECURSE_AGGREGATES));
724 : : Assert((flags & (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS))
725 : : != (PVC_INCLUDE_WINDOWFUNCS | PVC_RECURSE_WINDOWFUNCS));
726 : : Assert((flags & (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS))
727 : : != (PVC_INCLUDE_PLACEHOLDERS | PVC_RECURSE_PLACEHOLDERS));
728 : :
729 : 703910 : context.varlist = NIL;
730 : 703910 : context.flags = flags;
731 : :
732 : 703910 : pull_var_clause_walker(node, &context);
733 : 703910 : return context.varlist;
734 : : }
735 : :
736 : : static bool
737 : 4152828 : pull_var_clause_walker(Node *node, pull_var_clause_context *context)
738 : : {
739 [ + + ]: 4152828 : if (node == NULL)
740 : 178410 : return false;
741 [ + + ]: 3974418 : if (IsA(node, Var))
742 : : {
743 [ - + ]: 1506264 : if (((Var *) node)->varlevelsup != 0)
744 [ # # ]: 0 : elog(ERROR, "Upper-level Var found where not expected");
745 : 1506264 : context->varlist = lappend(context->varlist, node);
746 : 1506264 : return false;
747 : : }
748 [ + + ]: 2468154 : else if (IsA(node, Aggref))
749 : : {
750 [ - + ]: 89760 : if (((Aggref *) node)->agglevelsup != 0)
751 [ # # ]: 0 : elog(ERROR, "Upper-level Aggref found where not expected");
752 [ + + ]: 89760 : if (context->flags & PVC_INCLUDE_AGGREGATES)
753 : : {
754 : 7177 : context->varlist = lappend(context->varlist, node);
755 : : /* we do NOT descend into the contained expression */
756 : 7177 : return false;
757 : : }
758 [ - + ]: 82583 : else if (context->flags & PVC_RECURSE_AGGREGATES)
759 : : {
760 : : /* fall through to recurse into the aggregate's arguments */
761 : : }
762 : : else
763 [ # # ]: 0 : elog(ERROR, "Aggref found where not expected");
764 : : }
765 [ + + ]: 2378394 : else if (IsA(node, GroupingFunc))
766 : : {
767 [ - + ]: 567 : if (((GroupingFunc *) node)->agglevelsup != 0)
768 [ # # ]: 0 : elog(ERROR, "Upper-level GROUPING found where not expected");
769 [ + + ]: 567 : if (context->flags & PVC_INCLUDE_AGGREGATES)
770 : : {
771 : 2 : context->varlist = lappend(context->varlist, node);
772 : : /* we do NOT descend into the contained expression */
773 : 2 : return false;
774 : : }
775 [ - + ]: 565 : else if (context->flags & PVC_RECURSE_AGGREGATES)
776 : : {
777 : : /* fall through to recurse into the GroupingFunc's arguments */
778 : : }
779 : : else
780 [ # # ]: 0 : elog(ERROR, "GROUPING found where not expected");
781 : : }
782 [ + + ]: 2377827 : else if (IsA(node, WindowFunc))
783 : : {
784 : : /* WindowFuncs have no levelsup field to check ... */
785 [ + + ]: 6773 : if (context->flags & PVC_INCLUDE_WINDOWFUNCS)
786 : : {
787 : 66 : context->varlist = lappend(context->varlist, node);
788 : : /* we do NOT descend into the contained expressions */
789 : 66 : return false;
790 : : }
791 [ - + ]: 6707 : else if (context->flags & PVC_RECURSE_WINDOWFUNCS)
792 : : {
793 : : /* fall through to recurse into the windowfunc's arguments */
794 : : }
795 : : else
796 [ # # ]: 0 : elog(ERROR, "WindowFunc found where not expected");
797 : : }
798 [ + + ]: 2371054 : else if (IsA(node, PlaceHolderVar))
799 : : {
800 [ - + ]: 11186 : if (((PlaceHolderVar *) node)->phlevelsup != 0)
801 [ # # ]: 0 : elog(ERROR, "Upper-level PlaceHolderVar found where not expected");
802 [ + + ]: 11186 : if (context->flags & PVC_INCLUDE_PLACEHOLDERS)
803 : : {
804 : 6044 : context->varlist = lappend(context->varlist, node);
805 : : /* we do NOT descend into the contained expression */
806 : 6044 : return false;
807 : : }
808 [ - + ]: 5142 : else if (context->flags & PVC_RECURSE_PLACEHOLDERS)
809 : : {
810 : : /* fall through to recurse into the placeholder's expression */
811 : : }
812 : : else
813 [ # # ]: 0 : elog(ERROR, "PlaceHolderVar found where not expected");
814 : : }
815 : 2454865 : return expression_tree_walker(node, pull_var_clause_walker, context);
816 : : }
817 : :
818 : :
819 : : /*
820 : : * flatten_join_alias_vars
821 : : * Replace Vars that reference JOIN outputs with references to the original
822 : : * relation variables instead. This allows quals involving such vars to be
823 : : * pushed down. Whole-row Vars that reference JOIN relations are expanded
824 : : * into RowExpr constructs that name the individual output Vars. This
825 : : * is necessary since we will not scan the JOIN as a base relation, which
826 : : * is the only way that the executor can directly handle whole-row Vars.
827 : : *
828 : : * This also adjusts relid sets found in some expression node types to
829 : : * substitute the contained base+OJ rels for any join relid.
830 : : *
831 : : * If a JOIN contains sub-selects that have been flattened, its join alias
832 : : * entries might now be arbitrary expressions, not just Vars. This affects
833 : : * this function in two important ways. First, we might find ourselves
834 : : * inserting SubLink expressions into subqueries, and we must make sure that
835 : : * their Query.hasSubLinks fields get set to true if so. If there are any
836 : : * SubLinks in the join alias lists, the outer Query should already have
837 : : * hasSubLinks = true, so this is only relevant to un-flattened subqueries.
838 : : * Second, we have to preserve any varnullingrels info attached to the
839 : : * alias Vars we're replacing. If the replacement expression is a Var or
840 : : * PlaceHolderVar or constructed from those, we can just add the
841 : : * varnullingrels bits to the existing nullingrels field(s); otherwise
842 : : * we have to add a PlaceHolderVar wrapper.
843 : : *
844 : : * If root is NULL, nulled whole-row JOIN Vars are left unexpanded, so the
845 : : * result must be flattened again with a root before it can be executed.
846 : : */
847 : : Node *
848 : 217464 : flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
849 : : {
850 : : flatten_join_alias_vars_context context;
851 : :
852 : : /*
853 : : * We do not expect this to be applied to the whole Query, only to
854 : : * expressions or LATERAL subqueries. Hence, if the top node is a Query,
855 : : * it's okay to immediately increment sublevels_up.
856 : : */
857 : : Assert(node != (Node *) query);
858 : : /* add_nullingrels_if_needed relies on this */
859 : : Assert(root == NULL || query == root->parse);
860 : :
861 : 217464 : context.root = root;
862 : 217464 : context.query = query;
863 : 217464 : context.sublevels_up = 0;
864 : : /* flag whether join aliases could possibly contain SubLinks */
865 : 217464 : context.possible_sublink = query->hasSubLinks;
866 : : /* if hasSubLinks is already true, no need to work hard */
867 : 217464 : context.inserted_sublink = query->hasSubLinks;
868 : :
869 : 217464 : return flatten_join_alias_vars_mutator(node, &context);
870 : : }
871 : :
872 : : /*
873 : : * flatten_join_alias_for_parser
874 : : *
875 : : * This variant of flatten_join_alias_vars is used by the parser, to expand
876 : : * join alias Vars before checking GROUP BY validity. In that case we lack
877 : : * a root structure. Fortunately, we'd only need the root for making
878 : : * PlaceHolderVars. We can avoid making PlaceHolderVars in the parser's
879 : : * usage because it won't be dealing with arbitrary expressions: so long as
880 : : * adjust_standard_join_alias_expression can handle everything the parser
881 : : * would make as a join alias expression, we're OK. (Nulled whole-row join
882 : : * Vars are the exception; those are left unexpanded.)
883 : : *
884 : : * The "node" might be part of a sub-query of the Query whose join alias
885 : : * Vars are to be expanded. "sublevels_up" indicates how far below the
886 : : * given query we are starting.
887 : : */
888 : : Node *
889 : 4505 : flatten_join_alias_for_parser(Query *query, Node *node, int sublevels_up)
890 : : {
891 : : flatten_join_alias_vars_context context;
892 : :
893 : : /*
894 : : * We do not expect this to be applied to the whole Query, only to
895 : : * expressions or LATERAL subqueries. Hence, if the top node is a Query,
896 : : * it's okay to immediately increment sublevels_up.
897 : : */
898 : : Assert(node != (Node *) query);
899 : :
900 : 4505 : context.root = NULL;
901 : 4505 : context.query = query;
902 : 4505 : context.sublevels_up = sublevels_up;
903 : : /* flag whether join aliases could possibly contain SubLinks */
904 : 4505 : context.possible_sublink = query->hasSubLinks;
905 : : /* if hasSubLinks is already true, no need to work hard */
906 : 4505 : context.inserted_sublink = query->hasSubLinks;
907 : :
908 : 4505 : return flatten_join_alias_vars_mutator(node, &context);
909 : : }
910 : :
911 : : static Node *
912 : 3025183 : flatten_join_alias_vars_mutator(Node *node,
913 : : flatten_join_alias_vars_context *context)
914 : : {
915 [ + + ]: 3025183 : if (node == NULL)
916 : 253909 : return NULL;
917 [ + + ]: 2771274 : if (IsA(node, Var))
918 : : {
919 : 814374 : Var *var = (Var *) node;
920 : : RangeTblEntry *rte;
921 : : Node *newvar;
922 : :
923 : : /* No change unless Var belongs to a JOIN of the target level */
924 [ + + ]: 814374 : if (var->varlevelsup != context->sublevels_up)
925 : 43207 : return node; /* no need to copy, really */
926 : 771167 : rte = rt_fetch(var->varno, context->query->rtable);
927 [ + + ]: 771167 : if (rte->rtekind != RTE_JOIN)
928 : 770260 : return node;
929 [ + + ]: 907 : if (var->varattno == InvalidAttrNumber)
930 : : {
931 : : /* Must expand whole-row reference */
932 : : RowExpr *rowexpr;
933 : 222 : List *fields = NIL;
934 : 222 : List *colnames = NIL;
935 : : ListCell *lv;
936 : : ListCell *ln;
937 : :
938 : : /*
939 : : * A nulled whole-row expansion needs a PlaceHolderVar, which we
940 : : * can't make without a root; leave the Var unexpanded.
941 : : */
942 [ + + + - ]: 222 : if (context->root == NULL && var->varnullingrels != NULL)
943 : 12 : return node;
944 : :
945 : : Assert(list_length(rte->joinaliasvars) == list_length(rte->eref->colnames));
946 [ + + + + : 695 : forboth(lv, rte->joinaliasvars, ln, rte->eref->colnames)
+ + + + +
+ + - +
+ ]
947 : : {
948 : 485 : newvar = (Node *) lfirst(lv);
949 : : /* Ignore dropped columns */
950 [ - + ]: 485 : if (newvar == NULL)
951 : 0 : continue;
952 : 485 : newvar = copyObject(newvar);
953 : :
954 : : /*
955 : : * If we are expanding an alias carried down from an upper
956 : : * query, must adjust its varlevelsup fields.
957 : : */
958 [ + + ]: 485 : if (context->sublevels_up != 0)
959 : 110 : IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
960 : : /* Preserve original Var's location, if possible */
961 [ + + ]: 485 : if (IsA(newvar, Var))
962 : 400 : ((Var *) newvar)->location = var->location;
963 : : /* Recurse in case join input is itself a join */
964 : 485 : newvar = flatten_join_alias_vars_mutator(newvar, context);
965 : :
966 : : /* Detect if we are adding a sublink to query */
967 [ + + + + ]: 485 : if (context->possible_sublink && !context->inserted_sublink)
968 : 35 : context->inserted_sublink = checkExprHasSubLink(newvar);
969 : :
970 : 485 : fields = lappend(fields, newvar);
971 : : /* We need the names of non-dropped columns, too */
972 : 485 : colnames = lappend(colnames, copyObject((Node *) lfirst(ln)));
973 : : }
974 : 210 : rowexpr = makeNode(RowExpr);
975 : 210 : rowexpr->args = fields;
976 : 210 : rowexpr->row_typeid = var->vartype;
977 : 210 : rowexpr->row_format = COERCE_IMPLICIT_CAST;
978 : : /* vartype will always be RECORDOID, so we always need colnames */
979 : 210 : rowexpr->colnames = colnames;
980 : 210 : rowexpr->location = var->location;
981 : :
982 : : /* Lastly, add any varnullingrels to the replacement expression */
983 : 210 : return add_nullingrels_if_needed(context->root, (Node *) rowexpr,
984 : : var);
985 : : }
986 : :
987 : : /* Expand join alias reference */
988 : : Assert(var->varattno > 0);
989 : 685 : newvar = (Node *) list_nth(rte->joinaliasvars, var->varattno - 1);
990 : : Assert(newvar != NULL);
991 : 685 : newvar = copyObject(newvar);
992 : :
993 : : /*
994 : : * If we are expanding an alias carried down from an upper query, must
995 : : * adjust its varlevelsup fields.
996 : : */
997 [ + + ]: 685 : if (context->sublevels_up != 0)
998 : 53 : IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
999 : :
1000 : : /* Preserve original Var's location, if possible */
1001 [ - + ]: 685 : if (IsA(newvar, Var))
1002 : 0 : ((Var *) newvar)->location = var->location;
1003 : :
1004 : : /* Recurse in case join input is itself a join */
1005 : 685 : newvar = flatten_join_alias_vars_mutator(newvar, context);
1006 : :
1007 : : /* Detect if we are adding a sublink to query */
1008 [ + + + + ]: 685 : if (context->possible_sublink && !context->inserted_sublink)
1009 : 30 : context->inserted_sublink = checkExprHasSubLink(newvar);
1010 : :
1011 : : /* Lastly, add any varnullingrels to the replacement expression */
1012 : 685 : return add_nullingrels_if_needed(context->root, newvar, var);
1013 : : }
1014 [ + + ]: 1956900 : if (IsA(node, PlaceHolderVar))
1015 : : {
1016 : 2693 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
1017 : :
1018 : : /*
1019 : : * A PHV above the target level can't contain join aliases of the
1020 : : * target level and has no relid sets of ours to fix, so return it
1021 : : * unchanged.
1022 : : */
1023 [ + + ]: 2693 : if (phv->phlevelsup > context->sublevels_up)
1024 : 135 : return node; /* no need to copy, really */
1025 : :
1026 : : /*
1027 : : * A pushed-down copy of a target-level PHV is preprocessed by
1028 : : * preprocess_subquery_phvs, which handles its target-level aliases
1029 : : * and may leave SubPlans in it; so don't recurse into it. Any other
1030 : : * PHV may still hold target-level aliases, so recurse.
1031 : : */
1032 [ + - ]: 2558 : if (phv->phlevelsup == context->sublevels_up &&
1033 [ + + ]: 2558 : context->sublevels_up > 0)
1034 : 200 : {
1035 : 200 : PlaceHolderVar *newphv = makeNode(PlaceHolderVar);
1036 : :
1037 : 200 : memcpy(newphv, phv, sizeof(PlaceHolderVar));
1038 : 200 : phv = newphv;
1039 : : }
1040 : : else
1041 : 2358 : phv = (PlaceHolderVar *) expression_tree_mutator(node,
1042 : : flatten_join_alias_vars_mutator,
1043 : : context);
1044 : : /* now fix PlaceHolderVar's relid sets */
1045 [ + - ]: 2558 : if (phv->phlevelsup == context->sublevels_up)
1046 : : {
1047 : 2558 : phv->phrels = alias_relid_set(context->query,
1048 : : phv->phrels);
1049 : : /* we *don't* change phnullingrels */
1050 : : }
1051 : 2558 : return (Node *) phv;
1052 : : }
1053 : :
1054 [ + + ]: 1954207 : if (IsA(node, Query))
1055 : : {
1056 : : /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1057 : : Query *newnode;
1058 : : bool save_inserted_sublink;
1059 : :
1060 : 13054 : context->sublevels_up++;
1061 : 13054 : save_inserted_sublink = context->inserted_sublink;
1062 : 13054 : context->inserted_sublink = ((Query *) node)->hasSubLinks;
1063 : 13054 : newnode = query_tree_mutator((Query *) node,
1064 : : flatten_join_alias_vars_mutator,
1065 : : context,
1066 : : QTW_IGNORE_JOINALIASES);
1067 : 13054 : newnode->hasSubLinks |= context->inserted_sublink;
1068 : 13054 : context->inserted_sublink = save_inserted_sublink;
1069 : 13054 : context->sublevels_up--;
1070 : 13054 : return (Node *) newnode;
1071 : : }
1072 : : /* Already-planned tree not supported */
1073 : : Assert(!IsA(node, SubPlan));
1074 : : Assert(!IsA(node, AlternativeSubPlan));
1075 : : /* Shouldn't need to handle these planner auxiliary nodes here */
1076 : : Assert(!IsA(node, SpecialJoinInfo));
1077 : : Assert(!IsA(node, PlaceHolderInfo));
1078 : : Assert(!IsA(node, MinMaxAggInfo));
1079 : :
1080 : 1941153 : return expression_tree_mutator(node, flatten_join_alias_vars_mutator, context);
1081 : : }
1082 : :
1083 : : /*
1084 : : * flatten_group_exprs
1085 : : * Replace Vars that reference GROUP outputs with the underlying grouping
1086 : : * expressions.
1087 : : *
1088 : : * We have to preserve any varnullingrels info attached to the group Vars we're
1089 : : * replacing. If the replacement expression is a Var or PlaceHolderVar or
1090 : : * constructed from those, we can just add the varnullingrels bits to the
1091 : : * existing nullingrels field(s); otherwise we have to add a PlaceHolderVar
1092 : : * wrapper.
1093 : : *
1094 : : * NOTE: root may be passed as NULL, which is why we have to pass the Query
1095 : : * separately. We need the root itself only for preserving varnullingrels.
1096 : : * Callers can safely pass NULL if preserving varnullingrels is unnecessary for
1097 : : * their specific use case (e.g., deparsing source text, or scanning for
1098 : : * volatile functions), or if it is already guaranteed that the query cannot
1099 : : * contain grouping sets.
1100 : : */
1101 : : Node *
1102 : 9698 : flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
1103 : : {
1104 : : flatten_join_alias_vars_context context;
1105 : :
1106 : : /*
1107 : : * We do not expect this to be applied to the whole Query, only to
1108 : : * expressions or LATERAL subqueries. Hence, if the top node is a Query,
1109 : : * it's okay to immediately increment sublevels_up.
1110 : : */
1111 : : Assert(node != (Node *) query);
1112 : :
1113 : 9698 : context.root = root;
1114 : 9698 : context.query = query;
1115 : 9698 : context.sublevels_up = 0;
1116 : : /* flag whether grouping expressions could possibly contain SubLinks */
1117 : 9698 : context.possible_sublink = query->hasSubLinks;
1118 : : /* if hasSubLinks is already true, no need to work hard */
1119 : 9698 : context.inserted_sublink = query->hasSubLinks;
1120 : :
1121 : 9698 : return flatten_group_exprs_mutator(node, &context);
1122 : : }
1123 : :
1124 : : static Node *
1125 : 92617 : flatten_group_exprs_mutator(Node *node,
1126 : : flatten_join_alias_vars_context *context)
1127 : : {
1128 [ + + ]: 92617 : if (node == NULL)
1129 : 10689 : return NULL;
1130 [ + + ]: 81928 : if (IsA(node, Var))
1131 : : {
1132 : 15917 : Var *var = (Var *) node;
1133 : : RangeTblEntry *rte;
1134 : : Node *newvar;
1135 : :
1136 : : /* No change unless Var belongs to the GROUP of the target level */
1137 [ - + ]: 15917 : if (var->varlevelsup != context->sublevels_up)
1138 : 0 : return node; /* no need to copy, really */
1139 : 15917 : rte = rt_fetch(var->varno, context->query->rtable);
1140 [ + + ]: 15917 : if (rte->rtekind != RTE_GROUP)
1141 : 247 : return node;
1142 : :
1143 : : /* Expand group exprs reference */
1144 : : Assert(var->varattno > 0);
1145 : 15670 : newvar = (Node *) list_nth(rte->groupexprs, var->varattno - 1);
1146 : : Assert(newvar != NULL);
1147 : 15670 : newvar = copyObject(newvar);
1148 : :
1149 : : /*
1150 : : * If we are expanding an expr carried down from an upper query, must
1151 : : * adjust its varlevelsup fields.
1152 : : */
1153 [ - + ]: 15670 : if (context->sublevels_up != 0)
1154 : 0 : IncrementVarSublevelsUp(newvar, context->sublevels_up, 0);
1155 : :
1156 : : /* Preserve original Var's location, if possible */
1157 [ + + ]: 15670 : if (IsA(newvar, Var))
1158 : 13374 : ((Var *) newvar)->location = var->location;
1159 : :
1160 : : /* Detect if we are adding a sublink to query */
1161 [ + + - + ]: 15670 : if (context->possible_sublink && !context->inserted_sublink)
1162 : 0 : context->inserted_sublink = checkExprHasSubLink(newvar);
1163 : :
1164 : : /* Lastly, add any varnullingrels to the replacement expression */
1165 : 15670 : return mark_nullable_by_grouping(context->root, newvar, var);
1166 : : }
1167 : :
1168 [ + + ]: 66011 : if (IsA(node, Aggref))
1169 : : {
1170 : 6372 : Aggref *agg = (Aggref *) node;
1171 : :
1172 [ + - ]: 6372 : if ((int) agg->agglevelsup == context->sublevels_up)
1173 : : {
1174 : : /*
1175 : : * If we find an aggregate call of the original level, do not
1176 : : * recurse into its normal arguments, ORDER BY arguments, or
1177 : : * filter; there are no grouped vars there. But we should check
1178 : : * direct arguments as though they weren't in an aggregate.
1179 : : */
1180 : 6372 : agg = copyObject(agg);
1181 : 6372 : agg->aggdirectargs = (List *)
1182 : 6372 : flatten_group_exprs_mutator((Node *) agg->aggdirectargs, context);
1183 : :
1184 : 6372 : return (Node *) agg;
1185 : : }
1186 : :
1187 : : /*
1188 : : * We can skip recursing into aggregates of higher levels altogether,
1189 : : * since they could not possibly contain Vars of concern to us (see
1190 : : * transformAggregateCall). We do need to look at aggregates of lower
1191 : : * levels, however.
1192 : : */
1193 [ # # ]: 0 : if ((int) agg->agglevelsup > context->sublevels_up)
1194 : 0 : return node;
1195 : : }
1196 : :
1197 [ + + ]: 59639 : if (IsA(node, GroupingFunc))
1198 : : {
1199 : 312 : GroupingFunc *grp = (GroupingFunc *) node;
1200 : :
1201 : : /*
1202 : : * If we find a GroupingFunc node of the original or higher level, do
1203 : : * not recurse into its arguments; there are no grouped vars there.
1204 : : */
1205 [ + - ]: 312 : if ((int) grp->agglevelsup >= context->sublevels_up)
1206 : 312 : return node;
1207 : : }
1208 : :
1209 [ - + ]: 59327 : if (IsA(node, Query))
1210 : : {
1211 : : /* Recurse into RTE subquery or not-yet-planned sublink subquery */
1212 : : Query *newnode;
1213 : : bool save_inserted_sublink;
1214 : :
1215 : 0 : context->sublevels_up++;
1216 : 0 : save_inserted_sublink = context->inserted_sublink;
1217 : 0 : context->inserted_sublink = ((Query *) node)->hasSubLinks;
1218 : 0 : newnode = query_tree_mutator((Query *) node,
1219 : : flatten_group_exprs_mutator,
1220 : : context,
1221 : : QTW_IGNORE_GROUPEXPRS);
1222 : 0 : newnode->hasSubLinks |= context->inserted_sublink;
1223 : 0 : context->inserted_sublink = save_inserted_sublink;
1224 : 0 : context->sublevels_up--;
1225 : 0 : return (Node *) newnode;
1226 : : }
1227 : :
1228 : 59327 : return expression_tree_mutator(node, flatten_group_exprs_mutator,
1229 : : context);
1230 : : }
1231 : :
1232 : : /*
1233 : : * Add oldvar's varnullingrels, if any, to a flattened grouping expression.
1234 : : * The newnode has been copied, so we can modify it freely.
1235 : : */
1236 : : static Node *
1237 : 15670 : mark_nullable_by_grouping(PlannerInfo *root, Node *newnode, Var *oldvar)
1238 : : {
1239 : : Relids relids;
1240 : :
1241 [ + + ]: 15670 : if (root == NULL)
1242 : 6455 : return newnode;
1243 [ + + ]: 9215 : if (oldvar->varnullingrels == NULL)
1244 : 7403 : return newnode; /* nothing to do */
1245 : :
1246 : : Assert(bms_equal(oldvar->varnullingrels,
1247 : : bms_make_singleton(root->group_rtindex)));
1248 : :
1249 : 1812 : relids = pull_varnos_of_level(root, newnode, oldvar->varlevelsup);
1250 : :
1251 [ + + ]: 1812 : if (!bms_is_empty(relids))
1252 : : {
1253 : : /*
1254 : : * If the newnode is not variable-free, we set the nullingrels of Vars
1255 : : * or PHVs that are contained in the expression. This is not really
1256 : : * 'correct' in theory, because it is the whole expression that can be
1257 : : * nullable by grouping sets, not its individual vars. But it works
1258 : : * in practice, because what we need is that the expression can be
1259 : : * somehow distinguished from the same expression in ECs, and marking
1260 : : * its vars is sufficient for this purpose.
1261 : : */
1262 : 1772 : newnode = add_nulling_relids(newnode,
1263 : : relids,
1264 : 1772 : oldvar->varnullingrels);
1265 : : }
1266 : : else /* variable-free? */
1267 : : {
1268 : : /*
1269 : : * If the newnode is variable-free and does not contain volatile
1270 : : * functions or set-returning functions, it can be treated as a member
1271 : : * of EC that is redundant. So wrap it in a new PlaceHolderVar to
1272 : : * carry the nullingrels. Otherwise we do not bother to make any
1273 : : * changes.
1274 : : *
1275 : : * Aggregate functions and window functions are not allowed in
1276 : : * grouping expressions.
1277 : : */
1278 : : Assert(!contain_agg_clause(newnode));
1279 : : Assert(!contain_window_function(newnode));
1280 : :
1281 [ + - ]: 40 : if (!contain_volatile_functions(newnode) &&
1282 [ + + ]: 40 : !expression_returns_set(newnode))
1283 : : {
1284 : : PlaceHolderVar *newphv;
1285 : : Relids phrels;
1286 : :
1287 : 25 : phrels = get_relids_in_jointree((Node *) root->parse->jointree,
1288 : : true, false);
1289 : : Assert(!bms_is_empty(phrels));
1290 : :
1291 : 25 : newphv = make_placeholder_expr(root, (Expr *) newnode, phrels);
1292 : : /* newphv has zero phlevelsup and NULL phnullingrels; fix it */
1293 : 25 : newphv->phlevelsup = oldvar->varlevelsup;
1294 : 25 : newphv->phnullingrels = bms_copy(oldvar->varnullingrels);
1295 : 25 : newnode = (Node *) newphv;
1296 : : }
1297 : : }
1298 : :
1299 : 1812 : return newnode;
1300 : : }
1301 : :
1302 : : /*
1303 : : * Add oldvar's varnullingrels, if any, to a flattened join alias expression.
1304 : : * The newnode has been copied, so we can modify it freely.
1305 : : *
1306 : : * If we need a PlaceHolderVar, we reuse any PHV already made for the same
1307 : : * expression with this root, so that all expansions of the same alias get
1308 : : * the same phid, much as pullup_replace_vars_callback does with its rv_cache.
1309 : : */
1310 : : static Node *
1311 : 895 : add_nullingrels_if_needed(PlannerInfo *root, Node *newnode, Var *oldvar)
1312 : : {
1313 [ + + ]: 895 : if (oldvar->varnullingrels == NULL)
1314 : 579 : return newnode; /* nothing to do */
1315 : : /* If possible, do it by adding to existing nullingrel fields */
1316 [ + + ]: 316 : if (is_standard_join_alias_expression(newnode, oldvar))
1317 : 136 : adjust_standard_join_alias_expression(newnode, oldvar);
1318 [ + - ]: 180 : else if (root)
1319 : : {
1320 : : /*
1321 : : * We can insert a PlaceHolderVar to carry the nullingrels. However,
1322 : : * deciding where to evaluate the PHV is slightly tricky. We first
1323 : : * try to evaluate it at the natural semantic level of the new
1324 : : * expression, ignoring any lateral references to rels outside the
1325 : : * join; but if that leaves nothing, fall back to evaluating it at the
1326 : : * join that the oldvar is an alias Var for.
1327 : : */
1328 : 180 : PlaceHolderVar *newphv = NULL;
1329 : 180 : Index levelsup = oldvar->varlevelsup;
1330 : : Relids joinrelids;
1331 : : Relids phrels;
1332 : :
1333 : : /* oldvar belongs to root->parse even when levelsup > 0 */
1334 : 180 : joinrelids = get_relids_for_join(root->parse, oldvar->varno);
1335 : 180 : phrels = pull_varnos_of_level(root, newnode, levelsup);
1336 : 180 : phrels = bms_int_members(phrels, joinrelids);
1337 [ + + ]: 180 : if (bms_is_empty(phrels))
1338 : : {
1339 : : /* Keep the join's own OJ relid: this set spans both its sides */
1340 : 50 : phrels = joinrelids;
1341 : : }
1342 : :
1343 : : /* Look for an existing PHV, comparing at level zero */
1344 [ + + ]: 180 : if (levelsup != 0)
1345 : 65 : IncrementVarSublevelsUp(newnode, -((int) levelsup), 0);
1346 [ + + + - : 360 : foreach_node(PlaceHolderVar, phv, root->join_alias_phvs)
+ + ]
1347 : : {
1348 [ + - + - ]: 90 : if (bms_equal(phv->phrels, phrels) &&
1349 : 45 : equal(phv->phexpr, newnode))
1350 : : {
1351 : 45 : newphv = copyObject(phv);
1352 : 45 : break;
1353 : : }
1354 : : }
1355 [ + + ]: 180 : if (newphv == NULL)
1356 : : {
1357 : 135 : newphv = make_placeholder_expr(root, (Expr *) newnode, phrels);
1358 : 135 : root->join_alias_phvs = lappend(root->join_alias_phvs,
1359 : : copyObject(newphv));
1360 : : }
1361 : :
1362 : : /* newphv has zero phlevelsup and NULL phnullingrels; fix it */
1363 [ + + ]: 180 : if (levelsup != 0)
1364 : 65 : IncrementVarSublevelsUp((Node *) newphv, levelsup, 0);
1365 : 180 : newphv->phnullingrels = bms_copy(oldvar->varnullingrels);
1366 : 180 : newnode = (Node *) newphv;
1367 : : }
1368 : : else
1369 : : {
1370 : : /* ooops, we're missing support for something the parser can make */
1371 [ # # ]: 0 : elog(ERROR, "unsupported join alias expression");
1372 : : }
1373 : 316 : return newnode;
1374 : : }
1375 : :
1376 : : /*
1377 : : * Check to see if we can insert nullingrels into this join alias expression
1378 : : * without use of a separate PlaceHolderVar.
1379 : : *
1380 : : * This will handle Vars, PlaceHolderVars, and implicit-coercion and COALESCE
1381 : : * expressions built from those. This coverage needs to handle anything
1382 : : * that the parser would put into joinaliasvars.
1383 : : */
1384 : : static bool
1385 : 642 : is_standard_join_alias_expression(Node *newnode, Var *oldvar)
1386 : : {
1387 [ - + ]: 642 : if (newnode == NULL)
1388 : 0 : return false;
1389 [ + + ]: 642 : if (IsA(newnode, Var) &&
1390 [ + - ]: 246 : ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
1391 : 246 : return true;
1392 [ + + ]: 396 : else if (IsA(newnode, PlaceHolderVar) &&
1393 [ + - ]: 20 : ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
1394 : 20 : return true;
1395 [ + + ]: 376 : else if (IsA(newnode, FuncExpr))
1396 : : {
1397 : 33 : FuncExpr *fexpr = (FuncExpr *) newnode;
1398 : :
1399 : : /*
1400 : : * We need to assume that the function wouldn't produce non-NULL from
1401 : : * NULL, which is reasonable for implicit coercions but otherwise not
1402 : : * so much. (Looking at its strictness is likely overkill, and anyway
1403 : : * it would cause us to fail if someone forgot to mark an implicit
1404 : : * coercion as strict.)
1405 : : */
1406 [ + - ]: 33 : if (fexpr->funcformat != COERCE_IMPLICIT_CAST ||
1407 [ - + ]: 33 : fexpr->args == NIL)
1408 : 0 : return false;
1409 : :
1410 : : /*
1411 : : * Examine only the first argument --- coercions might have additional
1412 : : * arguments that are constants.
1413 : : */
1414 : 33 : return is_standard_join_alias_expression(linitial(fexpr->args), oldvar);
1415 : : }
1416 [ + + ]: 343 : else if (IsA(newnode, RelabelType))
1417 : : {
1418 : 13 : RelabelType *relabel = (RelabelType *) newnode;
1419 : :
1420 : : /* This definitely won't produce non-NULL from NULL */
1421 : 13 : return is_standard_join_alias_expression((Node *) relabel->arg, oldvar);
1422 : : }
1423 [ - + ]: 330 : else if (IsA(newnode, CoerceViaIO))
1424 : : {
1425 : 0 : CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
1426 : :
1427 : : /* This definitely won't produce non-NULL from NULL */
1428 : 0 : return is_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
1429 : : }
1430 [ - + ]: 330 : else if (IsA(newnode, ArrayCoerceExpr))
1431 : : {
1432 : 0 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
1433 : :
1434 : : /* This definitely won't produce non-NULL from NULL (at array level) */
1435 : 0 : return is_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
1436 : : }
1437 [ + + ]: 330 : else if (IsA(newnode, CoalesceExpr))
1438 : : {
1439 : 150 : CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
1440 : : ListCell *lc;
1441 : :
1442 : : Assert(cexpr->args != NIL);
1443 [ + - + + : 410 : foreach(lc, cexpr->args)
+ + ]
1444 : : {
1445 [ + + ]: 280 : if (!is_standard_join_alias_expression(lfirst(lc), oldvar))
1446 : 20 : return false;
1447 : : }
1448 : 130 : return true;
1449 : : }
1450 : : else
1451 : 180 : return false;
1452 : : }
1453 : :
1454 : : /*
1455 : : * Insert nullingrels into an expression accepted by
1456 : : * is_standard_join_alias_expression.
1457 : : */
1458 : : static void
1459 : 422 : adjust_standard_join_alias_expression(Node *newnode, Var *oldvar)
1460 : : {
1461 [ + + ]: 422 : if (IsA(newnode, Var) &&
1462 [ + - ]: 246 : ((Var *) newnode)->varlevelsup == oldvar->varlevelsup)
1463 : 246 : {
1464 : 246 : Var *newvar = (Var *) newnode;
1465 : :
1466 : 246 : newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
1467 : 246 : oldvar->varnullingrels);
1468 : : }
1469 [ + + ]: 176 : else if (IsA(newnode, PlaceHolderVar) &&
1470 [ + - ]: 20 : ((PlaceHolderVar *) newnode)->phlevelsup == oldvar->varlevelsup)
1471 : 20 : {
1472 : 20 : PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
1473 : :
1474 : 20 : newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
1475 : 20 : oldvar->varnullingrels);
1476 : : }
1477 [ + + ]: 156 : else if (IsA(newnode, FuncExpr))
1478 : : {
1479 : 13 : FuncExpr *fexpr = (FuncExpr *) newnode;
1480 : :
1481 : 13 : adjust_standard_join_alias_expression(linitial(fexpr->args), oldvar);
1482 : : }
1483 [ + + ]: 143 : else if (IsA(newnode, RelabelType))
1484 : : {
1485 : 13 : RelabelType *relabel = (RelabelType *) newnode;
1486 : :
1487 : 13 : adjust_standard_join_alias_expression((Node *) relabel->arg, oldvar);
1488 : : }
1489 [ - + ]: 130 : else if (IsA(newnode, CoerceViaIO))
1490 : : {
1491 : 0 : CoerceViaIO *iocoerce = (CoerceViaIO *) newnode;
1492 : :
1493 : 0 : adjust_standard_join_alias_expression((Node *) iocoerce->arg, oldvar);
1494 : : }
1495 [ - + ]: 130 : else if (IsA(newnode, ArrayCoerceExpr))
1496 : : {
1497 : 0 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) newnode;
1498 : :
1499 : 0 : adjust_standard_join_alias_expression((Node *) acoerce->arg, oldvar);
1500 : : }
1501 [ + - ]: 130 : else if (IsA(newnode, CoalesceExpr))
1502 : : {
1503 : 130 : CoalesceExpr *cexpr = (CoalesceExpr *) newnode;
1504 : : ListCell *lc;
1505 : :
1506 : : Assert(cexpr->args != NIL);
1507 [ + - + + : 390 : foreach(lc, cexpr->args)
+ + ]
1508 : : {
1509 : 260 : adjust_standard_join_alias_expression(lfirst(lc), oldvar);
1510 : : }
1511 : : }
1512 : : else
1513 : : Assert(false);
1514 : 422 : }
1515 : :
1516 : : /*
1517 : : * alias_relid_set: in a set of RT indexes, replace joins by their
1518 : : * underlying base+OJ relids
1519 : : */
1520 : : static Relids
1521 : 2558 : alias_relid_set(Query *query, Relids relids)
1522 : : {
1523 : 2558 : Relids result = NULL;
1524 : : int rtindex;
1525 : :
1526 : 2558 : rtindex = -1;
1527 [ + + ]: 6496 : while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
1528 : : {
1529 : 3938 : RangeTblEntry *rte = rt_fetch(rtindex, query->rtable);
1530 : :
1531 [ + + ]: 3938 : if (rte->rtekind == RTE_JOIN)
1532 : 512 : result = bms_join(result, get_relids_for_join(query, rtindex));
1533 : : else
1534 : 3426 : result = bms_add_member(result, rtindex);
1535 : : }
1536 : 2558 : return result;
1537 : : }
|