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)
 
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.

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

◆ 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 542 of file setrefs.c.

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

References addRTEPermissionInfo(), PlannerGlobal::allRelids, bms_add_member(), fb(), PlannerGlobal::finalrtable, PlannerGlobal::finalrteperminfos, getRTEPermissionInfo(), lappend(), lappend_oid(), list_length(), 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 396 of file setrefs.c.

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

References add_rte_to_flat_rtable(), add_rtes_to_flat_rtable(), Assert, fb(), fetch_upper_rel(), flatten_unplanned_rtes(), IS_DUMMY_REL, lfirst, 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 2780 of file setrefs.c.

2781{
2784 ListCell *l;
2785
2786 /* Create data structure with enough slots for all tlist entries */
2787 itlist = (indexed_tlist *)
2789 list_length(tlist) * sizeof(tlist_vinfo));
2790
2791 itlist->tlist = tlist;
2792 itlist->has_ph_vars = false;
2793 itlist->has_non_vars = false;
2794
2795 /* Find the Vars and fill in the index array */
2796 vinfo = itlist->vars;
2797 foreach(l, tlist)
2798 {
2800
2801 if (tle->expr && IsA(tle->expr, Var))
2802 {
2803 Var *var = (Var *) tle->expr;
2804
2805 vinfo->varno = var->varno;
2806 vinfo->varattno = var->varattno;
2807 vinfo->resno = tle->resno;
2808 vinfo->varnullingrels = var->varnullingrels;
2809 vinfo++;
2810 }
2811 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2812 itlist->has_ph_vars = true;
2813 else
2814 itlist->has_non_vars = true;
2815 }
2816
2817 itlist->num_vars = (vinfo - itlist->vars);
2818
2819 return itlist;
2820}

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 2831 of file setrefs.c.

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

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 1567 of file setrefs.c.

1568{
1569 /*
1570 * We have to be sure we don't lose any initplans, so move any that were
1571 * attached to the parent plan to the child. If any are parallel-unsafe,
1572 * the child is no longer parallel-safe. As a cosmetic matter, also add
1573 * the initplans' run costs to the child's costs.
1574 */
1575 if (parent->initPlan)
1576 {
1578 bool unsafe_initplans;
1579
1582 child->startup_cost += initplan_cost;
1583 child->total_cost += initplan_cost;
1584 if (unsafe_initplans)
1585 child->parallel_safe = false;
1586
1587 /*
1588 * Attach plans this way so that parent's initplans are processed
1589 * before any pre-existing initplans of the child. Probably doesn't
1590 * matter, but let's preserve the ordering just in case.
1591 */
1592 child->initPlan = list_concat(parent->initPlan,
1593 child->initPlan);
1594 }
1595
1596 /*
1597 * We also have to transfer the parent's column labeling info into the
1598 * child, else columns sent to client will be improperly labeled if this
1599 * is the topmost plan level. resjunk and so on may be important too.
1600 */
1602
1603 return child;
1604}

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 2645 of file setrefs.c.

2646{
2647 if (node == NULL)
2648 return NULL;
2649 if (IsA(node, Aggref))
2650 {
2651 Aggref *orig_agg = (Aggref *) node;
2654
2655 /* Assert we've not chosen to partial-ize any unsupported cases */
2656 Assert(orig_agg->aggorder == NIL);
2657 Assert(orig_agg->aggdistinct == NIL);
2658
2659 /*
2660 * Since aggregate calls can't be nested, we needn't recurse into the
2661 * arguments. But for safety, flat-copy the Aggref node itself rather
2662 * than modifying it in-place.
2663 */
2665 memcpy(child_agg, orig_agg, sizeof(Aggref));
2666
2667 /*
2668 * For the parent Aggref, we want to copy all the fields of the
2669 * original aggregate *except* the args list, which we'll replace
2670 * below, and the aggfilter expression, which should be applied only
2671 * by the child not the parent. Rather than explicitly knowing about
2672 * all the other fields here, we can momentarily modify child_agg to
2673 * provide a suitable source for copyObject.
2674 */
2675 child_agg->args = NIL;
2676 child_agg->aggfilter = NULL;
2678 child_agg->args = orig_agg->args;
2679 child_agg->aggfilter = orig_agg->aggfilter;
2680
2681 /*
2682 * Now, set up child_agg to represent the first phase of partial
2683 * aggregation. For now, assume serialization is required.
2684 */
2686
2687 /*
2688 * And set up parent_agg to represent the second phase.
2689 */
2691 1, NULL, false));
2693
2694 return (Node *) parent_agg;
2695 }
2697}

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

Referenced by convert_combining_aggrefs(), and set_plan_refs().

◆ copyVar()

static Var * copyVar ( Var var)
inlinestatic

Definition at line 2029 of file setrefs.c.

2030{
2032
2033 *newvar = *var;
2034 return newvar;
2035}

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 3656 of file setrefs.c.

3660{
3661 PlannerGlobal glob;
3663
3664 /* Make up dummy planner state so we can use this module's machinery */
3665 MemSet(&glob, 0, sizeof(glob));
3666 glob.type = T_PlannerGlobal;
3667 glob.relationOids = NIL;
3668 glob.invalItems = NIL;
3669 /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3670 glob.dependsOnRole = false;
3671
3672 MemSet(&root, 0, sizeof(root));
3673 root.type = T_PlannerInfo;
3674 root.glob = &glob;
3675
3677
3678 *relationOids = glob.relationOids;
3679 *invalItems = glob.invalItems;
3680 *hasRowSecurity = glob.dependsOnRole;
3681}

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 3692 of file setrefs.c.

3693{
3694 if (node == NULL)
3695 return false;
3696 Assert(!IsA(node, PlaceHolderVar));
3697 if (IsA(node, Query))
3698 {
3699 Query *query = (Query *) node;
3700 ListCell *lc;
3701
3702 if (query->commandType == CMD_UTILITY)
3703 {
3704 /*
3705 * This logic must handle any utility command for which parse
3706 * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3707 *
3708 * Notably, CALL requires its own processing.
3709 */
3710 if (IsA(query->utilityStmt, CallStmt))
3711 {
3712 CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3713
3714 /* We need not examine funccall, just the transformed exprs */
3716 context);
3718 context);
3719 return false;
3720 }
3721
3722 /*
3723 * Ignore other utility statements, except those (such as EXPLAIN)
3724 * that contain a parsed-but-not-planned query. For those, we
3725 * just need to transfer our attention to the contained query.
3726 */
3727 query = UtilityContainsQuery(query->utilityStmt);
3728 if (query == NULL)
3729 return false;
3730 }
3731
3732 /* Remember if any Query has RLS quals applied by rewriter */
3733 if (query->hasRowSecurity)
3734 context->glob->dependsOnRole = true;
3735
3736 /* Collect relation OIDs in this Query's rtable */
3737 foreach(lc, query->rtable)
3738 {
3740
3741 if (rte->rtekind == RTE_RELATION ||
3742 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3743 (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
3744 context->glob->relationOids =
3745 lappend_oid(context->glob->relationOids, rte->relid);
3746 }
3747
3748 /* And recurse into the query's subexpressions */
3750 context, 0);
3751 }
3752 /* Extract function dependencies and check for regclass Consts */
3753 fix_expr_common(context, node);
3755 context);
3756}

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 3542 of file setrefs.c.

3543{
3544 if (root->minmax_aggs != NIL &&
3545 list_length(aggref->args) == 1)
3546 {
3548 ListCell *lc;
3549
3550 foreach(lc, root->minmax_aggs)
3551 {
3553
3554 if (mminfo->aggfnoid == aggref->aggfnoid &&
3555 equal(mminfo->target, curTarget->expr))
3556 return mminfo->param;
3557 }
3558 }
3559 return NULL;
3560}

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 2177 of file setrefs.c.

2179{
2181 Cost bestcost = 0;
2182 ListCell *lc;
2183
2184 /*
2185 * Compute the estimated cost of each subplan assuming num_exec
2186 * executions, and keep the cheapest one. In event of exact equality of
2187 * estimates, we prefer the later plan; this is a bit arbitrary, but in
2188 * current usage it biases us to break ties against fast-start subplans.
2189 */
2190 Assert(asplan->subplans != NIL);
2191
2192 foreach(lc, asplan->subplans)
2193 {
2195 Cost curcost;
2196
2197 curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
2198 if (bestplan == NULL || curcost <= bestcost)
2199 {
2200 bestplan = curplan;
2201 bestcost = curcost;
2202 }
2203
2204 /* Also mark all subplans that are in AlternativeSubPlans */
2205 root->isAltSubplan[curplan->plan_id - 1] = true;
2206 }
2207
2208 /* Mark the subplan we selected */
2209 root->isUsedSubplan[bestplan->plan_id - 1] = true;
2210
2211 return (Node *) bestplan;
2212}

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 2051 of file setrefs.c.

2052{
2053 /* We assume callers won't call us on a NULL pointer */
2054 if (IsA(node, Aggref))
2055 {
2057 ((Aggref *) node)->aggfnoid);
2058 }
2059 else if (IsA(node, WindowFunc))
2060 {
2062 ((WindowFunc *) node)->winfnoid);
2063 }
2064 else if (IsA(node, FuncExpr))
2065 {
2067 ((FuncExpr *) node)->funcid);
2068 }
2069 else if (IsA(node, OpExpr))
2070 {
2071 set_opfuncid((OpExpr *) node);
2073 ((OpExpr *) node)->opfuncid);
2074 }
2075 else if (IsA(node, DistinctExpr))
2076 {
2077 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2079 ((DistinctExpr *) node)->opfuncid);
2080 }
2081 else if (IsA(node, NullIfExpr))
2082 {
2083 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2085 ((NullIfExpr *) node)->opfuncid);
2086 }
2087 else if (IsA(node, ScalarArrayOpExpr))
2088 {
2089 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2090
2091 set_sa_opfuncid(saop);
2092 record_plan_function_dependency(root, saop->opfuncid);
2093
2094 if (OidIsValid(saop->hashfuncid))
2095 record_plan_function_dependency(root, saop->hashfuncid);
2096
2097 if (OidIsValid(saop->negfuncid))
2098 record_plan_function_dependency(root, saop->negfuncid);
2099 }
2100 else if (IsA(node, Const))
2101 {
2102 Const *con = (Const *) node;
2103
2104 /* Check for regclass reference */
2105 if (ISREGCLASSCONST(con))
2106 root->glob->relationOids =
2107 lappend_oid(root->glob->relationOids,
2108 DatumGetObjectId(con->constvalue));
2109 }
2110 else if (IsA(node, GroupingFunc))
2111 {
2112 GroupingFunc *g = (GroupingFunc *) node;
2113 AttrNumber *grouping_map = root->grouping_map;
2114
2115 /* If there are no grouping sets, we don't need this. */
2116
2117 Assert(grouping_map || g->cols == NIL);
2118
2119 if (grouping_map)
2120 {
2121 ListCell *lc;
2122 List *cols = NIL;
2123
2124 foreach(lc, g->refs)
2125 {
2126 cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2127 }
2128
2129 Assert(!g->cols || equal(cols, g->cols));
2130
2131 if (!g->cols)
2132 g->cols = cols;
2133 }
2134 }
2135}

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 3125 of file setrefs.c.

3133{
3134 fix_join_expr_context context;
3135
3136 context.root = root;
3137 context.outer_itlist = outer_itlist;
3138 context.inner_itlist = inner_itlist;
3139 context.acceptable_rel = acceptable_rel;
3140 context.rtoffset = rtoffset;
3141 context.nrm_match = nrm_match;
3142 context.num_exec = num_exec;
3143 return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3144}

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 3147 of file setrefs.c.

3148{
3149 Var *newvar;
3150
3151 if (node == NULL)
3152 return NULL;
3153 if (IsA(node, Var))
3154 {
3155 Var *var = (Var *) node;
3156
3157 /*
3158 * Verify that Vars with non-default varreturningtype only appear in
3159 * the RETURNING list, and refer to the target relation.
3160 */
3162 {
3163 if (context->inner_itlist != NULL ||
3164 context->outer_itlist == NULL ||
3165 context->acceptable_rel == 0)
3166 elog(ERROR, "variable returning old/new found outside RETURNING list");
3167 if (var->varno != context->acceptable_rel)
3168 elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
3169 var->varno, context->acceptable_rel);
3170 }
3171
3172 /* Look for the var in the input tlists, first in the outer */
3173 if (context->outer_itlist)
3174 {
3176 context->outer_itlist,
3177 OUTER_VAR,
3178 context->rtoffset,
3179 context->nrm_match);
3180 if (newvar)
3181 return (Node *) newvar;
3182 }
3183
3184 /* then in the inner. */
3185 if (context->inner_itlist)
3186 {
3188 context->inner_itlist,
3189 INNER_VAR,
3190 context->rtoffset,
3191 context->nrm_match);
3192 if (newvar)
3193 return (Node *) newvar;
3194 }
3195
3196 /* If it's for acceptable_rel, adjust and return it */
3197 if (var->varno == context->acceptable_rel)
3198 {
3199 var = copyVar(var);
3200 var->varno += context->rtoffset;
3201 if (var->varnosyn > 0)
3202 var->varnosyn += context->rtoffset;
3203 return (Node *) var;
3204 }
3205
3206 /* No referent found for Var */
3207 elog(ERROR, "variable not found in subplan target lists");
3208 }
3209 if (IsA(node, PlaceHolderVar))
3210 {
3211 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3212
3213 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3214 if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3215 {
3217 context->outer_itlist,
3218 OUTER_VAR,
3219 context->nrm_match);
3220 if (newvar)
3221 return (Node *) newvar;
3222 }
3223 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3224 {
3226 context->inner_itlist,
3227 INNER_VAR,
3228 context->nrm_match);
3229 if (newvar)
3230 return (Node *) newvar;
3231 }
3232
3233 /* If not supplied by input plans, evaluate the contained expr */
3234 /* XXX can we assert something about phnullingrels? */
3235 return fix_join_expr_mutator((Node *) phv->phexpr, context);
3236 }
3237 /* Try matching more complex expressions too, if tlists have any */
3238 if (context->outer_itlist && context->outer_itlist->has_non_vars)
3239 {
3241 context->outer_itlist,
3242 OUTER_VAR);
3243 if (newvar)
3244 return (Node *) newvar;
3245 }
3246 if (context->inner_itlist && context->inner_itlist->has_non_vars)
3247 {
3249 context->inner_itlist,
3250 INNER_VAR);
3251 if (newvar)
3252 return (Node *) newvar;
3253 }
3254 /* Special cases (apply only AFTER failing to match to lower tlist) */
3255 if (IsA(node, Param))
3256 return fix_param_node(context->root, (Param *) node);
3257 if (IsA(node, AlternativeSubPlan))
3259 (AlternativeSubPlan *) node,
3260 context->num_exec),
3261 context);
3262 fix_expr_common(context->root, node);
3263 return expression_tree_mutator(node, fix_join_expr_mutator, context);
3264}

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 2146 of file setrefs.c.

2147{
2148 if (p->paramkind == PARAM_MULTIEXPR)
2149 {
2150 int subqueryid = p->paramid >> 16;
2151 int colno = p->paramid & 0xFFFF;
2152 List *params;
2153
2154 if (subqueryid <= 0 ||
2155 subqueryid > list_length(root->multiexpr_params))
2156 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2157 params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2159 elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2160 return copyObject(list_nth(params, colno - 1));
2161 }
2162 return (Node *) copyObject(p);
2163}

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 2233 of file setrefs.c.

2234{
2235 fix_scan_expr_context context;
2236
2237 context.root = root;
2238 context.rtoffset = rtoffset;
2239 context.num_exec = num_exec;
2240
2241 if (rtoffset != 0 ||
2242 root->multiexpr_params != NIL ||
2243 root->glob->lastPHId != 0 ||
2244 root->minmax_aggs != NIL ||
2245 root->hasAlternativeSubPlans)
2246 {
2247 return fix_scan_expr_mutator(node, &context);
2248 }
2249 else
2250 {
2251 /*
2252 * If rtoffset == 0, we don't need to change any Vars, and if there
2253 * are no MULTIEXPR subqueries then we don't need to replace
2254 * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2255 * we won't need to remove them, and if there are no minmax Aggrefs we
2256 * won't need to replace them, and if there are no AlternativeSubPlans
2257 * we won't need to remove them. Then it's OK to just scribble on the
2258 * input node tree instead of copying (since the only change, filling
2259 * in any unset opfuncid fields, is harmless). This saves just enough
2260 * cycles to be noticeable on trivial queries.
2261 */
2262 (void) fix_scan_expr_walker(node, &context);
2263 return node;
2264 }
2265}

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 2268 of file setrefs.c.

2269{
2270 if (node == NULL)
2271 return NULL;
2272 if (IsA(node, Var))
2273 {
2274 Var *var = copyVar((Var *) node);
2275
2276 Assert(var->varlevelsup == 0);
2277
2278 /*
2279 * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2280 * But an indexqual expression could contain INDEX_VAR Vars.
2281 */
2282 Assert(var->varno != INNER_VAR);
2283 Assert(var->varno != OUTER_VAR);
2284 Assert(var->varno != ROWID_VAR);
2285 if (!IS_SPECIAL_VARNO(var->varno))
2286 var->varno += context->rtoffset;
2287 if (var->varnosyn > 0)
2288 var->varnosyn += context->rtoffset;
2289 return (Node *) var;
2290 }
2291 if (IsA(node, Param))
2292 return fix_param_node(context->root, (Param *) node);
2293 if (IsA(node, Aggref))
2294 {
2295 Aggref *aggref = (Aggref *) node;
2296 Param *aggparam;
2297
2298 /* See if the Aggref should be replaced by a Param */
2300 if (aggparam != NULL)
2301 {
2302 /* Make a copy of the Param for paranoia's sake */
2303 return (Node *) copyObject(aggparam);
2304 }
2305 /* If no match, just fall through to process it normally */
2306 }
2307 if (IsA(node, CurrentOfExpr))
2308 {
2309 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2310
2311 Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2312 cexpr->cvarno += context->rtoffset;
2313 return (Node *) cexpr;
2314 }
2315 if (IsA(node, PlaceHolderVar))
2316 {
2317 /* At scan level, we should always just evaluate the contained expr */
2318 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2319
2320 /* XXX can we assert something about phnullingrels? */
2321 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2322 }
2323 if (IsA(node, AlternativeSubPlan))
2325 (AlternativeSubPlan *) node,
2326 context->num_exec),
2327 context);
2328 fix_expr_common(context->root, node);
2329 return expression_tree_mutator(node, fix_scan_expr_mutator, context);
2330}

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 2333 of file setrefs.c.

2334{
2335 if (node == NULL)
2336 return false;
2337 Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
2338 Assert(!IsA(node, PlaceHolderVar));
2339 Assert(!IsA(node, AlternativeSubPlan));
2340 fix_expr_common(context->root, node);
2341 return expression_tree_walker(node, fix_scan_expr_walker, context);
2342}

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 3319 of file setrefs.c.

3320{
3321 Var *newvar;
3322
3323 if (node == NULL)
3324 return NULL;
3325 if (IsA(node, Var))
3326 {
3327 Var *var = (Var *) node;
3328
3330 context->subplan_itlist,
3331 context->newvarno,
3332 context->rtoffset,
3333 context->nrm_match);
3334 if (!newvar)
3335 elog(ERROR, "variable not found in subplan target list");
3336 return (Node *) newvar;
3337 }
3338 if (IsA(node, PlaceHolderVar))
3339 {
3340 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3341
3342 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3343 if (context->subplan_itlist->has_ph_vars)
3344 {
3346 context->subplan_itlist,
3347 context->newvarno,
3348 context->nrm_match);
3349 if (newvar)
3350 return (Node *) newvar;
3351 }
3352 /* If not supplied by input plan, evaluate the contained expr */
3353 /* XXX can we assert something about phnullingrels? */
3354 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3355 }
3356 /* Try matching more complex expressions too, if tlist has any */
3357 if (context->subplan_itlist->has_non_vars)
3358 {
3360 context->subplan_itlist,
3361 context->newvarno);
3362 if (newvar)
3363 return (Node *) newvar;
3364 }
3365 /* Special cases (apply only AFTER failing to match to lower tlist) */
3366 if (IsA(node, Param))
3367 return fix_param_node(context->root, (Param *) node);
3368 if (IsA(node, Aggref))
3369 {
3370 Aggref *aggref = (Aggref *) node;
3371 Param *aggparam;
3372
3373 /* See if the Aggref should be replaced by a Param */
3375 if (aggparam != NULL)
3376 {
3377 /* Make a copy of the Param for paranoia's sake */
3378 return (Node *) copyObject(aggparam);
3379 }
3380 /* If no match, just fall through to process it normally */
3381 }
3382 if (IsA(node, AlternativeSubPlan))
3384 (AlternativeSubPlan *) node,
3385 context->num_exec),
3386 context);
3387 fix_expr_common(context->root, node);
3388 return expression_tree_mutator(node, fix_upper_expr_mutator, context);
3389}

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 3494 of file setrefs.c.

3497{
3499
3500 context.root = root;
3501 context.subplan_itlist = subplan_itlist;
3502 context.newvarno = 0;
3503
3504 return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3505 &context);
3506}

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 3464 of file setrefs.c.

3466{
3467 if (node == NULL)
3468 return NULL;
3469
3470 if (IsA(node, WindowFunc))
3471 {
3472 Var *newvar;
3473
3475 context->subplan_itlist,
3476 context->newvarno);
3477 if (newvar)
3478 return (Node *) newvar;
3479 elog(ERROR, "WindowFunc not found in subplan target lists");
3480 }
3481
3482 return expression_tree_mutator(node,
3484 context);
3485}

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 497 of file setrefs.c.

498{
499 if (node == NULL)
500 return false;
501 if (IsA(node, RangeTblEntry))
502 {
503 RangeTblEntry *rte = (RangeTblEntry *) node;
504
505 /* As above, we need only save relation RTEs and former relations */
506 if (rte->rtekind == RTE_RELATION ||
507 (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
508 add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
509 return false;
510 }
511 if (IsA(node, Query))
512 {
513 /*
514 * Recurse into subselects. Must update cxt->query to this query so
515 * that the rtable and rteperminfos correspond with each other.
516 */
517 Query *save_query = cxt->query;
518 bool result;
519
520 cxt->query = (Query *) node;
521 result = query_tree_walker((Query *) node,
523 cxt,
525 cxt->query = save_query;
526 return result;
527 }
529}

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, 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 485 of file setrefs.c.

486{
487 flatten_rtes_walker_context cxt = {glob, rte->subquery};
488
489 /* Use query_tree_walker to find all RTEs in the parse tree */
490 (void) query_tree_walker(rte->subquery,
492 &cxt,
494}

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 2007 of file setrefs.c.

2008{
2009 Relids result = NULL;
2010 int rtindex;
2011
2012 /* If there's no offset to apply, we needn't recompute the value */
2013 if (rtoffset == 0)
2014 return relids;
2015 rtindex = -1;
2016 while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
2017 result = bms_add_member(result, rtindex + rtoffset);
2018 return result;
2019}

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

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

◆ record_plan_function_dependency()

void record_plan_function_dependency ( PlannerInfo root,
Oid  funcid 
)

Definition at line 3575 of file setrefs.c.

3576{
3577 /*
3578 * For performance reasons, we don't bother to track built-in functions;
3579 * we just assume they'll never change (or at least not in ways that'd
3580 * invalidate plans using them). For this purpose we can consider a
3581 * built-in function to be one with OID less than FirstUnpinnedObjectId.
3582 * Note that the OID generator guarantees never to generate such an OID
3583 * after startup, even at OID wraparound.
3584 */
3585 if (funcid >= (Oid) FirstUnpinnedObjectId)
3586 {
3588
3589 /*
3590 * It would work to use any syscache on pg_proc, but the easiest is
3591 * PROCOID since we already have the function's OID at hand. Note
3592 * that plancache.c knows we use PROCOID.
3593 */
3594 inval_item->cacheId = PROCOID;
3596 ObjectIdGetDatum(funcid));
3597
3598 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3599 }
3600}

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 3615 of file setrefs.c.

3616{
3617 /*
3618 * As in record_plan_function_dependency, ignore the possibility that
3619 * someone would change a built-in domain.
3620 */
3621 if (typid >= (Oid) FirstUnpinnedObjectId)
3622 {
3624
3625 /*
3626 * It would work to use any syscache on pg_type, but the easiest is
3627 * TYPEOID since we already have the type's OID at hand. Note that
3628 * plancache.c knows we use TYPEOID.
3629 */
3630 inval_item->cacheId = TYPEOID;
3632 ObjectIdGetDatum(typid));
3633
3634 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3635 }
3636}

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 1781 of file setrefs.c.

1782{
1783 PlannerGlobal *glob = root->glob;
1784 PartitionPruneInfo *pinfo;
1785 ListCell *l;
1786
1787 Assert(part_prune_index >= 0 &&
1788 part_prune_index < list_length(root->partPruneInfos));
1789 pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
1790 part_prune_index);
1791
1792 pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
1793 foreach(l, pinfo->prune_infos)
1794 {
1795 List *prune_infos = lfirst(l);
1796 ListCell *l2;
1797
1798 foreach(l2, prune_infos)
1799 {
1801 int i;
1802
1803 prelinfo->rtindex += rtoffset;
1804 prelinfo->initial_pruning_steps =
1805 fix_scan_list(root, prelinfo->initial_pruning_steps,
1806 rtoffset, 1);
1807 prelinfo->exec_pruning_steps =
1808 fix_scan_list(root, prelinfo->exec_pruning_steps,
1809 rtoffset, 1);
1810
1811 for (i = 0; i < prelinfo->nparts; i++)
1812 {
1813 /*
1814 * Non-leaf partitions and partitions that do not have a
1815 * subplan are not included in this map as mentioned in
1816 * make_partitionedrel_pruneinfo().
1817 */
1818 if (prelinfo->leafpart_rti_map[i])
1819 {
1820 prelinfo->leafpart_rti_map[i] += rtoffset;
1821 if (prelinfo->initial_pruning_steps)
1823 prelinfo->leafpart_rti_map[i]);
1824 }
1825 }
1826 }
1827 }
1828
1829 glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
1830
1831 return list_length(glob->partPruneInfos) - 1;
1832}

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 3007 of file setrefs.c.

3009{
3011
3012 /*
3013 * If it's a simple Const, replacing it with a Var is silly, even if there
3014 * happens to be an identical Const below; a Var is more expensive to
3015 * execute than a Const. What's more, replacing it could confuse some
3016 * places in the executor that expect to see simple Consts for, eg,
3017 * dropped columns.
3018 */
3019 if (IsA(node, Const))
3020 return NULL;
3021
3022 tle = tlist_member(node, itlist->tlist);
3023 if (tle)
3024 {
3025 /* Found a matching subplan output expression */
3026 Var *newvar;
3027
3028 newvar = makeVarFromTargetEntry(newvarno, tle);
3029 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3030 newvar->varattnosyn = 0;
3031 return newvar;
3032 }
3033 return NULL; /* no match */
3034}

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 2954 of file setrefs.c.

2957{
2958 ListCell *lc;
2959
2960 foreach(lc, itlist->tlist)
2961 {
2963
2964 if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2965 {
2967 Var *newvar;
2968
2969 /*
2970 * Analogously to search_indexed_tlist_for_var, we match on phid
2971 * only. We don't use equal(), partially for speed but mostly
2972 * because phnullingrels might not be exactly equal.
2973 */
2974 if (phv->phid != subphv->phid)
2975 continue;
2976
2977 /* Verify that we kept all the nullingrels machinations straight */
2978 if (!(nrm_match == NRM_SUBSET ?
2979 bms_is_subset(phv->phnullingrels, subphv->phnullingrels) :
2980 nrm_match == NRM_SUPERSET ?
2981 bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
2982 bms_equal(subphv->phnullingrels, phv->phnullingrels)))
2983 elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
2984 bmsToString(phv->phnullingrels),
2985 bmsToString(subphv->phnullingrels),
2986 phv->phid);
2987
2988 /* Found a matching subplan output expression */
2989 newvar = makeVarFromTargetEntry(newvarno, tle);
2990 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2991 newvar->varattnosyn = 0;
2992 return newvar;
2993 }
2994 }
2995 return NULL; /* no match */
2996}

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 3047 of file setrefs.c.

3051{
3052 ListCell *lc;
3053
3054 foreach(lc, itlist->tlist)
3055 {
3057
3058 /*
3059 * Usually the equal() check is redundant, but in setop plans it may
3060 * not be, since prepunion.c assigns ressortgroupref equal to the
3061 * column resno without regard to whether that matches the topmost
3062 * level's sortgrouprefs and without regard to whether any implicit
3063 * coercions are added in the setop tree. We might have to clean that
3064 * up someday; but for now, just ignore any false matches.
3065 */
3066 if (tle->ressortgroupref == sortgroupref &&
3067 equal(node, tle->expr))
3068 {
3069 /* Found a matching subplan output expression */
3070 Var *newvar;
3071
3072 newvar = makeVarFromTargetEntry(newvarno, tle);
3073 newvar->varnosyn = 0; /* wasn't ever a plain Var */
3074 newvar->varattnosyn = 0;
3075 return newvar;
3076 }
3077 }
3078 return NULL; /* no match */
3079}

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 2889 of file setrefs.c.

2892{
2893 int varno = var->varno;
2894 AttrNumber varattno = var->varattno;
2896 int i;
2897
2898 vinfo = itlist->vars;
2899 i = itlist->num_vars;
2900 while (i-- > 0)
2901 {
2902 if (vinfo->varno == varno && vinfo->varattno == varattno)
2903 {
2904 /* Found a match */
2905 Var *newvar = copyVar(var);
2906
2907 /*
2908 * Verify that we kept all the nullingrels machinations straight.
2909 *
2910 * XXX we skip the check for system columns and whole-row Vars.
2911 * That's because such Vars might be row identity Vars, which are
2912 * generated without any varnullingrels. It'd be hard to do
2913 * otherwise, since they're normally made very early in planning,
2914 * when we haven't looked at the jointree yet and don't know which
2915 * joins might null such Vars. Doesn't seem worth the expense to
2916 * make them fully valid. (While it's slightly annoying that we
2917 * thereby lose checking for user-written references to such
2918 * columns, it seems unlikely that a bug in nullingrels logic
2919 * would affect only system columns.)
2920 */
2921 if (!(varattno <= 0 ||
2922 (nrm_match == NRM_SUBSET ?
2923 bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2924 nrm_match == NRM_SUPERSET ?
2925 bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2926 bms_equal(vinfo->varnullingrels, var->varnullingrels))))
2927 elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2928 bmsToString(var->varnullingrels),
2929 bmsToString(vinfo->varnullingrels),
2930 varno, varattno);
2931
2932 newvar->varno = newvarno;
2933 newvar->varattno = vinfo->resno;
2934 if (newvar->varnosyn > 0)
2935 newvar->varnosyn += rtoffset;
2936 return newvar;
2937 }
2938 vinfo++;
2939 }
2940 return NULL; /* no match */
2941}

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 1842 of file setrefs.c.

1845{
1846 ListCell *l;
1847
1848 /*
1849 * Append, like Sort et al, doesn't actually evaluate its targetlist or
1850 * check quals. If it's got exactly one child plan, then it's not doing
1851 * anything useful at all, and we can strip it out.
1852 */
1853 Assert(aplan->plan.qual == NIL);
1854
1855 /* First, we gotta recurse on the children */
1856 foreach(l, aplan->appendplans)
1857 {
1858 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1859 }
1860
1861 /*
1862 * See if it's safe to get rid of the Append entirely. For this to be
1863 * safe, there must be only one child plan and that child plan's parallel
1864 * awareness must match the Append's. The reason for the latter is that
1865 * if the Append is parallel aware and the child is not, then the calling
1866 * plan may execute the non-parallel aware child multiple times. (If you
1867 * change these rules, update create_append_path to match.)
1868 */
1869 if (list_length(aplan->appendplans) == 1)
1870 {
1871 Plan *p = (Plan *) linitial(aplan->appendplans);
1872
1873 if (p->parallel_aware == aplan->plan.parallel_aware)
1874 return clean_up_removed_plan_level((Plan *) aplan, p);
1875 }
1876
1877 /*
1878 * Otherwise, clean up the Append as needed. It's okay to do this after
1879 * recursing to the children, because set_dummy_tlist_references doesn't
1880 * look at those.
1881 */
1882 set_dummy_tlist_references((Plan *) aplan, rtoffset);
1883
1884 aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1885
1886 /*
1887 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1888 * Also update the RT indexes present in it to add the offset.
1889 */
1890 if (aplan->part_prune_index >= 0)
1891 aplan->part_prune_index =
1892 register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
1893
1894 /* We don't need to recurse to lefttree or righttree ... */
1895 Assert(aplan->plan.lefttree == NULL);
1896 Assert(aplan->plan.righttree == NULL);
1897
1898 return (Plan *) aplan;
1899}

References Assert, clean_up_removed_plan_level(), fb(), lfirst, linitial, list_length(), NIL, offset_relid_set(), Plan::parallel_aware, register_partpruneinfo(), 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 1698 of file setrefs.c.

1701{
1702 ListCell *lc;
1703
1704 /* Adjust scanrelid if it's valid */
1705 if (cscan->scan.scanrelid > 0)
1706 cscan->scan.scanrelid += rtoffset;
1707
1708 if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1709 {
1710 /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1711 indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
1712
1713 cscan->scan.plan.targetlist = (List *)
1715 (Node *) cscan->scan.plan.targetlist,
1716 itlist,
1717 INDEX_VAR,
1718 rtoffset,
1719 NRM_EQUAL,
1721 cscan->scan.plan.qual = (List *)
1723 (Node *) cscan->scan.plan.qual,
1724 itlist,
1725 INDEX_VAR,
1726 rtoffset,
1727 NRM_EQUAL,
1728 NUM_EXEC_QUAL((Plan *) cscan));
1729 cscan->custom_exprs = (List *)
1731 (Node *) cscan->custom_exprs,
1732 itlist,
1733 INDEX_VAR,
1734 rtoffset,
1735 NRM_EQUAL,
1736 NUM_EXEC_QUAL((Plan *) cscan));
1737 pfree(itlist);
1738 /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1739 cscan->custom_scan_tlist =
1740 fix_scan_list(root, cscan->custom_scan_tlist,
1741 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1742 }
1743 else
1744 {
1745 /* Adjust tlist, qual, custom_exprs in the standard way */
1746 cscan->scan.plan.targetlist =
1747 fix_scan_list(root, cscan->scan.plan.targetlist,
1748 rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1749 cscan->scan.plan.qual =
1750 fix_scan_list(root, cscan->scan.plan.qual,
1751 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1752 cscan->custom_exprs =
1753 fix_scan_list(root, cscan->custom_exprs,
1754 rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1755 }
1756
1757 /* Adjust child plan-nodes recursively, if needed */
1758 foreach(lc, cscan->custom_plans)
1759 {
1760 lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1761 }
1762
1763 cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1764}

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 2713 of file setrefs.c.

2714{
2716 ListCell *l;
2717
2719 foreach(l, plan->targetlist)
2720 {
2722 Var *oldvar = (Var *) tle->expr;
2723 Var *newvar;
2724
2725 /*
2726 * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2727 * as Consts, not Vars referencing Consts. Here, there's no speed
2728 * advantage to be had, but it makes EXPLAIN output look cleaner, and
2729 * again it avoids confusing the executor.
2730 */
2731 if (IsA(oldvar, Const))
2732 {
2733 /* just reuse the existing TLE node */
2735 continue;
2736 }
2737
2739 tle->resno,
2740 exprType((Node *) oldvar),
2741 exprTypmod((Node *) oldvar),
2743 0);
2744 if (IsA(oldvar, Var) &&
2745 oldvar->varnosyn > 0)
2746 {
2747 newvar->varnosyn = oldvar->varnosyn + rtoffset;
2748 newvar->varattnosyn = oldvar->varattnosyn;
2749 }
2750 else
2751 {
2752 newvar->varnosyn = 0; /* wasn't ever a plain Var */
2753 newvar->varattnosyn = 0;
2754 }
2755
2757 tle->expr = (Expr *) newvar;
2759 }
2760 plan->targetlist = output_targetlist;
2761
2762 /* We don't touch plan->qual here */
2763}

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 1611 of file setrefs.c.

1614{
1615 /* Adjust scanrelid if it's valid */
1616 if (fscan->scan.scanrelid > 0)
1617 fscan->scan.scanrelid += rtoffset;
1618
1619 if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1620 {
1621 /*
1622 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1623 * foreign scan tuple
1624 */
1625 indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
1626
1627 fscan->scan.plan.targetlist = (List *)
1629 (Node *) fscan->scan.plan.targetlist,
1630 itlist,
1631 INDEX_VAR,
1632 rtoffset,
1633 NRM_EQUAL,
1635 fscan->scan.plan.qual = (List *)
1637 (Node *) fscan->scan.plan.qual,
1638 itlist,
1639 INDEX_VAR,
1640 rtoffset,
1641 NRM_EQUAL,
1642 NUM_EXEC_QUAL((Plan *) fscan));
1643 fscan->fdw_exprs = (List *)
1645 (Node *) fscan->fdw_exprs,
1646 itlist,
1647 INDEX_VAR,
1648 rtoffset,
1649 NRM_EQUAL,
1650 NUM_EXEC_QUAL((Plan *) fscan));
1651 fscan->fdw_recheck_quals = (List *)
1653 (Node *) fscan->fdw_recheck_quals,
1654 itlist,
1655 INDEX_VAR,
1656 rtoffset,
1657 NRM_EQUAL,
1658 NUM_EXEC_QUAL((Plan *) fscan));
1659 pfree(itlist);
1660 /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1661 fscan->fdw_scan_tlist =
1662 fix_scan_list(root, fscan->fdw_scan_tlist,
1663 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1664 }
1665 else
1666 {
1667 /*
1668 * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1669 * way
1670 */
1671 fscan->scan.plan.targetlist =
1672 fix_scan_list(root, fscan->scan.plan.targetlist,
1673 rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1674 fscan->scan.plan.qual =
1675 fix_scan_list(root, fscan->scan.plan.qual,
1676 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1677 fscan->fdw_exprs =
1678 fix_scan_list(root, fscan->fdw_exprs,
1679 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1680 fscan->fdw_recheck_quals =
1681 fix_scan_list(root, fscan->fdw_recheck_quals,
1682 rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1683 }
1684
1685 fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1686 fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1687
1688 /* Adjust resultRelation if it's valid */
1689 if (fscan->resultRelation > 0)
1690 fscan->resultRelation += rtoffset;
1691}

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 1974 of file setrefs.c.

1975{
1976 Hash *hplan = (Hash *) plan;
1977 Plan *outer_plan = plan->lefttree;
1978 indexed_tlist *outer_itlist;
1979
1980 /*
1981 * Hash's hashkeys are used when feeding tuples into the hashtable,
1982 * therefore have them reference Hash's outer plan (which itself is the
1983 * inner plan of the HashJoin).
1984 */
1985 outer_itlist = build_tlist_index(outer_plan->targetlist);
1986 hplan->hashkeys = (List *)
1988 (Node *) hplan->hashkeys,
1989 outer_itlist,
1990 OUTER_VAR,
1991 rtoffset,
1992 NRM_EQUAL,
1994
1995 /* Hash doesn't project */
1997
1998 /* Hash nodes don't have their own quals */
1999 Assert(plan->qual == NIL);
2000}

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 1354 of file setrefs.c.

1357{
1360 ListCell *lc;
1361
1362 /*
1363 * Vars in the plan node's targetlist, qual, and recheckqual must only
1364 * reference columns that the index AM can actually return. To ensure
1365 * this, remove non-returnable columns (which are marked as resjunk) from
1366 * the indexed tlist. We can just drop them because the indexed_tlist
1367 * machinery pays attention to TLE resnos, not physical list position.
1368 */
1370 foreach(lc, plan->indextlist)
1371 {
1373
1374 if (!indextle->resjunk)
1376 }
1377
1379
1380 plan->scan.scanrelid += rtoffset;
1381 plan->scan.plan.targetlist = (List *)
1383 (Node *) plan->scan.plan.targetlist,
1385 INDEX_VAR,
1386 rtoffset,
1387 NRM_EQUAL,
1388 NUM_EXEC_TLIST((Plan *) plan));
1389 plan->scan.plan.qual = (List *)
1391 (Node *) plan->scan.plan.qual,
1393 INDEX_VAR,
1394 rtoffset,
1395 NRM_EQUAL,
1396 NUM_EXEC_QUAL((Plan *) plan));
1397 plan->recheckqual = (List *)
1399 (Node *) plan->recheckqual,
1401 INDEX_VAR,
1402 rtoffset,
1403 NRM_EQUAL,
1404 NUM_EXEC_QUAL((Plan *) plan));
1405 /* indexqual is already transformed to reference index columns */
1406 plan->indexqual = fix_scan_list(root, plan->indexqual,
1407 rtoffset, 1);
1408 /* indexorderby is already transformed to reference index columns */
1409 plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1410 rtoffset, 1);
1411 /* indextlist must NOT be transformed to reference index columns */
1412 plan->indextlist = fix_scan_list(root, plan->indextlist,
1413 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1414
1416
1417 return (Plan *) plan;
1418}

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 2353 of file setrefs.c.

2354{
2355 Plan *outer_plan = join->plan.lefttree;
2356 Plan *inner_plan = join->plan.righttree;
2357 indexed_tlist *outer_itlist;
2358 indexed_tlist *inner_itlist;
2359
2360 outer_itlist = build_tlist_index(outer_plan->targetlist);
2361 inner_itlist = build_tlist_index(inner_plan->targetlist);
2362
2363 /*
2364 * First process the joinquals (including merge or hash clauses). These
2365 * are logically below the join so they can always use all values
2366 * available from the input tlists. It's okay to also handle
2367 * NestLoopParams now, because those couldn't refer to nullable
2368 * subexpressions.
2369 */
2370 join->joinqual = fix_join_expr(root,
2371 join->joinqual,
2372 outer_itlist,
2373 inner_itlist,
2374 (Index) 0,
2375 rtoffset,
2376 NRM_EQUAL,
2377 NUM_EXEC_QUAL((Plan *) join));
2378
2379 /* Now do join-type-specific stuff */
2380 if (IsA(join, NestLoop))
2381 {
2382 NestLoop *nl = (NestLoop *) join;
2383 ListCell *lc;
2384
2385 foreach(lc, nl->nestParams)
2386 {
2388
2389 /*
2390 * Because we don't reparameterize parameterized paths to match
2391 * the outer-join level at which they are used, Vars seen in the
2392 * NestLoopParam expression may have nullingrels that are just a
2393 * subset of those in the Vars actually available from the outer
2394 * side. (Lateral references can also cause this, as explained in
2395 * the comments for identify_current_nestloop_params.) Not
2396 * checking this exactly is a bit grotty, but the work needed to
2397 * make things match up perfectly seems well out of proportion to
2398 * the value.
2399 */
2401 (Node *) nlp->paramval,
2402 outer_itlist,
2403 OUTER_VAR,
2404 rtoffset,
2405 NRM_SUBSET,
2406 NUM_EXEC_TLIST(outer_plan));
2407 /* Check we replaced any PlaceHolderVar with simple Var */
2408 if (!(IsA(nlp->paramval, Var) &&
2409 nlp->paramval->varno == OUTER_VAR))
2410 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2411 }
2412 }
2413 else if (IsA(join, MergeJoin))
2414 {
2415 MergeJoin *mj = (MergeJoin *) join;
2416
2418 mj->mergeclauses,
2419 outer_itlist,
2420 inner_itlist,
2421 (Index) 0,
2422 rtoffset,
2423 NRM_EQUAL,
2424 NUM_EXEC_QUAL((Plan *) join));
2425 }
2426 else if (IsA(join, HashJoin))
2427 {
2428 HashJoin *hj = (HashJoin *) join;
2429
2431 hj->hashclauses,
2432 outer_itlist,
2433 inner_itlist,
2434 (Index) 0,
2435 rtoffset,
2436 NRM_EQUAL,
2437 NUM_EXEC_QUAL((Plan *) join));
2438
2439 /*
2440 * HashJoin's hashkeys are used to look for matching tuples from its
2441 * outer plan (not the Hash node!) in the hashtable.
2442 */
2443 hj->hashkeys = (List *) fix_upper_expr(root,
2444 (Node *) hj->hashkeys,
2445 outer_itlist,
2446 OUTER_VAR,
2447 rtoffset,
2448 NRM_EQUAL,
2449 NUM_EXEC_QUAL((Plan *) join));
2450 }
2451
2452 /*
2453 * Now we need to fix up the targetlist and qpqual, which are logically
2454 * above the join. This means that, if it's not an inner join, any Vars
2455 * and PHVs appearing here should have nullingrels that include the
2456 * effects of the outer join, ie they will have nullingrels equal to the
2457 * input Vars' nullingrels plus the bit added by the outer join. We don't
2458 * currently have enough info available here to identify what that should
2459 * be, so we just tell fix_join_expr to accept superset nullingrels
2460 * matches instead of exact ones.
2461 */
2462 join->plan.targetlist = fix_join_expr(root,
2463 join->plan.targetlist,
2464 outer_itlist,
2465 inner_itlist,
2466 (Index) 0,
2467 rtoffset,
2469 NUM_EXEC_TLIST((Plan *) join));
2470 join->plan.qual = fix_join_expr(root,
2471 join->plan.qual,
2472 outer_itlist,
2473 inner_itlist,
2474 (Index) 0,
2475 rtoffset,
2477 NUM_EXEC_QUAL((Plan *) join));
2478
2479 pfree(outer_itlist);
2480 pfree(inner_itlist);
2481}

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 1909 of file setrefs.c.

1912{
1913 ListCell *l;
1914
1915 /*
1916 * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1917 * or check quals. If it's got exactly one child plan, then it's not
1918 * doing anything useful at all, and we can strip it out.
1919 */
1920 Assert(mplan->plan.qual == NIL);
1921
1922 /* First, we gotta recurse on the children */
1923 foreach(l, mplan->mergeplans)
1924 {
1925 lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1926 }
1927
1928 /*
1929 * See if it's safe to get rid of the MergeAppend entirely. For this to
1930 * be safe, there must be only one child plan and that child plan's
1931 * parallel awareness must match the MergeAppend's. The reason for the
1932 * latter is that if the MergeAppend is parallel aware and the child is
1933 * not, then the calling plan may execute the non-parallel aware child
1934 * multiple times. (If you change these rules, update
1935 * create_merge_append_path to match.)
1936 */
1937 if (list_length(mplan->mergeplans) == 1)
1938 {
1939 Plan *p = (Plan *) linitial(mplan->mergeplans);
1940
1941 if (p->parallel_aware == mplan->plan.parallel_aware)
1942 return clean_up_removed_plan_level((Plan *) mplan, p);
1943 }
1944
1945 /*
1946 * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1947 * after recursing to the children, because set_dummy_tlist_references
1948 * doesn't look at those.
1949 */
1950 set_dummy_tlist_references((Plan *) mplan, rtoffset);
1951
1952 mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
1953
1954 /*
1955 * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1956 * Also update the RT indexes present in it to add the offset.
1957 */
1958 if (mplan->part_prune_index >= 0)
1959 mplan->part_prune_index =
1960 register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
1961
1962 /* We don't need to recurse to lefttree or righttree ... */
1963 Assert(mplan->plan.lefttree == NULL);
1964 Assert(mplan->plan.righttree == NULL);
1965
1966 return (Plan *) mplan;
1967}

References Assert, clean_up_removed_plan_level(), fb(), lfirst, linitial, list_length(), NIL, offset_relid_set(), Plan::parallel_aware, register_partpruneinfo(), 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 2590 of file setrefs.c.

2591{
2593
2594 if (plan->lefttree->extParam)
2595 {
2598 ListCell *l;
2599
2600 for (proot = root; proot != NULL; proot = proot->parent_root)
2601 {
2602 foreach(l, proot->init_plans)
2603 {
2605 ListCell *l2;
2606
2607 foreach(l2, initsubplan->setParam)
2608 {
2610 }
2611 }
2612 }
2613
2614 /*
2615 * Remember the list of all external initplan params that are used by
2616 * the children of Gather or Gather merge node.
2617 */
2618 if (IsA(plan, Gather))
2619 ((Gather *) plan)->initParam =
2620 bms_intersect(plan->lefttree->extParam, initSetParam);
2621 else
2622 ((GatherMerge *) plan)->initParam =
2623 bms_intersect(plan->lefttree->extParam, initSetParam);
2624 }
2625}

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 288 of file setrefs.c.

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

References add_rtes_to_flat_rtable(), PlannerGlobal::appendRelations, Assert, fb(), PlannerGlobal::finalrowmarks, PlannerGlobal::finalrtable, foreach_current_index, lappend(), lfirst, lfirst_node, list_length(), NIL, palloc0(), palloc_object, plan, 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 619 of file setrefs.c.

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

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(), 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 3420 of file setrefs.c.

3425{
3427
3428 /*
3429 * We can perform the desired Var fixup by abusing the fix_join_expr
3430 * machinery that formerly handled inner indexscan fixup. We search the
3431 * top plan's targetlist for Vars of non-result relations, and use
3432 * fix_join_expr to convert RETURNING Vars into references to those tlist
3433 * entries, while leaving result-rel Vars as-is.
3434 *
3435 * PlaceHolderVars will also be sought in the targetlist, but no
3436 * more-complex expressions will be. Note that it is not possible for a
3437 * PlaceHolderVar to refer to the result relation, since the result is
3438 * never below an outer join. If that case could happen, we'd have to be
3439 * prepared to pick apart the PlaceHolderVar and evaluate its contained
3440 * expression instead.
3441 */
3442 itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3443
3445 rlist,
3446 itlist,
3447 NULL,
3448 resultRelation,
3449 rtoffset,
3450 NRM_EQUAL,
3452
3453 pfree(itlist);
3454
3455 return rlist;
3456}

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 1428 of file setrefs.c.

1431{
1432 RelOptInfo *rel;
1433 Plan *result;
1434
1435 /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1436 rel = find_base_rel(root, plan->scan.scanrelid);
1437
1438 /* Recursively process the subplan */
1439 plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1440
1442 {
1443 /*
1444 * We can omit the SubqueryScan node and just pull up the subplan.
1445 */
1446 result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
1447 }
1448 else
1449 {
1450 /*
1451 * Keep the SubqueryScan node. We have to do the processing that
1452 * set_plan_references would otherwise have done on it. Notice we do
1453 * not do set_upper_references() here, because a SubqueryScan will
1454 * always have been created with correct references to its subplan's
1455 * outputs to begin with.
1456 */
1457 plan->scan.scanrelid += rtoffset;
1458 plan->scan.plan.targetlist =
1459 fix_scan_list(root, plan->scan.plan.targetlist,
1460 rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1461 plan->scan.plan.qual =
1462 fix_scan_list(root, plan->scan.plan.qual,
1463 rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1464
1465 result = (Plan *) plan;
1466 }
1467
1468 return result;
1469}

References clean_up_removed_plan_level(), find_base_rel(), fix_scan_list, NUM_EXEC_QUAL, NUM_EXEC_TLIST, plan, 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 2502 of file setrefs.c.

2503{
2504 Plan *subplan = plan->lefttree;
2505 indexed_tlist *subplan_itlist;
2507 ListCell *l;
2508
2509 subplan_itlist = build_tlist_index(subplan->targetlist);
2510
2511 /*
2512 * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2513 * in the targetlist and quals should have nullingrels that include the
2514 * effects of the grouping step, ie they will have nullingrels equal to
2515 * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2516 * step. In order to perform exact nullingrels matches, we remove the RT
2517 * index of the grouping step first.
2518 */
2519 if (IsA(plan, Agg) &&
2520 root->group_rtindex > 0 &&
2521 ((Agg *) plan)->groupingSets)
2522 {
2523 plan->targetlist = (List *)
2524 remove_nulling_relids((Node *) plan->targetlist,
2525 bms_make_singleton(root->group_rtindex),
2526 NULL);
2527 plan->qual = (List *)
2529 bms_make_singleton(root->group_rtindex),
2530 NULL);
2531 }
2532
2534 foreach(l, plan->targetlist)
2535 {
2537 Node *newexpr;
2538
2539 /* If it's a sort/group item, first try to match by sortref */
2540 if (tle->ressortgroupref != 0)
2541 {
2542 newexpr = (Node *)
2544 tle->ressortgroupref,
2545 subplan_itlist,
2546 OUTER_VAR);
2547 if (!newexpr)
2549 (Node *) tle->expr,
2550 subplan_itlist,
2551 OUTER_VAR,
2552 rtoffset,
2553 NRM_EQUAL,
2555 }
2556 else
2558 (Node *) tle->expr,
2559 subplan_itlist,
2560 OUTER_VAR,
2561 rtoffset,
2562 NRM_EQUAL,
2565 tle->expr = (Expr *) newexpr;
2567 }
2568 plan->targetlist = output_targetlist;
2569
2570 plan->qual = (List *)
2572 (Node *) plan->qual,
2573 subplan_itlist,
2574 OUTER_VAR,
2575 rtoffset,
2576 NRM_EQUAL,
2578
2579 pfree(subplan_itlist);
2580}

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 3515 of file setrefs.c.

3518{
3519 List *newlist;
3521
3522 itlist = build_tlist_index(plan->targetlist);
3523
3525
3526 pfree(itlist);
3527
3528 return newlist;
3529}

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 1497 of file setrefs.c.

1498{
1499 int attrno;
1500 ListCell *lp,
1501 *lc;
1502
1503 /* We might have detected this already; in which case reuse the result */
1504 if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1505 return true;
1506 if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1507 return false;
1508 Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1509 /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1510 plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1511
1512 if (plan->scan.plan.qual != NIL)
1513 return false;
1514
1515 if (list_length(plan->scan.plan.targetlist) !=
1516 list_length(plan->subplan->targetlist))
1517 return false; /* tlists not same length */
1518
1519 attrno = 1;
1520 forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1521 {
1524
1525 if (ptle->resjunk != ctle->resjunk)
1526 return false; /* tlist doesn't match junk status */
1527
1528 /*
1529 * We accept either a Var referencing the corresponding element of the
1530 * subplan tlist, or a Const equaling the subplan element. See
1531 * generate_setop_tlist() for motivation.
1532 */
1533 if (ptle->expr && IsA(ptle->expr, Var))
1534 {
1535 Var *var = (Var *) ptle->expr;
1536
1537 Assert(var->varno == plan->scan.scanrelid);
1538 Assert(var->varlevelsup == 0);
1539 if (var->varattno != attrno)
1540 return false; /* out of order */
1541 }
1542 else if (ptle->expr && IsA(ptle->expr, Const))
1543 {
1544 if (!equal(ptle->expr, ctle->expr))
1545 return false;
1546 }
1547 else
1548 return false;
1549
1550 attrno++;
1551 }
1552
1553 /* Re-mark the SubqueryScan as deletable from the plan tree */
1554 plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1555
1556 return true;
1557}

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().