PostgreSQL Source Code git master
Loading...
Searching...
No Matches
setrefs.c File Reference
#include "postgres.h"
#include "access/transam.h"
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/parse_relation.h"
#include "rewrite/rewriteManip.h"
#include "tcop/utility.h"
#include "utils/syscache.h"
Include dependency graph for setrefs.c:

Go to the source code of this file.

Data Structures

struct  tlist_vinfo
 
struct  indexed_tlist
 
struct  fix_scan_expr_context
 
struct  fix_join_expr_context
 
struct  fix_upper_expr_context
 
struct  fix_windowagg_cond_context
 
struct  flatten_rtes_walker_context
 

Macros

#define NUM_EXEC_TLIST(parentplan)   ((parentplan)->plan_rows)
 
#define NUM_EXEC_QUAL(parentplan)   ((parentplan)->plan_rows * 2.0)
 
#define ISREGCLASSCONST(con)
 
#define fix_scan_list(root, lst, rtoffset, num_exec)    ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))
 

Enumerations

enum  NullingRelsMatch { NRM_EQUAL , NRM_SUBSET , NRM_SUPERSET }
 

Functions

static void add_rtes_to_flat_rtable (PlannerInfo *root, bool recursing)
 
static void flatten_unplanned_rtes (PlannerGlobal *glob, RangeTblEntry *rte)
 
static bool flatten_rtes_walker (Node *node, flatten_rtes_walker_context *cxt)
 
static void add_rte_to_flat_rtable (PlannerGlobal *glob, List *rteperminfos, RangeTblEntry *rte)
 
static Planset_plan_refs (PlannerInfo *root, Plan *plan, int rtoffset)
 
static Planset_indexonlyscan_references (PlannerInfo *root, IndexOnlyScan *plan, int rtoffset)
 
static Planset_subqueryscan_references (PlannerInfo *root, SubqueryScan *plan, int rtoffset)
 
static Planclean_up_removed_plan_level (Plan *parent, Plan *child)
 
static void set_foreignscan_references (PlannerInfo *root, ForeignScan *fscan, int rtoffset)
 
static void set_customscan_references (PlannerInfo *root, CustomScan *cscan, int rtoffset)
 
static Planset_append_references (PlannerInfo *root, Append *aplan, int rtoffset)
 
static Planset_mergeappend_references (PlannerInfo *root, MergeAppend *mplan, int rtoffset)
 
static void set_hash_references (PlannerInfo *root, Plan *plan, int rtoffset)
 
static Relids offset_relid_set (Relids relids, int rtoffset)
 
static Nodefix_scan_expr (PlannerInfo *root, Node *node, int rtoffset, double num_exec)
 
static Nodefix_scan_expr_mutator (Node *node, fix_scan_expr_context *context)
 
static bool fix_scan_expr_walker (Node *node, fix_scan_expr_context *context)
 
static void set_join_references (PlannerInfo *root, Join *join, int rtoffset)
 
static void set_upper_references (PlannerInfo *root, Plan *plan, int rtoffset)
 
static void set_param_references (PlannerInfo *root, Plan *plan)
 
static Nodeconvert_combining_aggrefs (Node *node, void *context)
 
static void set_dummy_tlist_references (Plan *plan, int rtoffset)
 
static indexed_tlistbuild_tlist_index (List *tlist)
 
static Varsearch_indexed_tlist_for_var (Var *var, indexed_tlist *itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match)
 
static Varsearch_indexed_tlist_for_phv (PlaceHolderVar *phv, indexed_tlist *itlist, int newvarno, NullingRelsMatch nrm_match)
 
static Varsearch_indexed_tlist_for_non_var (Expr *node, indexed_tlist *itlist, int newvarno)
 
static Varsearch_indexed_tlist_for_sortgroupref (Expr *node, Index sortgroupref, indexed_tlist *itlist, int newvarno)
 
static Listfix_join_expr (PlannerInfo *root, List *clauses, indexed_tlist *outer_itlist, indexed_tlist *inner_itlist, Index acceptable_rel, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
 
static Nodefix_join_expr_mutator (Node *node, fix_join_expr_context *context)
 
static Nodefix_upper_expr (PlannerInfo *root, Node *node, indexed_tlist *subplan_itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
 
static Nodefix_upper_expr_mutator (Node *node, fix_upper_expr_context *context)
 
static Listset_returning_clause_references (PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, int rtoffset)
 
static Listset_windowagg_runcondition_references (PlannerInfo *root, List *runcondition, Plan *plan)
 
static void record_elided_node (PlannerGlobal *glob, int plan_node_id, NodeTag elided_type, Bitmapset *relids)
 
Planset_plan_references (PlannerInfo *root, Plan *plan)
 
bool trivial_subqueryscan (SubqueryScan *plan)
 
static int register_partpruneinfo (PlannerInfo *root, int part_prune_index, int rtoffset)
 
static VarcopyVar (Var *var)
 
static void fix_expr_common (PlannerInfo *root, Node *node)
 
static Nodefix_param_node (PlannerInfo *root, Param *p)
 
static Nodefix_alternative_subplan (PlannerInfo *root, AlternativeSubPlan *asplan, double num_exec)
 
static indexed_tlistbuild_tlist_index_other_vars (List *tlist, int ignore_rel)
 
static Nodefix_windowagg_condition_expr_mutator (Node *node, fix_windowagg_cond_context *context)
 
static Listfix_windowagg_condition_expr (PlannerInfo *root, List *runcondition, indexed_tlist *subplan_itlist)
 
Paramfind_minmax_agg_replacement_param (PlannerInfo *root, Aggref *aggref)
 
void record_plan_function_dependency (PlannerInfo *root, Oid funcid)
 
void record_plan_type_dependency (PlannerInfo *root, Oid typid)
 
void extract_query_dependencies (Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
 
bool extract_query_dependencies_walker (Node *node, PlannerInfo *context)
 

Macro Definition Documentation

◆ fix_scan_list

#define fix_scan_list (   root,
  lst,
  rtoffset,
  num_exec 
)     ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))

Definition at line 130 of file setrefs.c.

291{
292 Plan *result;
293 PlannerGlobal *glob = root->glob;
294 int rtoffset = list_length(glob->finalrtable);
295 ListCell *lc;
296
297 /*
298 * Add all the query's RTEs to the flattened rangetable. The live ones
299 * will have their rangetable indexes increased by rtoffset. (Additional
300 * RTEs, not referenced by the Plan tree, might get added after those.)
301 */
303
304 /*
305 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
306 */
307 foreach(lc, root->rowMarks)
308 {
311
312 /* sanity check on existing row marks */
313 Assert(root->simple_rel_array[rc->rti] != NULL &&
314 root->simple_rte_array[rc->rti] != NULL);
315
316 /* flat copy is enough since all fields are scalars */
318 memcpy(newrc, rc, sizeof(PlanRowMark));
319
320 /* adjust indexes ... but *not* the rowmarkId */
321 newrc->rti += rtoffset;
322 newrc->prti += rtoffset;
323
325 }
326
327 /*
328 * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
329 * We assume the AppendRelInfos were built during planning and don't need
330 * to be copied.
331 */
332 foreach(lc, root->append_rel_list)
333 {
335
336 /* adjust RT indexes */
337 appinfo->parent_relid += rtoffset;
338 appinfo->child_relid += rtoffset;
339
340 /*
341 * Rather than adjust the translated_vars entries, just drop 'em.
342 * Neither the executor nor EXPLAIN currently need that data.
343 */
344 appinfo->translated_vars = NIL;
345
347 }
348
349 /* If needed, create workspace for processing AlternativeSubPlans */
350 if (root->hasAlternativeSubPlans)
351 {
352 root->isAltSubplan = (bool *)
353 palloc0(list_length(glob->subplans) * sizeof(bool));
354 root->isUsedSubplan = (bool *)
355 palloc0(list_length(glob->subplans) * sizeof(bool));
356 }
357
358 /* Now fix the Plan tree */
359 result = set_plan_refs(root, plan, rtoffset);
360
361 /*
362 * If we have AlternativeSubPlans, it is likely that we now have some
363 * unreferenced subplans in glob->subplans. To avoid expending cycles on
364 * those subplans later, get rid of them by setting those list entries to
365 * NULL. (Note: we can't do this immediately upon processing an
366 * AlternativeSubPlan, because there may be multiple copies of the
367 * AlternativeSubPlan, and they can get resolved differently.)
368 */
369 if (root->hasAlternativeSubPlans)
370 {
371 foreach(lc, glob->subplans)
372 {
374
375 /*
376 * If it was used by some AlternativeSubPlan in this query level,
377 * but wasn't selected as best by any AlternativeSubPlan, then we
378 * don't need it. Do not touch subplans that aren't parts of
379 * AlternativeSubPlans.
380 */
381 if (root->isAltSubplan[ndx] && !root->isUsedSubplan[ndx])
382 lfirst(lc) = NULL;
383 }
384 }
385
386 return result;
387}
388
389/*
390 * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
391 *
392 * This can recurse into subquery plans; "recursing" is true if so.
393 *
394 * This also seems like a good place to add the query's RTEPermissionInfos to
395 * the flat rteperminfos.
396 */
397static void
399{
400 PlannerGlobal *glob = root->glob;
401 Index rti;
402 ListCell *lc;
403
404 /*
405 * Record enough information to make it possible for code that looks at
406 * the final range table to understand how it was constructed. (If
407 * finalrtable is still NIL, then this is the very topmost PlannerInfo,
408 * which will always have plan_name == NULL and rtoffset == 0; we omit the
409 * degenerate list entry.)
410 */
411 if (root->glob->finalrtable != NIL)
412 {
414
415 rtinfo->plan_name = root->plan_name;
416 rtinfo->rtoffset = list_length(root->glob->finalrtable);
417
418 /* When recursing = true, it's an unplanned or dummy subquery. */
419 rtinfo->dummy = recursing;
420
421 root->glob->subrtinfos = lappend(root->glob->subrtinfos, rtinfo);
422 }
423
424 /*
425 * Add the query's own RTEs to the flattened rangetable.
426 *
427 * At top level, we must add all RTEs so that their indexes in the
428 * flattened rangetable match up with their original indexes. When
429 * recursing, we only care about extracting relation RTEs (and subquery
430 * RTEs that were once relation RTEs).
431 */
432 foreach(lc, root->parse->rtable)
433 {
435
436 if (!recursing || rte->rtekind == RTE_RELATION ||
437 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
438 add_rte_to_flat_rtable(glob, root->parse->rteperminfos, rte);
439 }
440
441 /*
442 * If there are any dead subqueries, they are not referenced in the Plan
443 * tree, so we must add RTEs contained in them to the flattened rtable
444 * separately. (If we failed to do this, the executor would not perform
445 * expected permission checks for tables mentioned in such subqueries.)
446 *
447 * Note: this pass over the rangetable can't be combined with the previous
448 * one, because that would mess up the numbering of the live RTEs in the
449 * flattened rangetable.
450 */
451 rti = 1;
452 foreach(lc, root->parse->rtable)
453 {
455
456 /*
457 * We should ignore inheritance-parent RTEs: their contents have been
458 * pulled up into our rangetable already. Also ignore any subquery
459 * RTEs without matching RelOptInfos, as they likewise have been
460 * pulled up.
461 */
462 if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
463 rti < root->simple_rel_array_size)
464 {
465 RelOptInfo *rel = root->simple_rel_array[rti];
466
467 if (rel != NULL)
468 {
469 Assert(rel->relid == rti); /* sanity check on array */
470
471 /*
472 * The subquery might never have been planned at all, if it
473 * was excluded on the basis of self-contradictory constraints
474 * in our query level. In this case apply
475 * flatten_unplanned_rtes.
476 *
477 * If it was planned but the result rel is dummy, we assume
478 * that it has been omitted from our plan tree (see
479 * set_subquery_pathlist), and recurse to pull up its RTEs.
480 *
481 * Otherwise, it should be represented by a SubqueryScan node
482 * somewhere in our plan tree, and we'll pull up its RTEs when
483 * we process that plan node.
484 *
485 * However, if we're recursing, then we should pull up RTEs
486 * whether the subquery is dummy or not, because we've found
487 * that some upper query level is treating this one as dummy,
488 * and so we won't scan this level's plan tree at all.
489 */
490 if (rel->subroot == NULL)
492 else if (recursing ||
496 }
497 }
498 rti++;
499 }
500}
501
502/*
503 * Extract RangeTblEntries from a subquery that was never planned at all
504 */
505
506static void
508{
509 flatten_rtes_walker_context cxt = {glob, rte->subquery};
510
511 /* Use query_tree_walker to find all RTEs in the parse tree */
512 (void) query_tree_walker(rte->subquery,
514 &cxt,
516}
517
518static bool
520{
521 if (node == NULL)
522 return false;
523 if (IsA(node, RangeTblEntry))
524 {
525 RangeTblEntry *rte = (RangeTblEntry *) node;
526
527 /* As above, we need only save relation RTEs and former relations */
528 if (rte->rtekind == RTE_RELATION ||
529 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
530 add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
531 return false;
532 }
533 if (IsA(node, Query))
534 {
535 /*
536 * Recurse into subselects. Must update cxt->query to this query so
537 * that the rtable and rteperminfos correspond with each other.
538 */
539 Query *save_query = cxt->query;
540 bool result;
541
542 cxt->query = (Query *) node;
543 result = query_tree_walker((Query *) node,
545 cxt,
547 cxt->query = save_query;
548 return result;
549 }
551}
552
553/*
554 * Add (a copy of) the given RTE to the final rangetable and also the
555 * corresponding RTEPermissionInfo, if any, to final rteperminfos.
556 *
557 * In the flat rangetable, we zero out substructure pointers that are not
558 * needed by the executor; this reduces the storage space and copying cost
559 * for cached plans. We keep only the ctename, alias, eref Alias fields,
560 * which are needed by EXPLAIN, and perminfoindex which is needed by the
561 * executor to fetch the RTE's RTEPermissionInfo.
562 */
563static void
564add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
566{
568
569 /* flat copy to duplicate all the scalar fields */
571 memcpy(newrte, rte, sizeof(RangeTblEntry));
572
573 /* zap unneeded sub-structure */
574 newrte->tablesample = NULL;
575 newrte->subquery = NULL;
576 newrte->joinaliasvars = NIL;
577 newrte->joinleftcols = NIL;
578 newrte->joinrightcols = NIL;
579 newrte->join_using_alias = NULL;
580 newrte->functions = NIL;
581 newrte->tablefunc = NULL;
582 newrte->values_lists = NIL;
583 newrte->coltypes = NIL;
584 newrte->coltypmods = NIL;
585 newrte->colcollations = NIL;
586 newrte->groupexprs = NIL;
587 newrte->securityQuals = NIL;
588
589 glob->finalrtable = lappend(glob->finalrtable, newrte);
590
591 /*
592 * If it's a plain relation RTE (or a subquery that was once a view
593 * reference), add the relation OID to relationOids. Also add its new RT
594 * index to the set of relations to be potentially accessed during
595 * execution.
596 *
597 * We do this even though the RTE might be unreferenced in the plan tree;
598 * this would correspond to cases such as views that were expanded, child
599 * tables that were eliminated by constraint exclusion, etc. Schema
600 * invalidation on such a rel must still force rebuilding of the plan.
601 *
602 * Note we don't bother to avoid making duplicate list entries. We could,
603 * but it would probably cost more cycles than it would save.
604 */
605 if (newrte->rtekind == RTE_RELATION ||
606 (newrte->rtekind == RTE_SUBQUERY && OidIsValid(newrte->relid)))
607 {
608 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
609 glob->allRelids = bms_add_member(glob->allRelids,
610 list_length(glob->finalrtable));
611 }
612
613 /*
614 * Add a copy of the RTEPermissionInfo, if any, corresponding to this RTE
615 * to the flattened global list.
616 */
617 if (rte->perminfoindex > 0)
618 {
621
622 /* Get the existing one from this query's rteperminfos. */
623 perminfo = getRTEPermissionInfo(rteperminfos, newrte);
624
625 /*
626 * Add a new one to finalrteperminfos and copy the contents of the
627 * existing one into it. Note that addRTEPermissionInfo() also
628 * updates newrte->perminfoindex to point to newperminfo in
629 * finalrteperminfos.
630 */
631 newrte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
634 }
635}
636
637/*
638 * set_plan_refs: recurse through the Plan nodes of a single subquery level
639 */
640static Plan *
641set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
642{
643 ListCell *l;
644
645 if (plan == NULL)
646 return NULL;
647
648 /* Assign this node a unique ID. */
649 plan->plan_node_id = root->glob->lastPlanNodeId++;
650
651 /*
652 * Plan-type-specific fixes
653 */
654 switch (nodeTag(plan))
655 {
656 case T_SeqScan:
657 {
658 SeqScan *splan = (SeqScan *) plan;
659
660 splan->scan.scanrelid += rtoffset;
661 splan->scan.plan.targetlist =
662 fix_scan_list(root, splan->scan.plan.targetlist,
663 rtoffset, NUM_EXEC_TLIST(plan));
664 splan->scan.plan.qual =
665 fix_scan_list(root, splan->scan.plan.qual,
666 rtoffset, NUM_EXEC_QUAL(plan));
667 }
668 break;
669 case T_SampleScan:
670 {
671 SampleScan *splan = (SampleScan *) plan;
672
673 splan->scan.scanrelid += rtoffset;
674 splan->scan.plan.targetlist =
675 fix_scan_list(root, splan->scan.plan.targetlist,
676 rtoffset, NUM_EXEC_TLIST(plan));
677 splan->scan.plan.qual =
678 fix_scan_list(root, splan->scan.plan.qual,
679 rtoffset, NUM_EXEC_QUAL(plan));
680 splan->tablesample = (TableSampleClause *)
682 rtoffset, 1);
683 }
684 break;
685 case T_IndexScan:
686 {
687 IndexScan *splan = (IndexScan *) plan;
688
689 splan->scan.scanrelid += rtoffset;
690 splan->scan.plan.targetlist =
691 fix_scan_list(root, splan->scan.plan.targetlist,
692 rtoffset, NUM_EXEC_TLIST(plan));
693 splan->scan.plan.qual =
694 fix_scan_list(root, splan->scan.plan.qual,
695 rtoffset, NUM_EXEC_QUAL(plan));
696 splan->indexqual =
698 rtoffset, 1);
699 splan->indexqualorig =
701 rtoffset, NUM_EXEC_QUAL(plan));
702 splan->indexorderby =
704 rtoffset, 1);
705 splan->indexorderbyorig =
707 rtoffset, NUM_EXEC_QUAL(plan));
708 }
709 break;
710 case T_IndexOnlyScan:
711 {
712 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
713
714 return set_indexonlyscan_references(root, splan, rtoffset);
715 }
716 break;
718 {
720
721 splan->scan.scanrelid += rtoffset;
722 /* no need to fix targetlist and qual */
723 Assert(splan->scan.plan.targetlist == NIL);
724 Assert(splan->scan.plan.qual == NIL);
725 splan->indexqual =
726 fix_scan_list(root, splan->indexqual, rtoffset, 1);
727 splan->indexqualorig =
729 rtoffset, NUM_EXEC_QUAL(plan));
730 }
731 break;
732 case T_BitmapHeapScan:
733 {
735
736 splan->scan.scanrelid += rtoffset;
737 splan->scan.plan.targetlist =
738 fix_scan_list(root, splan->scan.plan.targetlist,
739 rtoffset, NUM_EXEC_TLIST(plan));
740 splan->scan.plan.qual =
741 fix_scan_list(root, splan->scan.plan.qual,
742 rtoffset, NUM_EXEC_QUAL(plan));
743 splan->bitmapqualorig =
745 rtoffset, NUM_EXEC_QUAL(plan));
746 }
747 break;
748 case T_TidScan:
749 {
750 TidScan *splan = (TidScan *) plan;
751
752 splan->scan.scanrelid += rtoffset;
753 splan->scan.plan.targetlist =
754 fix_scan_list(root, splan->scan.plan.targetlist,
755 rtoffset, NUM_EXEC_TLIST(plan));
756 splan->scan.plan.qual =
757 fix_scan_list(root, splan->scan.plan.qual,
758 rtoffset, NUM_EXEC_QUAL(plan));
759 splan->tidquals =
761 rtoffset, 1);
762 }
763 break;
764 case T_TidRangeScan:
765 {
766 TidRangeScan *splan = (TidRangeScan *) plan;
767
768 splan->scan.scanrelid += rtoffset;
769 splan->scan.plan.targetlist =
770 fix_scan_list(root, splan->scan.plan.targetlist,
771 rtoffset, NUM_EXEC_TLIST(plan));
772 splan->scan.plan.qual =
773 fix_scan_list(root, splan->scan.plan.qual,
774 rtoffset, NUM_EXEC_QUAL(plan));
775 splan->tidrangequals =
777 rtoffset, 1);
778 }
779 break;
780 case T_SubqueryScan:
781 /* Needs special treatment, see comments below */
783 (SubqueryScan *) plan,
784 rtoffset);
785 case T_FunctionScan:
786 {
787 FunctionScan *splan = (FunctionScan *) plan;
788
789 splan->scan.scanrelid += rtoffset;
790 splan->scan.plan.targetlist =
791 fix_scan_list(root, splan->scan.plan.targetlist,
792 rtoffset, NUM_EXEC_TLIST(plan));
793 splan->scan.plan.qual =
794 fix_scan_list(root, splan->scan.plan.qual,
795 rtoffset, NUM_EXEC_QUAL(plan));
796 splan->functions =
797 fix_scan_list(root, splan->functions, rtoffset, 1);
798 }
799 break;
800 case T_TableFuncScan:
801 {
802 TableFuncScan *splan = (TableFuncScan *) plan;
803
804 splan->scan.scanrelid += rtoffset;
805 splan->scan.plan.targetlist =
806 fix_scan_list(root, splan->scan.plan.targetlist,
807 rtoffset, NUM_EXEC_TLIST(plan));
808 splan->scan.plan.qual =
809 fix_scan_list(root, splan->scan.plan.qual,
810 rtoffset, NUM_EXEC_QUAL(plan));
811 splan->tablefunc = (TableFunc *)
812 fix_scan_expr(root, (Node *) splan->tablefunc,
813 rtoffset, 1);
814 }
815 break;
816 case T_ValuesScan:
817 {
818 ValuesScan *splan = (ValuesScan *) plan;
819
820 splan->scan.scanrelid += rtoffset;
821 splan->scan.plan.targetlist =
822 fix_scan_list(root, splan->scan.plan.targetlist,
823 rtoffset, NUM_EXEC_TLIST(plan));
824 splan->scan.plan.qual =
825 fix_scan_list(root, splan->scan.plan.qual,
826 rtoffset, NUM_EXEC_QUAL(plan));
827 splan->values_lists =
829 rtoffset, 1);
830 }
831 break;
832 case T_CteScan:
833 {
834 CteScan *splan = (CteScan *) plan;
835
836 splan->scan.scanrelid += rtoffset;
837 splan->scan.plan.targetlist =
838 fix_scan_list(root, splan->scan.plan.targetlist,
839 rtoffset, NUM_EXEC_TLIST(plan));
840 splan->scan.plan.qual =
841 fix_scan_list(root, splan->scan.plan.qual,
842 rtoffset, NUM_EXEC_QUAL(plan));
843 }
844 break;
846 {
848
849 splan->scan.scanrelid += rtoffset;
850 splan->scan.plan.targetlist =
851 fix_scan_list(root, splan->scan.plan.targetlist,
852 rtoffset, NUM_EXEC_TLIST(plan));
853 splan->scan.plan.qual =
854 fix_scan_list(root, splan->scan.plan.qual,
855 rtoffset, NUM_EXEC_QUAL(plan));
856 }
857 break;
858 case T_WorkTableScan:
859 {
860 WorkTableScan *splan = (WorkTableScan *) plan;
861
862 splan->scan.scanrelid += rtoffset;
863 splan->scan.plan.targetlist =
864 fix_scan_list(root, splan->scan.plan.targetlist,
865 rtoffset, NUM_EXEC_TLIST(plan));
866 splan->scan.plan.qual =
867 fix_scan_list(root, splan->scan.plan.qual,
868 rtoffset, NUM_EXEC_QUAL(plan));
869 }
870 break;
871 case T_ForeignScan:
873 break;
874 case T_CustomScan:
876 break;
877
878 case T_NestLoop:
879 case T_MergeJoin:
880 case T_HashJoin:
881 set_join_references(root, (Join *) plan, rtoffset);
882 break;
883
884 case T_Gather:
885 case T_GatherMerge:
886 {
887 set_upper_references(root, plan, rtoffset);
889 }
890 break;
891
892 case T_Hash:
893 set_hash_references(root, plan, rtoffset);
894 break;
895
896 case T_Memoize:
897 {
898 Memoize *mplan = (Memoize *) plan;
899
900 /*
901 * Memoize does not evaluate its targetlist. It just uses the
902 * same targetlist from its outer subnode.
903 */
905
906 mplan->param_exprs = fix_scan_list(root, mplan->param_exprs,
907 rtoffset,
909 break;
910 }
911
912 case T_Material:
913 case T_Sort:
915 case T_Unique:
916 case T_SetOp:
917
918 /*
919 * These plan types don't actually bother to evaluate their
920 * targetlists, because they just return their unmodified input
921 * tuples. Even though the targetlist won't be used by the
922 * executor, we fix it up for possible use by EXPLAIN (not to
923 * mention ease of debugging --- wrong varnos are very confusing).
924 */
926
927 /*
928 * Since these plan types don't check quals either, we should not
929 * find any qual expression attached to them.
930 */
931 Assert(plan->qual == NIL);
932 break;
933 case T_LockRows:
934 {
935 LockRows *splan = (LockRows *) plan;
936
937 /*
938 * Like the plan types above, LockRows doesn't evaluate its
939 * tlist or quals. But we have to fix up the RT indexes in
940 * its rowmarks.
941 */
943 Assert(splan->plan.qual == NIL);
944
945 foreach(l, splan->rowMarks)
946 {
947 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
948
949 rc->rti += rtoffset;
950 rc->prti += rtoffset;
951 }
952 }
953 break;
954 case T_Limit:
955 {
956 Limit *splan = (Limit *) plan;
957
958 /*
959 * Like the plan types above, Limit doesn't evaluate its tlist
960 * or quals. It does have live expressions for limit/offset,
961 * however; and those cannot contain subplan variable refs, so
962 * fix_scan_expr works for them.
963 */
965 Assert(splan->plan.qual == NIL);
966
967 splan->limitOffset =
968 fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
969 splan->limitCount =
970 fix_scan_expr(root, splan->limitCount, rtoffset, 1);
971 }
972 break;
973 case T_Agg:
974 {
975 Agg *agg = (Agg *) plan;
976
977 /*
978 * If this node is combining partial-aggregation results, we
979 * must convert its Aggrefs to contain references to the
980 * partial-aggregate subexpressions that will be available
981 * from the child plan node.
982 */
983 if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
984 {
985 plan->targetlist = (List *)
986 convert_combining_aggrefs((Node *) plan->targetlist,
987 NULL);
988 plan->qual = (List *)
990 NULL);
991 }
992
993 set_upper_references(root, plan, rtoffset);
994 }
995 break;
996 case T_Group:
997 set_upper_references(root, plan, rtoffset);
998 break;
999 case T_WindowAgg:
1000 {
1002
1003 /*
1004 * Adjust the WindowAgg's run conditions by swapping the
1005 * WindowFuncs references out to instead reference the Var in
1006 * the scan slot so that when the executor evaluates the
1007 * runCondition, it receives the WindowFunc's value from the
1008 * slot that the result has just been stored into rather than
1009 * evaluating the WindowFunc all over again.
1010 */
1012 wplan->runCondition,
1013 (Plan *) wplan);
1014
1015 set_upper_references(root, plan, rtoffset);
1016
1017 /*
1018 * Like Limit node limit/offset expressions, WindowAgg has
1019 * frame offset expressions, which cannot contain subplan
1020 * variable refs, so fix_scan_expr works for them.
1021 */
1022 wplan->startOffset =
1023 fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
1024 wplan->endOffset =
1025 fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
1026 wplan->runCondition = fix_scan_list(root,
1027 wplan->runCondition,
1028 rtoffset,
1030 wplan->runConditionOrig = fix_scan_list(root,
1031 wplan->runConditionOrig,
1032 rtoffset,
1034 }
1035 break;
1036 case T_Result:
1037 {
1038 Result *splan = (Result *) plan;
1039
1040 /*
1041 * Result may or may not have a subplan; if not, it's more
1042 * like a scan node than an upper node.
1043 */
1044 if (splan->plan.lefttree != NULL)
1045 set_upper_references(root, plan, rtoffset);
1046 else
1047 {
1048 /*
1049 * The tlist of a childless Result could contain
1050 * unresolved ROWID_VAR Vars, in case it's representing a
1051 * target relation which is completely empty because of
1052 * constraint exclusion. Replace any such Vars by null
1053 * constants, as though they'd been resolved for a leaf
1054 * scan node that doesn't support them. We could have
1055 * fix_scan_expr do this, but since the case is only
1056 * expected to occur here, it seems safer to special-case
1057 * it here and keep the assertions that ROWID_VARs
1058 * shouldn't be seen by fix_scan_expr.
1059 *
1060 * We also must handle the case where set operations have
1061 * been short-circuited resulting in a dummy Result node.
1062 * prepunion.c uses varno==0 for the set op targetlist.
1063 * See generate_setop_tlist() and generate_setop_tlist().
1064 * Here we rewrite these to use varno==1, which is the
1065 * varno of the first set-op child. Without this, EXPLAIN
1066 * will have trouble displaying targetlists of dummy set
1067 * operations.
1068 */
1069 foreach(l, splan->plan.targetlist)
1070 {
1072 Var *var = (Var *) tle->expr;
1073
1074 if (var && IsA(var, Var))
1075 {
1076 if (var->varno == ROWID_VAR)
1077 tle->expr = (Expr *) makeNullConst(var->vartype,
1078 var->vartypmod,
1079 var->varcollid);
1080 else if (var->varno == 0)
1081 tle->expr = (Expr *) makeVar(1,
1082 var->varattno,
1083 var->vartype,
1084 var->vartypmod,
1085 var->varcollid,
1086 var->varlevelsup);
1087 }
1088 }
1089
1090 splan->plan.targetlist =
1092 rtoffset, NUM_EXEC_TLIST(plan));
1093 splan->plan.qual =
1094 fix_scan_list(root, splan->plan.qual,
1095 rtoffset, NUM_EXEC_QUAL(plan));
1096 }
1097 /* resconstantqual can't contain any subplan variable refs */
1098 splan->resconstantqual =
1099 fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
1100 /* adjust the relids set */
1101 splan->relids = offset_relid_set(splan->relids, rtoffset);
1102 }
1103 break;
1104 case T_ProjectSet:
1105 set_upper_references(root, plan, rtoffset);
1106 break;
1107 case T_ModifyTable:
1108 {
1109 ModifyTable *splan = (ModifyTable *) plan;
1110 Plan *subplan = outerPlan(splan);
1111
1112 Assert(splan->plan.targetlist == NIL);
1113 Assert(splan->plan.qual == NIL);
1114
1115 splan->withCheckOptionLists =
1117 rtoffset, 1);
1118
1119 if (splan->returningLists)
1120 {
1121 List *newRL = NIL;
1122 ListCell *lcrl,
1123 *lcrr;
1124
1125 /*
1126 * Pass each per-resultrel returningList through
1127 * set_returning_clause_references().
1128 */
1130 forboth(lcrl, splan->returningLists,
1131 lcrr, splan->resultRelations)
1132 {
1133 List *rlist = (List *) lfirst(lcrl);
1135
1137 rlist,
1138 subplan,
1139 resultrel,
1140 rtoffset);
1142 }
1143 splan->returningLists = newRL;
1144
1145 /*
1146 * Set up the visible plan targetlist as being the same as
1147 * the first RETURNING list. This is mostly for the use
1148 * of EXPLAIN; the executor won't execute that targetlist,
1149 * although it does use it to prepare the node's result
1150 * tuple slot. We postpone this step until here so that
1151 * we don't have to do set_returning_clause_references()
1152 * twice on identical targetlists.
1153 */
1155 }
1156
1157 /*
1158 * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
1159 * join', where the inner side is the EXCLUDED tuple.
1160 * Therefore use fix_join_expr to setup the relevant variables
1161 * to INNER_VAR. We explicitly don't create any OUTER_VARs as
1162 * those are already used by RETURNING and it seems better to
1163 * be non-conflicting.
1164 */
1165 if (splan->onConflictAction == ONCONFLICT_UPDATE ||
1167 {
1169
1171
1172 splan->onConflictSet =
1174 NULL, itlist,
1176 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1177
1178 splan->onConflictWhere = (Node *)
1180 NULL, itlist,
1182 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1183
1184 pfree(itlist);
1185
1186 splan->exclRelTlist =
1187 fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
1188 }
1189
1190 /*
1191 * The MERGE statement produces the target rows by performing
1192 * a right join between the target relation and the source
1193 * relation (which could be a plain relation or a subquery).
1194 * The INSERT and UPDATE actions of the MERGE statement
1195 * require access to the columns from the source relation. We
1196 * arrange things so that the source relation attributes are
1197 * available as INNER_VAR and the target relation attributes
1198 * are available from the scan tuple.
1199 */
1200 if (splan->mergeActionLists != NIL)
1201 {
1202 List *newMJC = NIL;
1203 ListCell *lca,
1204 *lcj,
1205 *lcr;
1206
1207 /*
1208 * Fix the targetList of individual action nodes so that
1209 * the so-called "source relation" Vars are referenced as
1210 * INNER_VAR. Note that for this to work correctly during
1211 * execution, the ecxt_innertuple must be set to the tuple
1212 * obtained by executing the subplan, which is what
1213 * constitutes the "source relation".
1214 *
1215 * We leave the Vars from the result relation (i.e. the
1216 * target relation) unchanged i.e. those Vars would be
1217 * picked from the scan slot. So during execution, we must
1218 * ensure that ecxt_scantuple is setup correctly to refer
1219 * to the tuple from the target relation.
1220 */
1222
1224
1226 lcj, splan->mergeJoinConditions,
1227 lcr, splan->resultRelations)
1228 {
1229 List *mergeActionList = lfirst(lca);
1230 Node *mergeJoinCondition = lfirst(lcj);
1232
1233 foreach(l, mergeActionList)
1234 {
1236
1237 /* Fix targetList of each action. */
1238 action->targetList = fix_join_expr(root,
1239 action->targetList,
1240 NULL, itlist,
1241 resultrel,
1242 rtoffset,
1243 NRM_EQUAL,
1245
1246 /* Fix quals too. */
1247 action->qual = (Node *) fix_join_expr(root,
1248 (List *) action->qual,
1249 NULL, itlist,
1250 resultrel,
1251 rtoffset,
1252 NRM_EQUAL,
1254 }
1255
1256 /* Fix join condition too. */
1257 mergeJoinCondition = (Node *)
1259 (List *) mergeJoinCondition,
1260 NULL, itlist,
1261 resultrel,
1262 rtoffset,
1263 NRM_EQUAL,
1265 newMJC = lappend(newMJC, mergeJoinCondition);
1266 }
1267 splan->mergeJoinConditions = newMJC;
1268 }
1269
1270 splan->nominalRelation += rtoffset;
1271 if (splan->rootRelation)
1272 splan->rootRelation += rtoffset;
1273 splan->exclRelRTI += rtoffset;
1274
1275 foreach(l, splan->resultRelations)
1276 {
1277 lfirst_int(l) += rtoffset;
1278 }
1279 foreach(l, splan->rowMarks)
1280 {
1281 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1282
1283 rc->rti += rtoffset;
1284 rc->prti += rtoffset;
1285 }
1286
1287 /*
1288 * Append this ModifyTable node's final result relation RT
1289 * index(es) to the global list for the plan.
1290 */
1291 root->glob->resultRelations =
1292 list_concat(root->glob->resultRelations,
1293 splan->resultRelations);
1294 if (splan->rootRelation)
1295 {
1296 root->glob->resultRelations =
1297 lappend_int(root->glob->resultRelations,
1298 splan->rootRelation);
1299 }
1300 }
1301 break;
1302 case T_Append:
1303 /* Needs special treatment, see comments below */
1305 (Append *) plan,
1306 rtoffset);
1307 case T_MergeAppend:
1308 /* Needs special treatment, see comments below */
1310 (MergeAppend *) plan,
1311 rtoffset);
1312 case T_RecursiveUnion:
1313 /* This doesn't evaluate targetlist or check quals either */
1315 Assert(plan->qual == NIL);
1316 break;
1317 case T_BitmapAnd:
1318 {
1319 BitmapAnd *splan = (BitmapAnd *) plan;
1320
1321 /* BitmapAnd works like Append, but has no tlist */
1322 Assert(splan->plan.targetlist == NIL);
1323 Assert(splan->plan.qual == NIL);
1324 foreach(l, splan->bitmapplans)
1325 {
1327 (Plan *) lfirst(l),
1328 rtoffset);
1329 }
1330 }
1331 break;
1332 case T_BitmapOr:
1333 {
1334 BitmapOr *splan = (BitmapOr *) plan;
1335
1336 /* BitmapOr works like Append, but has no tlist */
1337 Assert(splan->plan.targetlist == NIL);
1338 Assert(splan->plan.qual == NIL);
1339 foreach(l, splan->bitmapplans)
1340 {
1342 (Plan *) lfirst(l),
1343 rtoffset);
1344 }
1345 }
1346 break;
1347 default:
1348 elog(ERROR, "unrecognized node type: %d",
1349 (int) nodeTag(plan));
1350 break;
1351 }
1352
1353 /*
1354 * Now recurse into child plans, if any
1355 *
1356 * NOTE: it is essential that we recurse into child plans AFTER we set
1357 * subplan references in this plan's tlist and quals. If we did the
1358 * reference-adjustments bottom-up, then we would fail to match this
1359 * plan's var nodes against the already-modified nodes of the children.
1360 */
1361 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1362 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1363
1364 return plan;
1365}
1366
1367/*
1368 * set_indexonlyscan_references
1369 * Do set_plan_references processing on an IndexOnlyScan
1370 *
1371 * This is unlike the handling of a plain IndexScan because we have to
1372 * convert Vars referencing the heap into Vars referencing the index.
1373 * We can use the fix_upper_expr machinery for that, by working from a
1374 * targetlist describing the index columns.
1375 */
1376static Plan *
1379 int rtoffset)
1380{
1383 ListCell *lc;
1384
1385 /*
1386 * Vars in the plan node's targetlist, qual, and recheckqual must only
1387 * reference columns that the index AM can actually return. To ensure
1388 * this, remove non-returnable columns (which are marked as resjunk) from
1389 * the indexed tlist. We can just drop them because the indexed_tlist
1390 * machinery pays attention to TLE resnos, not physical list position.
1391 */
1393 foreach(lc, plan->indextlist)
1394 {
1396
1397 if (!indextle->resjunk)
1399 }
1400
1402
1403 plan->scan.scanrelid += rtoffset;
1404 plan->scan.plan.targetlist = (List *)
1406 (Node *) plan->scan.plan.targetlist,
1408 INDEX_VAR,
1409 rtoffset,
1410 NRM_EQUAL,
1411 NUM_EXEC_TLIST((Plan *) plan));
1412 plan->scan.plan.qual = (List *)
1414 (Node *) plan->scan.plan.qual,
1416 INDEX_VAR,
1417 rtoffset,
1418 NRM_EQUAL,
1419 NUM_EXEC_QUAL((Plan *) plan));
1420 plan->recheckqual = (List *)
1422 (Node *) plan->recheckqual,
1424 INDEX_VAR,
1425 rtoffset,
1426 NRM_EQUAL,
1427 NUM_EXEC_QUAL((Plan *) plan));
1428 /* indexqual is already transformed to reference index columns */
1429 plan->indexqual = fix_scan_list(root, plan->indexqual,
1430 rtoffset, 1);
1431 /* indexorderby is already transformed to reference index columns */
1432 plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1433 rtoffset, 1);
1434 /* indextlist must NOT be transformed to reference index columns */
1435 plan->indextlist = fix_scan_list(root, plan->indextlist,
1436 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1437
1439
1440 return (Plan *) plan;
1441}
1442
1443/*
1444 * set_subqueryscan_references
1445 * Do set_plan_references processing on a SubqueryScan
1446 *
1447 * We try to strip out the SubqueryScan entirely; if we can't, we have
1448 * to do the normal processing on it.
1449 */
1450static Plan *
1453 int rtoffset)
1454{
1455 RelOptInfo *rel;
1456 Plan *result;
1457
1458 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1459 rel = find_base_rel(root, plan->scan.scanrelid);
1460
1461 /* Recursively process the subplan */
1462 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1463
1465 {
1466 Index scanrelid;
1467
1468 /*
1469 * We can omit the SubqueryScan node and just pull up the subplan.
1470 */
1472
1473 /* Remember that we removed a SubqueryScan */
1474 scanrelid = plan->scan.scanrelid + rtoffset;
1475 record_elided_node(root->glob, plan->subplan->plan_node_id,
1477 }
1478 else
1479 {
1480 /*
1481 * Keep the SubqueryScan node. We have to do the processing that
1482 * set_plan_references would otherwise have done on it. Notice we do
1483 * not do set_upper_references() here, because a SubqueryScan will
1484 * always have been created with correct references to its subplan's
1485 * outputs to begin with.
1486 */
1487 plan->scan.scanrelid += rtoffset;
1488 plan->scan.plan.targetlist =
1489 fix_scan_list(root, plan->scan.plan.targetlist,
1490 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1491 plan->scan.plan.qual =
1492 fix_scan_list(root, plan->scan.plan.qual,
1493 rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1494
1495 result = (Plan *) plan;
1496 }
1497
1498 return result;
1499}
1500
1501/*
1502 * trivial_subqueryscan
1503 * Detect whether a SubqueryScan can be deleted from the plan tree.
1504 *
1505 * We can delete it if it has no qual to check and the targetlist just
1506 * regurgitates the output of the child plan.
1507 *
1508 * This can be called from mark_async_capable_plan(), a helper function for
1509 * create_append_plan(), before set_subqueryscan_references(), to determine
1510 * triviality of a SubqueryScan that is a child of an Append node. So we
1511 * cache the result in the SubqueryScan node to avoid repeated computation.
1512 *
1513 * Note: when called from mark_async_capable_plan(), we determine the result
1514 * before running finalize_plan() on the SubqueryScan node (if needed) and
1515 * set_plan_references() on the subplan tree, but this would be safe, because
1516 * 1) finalize_plan() doesn't modify the tlist or quals for the SubqueryScan
1517 * node (or that for any plan node in the subplan tree), and
1518 * 2) set_plan_references() modifies the tlist for every plan node in the
1519 * subplan tree, but keeps const/resjunk columns as const/resjunk ones and
1520 * preserves the length and order of the tlist, and
1521 * 3) set_plan_references() might delete the topmost plan node like an Append
1522 * or MergeAppend from the subplan tree and pull up the child plan node,
1523 * but in that case, the tlist for the child plan node exactly matches the
1524 * parent.
1525 */
1526bool
1528{
1529 int attrno;
1530 ListCell *lp,
1531 *lc;
1532
1533 /* We might have detected this already; in which case reuse the result */
1534 if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1535 return true;
1536 if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1537 return false;
1538 Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1539 /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1540 plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1541
1542 if (plan->scan.plan.qual != NIL)
1543 return false;
1544
1545 if (list_length(plan->scan.plan.targetlist) !=
1546 list_length(plan->subplan->targetlist))
1547 return false; /* tlists not same length */
1548
1549 attrno = 1;
1550 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1551 {
1554
1555 if (ptle->resjunk != ctle->resjunk)
1556 return false; /* tlist doesn't match junk status */
1557
1558 /*
1559 * We accept either a Var referencing the corresponding element of the
1560 * subplan tlist, or a Const equaling the subplan element. See
1561 * generate_setop_tlist() for motivation.
1562 */
1563 if (ptle->expr && IsA(ptle->expr, Var))
1564 {
1565 Var *var = (Var *) ptle->expr;
1566
1567 Assert(var->varno == plan->scan.scanrelid);
1568 Assert(var->varlevelsup == 0);
1569 if (var->varattno != attrno)
1570 return false; /* out of order */
1571 }
1572 else if (ptle->expr && IsA(ptle->expr, Const))
1573 {
1574 if (!equal(ptle->expr, ctle->expr))
1575 return false;
1576 }
1577 else
1578 return false;
1579
1580 attrno++;
1581 }
1582
1583 /* Re-mark the SubqueryScan as deletable from the plan tree */
1584 plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1585
1586 return true;
1587}
1588
1589/*
1590 * clean_up_removed_plan_level
1591 * Do necessary cleanup when we strip out a SubqueryScan, Append, etc
1592 *
1593 * We are dropping the "parent" plan in favor of returning just its "child".
1594 * A few small tweaks are needed.
1595 */
1596static Plan *
1597clean_up_removed_plan_level(Plan *parent, Plan *child)
1598{
1599 /*
1600 * We have to be sure we don't lose any initplans, so move any that were
1601 * attached to the parent plan to the child. If any are parallel-unsafe,
1602 * the child is no longer parallel-safe. As a cosmetic matter, also add
1603 * the initplans' run costs to the child's costs.
1604 */
1605 if (parent->initPlan)
1606 {
1608 bool unsafe_initplans;
1609
1612 child->startup_cost += initplan_cost;
1613 child->total_cost += initplan_cost;
1614 if (unsafe_initplans)
1615 child->parallel_safe = false;
1616
1617 /*
1618 * Attach plans this way so that parent's initplans are processed
1619 * before any pre-existing initplans of the child. Probably doesn't
1620 * matter, but let's preserve the ordering just in case.
1621 */
1622 child->initPlan = list_concat(parent->initPlan,
1623 child->initPlan);
1624 }
1625
1626 /*
1627 * We also have to transfer the parent's column labeling info into the
1628 * child, else columns sent to client will be improperly labeled if this
1629 * is the topmost plan level. resjunk and so on may be important too.
1630 */
1632
1633 return child;
1634}
1635
1636/*
1637 * set_foreignscan_references
1638 * Do set_plan_references processing on a ForeignScan
1639 */
1640static void
1643 int rtoffset)
1644{
1645 /* Adjust scanrelid if it's valid */
1646 if (fscan->scan.scanrelid > 0)
1647 fscan->scan.scanrelid += rtoffset;
1648
1649 if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1650 {
1651 /*
1652 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1653 * foreign scan tuple
1654 */
1655 indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
1656
1657 fscan->scan.plan.targetlist = (List *)
1659 (Node *) fscan->scan.plan.targetlist,
1660 itlist,
1661 INDEX_VAR,
1662 rtoffset,
1663 NRM_EQUAL,
1665 fscan->scan.plan.qual = (List *)
1667 (Node *) fscan->scan.plan.qual,
1668 itlist,
1669 INDEX_VAR,
1670 rtoffset,
1671 NRM_EQUAL,
1672 NUM_EXEC_QUAL((Plan *) fscan));
1673 fscan->fdw_exprs = (List *)
1675 (Node *) fscan->fdw_exprs,
1676 itlist,
1677 INDEX_VAR,
1678 rtoffset,
1679 NRM_EQUAL,
1680 NUM_EXEC_QUAL((Plan *) fscan));
1681 fscan->fdw_recheck_quals = (List *)
1683 (Node *) fscan->fdw_recheck_quals,
1684 itlist,
1685 INDEX_VAR,
1686 rtoffset,
1687 NRM_EQUAL,
1688 NUM_EXEC_QUAL((Plan *) fscan));
1689 pfree(itlist);
1690 /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1691 fscan->fdw_scan_tlist =
1692 fix_scan_list(root, fscan->fdw_scan_tlist,
1693 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1694 }
1695 else
1696 {
1697 /*
1698 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1699 * way
1700 */
1701 fscan->scan.plan.targetlist =
1702 fix_scan_list(root, fscan->scan.plan.targetlist,
1703 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1704 fscan->scan.plan.qual =
1705 fix_scan_list(root, fscan->scan.plan.qual,
1706 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1707 fscan->fdw_exprs =
1708 fix_scan_list(root, fscan->fdw_exprs,
1709 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1710 fscan->fdw_recheck_quals =
1711 fix_scan_list(root, fscan->fdw_recheck_quals,
1712 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1713 }
1714
1715 fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1716 fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1717
1718 /* Adjust resultRelation if it's valid */
1719 if (fscan->resultRelation > 0)
1720 fscan->resultRelation += rtoffset;
1721}
1722
1723/*
1724 * set_customscan_references
1725 * Do set_plan_references processing on a CustomScan
1726 */
1727static void
1730 int rtoffset)
1731{
1732 ListCell *lc;
1733
1734 /* Adjust scanrelid if it's valid */
1735 if (cscan->scan.scanrelid > 0)
1736 cscan->scan.scanrelid += rtoffset;
1737
1738 if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1739 {
1740 /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1741 indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
1742
1743 cscan->scan.plan.targetlist = (List *)
1745 (Node *) cscan->scan.plan.targetlist,
1746 itlist,
1747 INDEX_VAR,
1748 rtoffset,
1749 NRM_EQUAL,
1751 cscan->scan.plan.qual = (List *)
1753 (Node *) cscan->scan.plan.qual,
1754 itlist,
1755 INDEX_VAR,
1756 rtoffset,
1757 NRM_EQUAL,
1758 NUM_EXEC_QUAL((Plan *) cscan));
1759 cscan->custom_exprs = (List *)
1761 (Node *) cscan->custom_exprs,
1762 itlist,
1763 INDEX_VAR,
1764 rtoffset,
1765 NRM_EQUAL,
1766 NUM_EXEC_QUAL((Plan *) cscan));
1767 pfree(itlist);
1768 /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1769 cscan->custom_scan_tlist =
1770 fix_scan_list(root, cscan->custom_scan_tlist,
1771 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1772 }
1773 else
1774 {
1775 /* Adjust tlist, qual, custom_exprs in the standard way */
1776 cscan->scan.plan.targetlist =
1777 fix_scan_list(root, cscan->scan.plan.targetlist,
1778 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1779 cscan->scan.plan.qual =
1780 fix_scan_list(root, cscan->scan.plan.qual,
1781 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1782 cscan->custom_exprs =
1783 fix_scan_list(root, cscan->custom_exprs,
1784 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1785 }
1786
1787 /* Adjust child plan-nodes recursively, if needed */
1788 foreach(lc, cscan->custom_plans)
1789 {
1790 lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1791 }
1792
1793 cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1794}
1795
1796/*
1797 * register_partpruneinfo
1798 * Subroutine for set_append_references and set_mergeappend_references
1799 *
1800 * Add the PartitionPruneInfo from root->partPruneInfos at the given index
1801 * into PlannerGlobal->partPruneInfos and return its index there.
1802 *
1803 * Also update the RT indexes present in PartitionedRelPruneInfos to add the
1804 * offset.
1805 *
1806 * Finally, if there are initial pruning steps, add the RT indexes of the
1807 * leaf partitions to the set of relations that are prunable at execution
1808 * startup time.
1809 */
1810static int
1811register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
1812{
1813 PlannerGlobal *glob = root->glob;
1814 PartitionPruneInfo *pinfo;
1815 ListCell *l;
1816
1817 Assert(part_prune_index >= 0 &&
1818 part_prune_index < list_length(root->partPruneInfos));
1819 pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
1820 part_prune_index);
1821
1822 pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
1823 foreach(l, pinfo->prune_infos)
1824 {
1825 List *prune_infos = lfirst(l);
1826 ListCell *l2;
1827
1828 foreach(l2, prune_infos)
1829 {
1831 int i;
1832
1833 prelinfo->rtindex += rtoffset;
1834 prelinfo->initial_pruning_steps =
1835 fix_scan_list(root, prelinfo->initial_pruning_steps,
1836 rtoffset, 1);
1837 prelinfo->exec_pruning_steps =
1838 fix_scan_list(root, prelinfo->exec_pruning_steps,
1839 rtoffset, 1);
1840
1841 for (i = 0; i < prelinfo->nparts; i++)
1842 {
1843 /*
1844 * Non-leaf partitions and partitions that do not have a
1845 * subplan are not included in this map as mentioned in
1846 * make_partitionedrel_pruneinfo().
1847 */
1848 if (prelinfo->leafpart_rti_map[i])
1849 {
1850 prelinfo->leafpart_rti_map[i] += rtoffset;
1851 if (prelinfo->initial_pruning_steps)
1853 prelinfo->leafpart_rti_map[i]);
1854 }
1855 }
1856 }
1857 }
1858
1859 glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
1860
1861 return list_length(glob->partPruneInfos) - 1;
1862}
1863
1864/*
1865 * set_append_references
1866 * Do set_plan_references processing on an Append
1867 *
1868 * We try to strip out the Append entirely; if we can't, we have
1869 * to do the normal processing on it.
1870 */
1871static Plan *
1873 Append *aplan,
1874 int rtoffset)
1875{
1876 ListCell *l;
1877
1878 /*
1879 * Append, like Sort et al, doesn't actually evaluate its targetlist or
1880 * check quals. If it's got exactly one child plan, then it's not doing
1881 * anything useful at all, and we can strip it out.
1882 */
1883 Assert(aplan->plan.qual == NIL);
1884
1885 /* First, we gotta recurse on the children */
1886 foreach(l, aplan->appendplans)
1887 {
1888 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1889 }
1890
1891 /*
1892 * See if it's safe to get rid of the Append entirely. For this to be
1893 * safe, there must be only one child plan and that child plan's parallel
1894 * awareness must match the Append's. The reason for the latter is that
1895 * if the Append is parallel aware and the child is not, then the calling
1896 * plan may execute the non-parallel aware child multiple times. (If you
1897 * change these rules, update create_append_path to match.)
1898 */
1899 if (list_length(aplan->appendplans) == 1)
1900 {
1901 Plan *p = (Plan *) linitial(aplan->appendplans);
1902
1903 if (p->parallel_aware == aplan->plan.parallel_aware)
1904 {
1905 Plan *result;
1906
1908
1909 /* Remember that we removed an Append */
1911 offset_relid_set(aplan->apprelids, rtoffset));
1912
1913 return result;
1914 }
1915 }
1916
1917 /*
1918 * Otherwise, clean up the Append as needed. It's okay to do this after
1919 * recursing to the children, because set_dummy_tlist_references doesn't
1920 * look at those.
1921 */
1922 set_dummy_tlist_references((Plan *) aplan, rtoffset);
1923
1924 aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1925
1926 /*
1927 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1928 * Also update the RT indexes present in it to add the offset.
1929 */
1930 if (aplan->part_prune_index >= 0)
1931 aplan->part_prune_index =
1932 register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
1933
1934 /* We don't need to recurse to lefttree or righttree ... */
1935 Assert(aplan->plan.lefttree == NULL);
1936 Assert(aplan->plan.righttree == NULL);
1937
1938 return (Plan *) aplan;
1939}
1940
1941/*
1942 * set_mergeappend_references
1943 * Do set_plan_references processing on a MergeAppend
1944 *
1945 * We try to strip out the MergeAppend entirely; if we can't, we have
1946 * to do the normal processing on it.
1947 */
1948static Plan *
1951 int rtoffset)
1952{
1953 ListCell *l;
1954
1955 /*
1956 * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1957 * or check quals. If it's got exactly one child plan, then it's not
1958 * doing anything useful at all, and we can strip it out.
1959 */
1960 Assert(mplan->plan.qual == NIL);
1961
1962 /* First, we gotta recurse on the children */
1963 foreach(l, mplan->mergeplans)
1964 {
1965 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1966 }
1967
1968 /*
1969 * See if it's safe to get rid of the MergeAppend entirely. For this to
1970 * be safe, there must be only one child plan and that child plan's
1971 * parallel awareness must match the MergeAppend's. The reason for the
1972 * latter is that if the MergeAppend is parallel aware and the child is
1973 * not, then the calling plan may execute the non-parallel aware child
1974 * multiple times. (If you change these rules, update
1975 * create_merge_append_path to match.)
1976 */
1977 if (list_length(mplan->mergeplans) == 1)
1978 {
1979 Plan *p = (Plan *) linitial(mplan->mergeplans);
1980
1981 if (p->parallel_aware == mplan->plan.parallel_aware)
1982 {
1983 Plan *result;
1984
1986
1987 /* Remember that we removed a MergeAppend */
1989 offset_relid_set(mplan->apprelids, rtoffset));
1990
1991 return result;
1992 }
1993 }
1994
1995 /*
1996 * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1997 * after recursing to the children, because set_dummy_tlist_references
1998 * doesn't look at those.
1999 */
2000 set_dummy_tlist_references((Plan *) mplan, rtoffset);
2001
2002 mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
2003
2004 /*
2005 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
2006 * Also update the RT indexes present in it to add the offset.
2007 */
2008 if (mplan->part_prune_index >= 0)
2009 mplan->part_prune_index =
2010 register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
2011
2012 /* We don't need to recurse to lefttree or righttree ... */
2013 Assert(mplan->plan.lefttree == NULL);
2014 Assert(mplan->plan.righttree == NULL);
2015
2016 return (Plan *) mplan;
2017}
2018
2019/*
2020 * set_hash_references
2021 * Do set_plan_references processing on a Hash node
2022 */
2023static void
2025{
2026 Hash *hplan = (Hash *) plan;
2027 Plan *outer_plan = plan->lefttree;
2028 indexed_tlist *outer_itlist;
2029
2030 /*
2031 * Hash's hashkeys are used when feeding tuples into the hashtable,
2032 * therefore have them reference Hash's outer plan (which itself is the
2033 * inner plan of the HashJoin).
2034 */
2035 outer_itlist = build_tlist_index(outer_plan->targetlist);
2036 hplan->hashkeys = (List *)
2038 (Node *) hplan->hashkeys,
2039 outer_itlist,
2040 OUTER_VAR,
2041 rtoffset,
2042 NRM_EQUAL,
2044
2045 /* Hash doesn't project */
2047
2048 /* Hash nodes don't have their own quals */
2049 Assert(plan->qual == NIL);
2050}
2051
2052/*
2053 * offset_relid_set
2054 * Apply rtoffset to the members of a Relids set.
2055 */
2056static Relids
2057offset_relid_set(Relids relids, int rtoffset)
2058{
2059 Relids result = NULL;
2060 int rtindex;
2061
2062 /* If there's no offset to apply, we needn't recompute the value */
2063 if (rtoffset == 0)
2064 return relids;
2065 rtindex = -1;
2066 while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
2067 result = bms_add_member(result, rtindex + rtoffset);
2068 return result;
2069}
2070
2071/*
2072 * copyVar
2073 * Copy a Var node.
2074 *
2075 * fix_scan_expr and friends do this enough times that it's worth having
2076 * a bespoke routine instead of using the generic copyObject() function.
2077 */
2078static inline Var *
2079copyVar(Var *var)
2080{
2082
2083 *newvar = *var;
2084 return newvar;
2085}
2086
2087/*
2088 * fix_expr_common
2089 * Do generic set_plan_references processing on an expression node
2090 *
2091 * This is code that is common to all variants of expression-fixing.
2092 * We must look up operator opcode info for OpExpr and related nodes,
2093 * add OIDs from regclass Const nodes into root->glob->relationOids, and
2094 * add PlanInvalItems for user-defined functions into root->glob->invalItems.
2095 * We also fill in column index lists for GROUPING() expressions.
2096 *
2097 * We assume it's okay to update opcode info in-place. So this could possibly
2098 * scribble on the planner's input data structures, but it's OK.
2099 */
2100static void
2102{
2103 /* We assume callers won't call us on a NULL pointer */
2104 if (IsA(node, Aggref))
2105 {
2107 ((Aggref *) node)->aggfnoid);
2108 }
2109 else if (IsA(node, WindowFunc))
2110 {
2112 ((WindowFunc *) node)->winfnoid);
2113 }
2114 else if (IsA(node, FuncExpr))
2115 {
2117 ((FuncExpr *) node)->funcid);
2118 }
2119 else if (IsA(node, OpExpr))
2120 {
2121 set_opfuncid((OpExpr *) node);
2123 ((OpExpr *) node)->opfuncid);
2124 }
2125 else if (IsA(node, DistinctExpr))
2126 {
2127 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2129 ((DistinctExpr *) node)->opfuncid);
2130 }
2131 else if (IsA(node, NullIfExpr))
2132 {
2133 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2135 ((NullIfExpr *) node)->opfuncid);
2136 }
2137 else if (IsA(node, ScalarArrayOpExpr))
2138 {
2139 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2140
2141 set_sa_opfuncid(saop);
2142 record_plan_function_dependency(root, saop->opfuncid);
2143
2144 if (OidIsValid(saop->hashfuncid))
2145 record_plan_function_dependency(root, saop->hashfuncid);
2146
2147 if (OidIsValid(saop->negfuncid))
2148 record_plan_function_dependency(root, saop->negfuncid);
2149 }
2150 else if (IsA(node, Const))
2151 {
2152 Const *con = (Const *) node;
2153
2154 /* Check for regclass reference */
2155 if (ISREGCLASSCONST(con))
2156 root->glob->relationOids =
2157 lappend_oid(root->glob->relationOids,
2158 DatumGetObjectId(con->constvalue));
2159 }
2160 else if (IsA(node, GroupingFunc))
2161 {
2162 GroupingFunc *g = (GroupingFunc *) node;
2163 AttrNumber *grouping_map = root->grouping_map;
2164
2165 /* If there are no grouping sets, we don't need this. */
2166
2167 Assert(grouping_map || g->cols == NIL);
2168
2169 if (grouping_map)
2170 {
2171 ListCell *lc;
2172 List *cols = NIL;
2173
2174 foreach(lc, g->refs)
2175 {
2176 cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2177 }
2178
2179 Assert(!g->cols || equal(cols, g->cols));
2180
2181 if (!g->cols)
2182 g->cols = cols;
2183 }
2184 }
2185}
2186
2187/*
2188 * fix_param_node
2189 * Do set_plan_references processing on a Param
2190 *
2191 * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
2192 * root->multiexpr_params; otherwise no change is needed.
2193 * Just for paranoia's sake, we make a copy of the node in either case.
2194 */
2195static Node *
2197{
2198 if (p->paramkind == PARAM_MULTIEXPR)
2199 {
2200 int subqueryid = p->paramid >> 16;
2201 int colno = p->paramid & 0xFFFF;
2202 List *params;
2203
2204 if (subqueryid <= 0 ||
2205 subqueryid > list_length(root->multiexpr_params))
2206 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2207 params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2209 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2210 return copyObject(list_nth(params, colno - 1));
2211 }
2212 return (Node *) copyObject(p);
2213}
2214
2215/*
2216 * fix_alternative_subplan
2217 * Do set_plan_references processing on an AlternativeSubPlan
2218 *
2219 * Choose one of the alternative implementations and return just that one,
2220 * discarding the rest of the AlternativeSubPlan structure.
2221 * Note: caller must still recurse into the result!
2222 *
2223 * We don't make any attempt to fix up cost estimates in the parent plan
2224 * node or higher-level nodes.
2225 */
2226static Node *
2228 double num_exec)
2229{
2231 Cost bestcost = 0;
2232 ListCell *lc;
2233
2234 /*
2235 * Compute the estimated cost of each subplan assuming num_exec
2236 * executions, and keep the cheapest one. If one subplan has more
2237 * disabled nodes than another, choose the one with fewer disabled nodes
2238 * regardless of cost; this parallels compare_path_costs. In event of
2239 * exact equality of estimates, we prefer the later plan; this is a bit
2240 * arbitrary, but in current usage it biases us to break ties against
2241 * fast-start subplans.
2242 */
2243 Assert(asplan->subplans != NIL);
2244
2245 foreach(lc, asplan->subplans)
2246 {
2248 Cost curcost;
2249
2250 curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
2251 if (bestplan == NULL ||
2252 curplan->disabled_nodes < bestplan->disabled_nodes ||
2253 (curplan->disabled_nodes == bestplan->disabled_nodes &&
2254 curcost <= bestcost))
2255 {
2256 bestplan = curplan;
2257 bestcost = curcost;
2258 }
2259
2260 /* Also mark all subplans that are in AlternativeSubPlans */
2261 root->isAltSubplan[curplan->plan_id - 1] = true;
2262 }
2263
2264 /* Mark the subplan we selected */
2265 root->isUsedSubplan[bestplan->plan_id - 1] = true;
2266
2267 return (Node *) bestplan;
2268}
2269
2270/*
2271 * fix_scan_expr
2272 * Do set_plan_references processing on a scan-level expression
2273 *
2274 * This consists of incrementing all Vars' varnos by rtoffset,
2275 * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
2276 * replacing Aggref nodes that should be replaced by initplan output Params,
2277 * choosing the best implementation for AlternativeSubPlans,
2278 * looking up operator opcode info for OpExpr and related nodes,
2279 * and adding OIDs from regclass Const nodes into root->glob->relationOids.
2280 *
2281 * 'node': the expression to be modified
2282 * 'rtoffset': how much to increment varnos by
2283 * 'num_exec': estimated number of executions of expression
2284 *
2285 * The expression tree is either copied-and-modified, or modified in-place
2286 * if that seems safe.
2287 */
2288static Node *
2289fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
2290{
2291 fix_scan_expr_context context;
2292
2293 context.root = root;
2294 context.rtoffset = rtoffset;
2295 context.num_exec = num_exec;
2296
2297 if (rtoffset != 0 ||
2298 root->multiexpr_params != NIL ||
2299 root->glob->lastPHId != 0 ||
2300 root->minmax_aggs != NIL ||
2301 root->hasAlternativeSubPlans)
2302 {
2303 return fix_scan_expr_mutator(node, &context);
2304 }
2305 else
2306 {
2307 /*
2308 * If rtoffset == 0, we don't need to change any Vars, and if there
2309 * are no MULTIEXPR subqueries then we don't need to replace
2310 * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2311 * we won't need to remove them, and if there are no minmax Aggrefs we
2312 * won't need to replace them, and if there are no AlternativeSubPlans
2313 * we won't need to remove them. Then it's OK to just scribble on the
2314 * input node tree instead of copying (since the only change, filling
2315 * in any unset opfuncid fields, is harmless). This saves just enough
2316 * cycles to be noticeable on trivial queries.
2317 */
2318 (void) fix_scan_expr_walker(node, &context);
2319 return node;
2320 }
2321}
2322
2323static Node *
2325{
2326 if (node == NULL)
2327 return NULL;
2328 if (IsA(node, Var))
2329 {
2330 Var *var = copyVar((Var *) node);
2331
2332 Assert(var->varlevelsup == 0);
2333
2334 /*
2335 * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2336 * But an indexqual expression could contain INDEX_VAR Vars.
2337 */
2338 Assert(var->varno != INNER_VAR);
2339 Assert(var->varno != OUTER_VAR);
2340 Assert(var->varno != ROWID_VAR);
2341 if (!IS_SPECIAL_VARNO(var->varno))
2342 var->varno += context->rtoffset;
2343 if (var->varnosyn > 0)
2344 var->varnosyn += context->rtoffset;
2345 return (Node *) var;
2346 }
2347 if (IsA(node, Param))
2348 return fix_param_node(context->root, (Param *) node);
2349 if (IsA(node, Aggref))
2350 {
2351 Aggref *aggref = (Aggref *) node;
2352 Param *aggparam;
2353
2354 /* See if the Aggref should be replaced by a Param */
2356 if (aggparam != NULL)
2357 {
2358 /* Make a copy of the Param for paranoia's sake */
2359 return (Node *) copyObject(aggparam);
2360 }
2361 /* If no match, just fall through to process it normally */
2362 }
2363 if (IsA(node, CurrentOfExpr))
2364 {
2365 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2366
2367 Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2368 cexpr->cvarno += context->rtoffset;
2369 return (Node *) cexpr;
2370 }
2371 if (IsA(node, PlaceHolderVar))
2372 {
2373 /* At scan level, we should always just evaluate the contained expr */
2374 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2375
2376 /* XXX can we assert something about phnullingrels? */
2377 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2378 }
2379 if (IsA(node, AlternativeSubPlan))
2381 (AlternativeSubPlan *) node,
2382 context->num_exec),
2383 context);
2384 fix_expr_common(context->root, node);
2385 return expression_tree_mutator(node, fix_scan_expr_mutator, context);
2386}
2387
2388static bool
2390{
2391 if (node == NULL)
2392 return false;
2393 Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
2394 Assert(!IsA(node, PlaceHolderVar));
2395 Assert(!IsA(node, AlternativeSubPlan));
2396 fix_expr_common(context->root, node);
2397 return expression_tree_walker(node, fix_scan_expr_walker, context);
2398}
2399
2400/*
2401 * set_join_references
2402 * Modify the target list and quals of a join node to reference its
2403 * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
2404 * attno values to the result domain number of either the corresponding
2405 * outer or inner join tuple item. Also perform opcode lookup for these
2406 * expressions, and add regclass OIDs to root->glob->relationOids.
2407 */
2408static void
2409set_join_references(PlannerInfo *root, Join *join, int rtoffset)
2410{
2411 Plan *outer_plan = join->plan.lefttree;
2412 Plan *inner_plan = join->plan.righttree;
2413 indexed_tlist *outer_itlist;
2414 indexed_tlist *inner_itlist;
2415
2416 outer_itlist = build_tlist_index(outer_plan->targetlist);
2417 inner_itlist = build_tlist_index(inner_plan->targetlist);
2418
2419 /*
2420 * First process the joinquals (including merge or hash clauses). These
2421 * are logically below the join so they can always use all values
2422 * available from the input tlists. It's okay to also handle
2423 * NestLoopParams now, because those couldn't refer to nullable
2424 * subexpressions.
2425 */
2426 join->joinqual = fix_join_expr(root,
2427 join->joinqual,
2428 outer_itlist,
2429 inner_itlist,
2430 (Index) 0,
2431 rtoffset,
2432 NRM_EQUAL,
2433 NUM_EXEC_QUAL((Plan *) join));
2434
2435 /* Now do join-type-specific stuff */
2436 if (IsA(join, NestLoop))
2437 {
2438 NestLoop *nl = (NestLoop *) join;
2439 ListCell *lc;
2440
2441 foreach(lc, nl->nestParams)
2442 {
2444
2445 /*
2446 * Because we don't reparameterize parameterized paths to match
2447 * the outer-join level at which they are used, Vars seen in the
2448 * NestLoopParam expression may have nullingrels that are just a
2449 * subset of those in the Vars actually available from the outer
2450 * side. (Lateral references can also cause this, as explained in
2451 * the comments for identify_current_nestloop_params.) Not
2452 * checking this exactly is a bit grotty, but the work needed to
2453 * make things match up perfectly seems well out of proportion to
2454 * the value.
2455 */
2457 (Node *) nlp->paramval,
2458 outer_itlist,
2459 OUTER_VAR,
2460 rtoffset,
2461 NRM_SUBSET,
2462 NUM_EXEC_TLIST(outer_plan));
2463 /* Check we replaced any PlaceHolderVar with simple Var */
2464 if (!(IsA(nlp->paramval, Var) &&
2465 nlp->paramval->varno == OUTER_VAR))
2466 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2467 }
2468 }
2469 else if (IsA(join, MergeJoin))
2470 {
2471 MergeJoin *mj = (MergeJoin *) join;
2472
2474 mj->mergeclauses,
2475 outer_itlist,
2476 inner_itlist,
2477 (Index) 0,
2478 rtoffset,
2479 NRM_EQUAL,
2480 NUM_EXEC_QUAL((Plan *) join));
2481 }
2482 else if (IsA(join, HashJoin))
2483 {
2484 HashJoin *hj = (HashJoin *) join;
2485
2487 hj->hashclauses,
2488 outer_itlist,
2489 inner_itlist,
2490 (Index) 0,
2491 rtoffset,
2492 NRM_EQUAL,
2493 NUM_EXEC_QUAL((Plan *) join));
2494
2495 /*
2496 * HashJoin's hashkeys are used to look for matching tuples from its
2497 * outer plan (not the Hash node!) in the hashtable.
2498 */
2499 hj->hashkeys = (List *) fix_upper_expr(root,
2500 (Node *) hj->hashkeys,
2501 outer_itlist,
2502 OUTER_VAR,
2503 rtoffset,
2504 NRM_EQUAL,
2505 NUM_EXEC_QUAL((Plan *) join));
2506 }
2507
2508 /*
2509 * Now we need to fix up the targetlist and qpqual, which are logically
2510 * above the join. This means that, if it's not an inner join, any Vars
2511 * and PHVs appearing here should have nullingrels that include the
2512 * effects of the outer join, ie they will have nullingrels equal to the
2513 * input Vars' nullingrels plus the bit added by the outer join. We don't
2514 * currently have enough info available here to identify what that should
2515 * be, so we just tell fix_join_expr to accept superset nullingrels
2516 * matches instead of exact ones.
2517 */
2518 join->plan.targetlist = fix_join_expr(root,
2519 join->plan.targetlist,
2520 outer_itlist,
2521 inner_itlist,
2522 (Index) 0,
2523 rtoffset,
2525 NUM_EXEC_TLIST((Plan *) join));
2526 join->plan.qual = fix_join_expr(root,
2527 join->plan.qual,
2528 outer_itlist,
2529 inner_itlist,
2530 (Index) 0,
2531 rtoffset,
2533 NUM_EXEC_QUAL((Plan *) join));
2534
2535 pfree(outer_itlist);
2536 pfree(inner_itlist);
2537}
2538
2539/*
2540 * set_upper_references
2541 * Update the targetlist and quals of an upper-level plan node
2542 * to refer to the tuples returned by its lefttree subplan.
2543 * Also perform opcode lookup for these expressions, and
2544 * add regclass OIDs to root->glob->relationOids.
2545 *
2546 * This is used for single-input plan types like Agg, Group, Result.
2547 *
2548 * In most cases, we have to match up individual Vars in the tlist and
2549 * qual expressions with elements of the subplan's tlist (which was
2550 * generated by flattening these selfsame expressions, so it should have all
2551 * the required variables). There is an important exception, however:
2552 * depending on where we are in the plan tree, sort/group columns may have
2553 * been pushed into the subplan tlist unflattened. If these values are also
2554 * needed in the output then we want to reference the subplan tlist element
2555 * rather than recomputing the expression.
2556 */
2557static void
2559{
2560 Plan *subplan = plan->lefttree;
2561 indexed_tlist *subplan_itlist;
2563 ListCell *l;
2564
2565 subplan_itlist = build_tlist_index(subplan->targetlist);
2566
2567 /*
2568 * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2569 * in the targetlist and quals should have nullingrels that include the
2570 * effects of the grouping step, ie they will have nullingrels equal to
2571 * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2572 * step. In order to perform exact nullingrels matches, we remove the RT
2573 * index of the grouping step first.
2574 */
2575 if (IsA(plan, Agg) &&
2576 root->group_rtindex > 0 &&
2577 ((Agg *) plan)->groupingSets)
2578 {
2579 plan->targetlist = (List *)
2580 remove_nulling_relids((Node *) plan->targetlist,
2581 bms_make_singleton(root->group_rtindex),
2582 NULL);
2583 plan->qual = (List *)
2585 bms_make_singleton(root->group_rtindex),
2586 NULL);
2587 }
2588
2590 foreach(l, plan->targetlist)
2591 {
2593 Node *newexpr;
2594
2595 /* If it's a sort/group item, first try to match by sortref */
2596 if (tle->ressortgroupref != 0)
2597 {
2598 newexpr = (Node *)
2600 tle->ressortgroupref,
2601 subplan_itlist,
2602 OUTER_VAR);
2603 if (!newexpr)
2605 (Node *) tle->expr,
2606 subplan_itlist,
2607 OUTER_VAR,
2608 rtoffset,
2609 NRM_EQUAL,
2611 }
2612 else
2614 (Node *) tle->expr,
2615 subplan_itlist,
2616 OUTER_VAR,
2617 rtoffset,
2618 NRM_EQUAL,
2621 tle->expr = (Expr *) newexpr;
2623 }
2624 plan->targetlist = output_targetlist;
2625
2626 plan->qual = (List *)
2628 (Node *) plan->qual,
2629 subplan_itlist,
2630 OUTER_VAR,
2631 rtoffset,
2632 NRM_EQUAL,
2634
2635 pfree(subplan_itlist);
2636}
2637
2638/*
2639 * set_param_references
2640 * Initialize the initParam list in Gather or Gather merge node such that
2641 * it contains reference of all the params that needs to be evaluated
2642 * before execution of the node. It contains the initplan params that are
2643 * being passed to the plan nodes below it.
2644 */
2645static void
2647{
2649
2650 if (plan->lefttree->extParam)
2651 {
2654 ListCell *l;
2655
2656 for (proot = root; proot != NULL; proot = proot->parent_root)
2657 {
2658 foreach(l, proot->init_plans)
2659 {
2661 ListCell *l2;
2662
2663 foreach(l2, initsubplan->setParam)
2664 {
2666 }
2667 }
2668 }
2669
2670 /*
2671 * Remember the list of all external initplan params that are used by
2672 * the children of Gather or Gather merge node.
2673 */
2674 if (IsA(plan, Gather))
2675 ((Gather *) plan)->initParam =
2676 bms_intersect(plan->lefttree->extParam, initSetParam);
2677 else
2678 ((GatherMerge *) plan)->initParam =
2679 bms_intersect(plan->lefttree->extParam, initSetParam);
2680 }
2681}
2682
2683/*
2684 * Recursively scan an expression tree and convert Aggrefs to the proper
2685 * intermediate form for combining aggregates. This means (1) replacing each
2686 * one's argument list with a single argument that is the original Aggref
2687 * modified to show partial aggregation and (2) changing the upper Aggref to
2688 * show combining aggregation.
2689 *
2690 * After this step, set_upper_references will replace the partial Aggrefs
2691 * with Vars referencing the lower Agg plan node's outputs, so that the final
2692 * form seen by the executor is a combining Aggref with a Var as input.
2693 *
2694 * It's rather messy to postpone this step until setrefs.c; ideally it'd be
2695 * done in createplan.c. The difficulty is that once we modify the Aggref
2696 * expressions, they will no longer be equal() to their original form and
2697 * so cross-plan-node-level matches will fail. So this has to happen after
2698 * the plan node above the Agg has resolved its subplan references.
2699 */
2700static Node *
2701convert_combining_aggrefs(Node *node, void *context)
2702{
2703 if (node == NULL)
2704 return NULL;
2705 if (IsA(node, Aggref))
2706 {
2707 Aggref *orig_agg = (Aggref *) node;
2710
2711 /* Assert we've not chosen to partial-ize any unsupported cases */
2712 Assert(orig_agg->aggorder == NIL);
2713 Assert(orig_agg->aggdistinct == NIL);
2714
2715 /*
2716 * Since aggregate calls can't be nested, we needn't recurse into the
2717 * arguments. But for safety, flat-copy the Aggref node itself rather
2718 * than modifying it in-place.
2719 */
2721 memcpy(child_agg, orig_agg, sizeof(Aggref));
2722
2723 /*
2724 * For the parent Aggref, we want to copy all the fields of the
2725 * original aggregate *except* the args list, which we'll replace
2726 * below, and the aggfilter expression, which should be applied only
2727 * by the child not the parent. Rather than explicitly knowing about
2728 * all the other fields here, we can momentarily modify child_agg to
2729 * provide a suitable source for copyObject.
2730 */
2731 child_agg->args = NIL;
2732 child_agg->aggfilter = NULL;
2734 child_agg->args = orig_agg->args;
2735 child_agg->aggfilter = orig_agg->aggfilter;
2736
2737 /*
2738 * Now, set up child_agg to represent the first phase of partial
2739 * aggregation. For now, assume serialization is required.
2740 */
2742
2743 /*
2744 * And set up parent_agg to represent the second phase.
2745 */
2747 1, NULL, false));
2749
2750 return (Node *) parent_agg;
2751 }
2753}
2754
2755/*
2756 * set_dummy_tlist_references
2757 * Replace the targetlist of an upper-level plan node with a simple
2758 * list of OUTER_VAR references to its child.
2759 *
2760 * This is used for plan types like Sort and Append that don't evaluate
2761 * their targetlists. Although the executor doesn't care at all what's in
2762 * the tlist, EXPLAIN needs it to be realistic.
2763 *
2764 * Note: we could almost use set_upper_references() here, but it fails for
2765 * Append for lack of a lefttree subplan. Single-purpose code is faster
2766 * anyway.
2767 */
2768static void
2769set_dummy_tlist_references(Plan *plan, int rtoffset)
2770{
2772 ListCell *l;
2773
2775 foreach(l, plan->targetlist)
2776 {
2778 Var *oldvar = (Var *) tle->expr;
2779 Var *newvar;
2780
2781 /*
2782 * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2783 * as Consts, not Vars referencing Consts. Here, there's no speed
2784 * advantage to be had, but it makes EXPLAIN output look cleaner, and
2785 * again it avoids confusing the executor.
2786 */
2787 if (IsA(oldvar, Const))
2788 {
2789 /* just reuse the existing TLE node */
2791 continue;
2792 }
2793
2795 tle->resno,
2796 exprType((Node *) oldvar),
2797 exprTypmod((Node *) oldvar),
2799 0);
2800 if (IsA(oldvar, Var) &&
2801 oldvar->varnosyn > 0)
2802 {
2803 newvar->varnosyn = oldvar->varnosyn + rtoffset;
2804 newvar->varattnosyn = oldvar->varattnosyn;
2805 }
2806 else
2807 {
2808 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2809 newvar->varattnosyn = 0;
2810 }
2811
2813 tle->expr = (Expr *) newvar;
2815 }
2816 plan->targetlist = output_targetlist;
2817
2818 /* We don't touch plan->qual here */
2819}
2820
2821
2822/*
2823 * build_tlist_index --- build an index data structure for a child tlist
2824 *
2825 * In most cases, subplan tlists will be "flat" tlists with only Vars,
2826 * so we try to optimize that case by extracting information about Vars
2827 * in advance. Matching a parent tlist to a child is still an O(N^2)
2828 * operation, but at least with a much smaller constant factor than plain
2829 * tlist_member() searches.
2830 *
2831 * The result of this function is an indexed_tlist struct to pass to
2832 * search_indexed_tlist_for_var() and siblings.
2833 * When done, the indexed_tlist may be freed with a single pfree().
2834 */
2835static indexed_tlist *
2836build_tlist_index(List *tlist)
2837{
2840 ListCell *l;
2841
2842 /* Create data structure with enough slots for all tlist entries */
2843 itlist = (indexed_tlist *)
2845 list_length(tlist) * sizeof(tlist_vinfo));
2846
2847 itlist->tlist = tlist;
2848 itlist->has_ph_vars = false;
2849 itlist->has_non_vars = false;
2850
2851 /* Find the Vars and fill in the index array */
2852 vinfo = itlist->vars;
2853 foreach(l, tlist)
2854 {
2856
2857 if (tle->expr && IsA(tle->expr, Var))
2858 {
2859 Var *var = (Var *) tle->expr;
2860
2861 vinfo->varno = var->varno;
2862 vinfo->varattno = var->varattno;
2863 vinfo->resno = tle->resno;
2864 vinfo->varnullingrels = var->varnullingrels;
2865 vinfo++;
2866 }
2867 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2868 itlist->has_ph_vars = true;
2869 else
2870 itlist->has_non_vars = true;
2871 }
2872
2873 itlist->num_vars = (vinfo - itlist->vars);
2874
2875 return itlist;
2876}
2877
2878/*
2879 * build_tlist_index_other_vars --- build a restricted tlist index
2880 *
2881 * This is like build_tlist_index, but we only index tlist entries that
2882 * are Vars belonging to some rel other than the one specified. We will set
2883 * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
2884 * (so nothing other than Vars and PlaceHolderVars can be matched).
2885 */
2886static indexed_tlist *
2888{
2891 ListCell *l;
2892
2893 /* Create data structure with enough slots for all tlist entries */
2894 itlist = (indexed_tlist *)
2896 list_length(tlist) * sizeof(tlist_vinfo));
2897
2898 itlist->tlist = tlist;
2899 itlist->has_ph_vars = false;
2900 itlist->has_non_vars = false;
2901
2902 /* Find the desired Vars and fill in the index array */
2903 vinfo = itlist->vars;
2904 foreach(l, tlist)
2905 {
2907
2908 if (tle->expr && IsA(tle->expr, Var))
2909 {
2910 Var *var = (Var *) tle->expr;
2911
2912 if (var->varno != ignore_rel)
2913 {
2914 vinfo->varno = var->varno;
2915 vinfo->varattno = var->varattno;
2916 vinfo->resno = tle->resno;
2917 vinfo->varnullingrels = var->varnullingrels;
2918 vinfo++;
2919 }
2920 }
2921 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2922 itlist->has_ph_vars = true;
2923 }
2924
2925 itlist->num_vars = (vinfo - itlist->vars);
2926
2927 return itlist;
2928}
2929
2930/*
2931 * search_indexed_tlist_for_var --- find a Var in an indexed tlist
2932 *
2933 * If a match is found, return a copy of the given Var with suitably
2934 * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
2935 * Also ensure that varnosyn is incremented by rtoffset.
2936 * If no match, return NULL.
2937 *
2938 * We cross-check the varnullingrels of the subplan output Var based on
2939 * nrm_match. Most call sites should pass NRM_EQUAL indicating we expect
2940 * an exact match. However, there are places where we haven't cleaned
2941 * things up completely, and we have to settle for allowing subset or
2942 * superset matches.
2943 */
2944static Var *
2946 int newvarno, int rtoffset,
2947 NullingRelsMatch nrm_match)
2948{
2949 int varno = var->varno;
2950 AttrNumber varattno = var->varattno;
2952 int i;
2953
2954 vinfo = itlist->vars;
2955 i = itlist->num_vars;
2956 while (i-- > 0)
2957 {
2958 if (vinfo->varno == varno && vinfo->varattno == varattno)
2959 {
2960 /* Found a match */
2961 Var *newvar = copyVar(var);
2962
2963 /*
2964 * Verify that we kept all the nullingrels machinations straight.
2965 *
2966 * XXX we skip the check for system columns and whole-row Vars.
2967 * That's because such Vars might be row identity Vars, which are
2968 * generated without any varnullingrels. It'd be hard to do
2969 * otherwise, since they're normally made very early in planning,
2970 * when we haven't looked at the jointree yet and don't know which
2971 * joins might null such Vars. Doesn't seem worth the expense to
2972 * make them fully valid. (While it's slightly annoying that we
2973 * thereby lose checking for user-written references to such
2974 * columns, it seems unlikely that a bug in nullingrels logic
2975 * would affect only system columns.)
2976 */
2977 if (!(varattno <= 0 ||
2978 (nrm_match == NRM_SUBSET ?
2979 bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2980 nrm_match == NRM_SUPERSET ?
2981 bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2982 bms_equal(vinfo->varnullingrels, var->varnullingrels))))
2983 elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2984 bmsToString(var->varnullingrels),
2985 bmsToString(vinfo->varnullingrels),
2986 varno, varattno);
2987
2988 newvar->varno = newvarno;
2989 newvar->varattno = vinfo->resno;
2990 if (newvar->varnosyn > 0)
2991 newvar->varnosyn += rtoffset;
2992 return newvar;
2993 }
2994 vinfo++;
2995 }
2996 return NULL; /* no match */
2997}
2998
2999/*
3000 * search_indexed_tlist_for_phv --- find a PlaceHolderVar in an indexed tlist
3001 *
3002 * If a match is found, return a Var constructed to reference the tlist item.
3003 * If no match, return NULL.
3004 *
3005 * Cross-check phnullingrels as in search_indexed_tlist_for_var.
3006 *
3007 * NOTE: it is a waste of time to call this unless itlist->has_ph_vars.
3008 */
3009static Var *
3011 indexed_tlist *itlist, int newvarno,
3012 NullingRelsMatch nrm_match)
3013{
3014 ListCell *lc;
3015
3016 foreach(lc, itlist->tlist)
3017 {
3019
3020 if (tle->expr && IsA(tle->expr, PlaceHolderVar))
3021 {
3023 Var *newvar;
3024
3025 /*
3026 * Analogously to search_indexed_tlist_for_var, we match on phid
3027 * only. We don't use equal(), partially for speed but mostly
3028 * because phnullingrels might not be exactly equal.
3029 */
3030 if (phv->phid != subphv->phid)
3031 continue;
3032
3033 /* Verify that we kept all the nullingrels machinations straight */
3034 if (!(nrm_match == NRM_SUBSET ?
3035 bms_is_subset(phv->phnullingrels, subphv->phnullingrels) :
3036 nrm_match == NRM_SUPERSET ?
3037 bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
3038 bms_equal(subphv->phnullingrels, phv->phnullingrels)))
3039 elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
3040 bmsToString(phv->phnullingrels),
3041 bmsToString(subphv->phnullingrels),
3042 phv->phid);
3043
3044 /* Found a matching subplan output expression */
3045 newvar = makeVarFromTargetEntry(newvarno, tle);
3046 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3047 newvar->varattnosyn = 0;
3048 return newvar;
3049 }
3050 }
3051 return NULL; /* no match */
3052}
3053
3054/*
3055 * search_indexed_tlist_for_non_var --- find a non-Var/PHV in an indexed tlist
3056 *
3057 * If a match is found, return a Var constructed to reference the tlist item.
3058 * If no match, return NULL.
3059 *
3060 * NOTE: it is a waste of time to call this unless itlist->has_non_vars.
3061 */
3062static Var *
3064 indexed_tlist *itlist, int newvarno)
3065{
3067
3068 /*
3069 * If it's a simple Const, replacing it with a Var is silly, even if there
3070 * happens to be an identical Const below; a Var is more expensive to
3071 * execute than a Const. What's more, replacing it could confuse some
3072 * places in the executor that expect to see simple Consts for, eg,
3073 * dropped columns.
3074 */
3075 if (IsA(node, Const))
3076 return NULL;
3077
3078 tle = tlist_member(node, itlist->tlist);
3079 if (tle)
3080 {
3081 /* Found a matching subplan output expression */
3082 Var *newvar;
3083
3084 newvar = makeVarFromTargetEntry(newvarno, tle);
3085 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3086 newvar->varattnosyn = 0;
3087 return newvar;
3088 }
3089 return NULL; /* no match */
3090}
3091
3092/*
3093 * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
3094 *
3095 * If a match is found, return a Var constructed to reference the tlist item.
3096 * If no match, return NULL.
3097 *
3098 * This is needed to ensure that we select the right subplan TLE in cases
3099 * where there are multiple textually-equal()-but-volatile sort expressions.
3100 * And it's also faster than search_indexed_tlist_for_non_var.
3101 */
3102static Var *
3104 Index sortgroupref,
3106 int newvarno)
3107{
3108 ListCell *lc;
3109
3110 foreach(lc, itlist->tlist)
3111 {
3113
3114 /*
3115 * Usually the equal() check is redundant, but in setop plans it may
3116 * not be, since prepunion.c assigns ressortgroupref equal to the
3117 * column resno without regard to whether that matches the topmost
3118 * level's sortgrouprefs and without regard to whether any implicit
3119 * coercions are added in the setop tree. We might have to clean that
3120 * up someday; but for now, just ignore any false matches.
3121 */
3122 if (tle->ressortgroupref == sortgroupref &&
3123 equal(node, tle->expr))
3124 {
3125 /* Found a matching subplan output expression */
3126 Var *newvar;
3127
3128 newvar = makeVarFromTargetEntry(newvarno, tle);
3129 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3130 newvar->varattnosyn = 0;
3131 return newvar;
3132 }
3133 }
3134 return NULL; /* no match */
3135}
3136
3137/*
3138 * fix_join_expr
3139 * Create a new set of targetlist entries or join qual clauses by
3140 * changing the varno/varattno values of variables in the clauses
3141 * to reference target list values from the outer and inner join
3142 * relation target lists. Also perform opcode lookup and add
3143 * regclass OIDs to root->glob->relationOids.
3144 *
3145 * This is used in four different scenarios:
3146 * 1) a normal join clause, where all the Vars in the clause *must* be
3147 * replaced by OUTER_VAR or INNER_VAR references. In this case
3148 * acceptable_rel should be zero so that any failure to match a Var will be
3149 * reported as an error.
3150 * 2) RETURNING clauses, which may contain both Vars of the target relation
3151 * and Vars of other relations. In this case we want to replace the
3152 * other-relation Vars by OUTER_VAR references, while leaving target Vars
3153 * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
3154 * target relation should be passed.
3155 * 3) ON CONFLICT SET and WHERE clauses. Here references to EXCLUDED are
3156 * to be replaced with INNER_VAR references, while leaving target Vars (the
3157 * to-be-updated relation) alone. Correspondingly inner_itlist is to be
3158 * EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
3159 * relation.
3160 * 4) MERGE. In this case, references to the source relation are to be
3161 * replaced with INNER_VAR references, leaving Vars of the target
3162 * relation (the to-be-modified relation) alone. So inner_itlist is to be
3163 * the source relation elements, outer_itlist = NULL and acceptable_rel
3164 * the target relation.
3165 *
3166 * 'clauses' is the targetlist or list of join clauses
3167 * 'outer_itlist' is the indexed target list of the outer join relation,
3168 * or NULL
3169 * 'inner_itlist' is the indexed target list of the inner join relation,
3170 * or NULL
3171 * 'acceptable_rel' is either zero or the rangetable index of a relation
3172 * whose Vars may appear in the clause without provoking an error
3173 * 'rtoffset': how much to increment varnos by
3174 * 'nrm_match': as for search_indexed_tlist_for_var()
3175 * 'num_exec': estimated number of executions of expression
3176 *
3177 * Returns the new expression tree. The original clause structure is
3178 * not modified.
3179 */
3180static List *
3182 List *clauses,
3183 indexed_tlist *outer_itlist,
3184 indexed_tlist *inner_itlist,
3185 Index acceptable_rel,
3186 int rtoffset,
3187 NullingRelsMatch nrm_match,
3188 double num_exec)
3189{
3190 fix_join_expr_context context;
3191
3192 context.root = root;
3193 context.outer_itlist = outer_itlist;
3194 context.inner_itlist = inner_itlist;
3195 context.acceptable_rel = acceptable_rel;
3196 context.rtoffset = rtoffset;
3197 context.nrm_match = nrm_match;
3198 context.num_exec = num_exec;
3199 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3200}
3201
3202static Node *
3204{
3205 Var *newvar;
3206
3207 if (node == NULL)
3208 return NULL;
3209 if (IsA(node, Var))
3210 {
3211 Var *var = (Var *) node;
3212
3213 /*
3214 * Verify that Vars with non-default varreturningtype only appear in
3215 * the RETURNING list, and refer to the target relation.
3216 */
3218 {
3219 if (context->inner_itlist != NULL ||
3220 context->outer_itlist == NULL ||
3221 context->acceptable_rel == 0)
3222 elog(ERROR, "variable returning old/new found outside RETURNING list");
3223 if (var->varno != context->acceptable_rel)
3224 elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
3225 var->varno, context->acceptable_rel);
3226 }
3227
3228 /* Look for the var in the input tlists, first in the outer */
3229 if (context->outer_itlist)
3230 {
3232 context->outer_itlist,
3233 OUTER_VAR,
3234 context->rtoffset,
3235 context->nrm_match);
3236 if (newvar)
3237 return (Node *) newvar;
3238 }
3239
3240 /* then in the inner. */
3241 if (context->inner_itlist)
3242 {
3244 context->inner_itlist,
3245 INNER_VAR,
3246 context->rtoffset,
3247 context->nrm_match);
3248 if (newvar)
3249 return (Node *) newvar;
3250 }
3251
3252 /* If it's for acceptable_rel, adjust and return it */
3253 if (var->varno == context->acceptable_rel)
3254 {
3255 var = copyVar(var);
3256 var->varno += context->rtoffset;
3257 if (var->varnosyn > 0)
3258 var->varnosyn += context->rtoffset;
3259 return (Node *) var;
3260 }
3261
3262 /* No referent found for Var */
3263 elog(ERROR, "variable not found in subplan target lists");
3264 }
3265 if (IsA(node, PlaceHolderVar))
3266 {
3267 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3268
3269 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3270 if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3271 {
3273 context->outer_itlist,
3274 OUTER_VAR,
3275 context->nrm_match);
3276 if (newvar)
3277 return (Node *) newvar;
3278 }
3279 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3280 {
3282 context->inner_itlist,
3283 INNER_VAR,
3284 context->nrm_match);
3285 if (newvar)
3286 return (Node *) newvar;
3287 }
3288
3289 /* If not supplied by input plans, evaluate the contained expr */
3290 /* XXX can we assert something about phnullingrels? */
3291 return fix_join_expr_mutator((Node *) phv->phexpr, context);
3292 }
3293 /* Try matching more complex expressions too, if tlists have any */
3294 if (context->outer_itlist && context->outer_itlist->has_non_vars)
3295 {
3297 context->outer_itlist,
3298 OUTER_VAR);
3299 if (newvar)
3300 return (Node *) newvar;
3301 }
3302 if (context->inner_itlist && context->inner_itlist->has_non_vars)
3303 {
3305 context->inner_itlist,
3306 INNER_VAR);
3307 if (newvar)
3308 return (Node *) newvar;
3309 }
3310 /* Special cases (apply only AFTER failing to match to lower tlist) */
3311 if (IsA(node, Param))
3312 return fix_param_node(context->root, (Param *) node);
3313 if (IsA(node, AlternativeSubPlan))
3315 (AlternativeSubPlan *) node,
3316 context->num_exec),
3317 context);
3318 fix_expr_common(context->root, node);
3319 return expression_tree_mutator(node, fix_join_expr_mutator, context);
3320}
3321
3322/*
3323 * fix_upper_expr
3324 * Modifies an expression tree so that all Var nodes reference outputs
3325 * of a subplan. Also looks for Aggref nodes that should be replaced
3326 * by initplan output Params. Also performs opcode lookup, and adds
3327 * regclass OIDs to root->glob->relationOids.
3328 *
3329 * This is used to fix up target and qual expressions of non-join upper-level
3330 * plan nodes, as well as index-only scan nodes.
3331 *
3332 * An error is raised if no matching var can be found in the subplan tlist
3333 * --- so this routine should only be applied to nodes whose subplans'
3334 * targetlists were generated by flattening the expressions used in the
3335 * parent node.
3336 *
3337 * If itlist->has_non_vars is true, then we try to match whole subexpressions
3338 * against elements of the subplan tlist, so that we can avoid recomputing
3339 * expressions that were already computed by the subplan. (This is relatively
3340 * expensive, so we don't want to try it in the common case where the
3341 * subplan tlist is just a flattened list of Vars.)
3342 *
3343 * 'node': the tree to be fixed (a target item or qual)
3344 * 'subplan_itlist': indexed target list for subplan (or index)
3345 * 'newvarno': varno to use for Vars referencing tlist elements
3346 * 'rtoffset': how much to increment varnos by
3347 * 'nrm_match': as for search_indexed_tlist_for_var()
3348 * 'num_exec': estimated number of executions of expression
3349 *
3350 * The resulting tree is a copy of the original in which all Var nodes have
3351 * varno = newvarno, varattno = resno of corresponding targetlist element.
3352 * The original tree is not modified.
3353 */
3354static Node *
3356 Node *node,
3357 indexed_tlist *subplan_itlist,
3358 int newvarno,
3359 int rtoffset,
3360 NullingRelsMatch nrm_match,
3361 double num_exec)
3362{
3363 fix_upper_expr_context context;
3364
3365 context.root = root;
3366 context.subplan_itlist = subplan_itlist;
3367 context.newvarno = newvarno;
3368 context.rtoffset = rtoffset;
3369 context.nrm_match = nrm_match;
3370 context.num_exec = num_exec;
3371 return fix_upper_expr_mutator(node, &context);
3372}
3373
3374static Node *
3376{
3377 Var *newvar;
3378
3379 if (node == NULL)
3380 return NULL;
3381 if (IsA(node, Var))
3382 {
3383 Var *var = (Var *) node;
3384
3386 context->subplan_itlist,
3387 context->newvarno,
3388 context->rtoffset,
3389 context->nrm_match);
3390 if (!newvar)
3391 elog(ERROR, "variable not found in subplan target list");
3392 return (Node *) newvar;
3393 }
3394 if (IsA(node, PlaceHolderVar))
3395 {
3396 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3397
3398 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3399 if (context->subplan_itlist->has_ph_vars)
3400 {
3402 context->subplan_itlist,
3403 context->newvarno,
3404 context->nrm_match);
3405 if (newvar)
3406 return (Node *) newvar;
3407 }
3408 /* If not supplied by input plan, evaluate the contained expr */
3409 /* XXX can we assert something about phnullingrels? */
3410 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3411 }
3412 /* Try matching more complex expressions too, if tlist has any */
3413 if (context->subplan_itlist->has_non_vars)
3414 {
3416 context->subplan_itlist,
3417 context->newvarno);
3418 if (newvar)
3419 return (Node *) newvar;
3420 }
3421 /* Special cases (apply only AFTER failing to match to lower tlist) */
3422 if (IsA(node, Param))
3423 return fix_param_node(context->root, (Param *) node);
3424 if (IsA(node, Aggref))
3425 {
3426 Aggref *aggref = (Aggref *) node;
3427 Param *aggparam;
3428
3429 /* See if the Aggref should be replaced by a Param */
3431 if (aggparam != NULL)
3432 {
3433 /* Make a copy of the Param for paranoia's sake */
3434 return (Node *) copyObject(aggparam);
3435 }
3436 /* If no match, just fall through to process it normally */
3437 }
3438 if (IsA(node, AlternativeSubPlan))
3440 (AlternativeSubPlan *) node,
3441 context->num_exec),
3442 context);
3443 fix_expr_common(context->root, node);
3444 return expression_tree_mutator(node, fix_upper_expr_mutator, context);
3445}
3446
3447/*
3448 * set_returning_clause_references
3449 * Perform setrefs.c's work on a RETURNING targetlist
3450 *
3451 * If the query involves more than just the result table, we have to
3452 * adjust any Vars that refer to other tables to reference junk tlist
3453 * entries in the top subplan's targetlist. Vars referencing the result
3454 * table should be left alone, however (the executor will evaluate them
3455 * using the actual heap tuple, after firing triggers if any). In the
3456 * adjusted RETURNING list, result-table Vars will have their original
3457 * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
3458 *
3459 * We also must perform opcode lookup and add regclass OIDs to
3460 * root->glob->relationOids.
3461 *
3462 * 'rlist': the RETURNING targetlist to be fixed
3463 * 'topplan': the top subplan node that will be just below the ModifyTable
3464 * node (note it's not yet passed through set_plan_refs)
3465 * 'resultRelation': RT index of the associated result relation
3466 * 'rtoffset': how much to increment varnos by
3467 *
3468 * Note: the given 'root' is for the parent query level, not the 'topplan'.
3469 * This does not matter currently since we only access the dependency-item
3470 * lists in root->glob, but it would need some hacking if we wanted a root
3471 * that actually matches the subplan.
3472 *
3473 * Note: resultRelation is not yet adjusted by rtoffset.
3474 */
3475static List *
3477 List *rlist,
3478 Plan *topplan,
3479 Index resultRelation,
3480 int rtoffset)
3481{
3483
3484 /*
3485 * We can perform the desired Var fixup by abusing the fix_join_expr
3486 * machinery that formerly handled inner indexscan fixup. We search the
3487 * top plan's targetlist for Vars of non-result relations, and use
3488 * fix_join_expr to convert RETURNING Vars into references to those tlist
3489 * entries, while leaving result-rel Vars as-is.
3490 *
3491 * PlaceHolderVars will also be sought in the targetlist, but no
3492 * more-complex expressions will be. Note that it is not possible for a
3493 * PlaceHolderVar to refer to the result relation, since the result is
3494 * never below an outer join. If that case could happen, we'd have to be
3495 * prepared to pick apart the PlaceHolderVar and evaluate its contained
3496 * expression instead.
3497 */
3498 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3499
3501 rlist,
3502 itlist,
3503 NULL,
3504 resultRelation,
3505 rtoffset,
3506 NRM_EQUAL,
3508
3509 pfree(itlist);
3510
3511 return rlist;
3512}
3513
3514/*
3515 * fix_windowagg_condition_expr_mutator
3516 * Mutator function for replacing WindowFuncs with the corresponding Var
3517 * in the targetlist which references that WindowFunc.
3518 */
3519static Node *
3522{
3523 if (node == NULL)
3524 return NULL;
3525
3526 if (IsA(node, WindowFunc))
3527 {
3528 Var *newvar;
3529
3531 context->subplan_itlist,
3532 context->newvarno);
3533 if (newvar)
3534 return (Node *) newvar;
3535 elog(ERROR, "WindowFunc not found in subplan target lists");
3536 }
3537
3538 return expression_tree_mutator(node,
3540 context);
3541}
3542
3543/*
3544 * fix_windowagg_condition_expr
3545 * Converts references in 'runcondition' so that any WindowFunc
3546 * references are swapped out for a Var which references the matching
3547 * WindowFunc in 'subplan_itlist'.
3548 */
3549static List *
3551 List *runcondition,
3552 indexed_tlist *subplan_itlist)
3553{
3555
3556 context.root = root;
3557 context.subplan_itlist = subplan_itlist;
3558 context.newvarno = 0;
3559
3560 return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3561 &context);
3562}
3563
3564/*
3565 * set_windowagg_runcondition_references
3566 * Converts references in 'runcondition' so that any WindowFunc
3567 * references are swapped out for a Var which references the matching
3568 * WindowFunc in 'plan' targetlist.
3569 */
3570static List *
3572 List *runcondition,
3573 Plan *plan)
3574{
3575 List *newlist;
3577
3578 itlist = build_tlist_index(plan->targetlist);
3579
3581
3582 pfree(itlist);
3583
3584 return newlist;
3585}
3586
3587/*
3588 * find_minmax_agg_replacement_param
3589 * If the given Aggref is one that we are optimizing into a subquery
3590 * (cf. planagg.c), then return the Param that should replace it.
3591 * Else return NULL.
3592 *
3593 * This is exported so that SS_finalize_plan can use it before setrefs.c runs.
3594 * Note that it will not find anything until we have built a Plan from a
3595 * MinMaxAggPath, as root->minmax_aggs will never be filled otherwise.
3596 */
3597Param *
3599{
3600 if (root->minmax_aggs != NIL &&
3601 list_length(aggref->args) == 1)
3602 {
3604 ListCell *lc;
3605
3606 foreach(lc, root->minmax_aggs)
3607 {
3609
3610 if (mminfo->aggfnoid == aggref->aggfnoid &&
3611 equal(mminfo->target, curTarget->expr))
3612 return mminfo->param;
3613 }
3614 }
3615 return NULL;
3616}
3617
3618
3619/*****************************************************************************
3620 * QUERY DEPENDENCY MANAGEMENT
3621 *****************************************************************************/
3622
3623/*
3624 * record_plan_function_dependency
3625 * Mark the current plan as depending on a particular function.
3626 *
3627 * This is exported so that the function-inlining code can record a
3628 * dependency on a function that it's removed from the plan tree.
3629 */
3630void
3632{
3633 /*
3634 * For performance reasons, we don't bother to track built-in functions;
3635 * we just assume they'll never change (or at least not in ways that'd
3636 * invalidate plans using them). For this purpose we can consider a
3637 * built-in function to be one with OID less than FirstUnpinnedObjectId.
3638 * Note that the OID generator guarantees never to generate such an OID
3639 * after startup, even at OID wraparound.
3640 */
3641 if (funcid >= (Oid) FirstUnpinnedObjectId)
3642 {
3644
3645 /*
3646 * It would work to use any syscache on pg_proc, but the easiest is
3647 * PROCOID since we already have the function's OID at hand. Note
3648 * that plancache.c knows we use PROCOID.
3649 */
3650 inval_item->cacheId = PROCOID;
3652 ObjectIdGetDatum(funcid));
3653
3654 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3655 }
3656}
3657
3658/*
3659 * record_plan_type_dependency
3660 * Mark the current plan as depending on a particular type.
3661 *
3662 * This is exported so that eval_const_expressions can record a
3663 * dependency on a domain that it's removed a CoerceToDomain node for.
3664 *
3665 * We don't currently need to record dependencies on domains that the
3666 * plan contains CoerceToDomain nodes for, though that might change in
3667 * future. Hence, this isn't actually called in this module, though
3668 * someday fix_expr_common might call it.
3669 */
3670void
3672{
3673 /*
3674 * As in record_plan_function_dependency, ignore the possibility that
3675 * someone would change a built-in domain.
3676 */
3677 if (typid >= (Oid) FirstUnpinnedObjectId)
3678 {
3680
3681 /*
3682 * It would work to use any syscache on pg_type, but the easiest is
3683 * TYPEOID since we already have the type's OID at hand. Note that
3684 * plancache.c knows we use TYPEOID.
3685 */
3686 inval_item->cacheId = TYPEOID;
3688 ObjectIdGetDatum(typid));
3689
3690 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3691 }
3692}
3693
3694/*
3695 * extract_query_dependencies
3696 * Given a rewritten, but not yet planned, query or queries
3697 * (i.e. a Query node or list of Query nodes), extract dependencies
3698 * just as set_plan_references would do. Also detect whether any
3699 * rewrite steps were affected by RLS.
3700 *
3701 * This is needed by plancache.c to handle invalidation of cached unplanned
3702 * queries.
3703 *
3704 * Note: this does not go through eval_const_expressions, and hence doesn't
3705 * reflect its additions of inlined functions and elided CoerceToDomain nodes
3706 * to the invalItems list. This is obviously OK for functions, since we'll
3707 * see them in the original query tree anyway. For domains, it's OK because
3708 * we don't care about domains unless they get elided. That is, a plan might
3709 * have domain dependencies that the query tree doesn't.
3710 */
3711void
3713 List **relationOids,
3714 List **invalItems,
3715 bool *hasRowSecurity)
3716{
3717 PlannerGlobal glob;
3719
3720 /* Make up dummy planner state so we can use this module's machinery */
3721 MemSet(&glob, 0, sizeof(glob));
3722 glob.type = T_PlannerGlobal;
3723 glob.relationOids = NIL;
3724 glob.invalItems = NIL;
3725 /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3726 glob.dependsOnRole = false;
3727
3728 MemSet(&root, 0, sizeof(root));
3729 root.type = T_PlannerInfo;
3730 root.glob = &glob;
3731
3733
3734 *relationOids = glob.relationOids;
3735 *invalItems = glob.invalItems;
3736 *hasRowSecurity = glob.dependsOnRole;
3737}
3738
3739/*
3740 * Tree walker for extract_query_dependencies.
3741 *
3742 * This is exported so that expression_planner_with_deps can call it on
3743 * simple expressions (post-planning, not before planning, in that case).
3744 * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
3745 * and invalItems lists are added to as needed.
3746 */
3747bool
3749{
3750 if (node == NULL)
3751 return false;
3752 Assert(!IsA(node, PlaceHolderVar));
3753 if (IsA(node, Query))
3754 {
3755 Query *query = (Query *) node;
3756 ListCell *lc;
3757
3758 if (query->commandType == CMD_UTILITY)
3759 {
3760 /*
3761 * This logic must handle any utility command for which parse
3762 * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3763 *
3764 * Notably, CALL requires its own processing.
3765 */
3766 if (IsA(query->utilityStmt, CallStmt))
3767 {
3768 CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3769
3770 /* We need not examine funccall, just the transformed exprs */
3772 context);
3774 context);
3775 return false;
3776 }
3777
3778 /*
3779 * Ignore other utility statements, except those (such as EXPLAIN)
3780 * that contain a parsed-but-not-planned query. For those, we
3781 * just need to transfer our attention to the contained query.
3782 */
3783 query = UtilityContainsQuery(query->utilityStmt);
3784 if (query == NULL)
3785 return false;
3786 }
3787
3788 /* Remember if any Query has RLS quals applied by rewriter */
3789 if (query->hasRowSecurity)
3790 context->glob->dependsOnRole = true;
3791
3792 /* Collect relation OIDs in this Query's rtable */
3793 foreach(lc, query->rtable)
3794 {
3796
3797 if (rte->rtekind == RTE_RELATION ||
3798 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3799 (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
3800 context->glob->relationOids =
3801 lappend_oid(context->glob->relationOids, rte->relid);
3802 }
3803
3804 /* And recurse into the query's subexpressions */
3806 context, 0);
3807 }
3808 /* Extract function dependencies and check for regclass Consts */
3809 fix_expr_common(context, node);
3811 context);
3812}
3813
3814/*
3815 * Record some details about a node removed from the plan during setrefs
3816 * processing, for the benefit of code trying to reconstruct planner decisions
3817 * from examination of the final plan tree.
3818 */
3819static void
3820record_elided_node(PlannerGlobal *glob, int plan_node_id,
3821 NodeTag elided_type, Bitmapset *relids)
3822{
3824
3825 n->plan_node_id = plan_node_id;
3826 n->elided_type = elided_type;
3827 n->relids = relids;
3828
3829 glob->elidedNodes = lappend(glob->elidedNodes, n);
3830}
int16 AttrNumber
Definition attnum.h:21
Bitmapset * bms_make_singleton(int x)
Definition bitmapset.c:216
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:292
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:142
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1290
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:412
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define Assert(condition)
Definition c.h:943
unsigned int Index
Definition c.h:698
#define MemSet(start, val, len)
Definition c.h:1107
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
#define palloc_object(type)
Definition fe_memutils.h:74
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_concat(List *list1, const List *list2)
Definition list.c:561
List * lappend_int(List *list, int datum)
Definition list.c:357
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
Datum lca(PG_FUNCTION_ARGS)
Definition ltree_op.c:563
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition makefuncs.c:107
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition makefuncs.c:388
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition makefuncs.c:322
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
void * palloc(Size size)
Definition mcxt.c:1387
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition nodeFuncs.c:1890
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1879
#define expression_tree_mutator(n, m, c)
Definition nodeFuncs.h:155
#define query_tree_walker(q, w, c, f)
Definition nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition nodeFuncs.h:153
#define QTW_EXAMINE_RTES_BEFORE
Definition nodeFuncs.h:27
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define copyObject(obj)
Definition nodes.h:232
double Cost
Definition nodes.h:261
#define nodeTag(nodeptr)
Definition nodes.h:139
#define DO_AGGSPLIT_COMBINE(as)
Definition nodes.h:395
@ ONCONFLICT_SELECT
Definition nodes.h:431
@ ONCONFLICT_UPDATE
Definition nodes.h:430
@ CMD_UTILITY
Definition nodes.h:280
NodeTag
Definition nodes.h:27
@ AGGSPLIT_FINAL_DESERIAL
Definition nodes.h:391
@ AGGSPLIT_INITIAL_SERIAL
Definition nodes.h:389
#define makeNode(_type_)
Definition nodes.h:161
@ JOIN_INNER
Definition nodes.h:303
char * bmsToString(const Bitmapset *bms)
Definition outfuncs.c:828
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
@ RTE_NAMEDTUPLESTORE
@ RTE_SUBQUERY
@ RTE_RELATION
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2299
@ UPPERREL_FINAL
Definition pathnodes.h:152
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
#define foreach_current_index(var_or_cell)
Definition pg_list.h:435
#define lfirst_int(lc)
Definition pg_list.h:173
#define list_make1(x1)
Definition pg_list.h:244
#define linitial_int(l)
Definition pg_list.h:179
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition pg_list.h:595
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define linitial(l)
Definition pg_list.h:178
#define list_nth_node(type, list, n)
Definition pg_list.h:359
#define plan(x)
Definition pg_regress.c:164
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition planner.c:5838
@ SUBQUERY_SCAN_NONTRIVIAL
Definition plannodes.h:770
@ SUBQUERY_SCAN_UNKNOWN
Definition plannodes.h:768
@ SUBQUERY_SCAN_TRIVIAL
Definition plannodes.h:769
#define outerPlan(node)
Definition plannodes.h:267
static Oid DatumGetObjectId(Datum X)
Definition postgres.h:242
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
unsigned int Oid
static int fb(int x)
#define ROWID_VAR
Definition primnodes.h:246
@ PARAM_MULTIEXPR
Definition primnodes.h:388
#define IS_SPECIAL_VARNO(varno)
Definition primnodes.h:248
@ VAR_RETURNING_DEFAULT
Definition primnodes.h:257
#define OUTER_VAR
Definition primnodes.h:244
#define INNER_VAR
Definition primnodes.h:243
#define INDEX_VAR
Definition primnodes.h:245
tree ctl root
Definition radixtree.h:1857
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:544
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition relnode.c:1617
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
NullingRelsMatch
Definition setrefs.c:35
@ NRM_EQUAL
Definition setrefs.c:36
@ NRM_SUPERSET
Definition setrefs.c:38
@ NRM_SUBSET
Definition setrefs.c:37
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition setrefs.c:3672
#define NUM_EXEC_QUAL(parentplan)
Definition setrefs.c:117
static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition setrefs.c:2025
static void fix_expr_common(PlannerInfo *root, Node *node)
Definition setrefs.c:2102
static void record_elided_node(PlannerGlobal *glob, int plan_node_id, NodeTag elided_type, Bitmapset *relids)
Definition setrefs.c:3821
static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
Definition setrefs.c:399
static Node * fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
Definition setrefs.c:3204
static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos, RangeTblEntry *rte)
Definition setrefs.c:565
static Plan * set_append_references(PlannerInfo *root, Append *aplan, int rtoffset)
Definition setrefs.c:1873
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition setrefs.c:291
static Plan * set_mergeappend_references(PlannerInfo *root, MergeAppend *mplan, int rtoffset)
Definition setrefs.c:1950
static List * set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, int rtoffset)
Definition setrefs.c:3477
static Node * fix_param_node(PlannerInfo *root, Param *p)
Definition setrefs.c:2197
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition setrefs.c:3632
static Relids offset_relid_set(Relids relids, int rtoffset)
Definition setrefs.c:2058
static bool flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt)
Definition setrefs.c:520
static indexed_tlist * build_tlist_index(List *tlist)
Definition setrefs.c:2837
static List * set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, Plan *plan)
Definition setrefs.c:3572
bool trivial_subqueryscan(SubqueryScan *plan)
Definition setrefs.c:1528
static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition setrefs.c:2559
static Var * search_indexed_tlist_for_sortgroupref(Expr *node, Index sortgroupref, indexed_tlist *itlist, int newvarno)
Definition setrefs.c:3104
static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
Definition setrefs.c:508
static Node * fix_upper_expr(PlannerInfo *root, Node *node, indexed_tlist *subplan_itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
Definition setrefs.c:3356
static void set_param_references(PlannerInfo *root, Plan *plan)
Definition setrefs.c:2647
static Var * search_indexed_tlist_for_non_var(Expr *node, indexed_tlist *itlist, int newvarno)
Definition setrefs.c:3064
static Node * fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
Definition setrefs.c:3376
Param * find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
Definition setrefs.c:3599
static Node * fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
Definition setrefs.c:2325
static void set_foreignscan_references(PlannerInfo *root, ForeignScan *fscan, int rtoffset)
Definition setrefs.c:1642
static Plan * set_subqueryscan_references(PlannerInfo *root, SubqueryScan *plan, int rtoffset)
Definition setrefs.c:1452
static Var * search_indexed_tlist_for_phv(PlaceHolderVar *phv, indexed_tlist *itlist, int newvarno, NullingRelsMatch nrm_match)
Definition setrefs.c:3011
static Plan * set_indexonlyscan_references(PlannerInfo *root, IndexOnlyScan *plan, int rtoffset)
Definition setrefs.c:1378
static List * fix_join_expr(PlannerInfo *root, List *clauses, indexed_tlist *outer_itlist, indexed_tlist *inner_itlist, Index acceptable_rel, int rtoffset, NullingRelsMatch nrm_match, double num_exec)
Definition setrefs.c:3182
static Node * convert_combining_aggrefs(Node *node, void *context)
Definition setrefs.c:2702
static void set_dummy_tlist_references(Plan *plan, int rtoffset)
Definition setrefs.c:2770
static int register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
Definition setrefs.c:1812
static void set_customscan_references(PlannerInfo *root, CustomScan *cscan, int rtoffset)
Definition setrefs.c:1729
#define ISREGCLASSCONST(con)
Definition setrefs.c:126
void extract_query_dependencies(Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
Definition setrefs.c:3713
static Node * fix_windowagg_condition_expr_mutator(Node *node, fix_windowagg_cond_context *context)
Definition setrefs.c:3521
static Var * copyVar(Var *var)
Definition setrefs.c:2080
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition setrefs.c:3749
static List * fix_windowagg_condition_expr(PlannerInfo *root, List *runcondition, indexed_tlist *subplan_itlist)
Definition setrefs.c:3551
#define NUM_EXEC_TLIST(parentplan)
Definition setrefs.c:116
static Node * fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan, double num_exec)
Definition setrefs.c:2228
static void set_join_references(PlannerInfo *root, Join *join, int rtoffset)
Definition setrefs.c:2410
static indexed_tlist * build_tlist_index_other_vars(List *tlist, int ignore_rel)
Definition setrefs.c:2888
static Plan * clean_up_removed_plan_level(Plan *parent, Plan *child)
Definition setrefs.c:1598
static Node * fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
Definition setrefs.c:2290
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition setrefs.c:642
static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
Definition setrefs.c:2390
static Var * search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match)
Definition setrefs.c:2946
#define fix_scan_list(root, lst, rtoffset, num_exec)
Definition setrefs.c:130
Oid aggfnoid
Definition primnodes.h:464
List * args
Definition primnodes.h:488
Plan plan
Definition plannodes.h:512
List * bitmapplans
Definition plannodes.h:513
List * bitmapqualorig
Definition plannodes.h:714
List * indexqualorig
Definition plannodes.h:698
List * bitmapplans
Definition plannodes.h:528
Plan plan
Definition plannodes.h:526
Scan scan
Definition plannodes.h:821
NodeTag elided_type
Definition plannodes.h:1872
int plan_node_id
Definition plannodes.h:1871
Bitmapset * relids
Definition plannodes.h:1873
List * functions
Definition plannodes.h:788
List * hashclauses
Definition plannodes.h:1067
List * indexorderby
Definition plannodes.h:614
Scan scan
Definition plannodes.h:606
List * indexqualorig
Definition plannodes.h:612
List * indexqual
Definition plannodes.h:610
List * indexorderbyorig
Definition plannodes.h:616
List * joinqual
Definition plannodes.h:992
JoinType jointype
Definition plannodes.h:989
Plan plan
Definition plannodes.h:1500
Node * limitCount
Definition plannodes.h:1506
Node * limitOffset
Definition plannodes.h:1503
Definition pg_list.h:54
List * rowMarks
Definition plannodes.h:1486
Plan plan
Definition plannodes.h:1484
List * mergeclauses
Definition plannodes.h:1043
Param * param
Definition pathnodes.h:3465
Index nominalRelation
Definition plannodes.h:344
List * mergeJoinConditions
Definition plannodes.h:388
List * resultRelations
Definition plannodes.h:348
List * onConflictSet
Definition plannodes.h:374
List * exclRelTlist
Definition plannodes.h:384
List * mergeActionLists
Definition plannodes.h:386
List * returningLists
Definition plannodes.h:358
List * withCheckOptionLists
Definition plannodes.h:352
Index rootRelation
Definition plannodes.h:346
Node * onConflictWhere
Definition plannodes.h:378
List * rowMarks
Definition plannodes.h:364
OnConflictAction onConflictAction
Definition plannodes.h:368
Index exclRelRTI
Definition plannodes.h:382
Definition nodes.h:135
int paramid
Definition primnodes.h:397
ParamKind paramkind
Definition primnodes.h:396
Bitmapset * relids
Definition plannodes.h:1668
struct Plan * lefttree
Definition plannodes.h:239
Cost total_cost
Definition plannodes.h:205
bool parallel_aware
Definition plannodes.h:219
Cost startup_cost
Definition plannodes.h:203
List * qual
Definition plannodes.h:237
bool parallel_safe
Definition plannodes.h:221
int plan_node_id
Definition plannodes.h:233
List * targetlist
Definition plannodes.h:235
List * initPlan
Definition plannodes.h:242
Bitmapset * prunableRelids
Definition pathnodes.h:206
List * subplans
Definition pathnodes.h:178
bool dependsOnRole
Definition pathnodes.h:251
Bitmapset * allRelids
Definition pathnodes.h:199
List * appendRelations
Definition pathnodes.h:221
List * finalrowmarks
Definition pathnodes.h:215
List * invalItems
Definition pathnodes.h:230
List * relationOids
Definition pathnodes.h:227
List * finalrteperminfos
Definition pathnodes.h:209
List * partPruneInfos
Definition pathnodes.h:224
List * finalrtable
Definition pathnodes.h:193
List * elidedNodes
Definition pathnodes.h:236
PlannerGlobal * glob
Definition pathnodes.h:312
List * rtable
Definition parsenodes.h:178
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
Index relid
Definition pathnodes.h:1069
PlannerInfo * subroot
Definition pathnodes.h:1100
Node * resconstantqual
Definition plannodes.h:305
Bitmapset * relids
Definition plannodes.h:306
Plan plan
Definition plannodes.h:303
struct TableSampleClause * tablesample
Definition plannodes.h:564
Index scanrelid
Definition plannodes.h:544
Scan scan
Definition plannodes.h:553
Cost startup_cost
Definition primnodes.h:1128
TableFunc * tablefunc
Definition plannodes.h:812
List * tidrangequals
Definition plannodes.h:743
Scan scan
Definition plannodes.h:727
List * tidquals
Definition plannodes.h:729
List * values_lists
Definition plannodes.h:801
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
VarReturningType varreturningtype
Definition primnodes.h:298
Index varlevelsup
Definition primnodes.h:295
List * runCondition
Definition plannodes.h:1295
NullingRelsMatch nrm_match
Definition setrefs.c:72
indexed_tlist * outer_itlist
Definition setrefs.c:68
PlannerInfo * root
Definition setrefs.c:67
indexed_tlist * inner_itlist
Definition setrefs.c:69
PlannerInfo * root
Definition setrefs.c:60
indexed_tlist * subplan_itlist
Definition setrefs.c:79
PlannerInfo * root
Definition setrefs.c:78
NullingRelsMatch nrm_match
Definition setrefs.c:82
indexed_tlist * subplan_itlist
Definition setrefs.c:89
PlannerGlobal * glob
Definition setrefs.c:96
bool has_ph_vars
Definition setrefs.c:53
bool has_non_vars
Definition setrefs.c:54
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition subselect.c:2493
#define GetSysCacheHashValue1(cacheId, key1)
Definition syscache.h:118
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition tlist.c:88
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition tlist.c:327
#define FirstUnpinnedObjectId
Definition transam.h:196
Query * UtilityContainsQuery(Node *parsetree)
Definition utility.c:2198

◆ ISREGCLASSCONST

#define ISREGCLASSCONST (   con)
Value:
(((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
!(con)->constisnull)

Definition at line 126 of file setrefs.c.

◆ NUM_EXEC_QUAL

#define NUM_EXEC_QUAL (   parentplan)    ((parentplan)->plan_rows * 2.0)

Definition at line 117 of file setrefs.c.

◆ NUM_EXEC_TLIST

#define NUM_EXEC_TLIST (   parentplan)    ((parentplan)->plan_rows)

Definition at line 116 of file setrefs.c.

Enumeration Type Documentation

◆ NullingRelsMatch

Enumerator
NRM_EQUAL 
NRM_SUBSET 
NRM_SUPERSET 

Definition at line 34 of file setrefs.c.

35{
36 NRM_EQUAL, /* expect exact match of nullingrels */
37 NRM_SUBSET, /* actual Var may have a subset of input */
38 NRM_SUPERSET, /* actual Var may have a superset of input */

Function Documentation

◆ add_rte_to_flat_rtable()

static void add_rte_to_flat_rtable ( PlannerGlobal glob,
List rteperminfos,
RangeTblEntry rte 
)
static

Definition at line 565 of file setrefs.c.

567{
569
570 /* flat copy to duplicate all the scalar fields */
572 memcpy(newrte, rte, sizeof(RangeTblEntry));
573
574 /* zap unneeded sub-structure */
575 newrte->tablesample = NULL;
576 newrte->subquery = NULL;
577 newrte->joinaliasvars = NIL;
578 newrte->joinleftcols = NIL;
579 newrte->joinrightcols = NIL;
580 newrte->join_using_alias = NULL;
581 newrte->functions = NIL;
582 newrte->tablefunc = NULL;
583 newrte->values_lists = NIL;
584 newrte->coltypes = NIL;
585 newrte->coltypmods = NIL;
586 newrte->colcollations = NIL;
587 newrte->groupexprs = NIL;
588 newrte->securityQuals = NIL;
589
590 glob->finalrtable = lappend(glob->finalrtable, newrte);
591
592 /*
593 * If it's a plain relation RTE (or a subquery that was once a view
594 * reference), add the relation OID to relationOids. Also add its new RT
595 * index to the set of relations to be potentially accessed during
596 * execution.
597 *
598 * We do this even though the RTE might be unreferenced in the plan tree;
599 * this would correspond to cases such as views that were expanded, child
600 * tables that were eliminated by constraint exclusion, etc. Schema
601 * invalidation on such a rel must still force rebuilding of the plan.
602 *
603 * Note we don't bother to avoid making duplicate list entries. We could,
604 * but it would probably cost more cycles than it would save.
605 */
606 if (newrte->rtekind == RTE_RELATION ||
607 (newrte->rtekind == RTE_SUBQUERY && OidIsValid(newrte->relid)))
608 {
609 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
610 glob->allRelids = bms_add_member(glob->allRelids,
611 list_length(glob->finalrtable));
612 }
613
614 /*
615 * Add a copy of the RTEPermissionInfo, if any, corresponding to this RTE
616 * to the flattened global list.
617 */
618 if (rte->perminfoindex > 0)
619 {
622
623 /* Get the existing one from this query's rteperminfos. */
624 perminfo = getRTEPermissionInfo(rteperminfos, newrte);
625
626 /*
627 * Add a new one to finalrteperminfos and copy the contents of the
628 * existing one into it. Note that addRTEPermissionInfo() also
629 * updates newrte->perminfoindex to point to newperminfo in
630 * finalrteperminfos.
631 */
632 newrte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
635 }
636}

References addRTEPermissionInfo(), PlannerGlobal::allRelids, bms_add_member(), fb(), PlannerGlobal::finalrtable, PlannerGlobal::finalrteperminfos, getRTEPermissionInfo(), lappend(), lappend_oid(), list_length(), memcpy(), NIL, OidIsValid, palloc_object, PlannerGlobal::relationOids, RTE_RELATION, and RTE_SUBQUERY.

Referenced by add_rtes_to_flat_rtable(), and flatten_rtes_walker().

◆ add_rtes_to_flat_rtable()

static void add_rtes_to_flat_rtable ( PlannerInfo root,
bool  recursing 
)
static

Definition at line 399 of file setrefs.c.

400{
401 PlannerGlobal *glob = root->glob;
402 Index rti;
403 ListCell *lc;
404
405 /*
406 * Record enough information to make it possible for code that looks at
407 * the final range table to understand how it was constructed. (If
408 * finalrtable is still NIL, then this is the very topmost PlannerInfo,
409 * which will always have plan_name == NULL and rtoffset == 0; we omit the
410 * degenerate list entry.)
411 */
412 if (root->glob->finalrtable != NIL)
413 {
415
416 rtinfo->plan_name = root->plan_name;
417 rtinfo->rtoffset = list_length(root->glob->finalrtable);
418
419 /* When recursing = true, it's an unplanned or dummy subquery. */
420 rtinfo->dummy = recursing;
421
422 root->glob->subrtinfos = lappend(root->glob->subrtinfos, rtinfo);
423 }
424
425 /*
426 * Add the query's own RTEs to the flattened rangetable.
427 *
428 * At top level, we must add all RTEs so that their indexes in the
429 * flattened rangetable match up with their original indexes. When
430 * recursing, we only care about extracting relation RTEs (and subquery
431 * RTEs that were once relation RTEs).
432 */
433 foreach(lc, root->parse->rtable)
434 {
436
437 if (!recursing || rte->rtekind == RTE_RELATION ||
438 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
439 add_rte_to_flat_rtable(glob, root->parse->rteperminfos, rte);
440 }
441
442 /*
443 * If there are any dead subqueries, they are not referenced in the Plan
444 * tree, so we must add RTEs contained in them to the flattened rtable
445 * separately. (If we failed to do this, the executor would not perform
446 * expected permission checks for tables mentioned in such subqueries.)
447 *
448 * Note: this pass over the rangetable can't be combined with the previous
449 * one, because that would mess up the numbering of the live RTEs in the
450 * flattened rangetable.
451 */
452 rti = 1;
453 foreach(lc, root->parse->rtable)
454 {
456
457 /*
458 * We should ignore inheritance-parent RTEs: their contents have been
459 * pulled up into our rangetable already. Also ignore any subquery
460 * RTEs without matching RelOptInfos, as they likewise have been
461 * pulled up.
462 */
463 if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
464 rti < root->simple_rel_array_size)
465 {
466 RelOptInfo *rel = root->simple_rel_array[rti];
467
468 if (rel != NULL)
469 {
470 Assert(rel->relid == rti); /* sanity check on array */
471
472 /*
473 * The subquery might never have been planned at all, if it
474 * was excluded on the basis of self-contradictory constraints
475 * in our query level. In this case apply
476 * flatten_unplanned_rtes.
477 *
478 * If it was planned but the result rel is dummy, we assume
479 * that it has been omitted from our plan tree (see
480 * set_subquery_pathlist), and recurse to pull up its RTEs.
481 *
482 * Otherwise, it should be represented by a SubqueryScan node
483 * somewhere in our plan tree, and we'll pull up its RTEs when
484 * we process that plan node.
485 *
486 * However, if we're recursing, then we should pull up RTEs
487 * whether the subquery is dummy or not, because we've found
488 * that some upper query level is treating this one as dummy,
489 * and so we won't scan this level's plan tree at all.
490 */
491 if (rel->subroot == NULL)
493 else if (recursing ||
497 }
498 }
499 rti++;
500 }
501}

References add_rte_to_flat_rtable(), add_rtes_to_flat_rtable(), Assert, fb(), fetch_upper_rel(), flatten_unplanned_rtes(), IS_DUMMY_REL, lappend(), lfirst, list_length(), makeNode, NIL, OidIsValid, RelOptInfo::relid, root, RTE_RELATION, RTE_SUBQUERY, RelOptInfo::subroot, and UPPERREL_FINAL.

Referenced by add_rtes_to_flat_rtable(), and set_plan_references().

◆ build_tlist_index()

static indexed_tlist * build_tlist_index ( List tlist)
static

Definition at line 2837 of file setrefs.c.

2838{
2841 ListCell *l;
2842
2843 /* Create data structure with enough slots for all tlist entries */
2844 itlist = (indexed_tlist *)
2846 list_length(tlist) * sizeof(tlist_vinfo));
2847
2848 itlist->tlist = tlist;
2849 itlist->has_ph_vars = false;
2850 itlist->has_non_vars = false;
2851
2852 /* Find the Vars and fill in the index array */
2853 vinfo = itlist->vars;
2854 foreach(l, tlist)
2855 {
2857
2858 if (tle->expr && IsA(tle->expr, Var))
2859 {
2860 Var *var = (Var *) tle->expr;
2861
2862 vinfo->varno = var->varno;
2863 vinfo->varattno = var->varattno;
2864 vinfo->resno = tle->resno;
2865 vinfo->varnullingrels = var->varnullingrels;
2866 vinfo++;
2867 }
2868 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2869 itlist->has_ph_vars = true;
2870 else
2871 itlist->has_non_vars = true;
2872 }
2873
2874 itlist->num_vars = (vinfo - itlist->vars);
2875
2876 return itlist;
2877}

References fb(), IsA, lfirst, list_length(), palloc(), Var::varattno, and Var::varno.

Referenced by set_customscan_references(), set_foreignscan_references(), set_hash_references(), set_indexonlyscan_references(), set_join_references(), set_plan_refs(), set_upper_references(), and set_windowagg_runcondition_references().

◆ build_tlist_index_other_vars()

static indexed_tlist * build_tlist_index_other_vars ( List tlist,
int  ignore_rel 
)
static

Definition at line 2888 of file setrefs.c.

2889{
2892 ListCell *l;
2893
2894 /* Create data structure with enough slots for all tlist entries */
2895 itlist = (indexed_tlist *)
2897 list_length(tlist) * sizeof(tlist_vinfo));
2898
2899 itlist->tlist = tlist;
2900 itlist->has_ph_vars = false;
2901 itlist->has_non_vars = false;
2902
2903 /* Find the desired Vars and fill in the index array */
2904 vinfo = itlist->vars;
2905 foreach(l, tlist)
2906 {
2908
2909 if (tle->expr && IsA(tle->expr, Var))
2910 {
2911 Var *var = (Var *) tle->expr;
2912
2913 if (var->varno != ignore_rel)
2914 {
2915 vinfo->varno = var->varno;
2916 vinfo->varattno = var->varattno;
2917 vinfo->resno = tle->resno;
2918 vinfo->varnullingrels = var->varnullingrels;
2919 vinfo++;
2920 }
2921 }
2922 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2923 itlist->has_ph_vars = true;
2924 }
2925
2926 itlist->num_vars = (vinfo - itlist->vars);
2927
2928 return itlist;
2929}

References fb(), IsA, lfirst, list_length(), palloc(), Var::varattno, and Var::varno.

Referenced by set_returning_clause_references().

◆ clean_up_removed_plan_level()

static Plan * clean_up_removed_plan_level ( Plan parent,
Plan child 
)
static

Definition at line 1598 of file setrefs.c.

1599{
1600 /*
1601 * We have to be sure we don't lose any initplans, so move any that were
1602 * attached to the parent plan to the child. If any are parallel-unsafe,
1603 * the child is no longer parallel-safe. As a cosmetic matter, also add
1604 * the initplans' run costs to the child's costs.
1605 */
1606 if (parent->initPlan)
1607 {
1609 bool unsafe_initplans;
1610
1613 child->startup_cost += initplan_cost;
1614 child->total_cost += initplan_cost;
1615 if (unsafe_initplans)
1616 child->parallel_safe = false;
1617
1618 /*
1619 * Attach plans this way so that parent's initplans are processed
1620 * before any pre-existing initplans of the child. Probably doesn't
1621 * matter, but let's preserve the ordering just in case.
1622 */
1623 child->initPlan = list_concat(parent->initPlan,
1624 child->initPlan);
1625 }
1626
1627 /*
1628 * We also have to transfer the parent's column labeling info into the
1629 * child, else columns sent to client will be improperly labeled if this
1630 * is the topmost plan level. resjunk and so on may be important too.
1631 */
1633
1634 return child;
1635}

References apply_tlist_labeling(), fb(), Plan::initPlan, list_concat(), Plan::parallel_safe, SS_compute_initplan_cost(), Plan::startup_cost, Plan::targetlist, and Plan::total_cost.

Referenced by set_append_references(), set_mergeappend_references(), and set_subqueryscan_references().

◆ convert_combining_aggrefs()

static Node * convert_combining_aggrefs ( Node node,
void context 
)
static

Definition at line 2702 of file setrefs.c.

2703{
2704 if (node == NULL)
2705 return NULL;
2706 if (IsA(node, Aggref))
2707 {
2708 Aggref *orig_agg = (Aggref *) node;
2711
2712 /* Assert we've not chosen to partial-ize any unsupported cases */
2713 Assert(orig_agg->aggorder == NIL);
2714 Assert(orig_agg->aggdistinct == NIL);
2715
2716 /*
2717 * Since aggregate calls can't be nested, we needn't recurse into the
2718 * arguments. But for safety, flat-copy the Aggref node itself rather
2719 * than modifying it in-place.
2720 */
2722 memcpy(child_agg, orig_agg, sizeof(Aggref));
2723
2724 /*
2725 * For the parent Aggref, we want to copy all the fields of the
2726 * original aggregate *except* the args list, which we'll replace
2727 * below, and the aggfilter expression, which should be applied only
2728 * by the child not the parent. Rather than explicitly knowing about
2729 * all the other fields here, we can momentarily modify child_agg to
2730 * provide a suitable source for copyObject.
2731 */
2732 child_agg->args = NIL;
2733 child_agg->aggfilter = NULL;
2735 child_agg->args = orig_agg->args;
2736 child_agg->aggfilter = orig_agg->aggfilter;
2737
2738 /*
2739 * Now, set up child_agg to represent the first phase of partial
2740 * aggregation. For now, assume serialization is required.
2741 */
2743
2744 /*
2745 * And set up parent_agg to represent the second phase.
2746 */
2748 1, NULL, false));
2750
2751 return (Node *) parent_agg;
2752 }
2754}

References AGGSPLIT_FINAL_DESERIAL, AGGSPLIT_INITIAL_SERIAL, Assert, convert_combining_aggrefs(), copyObject, expression_tree_mutator, fb(), IsA, list_make1, makeNode, makeTargetEntry(), mark_partial_aggref(), memcpy(), and NIL.

Referenced by convert_combining_aggrefs(), and set_plan_refs().

◆ copyVar()

static Var * copyVar ( Var var)
inlinestatic

Definition at line 2080 of file setrefs.c.

2081{
2083
2084 *newvar = *var;
2085 return newvar;
2086}

References fb(), and palloc_object.

Referenced by fix_join_expr_mutator(), fix_scan_expr_mutator(), and search_indexed_tlist_for_var().

◆ extract_query_dependencies()

void extract_query_dependencies ( Node query,
List **  relationOids,
List **  invalItems,
bool hasRowSecurity 
)

Definition at line 3713 of file setrefs.c.

3717{
3718 PlannerGlobal glob;
3720
3721 /* Make up dummy planner state so we can use this module's machinery */
3722 MemSet(&glob, 0, sizeof(glob));
3723 glob.type = T_PlannerGlobal;
3724 glob.relationOids = NIL;
3725 glob.invalItems = NIL;
3726 /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3727 glob.dependsOnRole = false;
3728
3729 MemSet(&root, 0, sizeof(root));
3730 root.type = T_PlannerInfo;
3731 root.glob = &glob;
3732
3734
3735 *relationOids = glob.relationOids;
3736 *invalItems = glob.invalItems;
3737 *hasRowSecurity = glob.dependsOnRole;
3738}

References PlannerGlobal::dependsOnRole, extract_query_dependencies_walker(), fb(), PlannerGlobal::invalItems, MemSet, NIL, PlannerGlobal::relationOids, and root.

Referenced by CompleteCachedPlan(), and RevalidateCachedQuery().

◆ extract_query_dependencies_walker()

bool extract_query_dependencies_walker ( Node node,
PlannerInfo context 
)

Definition at line 3749 of file setrefs.c.

3750{
3751 if (node == NULL)
3752 return false;
3753 Assert(!IsA(node, PlaceHolderVar));
3754 if (IsA(node, Query))
3755 {
3756 Query *query = (Query *) node;
3757 ListCell *lc;
3758
3759 if (query->commandType == CMD_UTILITY)
3760 {
3761 /*
3762 * This logic must handle any utility command for which parse
3763 * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3764 *
3765 * Notably, CALL requires its own processing.
3766 */
3767 if (IsA(query->utilityStmt, CallStmt))
3768 {
3769 CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3770
3771 /* We need not examine funccall, just the transformed exprs */
3773 context);
3775 context);
3776 return false;
3777 }
3778
3779 /*
3780 * Ignore other utility statements, except those (such as EXPLAIN)
3781 * that contain a parsed-but-not-planned query. For those, we
3782 * just need to transfer our attention to the contained query.
3783 */
3784 query = UtilityContainsQuery(query->utilityStmt);
3785 if (query == NULL)
3786 return false;
3787 }
3788
3789 /* Remember if any Query has RLS quals applied by rewriter */
3790 if (query->hasRowSecurity)
3791 context->glob->dependsOnRole = true;
3792
3793 /* Collect relation OIDs in this Query's rtable */
3794 foreach(lc, query->rtable)
3795 {
3797
3798 if (rte->rtekind == RTE_RELATION ||
3799 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3800 (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
3801 context->glob->relationOids =
3802 lappend_oid(context->glob->relationOids, rte->relid);
3803 }
3804
3805 /* And recurse into the query's subexpressions */
3807 context, 0);
3808 }
3809 /* Extract function dependencies and check for regclass Consts */
3810 fix_expr_common(context, node);
3812 context);
3813}

References Assert, CMD_UTILITY, Query::commandType, PlannerGlobal::dependsOnRole, expression_tree_walker, extract_query_dependencies_walker(), fb(), fix_expr_common(), PlannerInfo::glob, IsA, lappend_oid(), lfirst, OidIsValid, query_tree_walker, PlannerGlobal::relationOids, Query::rtable, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_SUBQUERY, UtilityContainsQuery(), and Query::utilityStmt.

Referenced by expression_planner_with_deps(), extract_query_dependencies(), and extract_query_dependencies_walker().

◆ find_minmax_agg_replacement_param()

Param * find_minmax_agg_replacement_param ( PlannerInfo root,
Aggref aggref 
)

Definition at line 3599 of file setrefs.c.

3600{
3601 if (root->minmax_aggs != NIL &&
3602 list_length(aggref->args) == 1)
3603 {
3605 ListCell *lc;
3606
3607 foreach(lc, root->minmax_aggs)
3608 {
3610
3611 if (mminfo->aggfnoid == aggref->aggfnoid &&
3612 equal(mminfo->target, curTarget->expr))
3613 return mminfo->param;
3614 }
3615 }
3616 return NULL;
3617}

References Aggref::aggfnoid, Aggref::args, equal(), fb(), lfirst, linitial, list_length(), NIL, MinMaxAggInfo::param, and root.

Referenced by finalize_primnode(), fix_scan_expr_mutator(), and fix_upper_expr_mutator().

◆ fix_alternative_subplan()

static Node * fix_alternative_subplan ( PlannerInfo root,
AlternativeSubPlan asplan,
double  num_exec 
)
static

Definition at line 2228 of file setrefs.c.

2230{
2232 Cost bestcost = 0;
2233 ListCell *lc;
2234
2235 /*
2236 * Compute the estimated cost of each subplan assuming num_exec
2237 * executions, and keep the cheapest one. If one subplan has more
2238 * disabled nodes than another, choose the one with fewer disabled nodes
2239 * regardless of cost; this parallels compare_path_costs. In event of
2240 * exact equality of estimates, we prefer the later plan; this is a bit
2241 * arbitrary, but in current usage it biases us to break ties against
2242 * fast-start subplans.
2243 */
2244 Assert(asplan->subplans != NIL);
2245
2246 foreach(lc, asplan->subplans)
2247 {
2249 Cost curcost;
2250
2251 curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
2252 if (bestplan == NULL ||
2253 curplan->disabled_nodes < bestplan->disabled_nodes ||
2254 (curplan->disabled_nodes == bestplan->disabled_nodes &&
2255 curcost <= bestcost))
2256 {
2257 bestplan = curplan;
2258 bestcost = curcost;
2259 }
2260
2261 /* Also mark all subplans that are in AlternativeSubPlans */
2262 root->isAltSubplan[curplan->plan_id - 1] = true;
2263 }
2264
2265 /* Mark the subplan we selected */
2266 root->isUsedSubplan[bestplan->plan_id - 1] = true;
2267
2268 return (Node *) bestplan;
2269}

References Assert, fb(), lfirst, NIL, root, and SubPlan::startup_cost.

Referenced by fix_join_expr_mutator(), fix_scan_expr_mutator(), and fix_upper_expr_mutator().

◆ fix_expr_common()

static void fix_expr_common ( PlannerInfo root,
Node node 
)
static

Definition at line 2102 of file setrefs.c.

2103{
2104 /* We assume callers won't call us on a NULL pointer */
2105 if (IsA(node, Aggref))
2106 {
2108 ((Aggref *) node)->aggfnoid);
2109 }
2110 else if (IsA(node, WindowFunc))
2111 {
2113 ((WindowFunc *) node)->winfnoid);
2114 }
2115 else if (IsA(node, FuncExpr))
2116 {
2118 ((FuncExpr *) node)->funcid);
2119 }
2120 else if (IsA(node, OpExpr))
2121 {
2122 set_opfuncid((OpExpr *) node);
2124 ((OpExpr *) node)->opfuncid);
2125 }
2126 else if (IsA(node, DistinctExpr))
2127 {
2128 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2130 ((DistinctExpr *) node)->opfuncid);
2131 }
2132 else if (IsA(node, NullIfExpr))
2133 {
2134 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2136 ((NullIfExpr *) node)->opfuncid);
2137 }
2138 else if (IsA(node, ScalarArrayOpExpr))
2139 {
2140 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2141
2142 set_sa_opfuncid(saop);
2143 record_plan_function_dependency(root, saop->opfuncid);
2144
2145 if (OidIsValid(saop->hashfuncid))
2146 record_plan_function_dependency(root, saop->hashfuncid);
2147
2148 if (OidIsValid(saop->negfuncid))
2149 record_plan_function_dependency(root, saop->negfuncid);
2150 }
2151 else if (IsA(node, Const))
2152 {
2153 Const *con = (Const *) node;
2154
2155 /* Check for regclass reference */
2156 if (ISREGCLASSCONST(con))
2157 root->glob->relationOids =
2158 lappend_oid(root->glob->relationOids,
2159 DatumGetObjectId(con->constvalue));
2160 }
2161 else if (IsA(node, GroupingFunc))
2162 {
2163 GroupingFunc *g = (GroupingFunc *) node;
2164 AttrNumber *grouping_map = root->grouping_map;
2165
2166 /* If there are no grouping sets, we don't need this. */
2167
2168 Assert(grouping_map || g->cols == NIL);
2169
2170 if (grouping_map)
2171 {
2172 ListCell *lc;
2173 List *cols = NIL;
2174
2175 foreach(lc, g->refs)
2176 {
2177 cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2178 }
2179
2180 Assert(!g->cols || equal(cols, g->cols));
2181
2182 if (!g->cols)
2183 g->cols = cols;
2184 }
2185 }
2186}

References Assert, DatumGetObjectId(), equal(), fb(), IsA, ISREGCLASSCONST, lappend_int(), lappend_oid(), lfirst_int, NIL, OidIsValid, record_plan_function_dependency(), root, set_opfuncid(), and set_sa_opfuncid().

Referenced by extract_query_dependencies_walker(), fix_join_expr_mutator(), fix_scan_expr_mutator(), fix_scan_expr_walker(), and fix_upper_expr_mutator().

◆ fix_join_expr()

static List * fix_join_expr ( PlannerInfo root,
List clauses,
indexed_tlist outer_itlist,
indexed_tlist inner_itlist,
Index  acceptable_rel,
int  rtoffset,
NullingRelsMatch  nrm_match,
double  num_exec 
)
static

Definition at line 3182 of file setrefs.c.

3190{
3191 fix_join_expr_context context;
3192
3193 context.root = root;
3194 context.outer_itlist = outer_itlist;
3195 context.inner_itlist = inner_itlist;
3196 context.acceptable_rel = acceptable_rel;
3197 context.rtoffset = rtoffset;
3198 context.nrm_match = nrm_match;
3199 context.num_exec = num_exec;
3200 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3201}

References fix_join_expr_context::acceptable_rel, fix_join_expr_mutator(), fix_join_expr_context::inner_itlist, fix_join_expr_context::nrm_match, fix_join_expr_context::num_exec, fix_join_expr_context::outer_itlist, fix_join_expr_context::root, root, and fix_join_expr_context::rtoffset.

Referenced by set_join_references(), set_plan_refs(), and set_returning_clause_references().

◆ fix_join_expr_mutator()

static Node * fix_join_expr_mutator ( Node node,
fix_join_expr_context context 
)
static

Definition at line 3204 of file setrefs.c.

3205{
3206 Var *newvar;
3207
3208 if (node == NULL)
3209 return NULL;
3210 if (IsA(node, Var))
3211 {
3212 Var *var = (Var *) node;
3213
3214 /*
3215 * Verify that Vars with non-default varreturningtype only appear in
3216 * the RETURNING list, and refer to the target relation.
3217 */
3219 {
3220 if (context->inner_itlist != NULL ||
3221 context->outer_itlist == NULL ||
3222 context->acceptable_rel == 0)
3223 elog(ERROR, "variable returning old/new found outside RETURNING list");
3224 if (var->varno != context->acceptable_rel)
3225 elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
3226 var->varno, context->acceptable_rel);
3227 }
3228
3229 /* Look for the var in the input tlists, first in the outer */
3230 if (context->outer_itlist)
3231 {
3233 context->outer_itlist,
3234 OUTER_VAR,
3235 context->rtoffset,
3236 context->nrm_match);
3237 if (newvar)
3238 return (Node *) newvar;
3239 }
3240
3241 /* then in the inner. */
3242 if (context->inner_itlist)
3243 {
3245 context->inner_itlist,
3246 INNER_VAR,
3247 context->rtoffset,
3248 context->nrm_match);
3249 if (newvar)
3250 return (Node *) newvar;
3251 }
3252
3253 /* If it's for acceptable_rel, adjust and return it */
3254 if (var->varno == context->acceptable_rel)
3255 {
3256 var = copyVar(var);
3257 var->varno += context->rtoffset;
3258 if (var->varnosyn > 0)
3259 var->varnosyn += context->rtoffset;
3260 return (Node *) var;
3261 }
3262
3263 /* No referent found for Var */
3264 elog(ERROR, "variable not found in subplan target lists");
3265 }
3266 if (IsA(node, PlaceHolderVar))
3267 {
3268 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3269
3270 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3271 if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3272 {
3274 context->outer_itlist,
3275 OUTER_VAR,
3276 context->nrm_match);
3277 if (newvar)
3278 return (Node *) newvar;
3279 }
3280 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3281 {
3283 context->inner_itlist,
3284 INNER_VAR,
3285 context->nrm_match);
3286 if (newvar)
3287 return (Node *) newvar;
3288 }
3289
3290 /* If not supplied by input plans, evaluate the contained expr */
3291 /* XXX can we assert something about phnullingrels? */
3292 return fix_join_expr_mutator((Node *) phv->phexpr, context);
3293 }
3294 /* Try matching more complex expressions too, if tlists have any */
3295 if (context->outer_itlist && context->outer_itlist->has_non_vars)
3296 {
3298 context->outer_itlist,
3299 OUTER_VAR);
3300 if (newvar)
3301 return (Node *) newvar;
3302 }
3303 if (context->inner_itlist && context->inner_itlist->has_non_vars)
3304 {
3306 context->inner_itlist,
3307 INNER_VAR);
3308 if (newvar)
3309 return (Node *) newvar;
3310 }
3311 /* Special cases (apply only AFTER failing to match to lower tlist) */
3312 if (IsA(node, Param))
3313 return fix_param_node(context->root, (Param *) node);
3314 if (IsA(node, AlternativeSubPlan))
3316 (AlternativeSubPlan *) node,
3317 context->num_exec),
3318 context);
3319 fix_expr_common(context->root, node);
3320 return expression_tree_mutator(node, fix_join_expr_mutator, context);
3321}

References fix_join_expr_context::acceptable_rel, copyVar(), elog, ERROR, expression_tree_mutator, fb(), fix_alternative_subplan(), fix_expr_common(), fix_join_expr_mutator(), fix_param_node(), indexed_tlist::has_non_vars, indexed_tlist::has_ph_vars, fix_join_expr_context::inner_itlist, INNER_VAR, IsA, fix_join_expr_context::nrm_match, fix_join_expr_context::num_exec, fix_join_expr_context::outer_itlist, OUTER_VAR, fix_join_expr_context::root, fix_join_expr_context::rtoffset, search_indexed_tlist_for_non_var(), search_indexed_tlist_for_phv(), search_indexed_tlist_for_var(), VAR_RETURNING_DEFAULT, Var::varno, and Var::varreturningtype.

Referenced by fix_join_expr(), and fix_join_expr_mutator().

◆ fix_param_node()

static Node * fix_param_node ( PlannerInfo root,
Param p 
)
static

Definition at line 2197 of file setrefs.c.

2198{
2199 if (p->paramkind == PARAM_MULTIEXPR)
2200 {
2201 int subqueryid = p->paramid >> 16;
2202 int colno = p->paramid & 0xFFFF;
2203 List *params;
2204
2205 if (subqueryid <= 0 ||
2206 subqueryid > list_length(root->multiexpr_params))
2207 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2208 params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2210 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2211 return copyObject(list_nth(params, colno - 1));
2212 }
2213 return (Node *) copyObject(p);
2214}

References copyObject, elog, ERROR, fb(), list_length(), list_nth(), PARAM_MULTIEXPR, Param::paramid, Param::paramkind, and root.

Referenced by fix_join_expr_mutator(), fix_scan_expr_mutator(), and fix_upper_expr_mutator().

◆ fix_scan_expr()

static Node * fix_scan_expr ( PlannerInfo root,
Node node,
int  rtoffset,
double  num_exec 
)
static

Definition at line 2290 of file setrefs.c.

2291{
2292 fix_scan_expr_context context;
2293
2294 context.root = root;
2295 context.rtoffset = rtoffset;
2296 context.num_exec = num_exec;
2297
2298 if (rtoffset != 0 ||
2299 root->multiexpr_params != NIL ||
2300 root->glob->lastPHId != 0 ||
2301 root->minmax_aggs != NIL ||
2302 root->hasAlternativeSubPlans)
2303 {
2304 return fix_scan_expr_mutator(node, &context);
2305 }
2306 else
2307 {
2308 /*
2309 * If rtoffset == 0, we don't need to change any Vars, and if there
2310 * are no MULTIEXPR subqueries then we don't need to replace
2311 * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2312 * we won't need to remove them, and if there are no minmax Aggrefs we
2313 * won't need to replace them, and if there are no AlternativeSubPlans
2314 * we won't need to remove them. Then it's OK to just scribble on the
2315 * input node tree instead of copying (since the only change, filling
2316 * in any unset opfuncid fields, is harmless). This saves just enough
2317 * cycles to be noticeable on trivial queries.
2318 */
2319 (void) fix_scan_expr_walker(node, &context);
2320 return node;
2321 }
2322}

References fb(), fix_scan_expr_mutator(), fix_scan_expr_walker(), NIL, fix_scan_expr_context::num_exec, fix_scan_expr_context::root, root, and fix_scan_expr_context::rtoffset.

Referenced by set_plan_refs().

◆ fix_scan_expr_mutator()

static Node * fix_scan_expr_mutator ( Node node,
fix_scan_expr_context context 
)
static

Definition at line 2325 of file setrefs.c.

2326{
2327 if (node == NULL)
2328 return NULL;
2329 if (IsA(node, Var))
2330 {
2331 Var *var = copyVar((Var *) node);
2332
2333 Assert(var->varlevelsup == 0);
2334
2335 /*
2336 * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2337 * But an indexqual expression could contain INDEX_VAR Vars.
2338 */
2339 Assert(var->varno != INNER_VAR);
2340 Assert(var->varno != OUTER_VAR);
2341 Assert(var->varno != ROWID_VAR);
2342 if (!IS_SPECIAL_VARNO(var->varno))
2343 var->varno += context->rtoffset;
2344 if (var->varnosyn > 0)
2345 var->varnosyn += context->rtoffset;
2346 return (Node *) var;
2347 }
2348 if (IsA(node, Param))
2349 return fix_param_node(context->root, (Param *) node);
2350 if (IsA(node, Aggref))
2351 {
2352 Aggref *aggref = (Aggref *) node;
2353 Param *aggparam;
2354
2355 /* See if the Aggref should be replaced by a Param */
2357 if (aggparam != NULL)
2358 {
2359 /* Make a copy of the Param for paranoia's sake */
2360 return (Node *) copyObject(aggparam);
2361 }
2362 /* If no match, just fall through to process it normally */
2363 }
2364 if (IsA(node, CurrentOfExpr))
2365 {
2366 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2367
2368 Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2369 cexpr->cvarno += context->rtoffset;
2370 return (Node *) cexpr;
2371 }
2372 if (IsA(node, PlaceHolderVar))
2373 {
2374 /* At scan level, we should always just evaluate the contained expr */
2375 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2376
2377 /* XXX can we assert something about phnullingrels? */
2378 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2379 }
2380 if (IsA(node, AlternativeSubPlan))
2382 (AlternativeSubPlan *) node,
2383 context->num_exec),
2384 context);
2385 fix_expr_common(context->root, node);
2386 return expression_tree_mutator(node, fix_scan_expr_mutator, context);
2387}

References Assert, copyObject, copyVar(), CurrentOfExpr::cvarno, expression_tree_mutator, fb(), find_minmax_agg_replacement_param(), fix_alternative_subplan(), fix_expr_common(), fix_param_node(), fix_scan_expr_mutator(), INNER_VAR, IS_SPECIAL_VARNO, IsA, fix_scan_expr_context::num_exec, OUTER_VAR, fix_scan_expr_context::root, ROWID_VAR, fix_scan_expr_context::rtoffset, Var::varlevelsup, and Var::varno.

Referenced by fix_scan_expr(), and fix_scan_expr_mutator().

◆ fix_scan_expr_walker()

static bool fix_scan_expr_walker ( Node node,
fix_scan_expr_context context 
)
static

Definition at line 2390 of file setrefs.c.

2391{
2392 if (node == NULL)
2393 return false;
2394 Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
2395 Assert(!IsA(node, PlaceHolderVar));
2396 Assert(!IsA(node, AlternativeSubPlan));
2397 fix_expr_common(context->root, node);
2398 return expression_tree_walker(node, fix_scan_expr_walker, context);
2399}

References Assert, expression_tree_walker, fb(), fix_expr_common(), fix_scan_expr_walker(), IsA, fix_scan_expr_context::root, and ROWID_VAR.

Referenced by fix_scan_expr(), and fix_scan_expr_walker().

◆ fix_upper_expr()

static Node * fix_upper_expr ( PlannerInfo root,
Node node,
indexed_tlist subplan_itlist,
int  newvarno,
int  rtoffset,
NullingRelsMatch  nrm_match,
double  num_exec 
)
static

◆ fix_upper_expr_mutator()

static Node * fix_upper_expr_mutator ( Node node,
fix_upper_expr_context context 
)
static

Definition at line 3376 of file setrefs.c.

3377{
3378 Var *newvar;
3379
3380 if (node == NULL)
3381 return NULL;
3382 if (IsA(node, Var))
3383 {
3384 Var *var = (Var *) node;
3385
3387 context->subplan_itlist,
3388 context->newvarno,
3389 context->rtoffset,
3390 context->nrm_match);
3391 if (!newvar)
3392 elog(ERROR, "variable not found in subplan target list");
3393 return (Node *) newvar;
3394 }
3395 if (IsA(node, PlaceHolderVar))
3396 {
3397 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3398
3399 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3400 if (context->subplan_itlist->has_ph_vars)
3401 {
3403 context->subplan_itlist,
3404 context->newvarno,
3405 context->nrm_match);
3406 if (newvar)
3407 return (Node *) newvar;
3408 }
3409 /* If not supplied by input plan, evaluate the contained expr */
3410 /* XXX can we assert something about phnullingrels? */
3411 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3412 }
3413 /* Try matching more complex expressions too, if tlist has any */
3414 if (context->subplan_itlist->has_non_vars)
3415 {
3417 context->subplan_itlist,
3418 context->newvarno);
3419 if (newvar)
3420 return (Node *) newvar;
3421 }
3422 /* Special cases (apply only AFTER failing to match to lower tlist) */
3423 if (IsA(node, Param))
3424 return fix_param_node(context->root, (Param *) node);
3425 if (IsA(node, Aggref))
3426 {
3427 Aggref *aggref = (Aggref *) node;
3428 Param *aggparam;
3429
3430 /* See if the Aggref should be replaced by a Param */
3432 if (aggparam != NULL)
3433 {
3434 /* Make a copy of the Param for paranoia's sake */
3435 return (Node *) copyObject(aggparam);
3436 }
3437 /* If no match, just fall through to process it normally */
3438 }
3439 if (IsA(node, AlternativeSubPlan))
3441 (AlternativeSubPlan *) node,
3442 context->num_exec),
3443 context);
3444 fix_expr_common(context->root, node);
3445 return expression_tree_mutator(node, fix_upper_expr_mutator, context);
3446}

References copyObject, elog, ERROR, expression_tree_mutator, fb(), find_minmax_agg_replacement_param(), fix_alternative_subplan(), fix_expr_common(), fix_param_node(), fix_upper_expr_mutator(), indexed_tlist::has_non_vars, indexed_tlist::has_ph_vars, IsA, fix_upper_expr_context::newvarno, fix_upper_expr_context::nrm_match, fix_upper_expr_context::num_exec, fix_upper_expr_context::root, fix_upper_expr_context::rtoffset, search_indexed_tlist_for_non_var(), search_indexed_tlist_for_phv(), search_indexed_tlist_for_var(), and fix_upper_expr_context::subplan_itlist.

Referenced by fix_upper_expr(), and fix_upper_expr_mutator().

◆ fix_windowagg_condition_expr()

static List * fix_windowagg_condition_expr ( PlannerInfo root,
List runcondition,
indexed_tlist subplan_itlist 
)
static

Definition at line 3551 of file setrefs.c.

3554{
3556
3557 context.root = root;
3558 context.subplan_itlist = subplan_itlist;
3559 context.newvarno = 0;
3560
3561 return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3562 &context);
3563}

References fix_windowagg_condition_expr_mutator(), fix_windowagg_cond_context::newvarno, fix_windowagg_cond_context::root, root, and fix_windowagg_cond_context::subplan_itlist.

Referenced by set_windowagg_runcondition_references().

◆ fix_windowagg_condition_expr_mutator()

static Node * fix_windowagg_condition_expr_mutator ( Node node,
fix_windowagg_cond_context context 
)
static

Definition at line 3521 of file setrefs.c.

3523{
3524 if (node == NULL)
3525 return NULL;
3526
3527 if (IsA(node, WindowFunc))
3528 {
3529 Var *newvar;
3530
3532 context->subplan_itlist,
3533 context->newvarno);
3534 if (newvar)
3535 return (Node *) newvar;
3536 elog(ERROR, "WindowFunc not found in subplan target lists");
3537 }
3538
3539 return expression_tree_mutator(node,
3541 context);
3542}

References elog, ERROR, expression_tree_mutator, fb(), fix_windowagg_condition_expr_mutator(), IsA, fix_windowagg_cond_context::newvarno, search_indexed_tlist_for_non_var(), and fix_windowagg_cond_context::subplan_itlist.

Referenced by fix_windowagg_condition_expr(), and fix_windowagg_condition_expr_mutator().

◆ flatten_rtes_walker()

static bool flatten_rtes_walker ( Node node,
flatten_rtes_walker_context cxt 
)
static

Definition at line 520 of file setrefs.c.

521{
522 if (node == NULL)
523 return false;
524 if (IsA(node, RangeTblEntry))
525 {
526 RangeTblEntry *rte = (RangeTblEntry *) node;
527
528 /* As above, we need only save relation RTEs and former relations */
529 if (rte->rtekind == RTE_RELATION ||
530 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
531 add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
532 return false;
533 }
534 if (IsA(node, Query))
535 {
536 /*
537 * Recurse into subselects. Must update cxt->query to this query so
538 * that the rtable and rteperminfos correspond with each other.
539 */
540 Query *save_query = cxt->query;
541 bool result;
542
543 cxt->query = (Query *) node;
544 result = query_tree_walker((Query *) node,
546 cxt,
548 cxt->query = save_query;
549 return result;
550 }
552}

References add_rte_to_flat_rtable(), expression_tree_walker, fb(), flatten_rtes_walker(), flatten_rtes_walker_context::glob, IsA, OidIsValid, QTW_EXAMINE_RTES_BEFORE, flatten_rtes_walker_context::query, query_tree_walker, result, RTE_RELATION, and RTE_SUBQUERY.

Referenced by flatten_rtes_walker(), and flatten_unplanned_rtes().

◆ flatten_unplanned_rtes()

static void flatten_unplanned_rtes ( PlannerGlobal glob,
RangeTblEntry rte 
)
static

Definition at line 508 of file setrefs.c.

509{
510 flatten_rtes_walker_context cxt = {glob, rte->subquery};
511
512 /* Use query_tree_walker to find all RTEs in the parse tree */
513 (void) query_tree_walker(rte->subquery,
515 &cxt,
517}

References fb(), flatten_rtes_walker(), QTW_EXAMINE_RTES_BEFORE, and query_tree_walker.

Referenced by add_rtes_to_flat_rtable().

◆ offset_relid_set()

static Relids offset_relid_set ( Relids  relids,
int  rtoffset 
)
static

Definition at line 2058 of file setrefs.c.

2059{
2060 Relids result = NULL;
2061 int rtindex;
2062
2063 /* If there's no offset to apply, we needn't recompute the value */
2064 if (rtoffset == 0)
2065 return relids;
2066 rtindex = -1;
2067 while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
2068 result = bms_add_member(result, rtindex + rtoffset);
2069 return result;
2070}

References bms_add_member(), bms_next_member(), fb(), and result.

Referenced by register_partpruneinfo(), set_append_references(), set_customscan_references(), set_foreignscan_references(), set_mergeappend_references(), and set_plan_refs().

◆ record_elided_node()

static void record_elided_node ( PlannerGlobal glob,
int  plan_node_id,
NodeTag  elided_type,
Bitmapset relids 
)
static

Definition at line 3821 of file setrefs.c.

3823{
3825
3826 n->plan_node_id = plan_node_id;
3827 n->elided_type = elided_type;
3828 n->relids = relids;
3829
3830 glob->elidedNodes = lappend(glob->elidedNodes, n);
3831}

References ElidedNode::elided_type, PlannerGlobal::elidedNodes, lappend(), makeNode, ElidedNode::plan_node_id, and ElidedNode::relids.

Referenced by set_append_references(), set_mergeappend_references(), and set_subqueryscan_references().

◆ record_plan_function_dependency()

void record_plan_function_dependency ( PlannerInfo root,
Oid  funcid 
)

Definition at line 3632 of file setrefs.c.

3633{
3634 /*
3635 * For performance reasons, we don't bother to track built-in functions;
3636 * we just assume they'll never change (or at least not in ways that'd
3637 * invalidate plans using them). For this purpose we can consider a
3638 * built-in function to be one with OID less than FirstUnpinnedObjectId.
3639 * Note that the OID generator guarantees never to generate such an OID
3640 * after startup, even at OID wraparound.
3641 */
3642 if (funcid >= (Oid) FirstUnpinnedObjectId)
3643 {
3645
3646 /*
3647 * It would work to use any syscache on pg_proc, but the easiest is
3648 * PROCOID since we already have the function's OID at hand. Note
3649 * that plancache.c knows we use PROCOID.
3650 */
3651 inval_item->cacheId = PROCOID;
3653 ObjectIdGetDatum(funcid));
3654
3655 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3656 }
3657}

References fb(), FirstUnpinnedObjectId, GetSysCacheHashValue1, lappend(), makeNode, ObjectIdGetDatum(), and root.

Referenced by fix_expr_common(), inline_function(), and inline_function_in_from().

◆ record_plan_type_dependency()

void record_plan_type_dependency ( PlannerInfo root,
Oid  typid 
)

Definition at line 3672 of file setrefs.c.

3673{
3674 /*
3675 * As in record_plan_function_dependency, ignore the possibility that
3676 * someone would change a built-in domain.
3677 */
3678 if (typid >= (Oid) FirstUnpinnedObjectId)
3679 {
3681
3682 /*
3683 * It would work to use any syscache on pg_type, but the easiest is
3684 * TYPEOID since we already have the type's OID at hand. Note that
3685 * plancache.c knows we use TYPEOID.
3686 */
3687 inval_item->cacheId = TYPEOID;
3689 ObjectIdGetDatum(typid));
3690
3691 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3692 }
3693}

References fb(), FirstUnpinnedObjectId, GetSysCacheHashValue1, lappend(), makeNode, ObjectIdGetDatum(), and root.

Referenced by eval_const_expressions_mutator().

◆ register_partpruneinfo()

static int register_partpruneinfo ( PlannerInfo root,
int  part_prune_index,
int  rtoffset 
)
static

Definition at line 1812 of file setrefs.c.

1813{
1814 PlannerGlobal *glob = root->glob;
1815 PartitionPruneInfo *pinfo;
1816 ListCell *l;
1817
1818 Assert(part_prune_index >= 0 &&
1819 part_prune_index < list_length(root->partPruneInfos));
1820 pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
1821 part_prune_index);
1822
1823 pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
1824 foreach(l, pinfo->prune_infos)
1825 {
1826 List *prune_infos = lfirst(l);
1827 ListCell *l2;
1828
1829 foreach(l2, prune_infos)
1830 {
1832 int i;
1833
1834 prelinfo->rtindex += rtoffset;
1835 prelinfo->initial_pruning_steps =
1836 fix_scan_list(root, prelinfo->initial_pruning_steps,
1837 rtoffset, 1);
1838 prelinfo->exec_pruning_steps =
1839 fix_scan_list(root, prelinfo->exec_pruning_steps,
1840 rtoffset, 1);
1841
1842 for (i = 0; i < prelinfo->nparts; i++)
1843 {
1844 /*
1845 * Non-leaf partitions and partitions that do not have a
1846 * subplan are not included in this map as mentioned in
1847 * make_partitionedrel_pruneinfo().
1848 */
1849 if (prelinfo->leafpart_rti_map[i])
1850 {
1851 prelinfo->leafpart_rti_map[i] += rtoffset;
1852 if (prelinfo->initial_pruning_steps)
1854 prelinfo->leafpart_rti_map[i]);
1855 }
1856 }
1857 }
1858 }
1859
1860 glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
1861
1862 return list_length(glob->partPruneInfos) - 1;
1863}

References Assert, bms_add_member(), fb(), fix_scan_list, i, lappend(), lfirst, list_length(), list_nth_node, offset_relid_set(), PlannerGlobal::partPruneInfos, PlannerGlobal::prunableRelids, PartitionPruneInfo::prune_infos, PartitionPruneInfo::relids, and root.

Referenced by set_append_references(), and set_mergeappend_references().

◆ search_indexed_tlist_for_non_var()

static Var * search_indexed_tlist_for_non_var ( Expr node,
indexed_tlist itlist,
int  newvarno 
)
static

Definition at line 3064 of file setrefs.c.

3066{
3068
3069 /*
3070 * If it's a simple Const, replacing it with a Var is silly, even if there
3071 * happens to be an identical Const below; a Var is more expensive to
3072 * execute than a Const. What's more, replacing it could confuse some
3073 * places in the executor that expect to see simple Consts for, eg,
3074 * dropped columns.
3075 */
3076 if (IsA(node, Const))
3077 return NULL;
3078
3079 tle = tlist_member(node, itlist->tlist);
3080 if (tle)
3081 {
3082 /* Found a matching subplan output expression */
3083 Var *newvar;
3084
3085 newvar = makeVarFromTargetEntry(newvarno, tle);
3086 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3087 newvar->varattnosyn = 0;
3088 return newvar;
3089 }
3090 return NULL; /* no match */
3091}

References fb(), IsA, makeVarFromTargetEntry(), and tlist_member().

Referenced by fix_join_expr_mutator(), fix_upper_expr_mutator(), and fix_windowagg_condition_expr_mutator().

◆ search_indexed_tlist_for_phv()

static Var * search_indexed_tlist_for_phv ( PlaceHolderVar phv,
indexed_tlist itlist,
int  newvarno,
NullingRelsMatch  nrm_match 
)
static

Definition at line 3011 of file setrefs.c.

3014{
3015 ListCell *lc;
3016
3017 foreach(lc, itlist->tlist)
3018 {
3020
3021 if (tle->expr && IsA(tle->expr, PlaceHolderVar))
3022 {
3024 Var *newvar;
3025
3026 /*
3027 * Analogously to search_indexed_tlist_for_var, we match on phid
3028 * only. We don't use equal(), partially for speed but mostly
3029 * because phnullingrels might not be exactly equal.
3030 */
3031 if (phv->phid != subphv->phid)
3032 continue;
3033
3034 /* Verify that we kept all the nullingrels machinations straight */
3035 if (!(nrm_match == NRM_SUBSET ?
3036 bms_is_subset(phv->phnullingrels, subphv->phnullingrels) :
3037 nrm_match == NRM_SUPERSET ?
3038 bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
3039 bms_equal(subphv->phnullingrels, phv->phnullingrels)))
3040 elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
3041 bmsToString(phv->phnullingrels),
3042 bmsToString(subphv->phnullingrels),
3043 phv->phid);
3044
3045 /* Found a matching subplan output expression */
3046 newvar = makeVarFromTargetEntry(newvarno, tle);
3047 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3048 newvar->varattnosyn = 0;
3049 return newvar;
3050 }
3051 }
3052 return NULL; /* no match */
3053}

References bms_equal(), bms_is_subset(), bmsToString(), elog, ERROR, fb(), IsA, lfirst, makeVarFromTargetEntry(), NRM_SUBSET, and NRM_SUPERSET.

Referenced by fix_join_expr_mutator(), and fix_upper_expr_mutator().

◆ search_indexed_tlist_for_sortgroupref()

static Var * search_indexed_tlist_for_sortgroupref ( Expr node,
Index  sortgroupref,
indexed_tlist itlist,
int  newvarno 
)
static

Definition at line 3104 of file setrefs.c.

3108{
3109 ListCell *lc;
3110
3111 foreach(lc, itlist->tlist)
3112 {
3114
3115 /*
3116 * Usually the equal() check is redundant, but in setop plans it may
3117 * not be, since prepunion.c assigns ressortgroupref equal to the
3118 * column resno without regard to whether that matches the topmost
3119 * level's sortgrouprefs and without regard to whether any implicit
3120 * coercions are added in the setop tree. We might have to clean that
3121 * up someday; but for now, just ignore any false matches.
3122 */
3123 if (tle->ressortgroupref == sortgroupref &&
3124 equal(node, tle->expr))
3125 {
3126 /* Found a matching subplan output expression */
3127 Var *newvar;
3128
3129 newvar = makeVarFromTargetEntry(newvarno, tle);
3130 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3131 newvar->varattnosyn = 0;
3132 return newvar;
3133 }
3134 }
3135 return NULL; /* no match */
3136}

References equal(), fb(), lfirst, and makeVarFromTargetEntry().

Referenced by set_upper_references().

◆ search_indexed_tlist_for_var()

static Var * search_indexed_tlist_for_var ( Var var,
indexed_tlist itlist,
int  newvarno,
int  rtoffset,
NullingRelsMatch  nrm_match 
)
static

Definition at line 2946 of file setrefs.c.

2949{
2950 int varno = var->varno;
2951 AttrNumber varattno = var->varattno;
2953 int i;
2954
2955 vinfo = itlist->vars;
2956 i = itlist->num_vars;
2957 while (i-- > 0)
2958 {
2959 if (vinfo->varno == varno && vinfo->varattno == varattno)
2960 {
2961 /* Found a match */
2962 Var *newvar = copyVar(var);
2963
2964 /*
2965 * Verify that we kept all the nullingrels machinations straight.
2966 *
2967 * XXX we skip the check for system columns and whole-row Vars.
2968 * That's because such Vars might be row identity Vars, which are
2969 * generated without any varnullingrels. It'd be hard to do
2970 * otherwise, since they're normally made very early in planning,
2971 * when we haven't looked at the jointree yet and don't know which
2972 * joins might null such Vars. Doesn't seem worth the expense to
2973 * make them fully valid. (While it's slightly annoying that we
2974 * thereby lose checking for user-written references to such
2975 * columns, it seems unlikely that a bug in nullingrels logic
2976 * would affect only system columns.)
2977 */
2978 if (!(varattno <= 0 ||
2979 (nrm_match == NRM_SUBSET ?
2980 bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2981 nrm_match == NRM_SUPERSET ?
2982 bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2983 bms_equal(vinfo->varnullingrels, var->varnullingrels))))
2984 elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2985 bmsToString(var->varnullingrels),
2986 bmsToString(vinfo->varnullingrels),
2987 varno, varattno);
2988
2989 newvar->varno = newvarno;
2990 newvar->varattno = vinfo->resno;
2991 if (newvar->varnosyn > 0)
2992 newvar->varnosyn += rtoffset;
2993 return newvar;
2994 }
2995 vinfo++;
2996 }
2997 return NULL; /* no match */
2998}

References bms_equal(), bms_is_subset(), bmsToString(), copyVar(), elog, ERROR, fb(), i, NRM_SUBSET, NRM_SUPERSET, Var::varattno, and Var::varno.

Referenced by fix_join_expr_mutator(), and fix_upper_expr_mutator().

◆ set_append_references()

static Plan * set_append_references ( PlannerInfo root,
Append aplan,
int  rtoffset 
)
static

Definition at line 1873 of file setrefs.c.

1876{
1877 ListCell *l;
1878
1879 /*
1880 * Append, like Sort et al, doesn't actually evaluate its targetlist or
1881 * check quals. If it's got exactly one child plan, then it's not doing
1882 * anything useful at all, and we can strip it out.
1883 */
1884 Assert(aplan->plan.qual == NIL);
1885
1886 /* First, we gotta recurse on the children */
1887 foreach(l, aplan->appendplans)
1888 {
1889 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1890 }
1891
1892 /*
1893 * See if it's safe to get rid of the Append entirely. For this to be
1894 * safe, there must be only one child plan and that child plan's parallel
1895 * awareness must match the Append's. The reason for the latter is that
1896 * if the Append is parallel aware and the child is not, then the calling
1897 * plan may execute the non-parallel aware child multiple times. (If you
1898 * change these rules, update create_append_path to match.)
1899 */
1900 if (list_length(aplan->appendplans) == 1)
1901 {
1902 Plan *p = (Plan *) linitial(aplan->appendplans);
1903
1904 if (p->parallel_aware == aplan->plan.parallel_aware)
1905 {
1906 Plan *result;
1907
1909
1910 /* Remember that we removed an Append */
1912 offset_relid_set(aplan->apprelids, rtoffset));
1913
1914 return result;
1915 }
1916 }
1917
1918 /*
1919 * Otherwise, clean up the Append as needed. It's okay to do this after
1920 * recursing to the children, because set_dummy_tlist_references doesn't
1921 * look at those.
1922 */
1923 set_dummy_tlist_references((Plan *) aplan, rtoffset);
1924
1925 aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1926
1927 /*
1928 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1929 * Also update the RT indexes present in it to add the offset.
1930 */
1931 if (aplan->part_prune_index >= 0)
1932 aplan->part_prune_index =
1933 register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
1934
1935 /* We don't need to recurse to lefttree or righttree ... */
1936 Assert(aplan->plan.lefttree == NULL);
1937 Assert(aplan->plan.righttree == NULL);
1938
1939 return (Plan *) aplan;
1940}

References Assert, clean_up_removed_plan_level(), fb(), lfirst, linitial, list_length(), NIL, offset_relid_set(), Plan::parallel_aware, Plan::plan_node_id, record_elided_node(), register_partpruneinfo(), result, root, set_dummy_tlist_references(), and set_plan_refs().

Referenced by set_plan_refs().

◆ set_customscan_references()

static void set_customscan_references ( PlannerInfo root,
CustomScan cscan,
int  rtoffset 
)
static

Definition at line 1729 of file setrefs.c.

1732{
1733 ListCell *lc;
1734
1735 /* Adjust scanrelid if it's valid */
1736 if (cscan->scan.scanrelid > 0)
1737 cscan->scan.scanrelid += rtoffset;
1738
1739 if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1740 {
1741 /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1742 indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
1743
1744 cscan->scan.plan.targetlist = (List *)
1746 (Node *) cscan->scan.plan.targetlist,
1747 itlist,
1748 INDEX_VAR,
1749 rtoffset,
1750 NRM_EQUAL,
1752 cscan->scan.plan.qual = (List *)
1754 (Node *) cscan->scan.plan.qual,
1755 itlist,
1756 INDEX_VAR,
1757 rtoffset,
1758 NRM_EQUAL,
1759 NUM_EXEC_QUAL((Plan *) cscan));
1760 cscan->custom_exprs = (List *)
1762 (Node *) cscan->custom_exprs,
1763 itlist,
1764 INDEX_VAR,
1765 rtoffset,
1766 NRM_EQUAL,
1767 NUM_EXEC_QUAL((Plan *) cscan));
1768 pfree(itlist);
1769 /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1770 cscan->custom_scan_tlist =
1771 fix_scan_list(root, cscan->custom_scan_tlist,
1772 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1773 }
1774 else
1775 {
1776 /* Adjust tlist, qual, custom_exprs in the standard way */
1777 cscan->scan.plan.targetlist =
1778 fix_scan_list(root, cscan->scan.plan.targetlist,
1779 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1780 cscan->scan.plan.qual =
1781 fix_scan_list(root, cscan->scan.plan.qual,
1782 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1783 cscan->custom_exprs =
1784 fix_scan_list(root, cscan->custom_exprs,
1785 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1786 }
1787
1788 /* Adjust child plan-nodes recursively, if needed */
1789 foreach(lc, cscan->custom_plans)
1790 {
1791 lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1792 }
1793
1794 cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1795}

References build_tlist_index(), fb(), fix_scan_list, fix_upper_expr(), INDEX_VAR, lfirst, NIL, NRM_EQUAL, NUM_EXEC_QUAL, NUM_EXEC_TLIST, offset_relid_set(), pfree(), root, and set_plan_refs().

Referenced by set_plan_refs().

◆ set_dummy_tlist_references()

static void set_dummy_tlist_references ( Plan plan,
int  rtoffset 
)
static

Definition at line 2770 of file setrefs.c.

2771{
2773 ListCell *l;
2774
2776 foreach(l, plan->targetlist)
2777 {
2779 Var *oldvar = (Var *) tle->expr;
2780 Var *newvar;
2781
2782 /*
2783 * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2784 * as Consts, not Vars referencing Consts. Here, there's no speed
2785 * advantage to be had, but it makes EXPLAIN output look cleaner, and
2786 * again it avoids confusing the executor.
2787 */
2788 if (IsA(oldvar, Const))
2789 {
2790 /* just reuse the existing TLE node */
2792 continue;
2793 }
2794
2796 tle->resno,
2797 exprType((Node *) oldvar),
2798 exprTypmod((Node *) oldvar),
2800 0);
2801 if (IsA(oldvar, Var) &&
2802 oldvar->varnosyn > 0)
2803 {
2804 newvar->varnosyn = oldvar->varnosyn + rtoffset;
2805 newvar->varattnosyn = oldvar->varattnosyn;
2806 }
2807 else
2808 {
2809 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2810 newvar->varattnosyn = 0;
2811 }
2812
2814 tle->expr = (Expr *) newvar;
2816 }
2817 plan->targetlist = output_targetlist;
2818
2819 /* We don't touch plan->qual here */
2820}

References exprCollation(), exprType(), exprTypmod(), fb(), flatCopyTargetEntry(), IsA, lappend(), lfirst, makeVar(), NIL, OUTER_VAR, and plan.

Referenced by set_append_references(), set_hash_references(), set_mergeappend_references(), and set_plan_refs().

◆ set_foreignscan_references()

static void set_foreignscan_references ( PlannerInfo root,
ForeignScan fscan,
int  rtoffset 
)
static

Definition at line 1642 of file setrefs.c.

1645{
1646 /* Adjust scanrelid if it's valid */
1647 if (fscan->scan.scanrelid > 0)
1648 fscan->scan.scanrelid += rtoffset;
1649
1650 if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1651 {
1652 /*
1653 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1654 * foreign scan tuple
1655 */
1656 indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
1657
1658 fscan->scan.plan.targetlist = (List *)
1660 (Node *) fscan->scan.plan.targetlist,
1661 itlist,
1662 INDEX_VAR,
1663 rtoffset,
1664 NRM_EQUAL,
1666 fscan->scan.plan.qual = (List *)
1668 (Node *) fscan->scan.plan.qual,
1669 itlist,
1670 INDEX_VAR,
1671 rtoffset,
1672 NRM_EQUAL,
1673 NUM_EXEC_QUAL((Plan *) fscan));
1674 fscan->fdw_exprs = (List *)
1676 (Node *) fscan->fdw_exprs,
1677 itlist,
1678 INDEX_VAR,
1679 rtoffset,
1680 NRM_EQUAL,
1681 NUM_EXEC_QUAL((Plan *) fscan));
1682 fscan->fdw_recheck_quals = (List *)
1684 (Node *) fscan->fdw_recheck_quals,
1685 itlist,
1686 INDEX_VAR,
1687 rtoffset,
1688 NRM_EQUAL,
1689 NUM_EXEC_QUAL((Plan *) fscan));
1690 pfree(itlist);
1691 /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1692 fscan->fdw_scan_tlist =
1693 fix_scan_list(root, fscan->fdw_scan_tlist,
1694 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1695 }
1696 else
1697 {
1698 /*
1699 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1700 * way
1701 */
1702 fscan->scan.plan.targetlist =
1703 fix_scan_list(root, fscan->scan.plan.targetlist,
1704 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1705 fscan->scan.plan.qual =
1706 fix_scan_list(root, fscan->scan.plan.qual,
1707 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1708 fscan->fdw_exprs =
1709 fix_scan_list(root, fscan->fdw_exprs,
1710 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1711 fscan->fdw_recheck_quals =
1712 fix_scan_list(root, fscan->fdw_recheck_quals,
1713 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1714 }
1715
1716 fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1717 fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1718
1719 /* Adjust resultRelation if it's valid */
1720 if (fscan->resultRelation > 0)
1721 fscan->resultRelation += rtoffset;
1722}

References build_tlist_index(), fb(), fix_scan_list, fix_upper_expr(), INDEX_VAR, NIL, NRM_EQUAL, NUM_EXEC_QUAL, NUM_EXEC_TLIST, offset_relid_set(), pfree(), and root.

Referenced by set_plan_refs().

◆ set_hash_references()

static void set_hash_references ( PlannerInfo root,
Plan plan,
int  rtoffset 
)
static

Definition at line 2025 of file setrefs.c.

2026{
2027 Hash *hplan = (Hash *) plan;
2028 Plan *outer_plan = plan->lefttree;
2029 indexed_tlist *outer_itlist;
2030
2031 /*
2032 * Hash's hashkeys are used when feeding tuples into the hashtable,
2033 * therefore have them reference Hash's outer plan (which itself is the
2034 * inner plan of the HashJoin).
2035 */
2036 outer_itlist = build_tlist_index(outer_plan->targetlist);
2037 hplan->hashkeys = (List *)
2039 (Node *) hplan->hashkeys,
2040 outer_itlist,
2041 OUTER_VAR,
2042 rtoffset,
2043 NRM_EQUAL,
2045
2046 /* Hash doesn't project */
2048
2049 /* Hash nodes don't have their own quals */
2050 Assert(plan->qual == NIL);
2051}

References Assert, build_tlist_index(), fb(), fix_upper_expr(), Plan::lefttree, NIL, NRM_EQUAL, NUM_EXEC_QUAL, OUTER_VAR, plan, root, set_dummy_tlist_references(), and Plan::targetlist.

Referenced by set_plan_refs().

◆ set_indexonlyscan_references()

static Plan * set_indexonlyscan_references ( PlannerInfo root,
IndexOnlyScan plan,
int  rtoffset 
)
static

Definition at line 1378 of file setrefs.c.

1381{
1384 ListCell *lc;
1385
1386 /*
1387 * Vars in the plan node's targetlist, qual, and recheckqual must only
1388 * reference columns that the index AM can actually return. To ensure
1389 * this, remove non-returnable columns (which are marked as resjunk) from
1390 * the indexed tlist. We can just drop them because the indexed_tlist
1391 * machinery pays attention to TLE resnos, not physical list position.
1392 */
1394 foreach(lc, plan->indextlist)
1395 {
1397
1398 if (!indextle->resjunk)
1400 }
1401
1403
1404 plan->scan.scanrelid += rtoffset;
1405 plan->scan.plan.targetlist = (List *)
1407 (Node *) plan->scan.plan.targetlist,
1409 INDEX_VAR,
1410 rtoffset,
1411 NRM_EQUAL,
1412 NUM_EXEC_TLIST((Plan *) plan));
1413 plan->scan.plan.qual = (List *)
1415 (Node *) plan->scan.plan.qual,
1417 INDEX_VAR,
1418 rtoffset,
1419 NRM_EQUAL,
1420 NUM_EXEC_QUAL((Plan *) plan));
1421 plan->recheckqual = (List *)
1423 (Node *) plan->recheckqual,
1425 INDEX_VAR,
1426 rtoffset,
1427 NRM_EQUAL,
1428 NUM_EXEC_QUAL((Plan *) plan));
1429 /* indexqual is already transformed to reference index columns */
1430 plan->indexqual = fix_scan_list(root, plan->indexqual,
1431 rtoffset, 1);
1432 /* indexorderby is already transformed to reference index columns */
1433 plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1434 rtoffset, 1);
1435 /* indextlist must NOT be transformed to reference index columns */
1436 plan->indextlist = fix_scan_list(root, plan->indextlist,
1437 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1438
1440
1441 return (Plan *) plan;
1442}

References build_tlist_index(), fb(), fix_scan_list, fix_upper_expr(), INDEX_VAR, lappend(), lfirst, NIL, NRM_EQUAL, NUM_EXEC_QUAL, NUM_EXEC_TLIST, pfree(), plan, and root.

Referenced by set_plan_refs().

◆ set_join_references()

static void set_join_references ( PlannerInfo root,
Join join,
int  rtoffset 
)
static

Definition at line 2410 of file setrefs.c.

2411{
2412 Plan *outer_plan = join->plan.lefttree;
2413 Plan *inner_plan = join->plan.righttree;
2414 indexed_tlist *outer_itlist;
2415 indexed_tlist *inner_itlist;
2416
2417 outer_itlist = build_tlist_index(outer_plan->targetlist);
2418 inner_itlist = build_tlist_index(inner_plan->targetlist);
2419
2420 /*
2421 * First process the joinquals (including merge or hash clauses). These
2422 * are logically below the join so they can always use all values
2423 * available from the input tlists. It's okay to also handle
2424 * NestLoopParams now, because those couldn't refer to nullable
2425 * subexpressions.
2426 */
2427 join->joinqual = fix_join_expr(root,
2428 join->joinqual,
2429 outer_itlist,
2430 inner_itlist,
2431 (Index) 0,
2432 rtoffset,
2433 NRM_EQUAL,
2434 NUM_EXEC_QUAL((Plan *) join));
2435
2436 /* Now do join-type-specific stuff */
2437 if (IsA(join, NestLoop))
2438 {
2439 NestLoop *nl = (NestLoop *) join;
2440 ListCell *lc;
2441
2442 foreach(lc, nl->nestParams)
2443 {
2445
2446 /*
2447 * Because we don't reparameterize parameterized paths to match
2448 * the outer-join level at which they are used, Vars seen in the
2449 * NestLoopParam expression may have nullingrels that are just a
2450 * subset of those in the Vars actually available from the outer
2451 * side. (Lateral references can also cause this, as explained in
2452 * the comments for identify_current_nestloop_params.) Not
2453 * checking this exactly is a bit grotty, but the work needed to
2454 * make things match up perfectly seems well out of proportion to
2455 * the value.
2456 */
2458 (Node *) nlp->paramval,
2459 outer_itlist,
2460 OUTER_VAR,
2461 rtoffset,
2462 NRM_SUBSET,
2463 NUM_EXEC_TLIST(outer_plan));
2464 /* Check we replaced any PlaceHolderVar with simple Var */
2465 if (!(IsA(nlp->paramval, Var) &&
2466 nlp->paramval->varno == OUTER_VAR))
2467 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2468 }
2469 }
2470 else if (IsA(join, MergeJoin))
2471 {
2472 MergeJoin *mj = (MergeJoin *) join;
2473
2475 mj->mergeclauses,
2476 outer_itlist,
2477 inner_itlist,
2478 (Index) 0,
2479 rtoffset,
2480 NRM_EQUAL,
2481 NUM_EXEC_QUAL((Plan *) join));
2482 }
2483 else if (IsA(join, HashJoin))
2484 {
2485 HashJoin *hj = (HashJoin *) join;
2486
2488 hj->hashclauses,
2489 outer_itlist,
2490 inner_itlist,
2491 (Index) 0,
2492 rtoffset,
2493 NRM_EQUAL,
2494 NUM_EXEC_QUAL((Plan *) join));
2495
2496 /*
2497 * HashJoin's hashkeys are used to look for matching tuples from its
2498 * outer plan (not the Hash node!) in the hashtable.
2499 */
2500 hj->hashkeys = (List *) fix_upper_expr(root,
2501 (Node *) hj->hashkeys,
2502 outer_itlist,
2503 OUTER_VAR,
2504 rtoffset,
2505 NRM_EQUAL,
2506 NUM_EXEC_QUAL((Plan *) join));
2507 }
2508
2509 /*
2510 * Now we need to fix up the targetlist and qpqual, which are logically
2511 * above the join. This means that, if it's not an inner join, any Vars
2512 * and PHVs appearing here should have nullingrels that include the
2513 * effects of the outer join, ie they will have nullingrels equal to the
2514 * input Vars' nullingrels plus the bit added by the outer join. We don't
2515 * currently have enough info available here to identify what that should
2516 * be, so we just tell fix_join_expr to accept superset nullingrels
2517 * matches instead of exact ones.
2518 */
2519 join->plan.targetlist = fix_join_expr(root,
2520 join->plan.targetlist,
2521 outer_itlist,
2522 inner_itlist,
2523 (Index) 0,
2524 rtoffset,
2526 NUM_EXEC_TLIST((Plan *) join));
2527 join->plan.qual = fix_join_expr(root,
2528 join->plan.qual,
2529 outer_itlist,
2530 inner_itlist,
2531 (Index) 0,
2532 rtoffset,
2534 NUM_EXEC_QUAL((Plan *) join));
2535
2536 pfree(outer_itlist);
2537 pfree(inner_itlist);
2538}

References build_tlist_index(), elog, ERROR, fb(), fix_join_expr(), fix_upper_expr(), IsA, JOIN_INNER, Join::joinqual, Join::jointype, lfirst, NRM_EQUAL, NRM_SUBSET, NRM_SUPERSET, NUM_EXEC_QUAL, NUM_EXEC_TLIST, OUTER_VAR, NestLoopParam::paramval, pfree(), root, and Plan::targetlist.

Referenced by set_plan_refs().

◆ set_mergeappend_references()

static Plan * set_mergeappend_references ( PlannerInfo root,
MergeAppend mplan,
int  rtoffset 
)
static

Definition at line 1950 of file setrefs.c.

1953{
1954 ListCell *l;
1955
1956 /*
1957 * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1958 * or check quals. If it's got exactly one child plan, then it's not
1959 * doing anything useful at all, and we can strip it out.
1960 */
1961 Assert(mplan->plan.qual == NIL);
1962
1963 /* First, we gotta recurse on the children */
1964 foreach(l, mplan->mergeplans)
1965 {
1966 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1967 }
1968
1969 /*
1970 * See if it's safe to get rid of the MergeAppend entirely. For this to
1971 * be safe, there must be only one child plan and that child plan's
1972 * parallel awareness must match the MergeAppend's. The reason for the
1973 * latter is that if the MergeAppend is parallel aware and the child is
1974 * not, then the calling plan may execute the non-parallel aware child
1975 * multiple times. (If you change these rules, update
1976 * create_merge_append_path to match.)
1977 */
1978 if (list_length(mplan->mergeplans) == 1)
1979 {
1980 Plan *p = (Plan *) linitial(mplan->mergeplans);
1981
1982 if (p->parallel_aware == mplan->plan.parallel_aware)
1983 {
1984 Plan *result;
1985
1987
1988 /* Remember that we removed a MergeAppend */
1990 offset_relid_set(mplan->apprelids, rtoffset));
1991
1992 return result;
1993 }
1994 }
1995
1996 /*
1997 * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1998 * after recursing to the children, because set_dummy_tlist_references
1999 * doesn't look at those.
2000 */
2001 set_dummy_tlist_references((Plan *) mplan, rtoffset);
2002
2003 mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
2004
2005 /*
2006 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
2007 * Also update the RT indexes present in it to add the offset.
2008 */
2009 if (mplan->part_prune_index >= 0)
2010 mplan->part_prune_index =
2011 register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
2012
2013 /* We don't need to recurse to lefttree or righttree ... */
2014 Assert(mplan->plan.lefttree == NULL);
2015 Assert(mplan->plan.righttree == NULL);
2016
2017 return (Plan *) mplan;
2018}

References Assert, clean_up_removed_plan_level(), fb(), lfirst, linitial, list_length(), NIL, offset_relid_set(), Plan::parallel_aware, Plan::plan_node_id, record_elided_node(), register_partpruneinfo(), result, root, set_dummy_tlist_references(), and set_plan_refs().

Referenced by set_plan_refs().

◆ set_param_references()

static void set_param_references ( PlannerInfo root,
Plan plan 
)
static

Definition at line 2647 of file setrefs.c.

2648{
2650
2651 if (plan->lefttree->extParam)
2652 {
2655 ListCell *l;
2656
2657 for (proot = root; proot != NULL; proot = proot->parent_root)
2658 {
2659 foreach(l, proot->init_plans)
2660 {
2662 ListCell *l2;
2663
2664 foreach(l2, initsubplan->setParam)
2665 {
2667 }
2668 }
2669 }
2670
2671 /*
2672 * Remember the list of all external initplan params that are used by
2673 * the children of Gather or Gather merge node.
2674 */
2675 if (IsA(plan, Gather))
2676 ((Gather *) plan)->initParam =
2677 bms_intersect(plan->lefttree->extParam, initSetParam);
2678 else
2679 ((GatherMerge *) plan)->initParam =
2680 bms_intersect(plan->lefttree->extParam, initSetParam);
2681 }
2682}

References Assert, bms_add_member(), bms_intersect(), fb(), IsA, lfirst, lfirst_int, plan, and root.

Referenced by set_plan_refs().

◆ set_plan_references()

Plan * set_plan_references ( PlannerInfo root,
Plan plan 
)

Definition at line 291 of file setrefs.c.

292{
293 Plan *result;
294 PlannerGlobal *glob = root->glob;
295 int rtoffset = list_length(glob->finalrtable);
296 ListCell *lc;
297
298 /*
299 * Add all the query's RTEs to the flattened rangetable. The live ones
300 * will have their rangetable indexes increased by rtoffset. (Additional
301 * RTEs, not referenced by the Plan tree, might get added after those.)
302 */
304
305 /*
306 * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
307 */
308 foreach(lc, root->rowMarks)
309 {
312
313 /* sanity check on existing row marks */
314 Assert(root->simple_rel_array[rc->rti] != NULL &&
315 root->simple_rte_array[rc->rti] != NULL);
316
317 /* flat copy is enough since all fields are scalars */
319 memcpy(newrc, rc, sizeof(PlanRowMark));
320
321 /* adjust indexes ... but *not* the rowmarkId */
322 newrc->rti += rtoffset;
323 newrc->prti += rtoffset;
324
326 }
327
328 /*
329 * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
330 * We assume the AppendRelInfos were built during planning and don't need
331 * to be copied.
332 */
333 foreach(lc, root->append_rel_list)
334 {
336
337 /* adjust RT indexes */
338 appinfo->parent_relid += rtoffset;
339 appinfo->child_relid += rtoffset;
340
341 /*
342 * Rather than adjust the translated_vars entries, just drop 'em.
343 * Neither the executor nor EXPLAIN currently need that data.
344 */
345 appinfo->translated_vars = NIL;
346
348 }
349
350 /* If needed, create workspace for processing AlternativeSubPlans */
351 if (root->hasAlternativeSubPlans)
352 {
353 root->isAltSubplan = (bool *)
354 palloc0(list_length(glob->subplans) * sizeof(bool));
355 root->isUsedSubplan = (bool *)
356 palloc0(list_length(glob->subplans) * sizeof(bool));
357 }
358
359 /* Now fix the Plan tree */
360 result = set_plan_refs(root, plan, rtoffset);
361
362 /*
363 * If we have AlternativeSubPlans, it is likely that we now have some
364 * unreferenced subplans in glob->subplans. To avoid expending cycles on
365 * those subplans later, get rid of them by setting those list entries to
366 * NULL. (Note: we can't do this immediately upon processing an
367 * AlternativeSubPlan, because there may be multiple copies of the
368 * AlternativeSubPlan, and they can get resolved differently.)
369 */
370 if (root->hasAlternativeSubPlans)
371 {
372 foreach(lc, glob->subplans)
373 {
375
376 /*
377 * If it was used by some AlternativeSubPlan in this query level,
378 * but wasn't selected as best by any AlternativeSubPlan, then we
379 * don't need it. Do not touch subplans that aren't parts of
380 * AlternativeSubPlans.
381 */
382 if (root->isAltSubplan[ndx] && !root->isUsedSubplan[ndx])
383 lfirst(lc) = NULL;
384 }
385 }
386
387 return result;
388}

References add_rtes_to_flat_rtable(), PlannerGlobal::appendRelations, Assert, fb(), PlannerGlobal::finalrowmarks, PlannerGlobal::finalrtable, foreach_current_index, lappend(), lfirst, lfirst_node, list_length(), memcpy(), NIL, palloc0(), palloc_object, plan, result, root, PlanRowMark::rti, set_plan_refs(), and PlannerGlobal::subplans.

Referenced by set_subqueryscan_references(), and standard_planner().

◆ set_plan_refs()

static Plan * set_plan_refs ( PlannerInfo root,
Plan plan,
int  rtoffset 
)
static

Definition at line 642 of file setrefs.c.

643{
644 ListCell *l;
645
646 if (plan == NULL)
647 return NULL;
648
649 /* Assign this node a unique ID. */
650 plan->plan_node_id = root->glob->lastPlanNodeId++;
651
652 /*
653 * Plan-type-specific fixes
654 */
655 switch (nodeTag(plan))
656 {
657 case T_SeqScan:
658 {
659 SeqScan *splan = (SeqScan *) plan;
660
661 splan->scan.scanrelid += rtoffset;
662 splan->scan.plan.targetlist =
663 fix_scan_list(root, splan->scan.plan.targetlist,
664 rtoffset, NUM_EXEC_TLIST(plan));
665 splan->scan.plan.qual =
666 fix_scan_list(root, splan->scan.plan.qual,
667 rtoffset, NUM_EXEC_QUAL(plan));
668 }
669 break;
670 case T_SampleScan:
671 {
672 SampleScan *splan = (SampleScan *) plan;
673
674 splan->scan.scanrelid += rtoffset;
675 splan->scan.plan.targetlist =
676 fix_scan_list(root, splan->scan.plan.targetlist,
677 rtoffset, NUM_EXEC_TLIST(plan));
678 splan->scan.plan.qual =
679 fix_scan_list(root, splan->scan.plan.qual,
680 rtoffset, NUM_EXEC_QUAL(plan));
681 splan->tablesample = (TableSampleClause *)
683 rtoffset, 1);
684 }
685 break;
686 case T_IndexScan:
687 {
688 IndexScan *splan = (IndexScan *) plan;
689
690 splan->scan.scanrelid += rtoffset;
691 splan->scan.plan.targetlist =
692 fix_scan_list(root, splan->scan.plan.targetlist,
693 rtoffset, NUM_EXEC_TLIST(plan));
694 splan->scan.plan.qual =
695 fix_scan_list(root, splan->scan.plan.qual,
696 rtoffset, NUM_EXEC_QUAL(plan));
697 splan->indexqual =
699 rtoffset, 1);
700 splan->indexqualorig =
702 rtoffset, NUM_EXEC_QUAL(plan));
703 splan->indexorderby =
705 rtoffset, 1);
706 splan->indexorderbyorig =
708 rtoffset, NUM_EXEC_QUAL(plan));
709 }
710 break;
711 case T_IndexOnlyScan:
712 {
713 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
714
715 return set_indexonlyscan_references(root, splan, rtoffset);
716 }
717 break;
719 {
721
722 splan->scan.scanrelid += rtoffset;
723 /* no need to fix targetlist and qual */
724 Assert(splan->scan.plan.targetlist == NIL);
725 Assert(splan->scan.plan.qual == NIL);
726 splan->indexqual =
727 fix_scan_list(root, splan->indexqual, rtoffset, 1);
728 splan->indexqualorig =
730 rtoffset, NUM_EXEC_QUAL(plan));
731 }
732 break;
733 case T_BitmapHeapScan:
734 {
736
737 splan->scan.scanrelid += rtoffset;
738 splan->scan.plan.targetlist =
739 fix_scan_list(root, splan->scan.plan.targetlist,
740 rtoffset, NUM_EXEC_TLIST(plan));
741 splan->scan.plan.qual =
742 fix_scan_list(root, splan->scan.plan.qual,
743 rtoffset, NUM_EXEC_QUAL(plan));
744 splan->bitmapqualorig =
746 rtoffset, NUM_EXEC_QUAL(plan));
747 }
748 break;
749 case T_TidScan:
750 {
751 TidScan *splan = (TidScan *) plan;
752
753 splan->scan.scanrelid += rtoffset;
754 splan->scan.plan.targetlist =
755 fix_scan_list(root, splan->scan.plan.targetlist,
756 rtoffset, NUM_EXEC_TLIST(plan));
757 splan->scan.plan.qual =
758 fix_scan_list(root, splan->scan.plan.qual,
759 rtoffset, NUM_EXEC_QUAL(plan));
760 splan->tidquals =
762 rtoffset, 1);
763 }
764 break;
765 case T_TidRangeScan:
766 {
767 TidRangeScan *splan = (TidRangeScan *) plan;
768
769 splan->scan.scanrelid += rtoffset;
770 splan->scan.plan.targetlist =
771 fix_scan_list(root, splan->scan.plan.targetlist,
772 rtoffset, NUM_EXEC_TLIST(plan));
773 splan->scan.plan.qual =
774 fix_scan_list(root, splan->scan.plan.qual,
775 rtoffset, NUM_EXEC_QUAL(plan));
776 splan->tidrangequals =
778 rtoffset, 1);
779 }
780 break;
781 case T_SubqueryScan:
782 /* Needs special treatment, see comments below */
784 (SubqueryScan *) plan,
785 rtoffset);
786 case T_FunctionScan:
787 {
788 FunctionScan *splan = (FunctionScan *) plan;
789
790 splan->scan.scanrelid += rtoffset;
791 splan->scan.plan.targetlist =
792 fix_scan_list(root, splan->scan.plan.targetlist,
793 rtoffset, NUM_EXEC_TLIST(plan));
794 splan->scan.plan.qual =
795 fix_scan_list(root, splan->scan.plan.qual,
796 rtoffset, NUM_EXEC_QUAL(plan));
797 splan->functions =
798 fix_scan_list(root, splan->functions, rtoffset, 1);
799 }
800 break;
801 case T_TableFuncScan:
802 {
803 TableFuncScan *splan = (TableFuncScan *) plan;
804
805 splan->scan.scanrelid += rtoffset;
806 splan->scan.plan.targetlist =
807 fix_scan_list(root, splan->scan.plan.targetlist,
808 rtoffset, NUM_EXEC_TLIST(plan));
809 splan->scan.plan.qual =
810 fix_scan_list(root, splan->scan.plan.qual,
811 rtoffset, NUM_EXEC_QUAL(plan));
812 splan->tablefunc = (TableFunc *)
813 fix_scan_expr(root, (Node *) splan->tablefunc,
814 rtoffset, 1);
815 }
816 break;
817 case T_ValuesScan:
818 {
819 ValuesScan *splan = (ValuesScan *) plan;
820
821 splan->scan.scanrelid += rtoffset;
822 splan->scan.plan.targetlist =
823 fix_scan_list(root, splan->scan.plan.targetlist,
824 rtoffset, NUM_EXEC_TLIST(plan));
825 splan->scan.plan.qual =
826 fix_scan_list(root, splan->scan.plan.qual,
827 rtoffset, NUM_EXEC_QUAL(plan));
828 splan->values_lists =
830 rtoffset, 1);
831 }
832 break;
833 case T_CteScan:
834 {
835 CteScan *splan = (CteScan *) plan;
836
837 splan->scan.scanrelid += rtoffset;
838 splan->scan.plan.targetlist =
839 fix_scan_list(root, splan->scan.plan.targetlist,
840 rtoffset, NUM_EXEC_TLIST(plan));
841 splan->scan.plan.qual =
842 fix_scan_list(root, splan->scan.plan.qual,
843 rtoffset, NUM_EXEC_QUAL(plan));
844 }
845 break;
847 {
849
850 splan->scan.scanrelid += rtoffset;
851 splan->scan.plan.targetlist =
852 fix_scan_list(root, splan->scan.plan.targetlist,
853 rtoffset, NUM_EXEC_TLIST(plan));
854 splan->scan.plan.qual =
855 fix_scan_list(root, splan->scan.plan.qual,
856 rtoffset, NUM_EXEC_QUAL(plan));
857 }
858 break;
859 case T_WorkTableScan:
860 {
861 WorkTableScan *splan = (WorkTableScan *) plan;
862
863 splan->scan.scanrelid += rtoffset;
864 splan->scan.plan.targetlist =
865 fix_scan_list(root, splan->scan.plan.targetlist,
866 rtoffset, NUM_EXEC_TLIST(plan));
867 splan->scan.plan.qual =
868 fix_scan_list(root, splan->scan.plan.qual,
869 rtoffset, NUM_EXEC_QUAL(plan));
870 }
871 break;
872 case T_ForeignScan:
874 break;
875 case T_CustomScan:
877 break;
878
879 case T_NestLoop:
880 case T_MergeJoin:
881 case T_HashJoin:
882 set_join_references(root, (Join *) plan, rtoffset);
883 break;
884
885 case T_Gather:
886 case T_GatherMerge:
887 {
888 set_upper_references(root, plan, rtoffset);
890 }
891 break;
892
893 case T_Hash:
894 set_hash_references(root, plan, rtoffset);
895 break;
896
897 case T_Memoize:
898 {
899 Memoize *mplan = (Memoize *) plan;
900
901 /*
902 * Memoize does not evaluate its targetlist. It just uses the
903 * same targetlist from its outer subnode.
904 */
906
907 mplan->param_exprs = fix_scan_list(root, mplan->param_exprs,
908 rtoffset,
910 break;
911 }
912
913 case T_Material:
914 case T_Sort:
916 case T_Unique:
917 case T_SetOp:
918
919 /*
920 * These plan types don't actually bother to evaluate their
921 * targetlists, because they just return their unmodified input
922 * tuples. Even though the targetlist won't be used by the
923 * executor, we fix it up for possible use by EXPLAIN (not to
924 * mention ease of debugging --- wrong varnos are very confusing).
925 */
927
928 /*
929 * Since these plan types don't check quals either, we should not
930 * find any qual expression attached to them.
931 */
932 Assert(plan->qual == NIL);
933 break;
934 case T_LockRows:
935 {
936 LockRows *splan = (LockRows *) plan;
937
938 /*
939 * Like the plan types above, LockRows doesn't evaluate its
940 * tlist or quals. But we have to fix up the RT indexes in
941 * its rowmarks.
942 */
944 Assert(splan->plan.qual == NIL);
945
946 foreach(l, splan->rowMarks)
947 {
948 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
949
950 rc->rti += rtoffset;
951 rc->prti += rtoffset;
952 }
953 }
954 break;
955 case T_Limit:
956 {
957 Limit *splan = (Limit *) plan;
958
959 /*
960 * Like the plan types above, Limit doesn't evaluate its tlist
961 * or quals. It does have live expressions for limit/offset,
962 * however; and those cannot contain subplan variable refs, so
963 * fix_scan_expr works for them.
964 */
966 Assert(splan->plan.qual == NIL);
967
968 splan->limitOffset =
969 fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
970 splan->limitCount =
971 fix_scan_expr(root, splan->limitCount, rtoffset, 1);
972 }
973 break;
974 case T_Agg:
975 {
976 Agg *agg = (Agg *) plan;
977
978 /*
979 * If this node is combining partial-aggregation results, we
980 * must convert its Aggrefs to contain references to the
981 * partial-aggregate subexpressions that will be available
982 * from the child plan node.
983 */
984 if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
985 {
986 plan->targetlist = (List *)
987 convert_combining_aggrefs((Node *) plan->targetlist,
988 NULL);
989 plan->qual = (List *)
991 NULL);
992 }
993
994 set_upper_references(root, plan, rtoffset);
995 }
996 break;
997 case T_Group:
998 set_upper_references(root, plan, rtoffset);
999 break;
1000 case T_WindowAgg:
1001 {
1003
1004 /*
1005 * Adjust the WindowAgg's run conditions by swapping the
1006 * WindowFuncs references out to instead reference the Var in
1007 * the scan slot so that when the executor evaluates the
1008 * runCondition, it receives the WindowFunc's value from the
1009 * slot that the result has just been stored into rather than
1010 * evaluating the WindowFunc all over again.
1011 */
1013 wplan->runCondition,
1014 (Plan *) wplan);
1015
1016 set_upper_references(root, plan, rtoffset);
1017
1018 /*
1019 * Like Limit node limit/offset expressions, WindowAgg has
1020 * frame offset expressions, which cannot contain subplan
1021 * variable refs, so fix_scan_expr works for them.
1022 */
1023 wplan->startOffset =
1024 fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
1025 wplan->endOffset =
1026 fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
1027 wplan->runCondition = fix_scan_list(root,
1028 wplan->runCondition,
1029 rtoffset,
1031 wplan->runConditionOrig = fix_scan_list(root,
1032 wplan->runConditionOrig,
1033 rtoffset,
1035 }
1036 break;
1037 case T_Result:
1038 {
1039 Result *splan = (Result *) plan;
1040
1041 /*
1042 * Result may or may not have a subplan; if not, it's more
1043 * like a scan node than an upper node.
1044 */
1045 if (splan->plan.lefttree != NULL)
1046 set_upper_references(root, plan, rtoffset);
1047 else
1048 {
1049 /*
1050 * The tlist of a childless Result could contain
1051 * unresolved ROWID_VAR Vars, in case it's representing a
1052 * target relation which is completely empty because of
1053 * constraint exclusion. Replace any such Vars by null
1054 * constants, as though they'd been resolved for a leaf
1055 * scan node that doesn't support them. We could have
1056 * fix_scan_expr do this, but since the case is only
1057 * expected to occur here, it seems safer to special-case
1058 * it here and keep the assertions that ROWID_VARs
1059 * shouldn't be seen by fix_scan_expr.
1060 *
1061 * We also must handle the case where set operations have
1062 * been short-circuited resulting in a dummy Result node.
1063 * prepunion.c uses varno==0 for the set op targetlist.
1064 * See generate_setop_tlist() and generate_setop_tlist().
1065 * Here we rewrite these to use varno==1, which is the
1066 * varno of the first set-op child. Without this, EXPLAIN
1067 * will have trouble displaying targetlists of dummy set
1068 * operations.
1069 */
1070 foreach(l, splan->plan.targetlist)
1071 {
1073 Var *var = (Var *) tle->expr;
1074
1075 if (var && IsA(var, Var))
1076 {
1077 if (var->varno == ROWID_VAR)
1078 tle->expr = (Expr *) makeNullConst(var->vartype,
1079 var->vartypmod,
1080 var->varcollid);
1081 else if (var->varno == 0)
1082 tle->expr = (Expr *) makeVar(1,
1083 var->varattno,
1084 var->vartype,
1085 var->vartypmod,
1086 var->varcollid,
1087 var->varlevelsup);
1088 }
1089 }
1090
1091 splan->plan.targetlist =
1093 rtoffset, NUM_EXEC_TLIST(plan));
1094 splan->plan.qual =
1095 fix_scan_list(root, splan->plan.qual,
1096 rtoffset, NUM_EXEC_QUAL(plan));
1097 }
1098 /* resconstantqual can't contain any subplan variable refs */
1099 splan->resconstantqual =
1100 fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
1101 /* adjust the relids set */
1102 splan->relids = offset_relid_set(splan->relids, rtoffset);
1103 }
1104 break;
1105 case T_ProjectSet:
1106 set_upper_references(root, plan, rtoffset);
1107 break;
1108 case T_ModifyTable:
1109 {
1110 ModifyTable *splan = (ModifyTable *) plan;
1111 Plan *subplan = outerPlan(splan);
1112
1113 Assert(splan->plan.targetlist == NIL);
1114 Assert(splan->plan.qual == NIL);
1115
1116 splan->withCheckOptionLists =
1118 rtoffset, 1);
1119
1120 if (splan->returningLists)
1121 {
1122 List *newRL = NIL;
1123 ListCell *lcrl,
1124 *lcrr;
1125
1126 /*
1127 * Pass each per-resultrel returningList through
1128 * set_returning_clause_references().
1129 */
1131 forboth(lcrl, splan->returningLists,
1132 lcrr, splan->resultRelations)
1133 {
1134 List *rlist = (List *) lfirst(lcrl);
1136
1138 rlist,
1139 subplan,
1140 resultrel,
1141 rtoffset);
1143 }
1144 splan->returningLists = newRL;
1145
1146 /*
1147 * Set up the visible plan targetlist as being the same as
1148 * the first RETURNING list. This is mostly for the use
1149 * of EXPLAIN; the executor won't execute that targetlist,
1150 * although it does use it to prepare the node's result
1151 * tuple slot. We postpone this step until here so that
1152 * we don't have to do set_returning_clause_references()
1153 * twice on identical targetlists.
1154 */
1156 }
1157
1158 /*
1159 * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
1160 * join', where the inner side is the EXCLUDED tuple.
1161 * Therefore use fix_join_expr to setup the relevant variables
1162 * to INNER_VAR. We explicitly don't create any OUTER_VARs as
1163 * those are already used by RETURNING and it seems better to
1164 * be non-conflicting.
1165 */
1166 if (splan->onConflictAction == ONCONFLICT_UPDATE ||
1168 {
1170
1172
1173 splan->onConflictSet =
1175 NULL, itlist,
1177 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1178
1179 splan->onConflictWhere = (Node *)
1181 NULL, itlist,
1183 rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1184
1185 pfree(itlist);
1186
1187 splan->exclRelTlist =
1188 fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
1189 }
1190
1191 /*
1192 * The MERGE statement produces the target rows by performing
1193 * a right join between the target relation and the source
1194 * relation (which could be a plain relation or a subquery).
1195 * The INSERT and UPDATE actions of the MERGE statement
1196 * require access to the columns from the source relation. We
1197 * arrange things so that the source relation attributes are
1198 * available as INNER_VAR and the target relation attributes
1199 * are available from the scan tuple.
1200 */
1201 if (splan->mergeActionLists != NIL)
1202 {
1203 List *newMJC = NIL;
1204 ListCell *lca,
1205 *lcj,
1206 *lcr;
1207
1208 /*
1209 * Fix the targetList of individual action nodes so that
1210 * the so-called "source relation" Vars are referenced as
1211 * INNER_VAR. Note that for this to work correctly during
1212 * execution, the ecxt_innertuple must be set to the tuple
1213 * obtained by executing the subplan, which is what
1214 * constitutes the "source relation".
1215 *
1216 * We leave the Vars from the result relation (i.e. the
1217 * target relation) unchanged i.e. those Vars would be
1218 * picked from the scan slot. So during execution, we must
1219 * ensure that ecxt_scantuple is setup correctly to refer
1220 * to the tuple from the target relation.
1221 */
1223
1225
1227 lcj, splan->mergeJoinConditions,
1228 lcr, splan->resultRelations)
1229 {
1230 List *mergeActionList = lfirst(lca);
1231 Node *mergeJoinCondition = lfirst(lcj);
1233
1234 foreach(l, mergeActionList)
1235 {
1237
1238 /* Fix targetList of each action. */
1239 action->targetList = fix_join_expr(root,
1240 action->targetList,
1241 NULL, itlist,
1242 resultrel,
1243 rtoffset,
1244 NRM_EQUAL,
1246
1247 /* Fix quals too. */
1248 action->qual = (Node *) fix_join_expr(root,
1249 (List *) action->qual,
1250 NULL, itlist,
1251 resultrel,
1252 rtoffset,
1253 NRM_EQUAL,
1255 }
1256
1257 /* Fix join condition too. */
1258 mergeJoinCondition = (Node *)
1260 (List *) mergeJoinCondition,
1261 NULL, itlist,
1262 resultrel,
1263 rtoffset,
1264 NRM_EQUAL,
1266 newMJC = lappend(newMJC, mergeJoinCondition);
1267 }
1268 splan->mergeJoinConditions = newMJC;
1269 }
1270
1271 splan->nominalRelation += rtoffset;
1272 if (splan->rootRelation)
1273 splan->rootRelation += rtoffset;
1274 splan->exclRelRTI += rtoffset;
1275
1276 foreach(l, splan->resultRelations)
1277 {
1278 lfirst_int(l) += rtoffset;
1279 }
1280 foreach(l, splan->rowMarks)
1281 {
1282 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1283
1284 rc->rti += rtoffset;
1285 rc->prti += rtoffset;
1286 }
1287
1288 /*
1289 * Append this ModifyTable node's final result relation RT
1290 * index(es) to the global list for the plan.
1291 */
1292 root->glob->resultRelations =
1293 list_concat(root->glob->resultRelations,
1294 splan->resultRelations);
1295 if (splan->rootRelation)
1296 {
1297 root->glob->resultRelations =
1298 lappend_int(root->glob->resultRelations,
1299 splan->rootRelation);
1300 }
1301 }
1302 break;
1303 case T_Append:
1304 /* Needs special treatment, see comments below */
1306 (Append *) plan,
1307 rtoffset);
1308 case T_MergeAppend:
1309 /* Needs special treatment, see comments below */
1311 (MergeAppend *) plan,
1312 rtoffset);
1313 case T_RecursiveUnion:
1314 /* This doesn't evaluate targetlist or check quals either */
1316 Assert(plan->qual == NIL);
1317 break;
1318 case T_BitmapAnd:
1319 {
1320 BitmapAnd *splan = (BitmapAnd *) plan;
1321
1322 /* BitmapAnd works like Append, but has no tlist */
1323 Assert(splan->plan.targetlist == NIL);
1324 Assert(splan->plan.qual == NIL);
1325 foreach(l, splan->bitmapplans)
1326 {
1328 (Plan *) lfirst(l),
1329 rtoffset);
1330 }
1331 }
1332 break;
1333 case T_BitmapOr:
1334 {
1335 BitmapOr *splan = (BitmapOr *) plan;
1336
1337 /* BitmapOr works like Append, but has no tlist */
1338 Assert(splan->plan.targetlist == NIL);
1339 Assert(splan->plan.qual == NIL);
1340 foreach(l, splan->bitmapplans)
1341 {
1343 (Plan *) lfirst(l),
1344 rtoffset);
1345 }
1346 }
1347 break;
1348 default:
1349 elog(ERROR, "unrecognized node type: %d",
1350 (int) nodeTag(plan));
1351 break;
1352 }
1353
1354 /*
1355 * Now recurse into child plans, if any
1356 *
1357 * NOTE: it is essential that we recurse into child plans AFTER we set
1358 * subplan references in this plan's tlist and quals. If we did the
1359 * reference-adjustments bottom-up, then we would fail to match this
1360 * plan's var nodes against the already-modified nodes of the children.
1361 */
1362 plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1363 plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1364
1365 return plan;
1366}

References Assert, BitmapAnd::bitmapplans, BitmapOr::bitmapplans, BitmapHeapScan::bitmapqualorig, build_tlist_index(), convert_combining_aggrefs(), copyObject, DO_AGGSPLIT_COMBINE, elog, ERROR, ModifyTable::exclRelRTI, ModifyTable::exclRelTlist, fb(), fix_join_expr(), fix_scan_expr(), fix_scan_list, forboth, forthree, FunctionScan::functions, IndexScan::indexorderby, IndexScan::indexorderbyorig, IndexScan::indexqual, BitmapIndexScan::indexqual, IndexScan::indexqualorig, BitmapIndexScan::indexqualorig, IsA, lappend(), lappend_int(), lca(), Plan::lefttree, lfirst, lfirst_int, Limit::limitCount, Limit::limitOffset, linitial, linitial_int, list_concat(), list_length(), makeNullConst(), makeVar(), ModifyTable::mergeActionLists, ModifyTable::mergeJoinConditions, NIL, nodeTag, ModifyTable::nominalRelation, NRM_EQUAL, NUM_EXEC_QUAL, NUM_EXEC_TLIST, offset_relid_set(), ONCONFLICT_SELECT, ONCONFLICT_UPDATE, ModifyTable::onConflictAction, ModifyTable::onConflictSet, ModifyTable::onConflictWhere, outerPlan, pfree(), Result::plan, ModifyTable::plan, BitmapAnd::plan, BitmapOr::plan, LockRows::plan, Limit::plan, plan, PlanRowMark::prti, Plan::qual, Result::relids, Result::resconstantqual, ModifyTable::resultRelations, ModifyTable::returningLists, root, ModifyTable::rootRelation, ROWID_VAR, ModifyTable::rowMarks, LockRows::rowMarks, PlanRowMark::rti, WindowAgg::runCondition, SeqScan::scan, SampleScan::scan, IndexScan::scan, BitmapIndexScan::scan, BitmapHeapScan::scan, TidScan::scan, TidRangeScan::scan, FunctionScan::scan, ValuesScan::scan, TableFuncScan::scan, CteScan::scan, NamedTuplestoreScan::scan, WorkTableScan::scan, Scan::scanrelid, set_append_references(), set_customscan_references(), set_dummy_tlist_references(), set_foreignscan_references(), set_hash_references(), set_indexonlyscan_references(), set_join_references(), set_mergeappend_references(), set_param_references(), set_plan_refs(), set_returning_clause_references(), set_subqueryscan_references(), set_upper_references(), set_windowagg_runcondition_references(), TableFuncScan::tablefunc, SampleScan::tablesample, Plan::targetlist, TidScan::tidquals, TidRangeScan::tidrangequals, ValuesScan::values_lists, Var::varattno, Var::varlevelsup, Var::varno, and ModifyTable::withCheckOptionLists.

Referenced by set_append_references(), set_customscan_references(), set_mergeappend_references(), set_plan_references(), and set_plan_refs().

◆ set_returning_clause_references()

static List * set_returning_clause_references ( PlannerInfo root,
List rlist,
Plan topplan,
Index  resultRelation,
int  rtoffset 
)
static

Definition at line 3477 of file setrefs.c.

3482{
3484
3485 /*
3486 * We can perform the desired Var fixup by abusing the fix_join_expr
3487 * machinery that formerly handled inner indexscan fixup. We search the
3488 * top plan's targetlist for Vars of non-result relations, and use
3489 * fix_join_expr to convert RETURNING Vars into references to those tlist
3490 * entries, while leaving result-rel Vars as-is.
3491 *
3492 * PlaceHolderVars will also be sought in the targetlist, but no
3493 * more-complex expressions will be. Note that it is not possible for a
3494 * PlaceHolderVar to refer to the result relation, since the result is
3495 * never below an outer join. If that case could happen, we'd have to be
3496 * prepared to pick apart the PlaceHolderVar and evaluate its contained
3497 * expression instead.
3498 */
3499 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3500
3502 rlist,
3503 itlist,
3504 NULL,
3505 resultRelation,
3506 rtoffset,
3507 NRM_EQUAL,
3509
3510 pfree(itlist);
3511
3512 return rlist;
3513}

References build_tlist_index_other_vars(), fb(), fix_join_expr(), NRM_EQUAL, NUM_EXEC_TLIST, pfree(), and root.

Referenced by set_plan_refs().

◆ set_subqueryscan_references()

static Plan * set_subqueryscan_references ( PlannerInfo root,
SubqueryScan plan,
int  rtoffset 
)
static

Definition at line 1452 of file setrefs.c.

1455{
1456 RelOptInfo *rel;
1457 Plan *result;
1458
1459 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1460 rel = find_base_rel(root, plan->scan.scanrelid);
1461
1462 /* Recursively process the subplan */
1463 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1464
1466 {
1467 Index scanrelid;
1468
1469 /*
1470 * We can omit the SubqueryScan node and just pull up the subplan.
1471 */
1473
1474 /* Remember that we removed a SubqueryScan */
1475 scanrelid = plan->scan.scanrelid + rtoffset;
1476 record_elided_node(root->glob, plan->subplan->plan_node_id,
1478 }
1479 else
1480 {
1481 /*
1482 * Keep the SubqueryScan node. We have to do the processing that
1483 * set_plan_references would otherwise have done on it. Notice we do
1484 * not do set_upper_references() here, because a SubqueryScan will
1485 * always have been created with correct references to its subplan's
1486 * outputs to begin with.
1487 */
1488 plan->scan.scanrelid += rtoffset;
1489 plan->scan.plan.targetlist =
1490 fix_scan_list(root, plan->scan.plan.targetlist,
1491 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1492 plan->scan.plan.qual =
1493 fix_scan_list(root, plan->scan.plan.qual,
1494 rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1495
1496 result = (Plan *) plan;
1497 }
1498
1499 return result;
1500}

References bms_make_singleton(), clean_up_removed_plan_level(), fb(), find_base_rel(), fix_scan_list, NUM_EXEC_QUAL, NUM_EXEC_TLIST, plan, record_elided_node(), result, root, set_plan_references(), RelOptInfo::subroot, and trivial_subqueryscan().

Referenced by set_plan_refs().

◆ set_upper_references()

static void set_upper_references ( PlannerInfo root,
Plan plan,
int  rtoffset 
)
static

Definition at line 2559 of file setrefs.c.

2560{
2561 Plan *subplan = plan->lefttree;
2562 indexed_tlist *subplan_itlist;
2564 ListCell *l;
2565
2566 subplan_itlist = build_tlist_index(subplan->targetlist);
2567
2568 /*
2569 * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2570 * in the targetlist and quals should have nullingrels that include the
2571 * effects of the grouping step, ie they will have nullingrels equal to
2572 * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2573 * step. In order to perform exact nullingrels matches, we remove the RT
2574 * index of the grouping step first.
2575 */
2576 if (IsA(plan, Agg) &&
2577 root->group_rtindex > 0 &&
2578 ((Agg *) plan)->groupingSets)
2579 {
2580 plan->targetlist = (List *)
2581 remove_nulling_relids((Node *) plan->targetlist,
2582 bms_make_singleton(root->group_rtindex),
2583 NULL);
2584 plan->qual = (List *)
2586 bms_make_singleton(root->group_rtindex),
2587 NULL);
2588 }
2589
2591 foreach(l, plan->targetlist)
2592 {
2594 Node *newexpr;
2595
2596 /* If it's a sort/group item, first try to match by sortref */
2597 if (tle->ressortgroupref != 0)
2598 {
2599 newexpr = (Node *)
2601 tle->ressortgroupref,
2602 subplan_itlist,
2603 OUTER_VAR);
2604 if (!newexpr)
2606 (Node *) tle->expr,
2607 subplan_itlist,
2608 OUTER_VAR,
2609 rtoffset,
2610 NRM_EQUAL,
2612 }
2613 else
2615 (Node *) tle->expr,
2616 subplan_itlist,
2617 OUTER_VAR,
2618 rtoffset,
2619 NRM_EQUAL,
2622 tle->expr = (Expr *) newexpr;
2624 }
2625 plan->targetlist = output_targetlist;
2626
2627 plan->qual = (List *)
2629 (Node *) plan->qual,
2630 subplan_itlist,
2631 OUTER_VAR,
2632 rtoffset,
2633 NRM_EQUAL,
2635
2636 pfree(subplan_itlist);
2637}

References bms_make_singleton(), build_tlist_index(), fb(), fix_upper_expr(), flatCopyTargetEntry(), IsA, lappend(), Plan::lefttree, lfirst, NIL, NRM_EQUAL, NUM_EXEC_QUAL, NUM_EXEC_TLIST, OUTER_VAR, pfree(), plan, remove_nulling_relids(), root, search_indexed_tlist_for_sortgroupref(), and Plan::targetlist.

Referenced by set_plan_refs().

◆ set_windowagg_runcondition_references()

static List * set_windowagg_runcondition_references ( PlannerInfo root,
List runcondition,
Plan plan 
)
static

Definition at line 3572 of file setrefs.c.

3575{
3576 List *newlist;
3578
3579 itlist = build_tlist_index(plan->targetlist);
3580
3582
3583 pfree(itlist);
3584
3585 return newlist;
3586}

References build_tlist_index(), fb(), fix_windowagg_condition_expr(), pfree(), plan, and root.

Referenced by set_plan_refs().

◆ trivial_subqueryscan()

bool trivial_subqueryscan ( SubqueryScan plan)

Definition at line 1528 of file setrefs.c.

1529{
1530 int attrno;
1531 ListCell *lp,
1532 *lc;
1533
1534 /* We might have detected this already; in which case reuse the result */
1535 if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1536 return true;
1537 if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1538 return false;
1539 Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1540 /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1541 plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1542
1543 if (plan->scan.plan.qual != NIL)
1544 return false;
1545
1546 if (list_length(plan->scan.plan.targetlist) !=
1547 list_length(plan->subplan->targetlist))
1548 return false; /* tlists not same length */
1549
1550 attrno = 1;
1551 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1552 {
1555
1556 if (ptle->resjunk != ctle->resjunk)
1557 return false; /* tlist doesn't match junk status */
1558
1559 /*
1560 * We accept either a Var referencing the corresponding element of the
1561 * subplan tlist, or a Const equaling the subplan element. See
1562 * generate_setop_tlist() for motivation.
1563 */
1564 if (ptle->expr && IsA(ptle->expr, Var))
1565 {
1566 Var *var = (Var *) ptle->expr;
1567
1568 Assert(var->varno == plan->scan.scanrelid);
1569 Assert(var->varlevelsup == 0);
1570 if (var->varattno != attrno)
1571 return false; /* out of order */
1572 }
1573 else if (ptle->expr && IsA(ptle->expr, Const))
1574 {
1575 if (!equal(ptle->expr, ctle->expr))
1576 return false;
1577 }
1578 else
1579 return false;
1580
1581 attrno++;
1582 }
1583
1584 /* Re-mark the SubqueryScan as deletable from the plan tree */
1585 plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1586
1587 return true;
1588}

References Assert, equal(), fb(), forboth, IsA, lfirst, list_length(), NIL, plan, SUBQUERY_SCAN_NONTRIVIAL, SUBQUERY_SCAN_TRIVIAL, SUBQUERY_SCAN_UNKNOWN, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by mark_async_capable_plan(), and set_subqueryscan_references().