PostgreSQL Source Code  git master
prepjointree.c File Reference
#include "postgres.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/multibitmapset.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "optimizer/placeholder.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
Include dependency graph for prepjointree.c:

Go to the source code of this file.

Data Structures

struct  pullup_replace_vars_context
 
struct  reduce_outer_joins_pass1_state
 
struct  reduce_outer_joins_pass2_state
 
struct  reduce_outer_joins_partial_state
 
struct  find_dependent_phvs_context
 
struct  substitute_phv_relids_context
 

Typedefs

typedef struct pullup_replace_vars_context pullup_replace_vars_context
 
typedef struct reduce_outer_joins_pass1_state reduce_outer_joins_pass1_state
 
typedef struct reduce_outer_joins_pass2_state reduce_outer_joins_pass2_state
 
typedef struct reduce_outer_joins_partial_state reduce_outer_joins_partial_state
 

Functions

static Nodepull_up_sublinks_jointree_recurse (PlannerInfo *root, Node *jtnode, Relids *relids)
 
static Nodepull_up_sublinks_qual_recurse (PlannerInfo *root, Node *node, Node **jtlink1, Relids available_rels1, Node **jtlink2, Relids available_rels2)
 
static Nodepull_up_subqueries_recurse (PlannerInfo *root, Node *jtnode, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
 
static Nodepull_up_simple_subquery (PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
 
static Nodepull_up_simple_union_all (PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
 
static void pull_up_union_leaf_queries (Node *setOp, PlannerInfo *root, int parentRTindex, Query *setOpQuery, int childRToffset)
 
static void make_setop_translation_list (Query *query, int newvarno, AppendRelInfo *appinfo)
 
static bool is_simple_subquery (PlannerInfo *root, Query *subquery, RangeTblEntry *rte, JoinExpr *lowest_outer_join)
 
static Nodepull_up_simple_values (PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
 
static bool is_simple_values (PlannerInfo *root, RangeTblEntry *rte)
 
static Nodepull_up_constant_function (PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, AppendRelInfo *containing_appendrel)
 
static bool is_simple_union_all (Query *subquery)
 
static bool is_simple_union_all_recurse (Node *setOp, Query *setOpQuery, List *colTypes)
 
static bool is_safe_append_member (Query *subquery)
 
static bool jointree_contains_lateral_outer_refs (PlannerInfo *root, Node *jtnode, bool restricted, Relids safe_upper_varnos)
 
static void perform_pullup_replace_vars (PlannerInfo *root, pullup_replace_vars_context *rvcontext, AppendRelInfo *containing_appendrel)
 
static void replace_vars_in_jointree (Node *jtnode, pullup_replace_vars_context *context)
 
static Nodepullup_replace_vars (Node *expr, pullup_replace_vars_context *context)
 
static Nodepullup_replace_vars_callback (Var *var, replace_rte_variables_context *context)
 
static Querypullup_replace_vars_subquery (Query *query, pullup_replace_vars_context *context)
 
static reduce_outer_joins_pass1_statereduce_outer_joins_pass1 (Node *jtnode)
 
static void reduce_outer_joins_pass2 (Node *jtnode, reduce_outer_joins_pass1_state *state1, reduce_outer_joins_pass2_state *state2, PlannerInfo *root, Relids nonnullable_rels, List *forced_null_vars)
 
static void report_reduced_full_join (reduce_outer_joins_pass2_state *state2, int rtindex, Relids relids)
 
static Noderemove_useless_results_recurse (PlannerInfo *root, Node *jtnode, Node **parent_quals, Relids *dropped_outer_joins)
 
static int get_result_relid (PlannerInfo *root, Node *jtnode)
 
static void remove_result_refs (PlannerInfo *root, int varno, Node *newjtloc)
 
static bool find_dependent_phvs (PlannerInfo *root, int varno)
 
static bool find_dependent_phvs_in_jointree (PlannerInfo *root, Node *node, int varno)
 
static void substitute_phv_relids (Node *node, int varno, Relids subrelids)
 
static void fix_append_rel_relids (PlannerInfo *root, int varno, Relids subrelids)
 
static Nodefind_jointree_node_for_rel (Node *jtnode, int relid)
 
void transform_MERGE_to_join (Query *parse)
 
void replace_empty_jointree (Query *parse)
 
void pull_up_sublinks (PlannerInfo *root)
 
void preprocess_function_rtes (PlannerInfo *root)
 
void pull_up_subqueries (PlannerInfo *root)
 
void flatten_simple_union_all (PlannerInfo *root)
 
void reduce_outer_joins (PlannerInfo *root)
 
void remove_useless_result_rtes (PlannerInfo *root)
 
static bool find_dependent_phvs_walker (Node *node, find_dependent_phvs_context *context)
 
static bool substitute_phv_relids_walker (Node *node, substitute_phv_relids_context *context)
 
Relids get_relids_in_jointree (Node *jtnode, bool include_outer_joins, bool include_inner_joins)
 
Relids get_relids_for_join (Query *query, int joinrelid)
 

Typedef Documentation

◆ pullup_replace_vars_context

◆ reduce_outer_joins_partial_state

◆ reduce_outer_joins_pass1_state

◆ reduce_outer_joins_pass2_state

Function Documentation

◆ find_dependent_phvs()

static bool find_dependent_phvs ( PlannerInfo root,
int  varno 
)
static

Definition at line 3648 of file prepjointree.c.

3649 {
3651 
3652  /* If there are no PHVs anywhere, we needn't work hard */
3653  if (root->glob->lastPHId == 0)
3654  return false;
3655 
3656  context.relids = bms_make_singleton(varno);
3657  context.sublevels_up = 0;
3658 
3659  if (query_tree_walker(root->parse,
3661  (void *) &context,
3662  0))
3663  return true;
3664  /* The append_rel_list could be populated already, so check it too */
3665  if (expression_tree_walker((Node *) root->append_rel_list,
3667  (void *) &context))
3668  return true;
3669  return false;
3670 }
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
static bool find_dependent_phvs_walker(Node *node, find_dependent_phvs_context *context)
tree context
Definition: radixtree.h:1835
tree ctl root
Definition: radixtree.h:1886
Definition: nodes.h:129

References bms_make_singleton(), context, expression_tree_walker, find_dependent_phvs_walker(), query_tree_walker, and root.

Referenced by remove_useless_results_recurse().

◆ find_dependent_phvs_in_jointree()

static bool find_dependent_phvs_in_jointree ( PlannerInfo root,
Node node,
int  varno 
)
static

Definition at line 3673 of file prepjointree.c.

3674 {
3676  Relids subrelids;
3677  int relid;
3678 
3679  /* If there are no PHVs anywhere, we needn't work hard */
3680  if (root->glob->lastPHId == 0)
3681  return false;
3682 
3683  context.relids = bms_make_singleton(varno);
3684  context.sublevels_up = 0;
3685 
3686  /*
3687  * See if the jointree fragment itself contains references (in join quals)
3688  */
3689  if (find_dependent_phvs_walker(node, &context))
3690  return true;
3691 
3692  /*
3693  * Otherwise, identify the set of referenced RTEs (we can ignore joins,
3694  * since they should be flattened already, so their join alias lists no
3695  * longer matter), and tediously check each RTE. We can ignore RTEs that
3696  * are not marked LATERAL, though, since they couldn't possibly contain
3697  * any cross-references to other RTEs.
3698  */
3699  subrelids = get_relids_in_jointree(node, false, false);
3700  relid = -1;
3701  while ((relid = bms_next_member(subrelids, relid)) >= 0)
3702  {
3703  RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
3704 
3705  if (rte->lateral &&
3708  (void *) &context,
3709  0))
3710  return true;
3711  }
3712 
3713  return false;
3714 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
#define range_table_entry_walker(r, w, c, f)
Definition: nodeFuncs.h:166
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins, bool include_inner_joins)

References bms_make_singleton(), bms_next_member(), context, find_dependent_phvs_walker(), get_relids_in_jointree(), range_table_entry_walker, root, and rt_fetch.

Referenced by remove_useless_results_recurse().

◆ find_dependent_phvs_walker()

static bool find_dependent_phvs_walker ( Node node,
find_dependent_phvs_context context 
)
static

Definition at line 3612 of file prepjointree.c.

3614 {
3615  if (node == NULL)
3616  return false;
3617  if (IsA(node, PlaceHolderVar))
3618  {
3619  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3620 
3621  if (phv->phlevelsup == context->sublevels_up &&
3622  bms_equal(context->relids, phv->phrels))
3623  return true;
3624  /* fall through to examine children */
3625  }
3626  if (IsA(node, Query))
3627  {
3628  /* Recurse into subselects */
3629  bool result;
3630 
3631  context->sublevels_up++;
3632  result = query_tree_walker((Query *) node,
3634  (void *) context, 0);
3635  context->sublevels_up--;
3636  return result;
3637  }
3638  /* Shouldn't need to handle most planner auxiliary nodes here */
3639  Assert(!IsA(node, SpecialJoinInfo));
3640  Assert(!IsA(node, PlaceHolderInfo));
3641  Assert(!IsA(node, MinMaxAggInfo));
3642 
3644  (void *) context);
3645 }
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
#define Assert(condition)
Definition: c.h:858
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
Index phlevelsup
Definition: pathnodes.h:2797

References Assert, bms_equal(), context, expression_tree_walker, IsA, PlaceHolderVar::phlevelsup, and query_tree_walker.

Referenced by find_dependent_phvs(), and find_dependent_phvs_in_jointree().

◆ find_jointree_node_for_rel()

static Node * find_jointree_node_for_rel ( Node jtnode,
int  relid 
)
static

Definition at line 3931 of file prepjointree.c.

3932 {
3933  if (jtnode == NULL)
3934  return NULL;
3935  if (IsA(jtnode, RangeTblRef))
3936  {
3937  int varno = ((RangeTblRef *) jtnode)->rtindex;
3938 
3939  if (relid == varno)
3940  return jtnode;
3941  }
3942  else if (IsA(jtnode, FromExpr))
3943  {
3944  FromExpr *f = (FromExpr *) jtnode;
3945  ListCell *l;
3946 
3947  foreach(l, f->fromlist)
3948  {
3949  jtnode = find_jointree_node_for_rel(lfirst(l), relid);
3950  if (jtnode)
3951  return jtnode;
3952  }
3953  }
3954  else if (IsA(jtnode, JoinExpr))
3955  {
3956  JoinExpr *j = (JoinExpr *) jtnode;
3957 
3958  if (relid == j->rtindex)
3959  return jtnode;
3960  jtnode = find_jointree_node_for_rel(j->larg, relid);
3961  if (jtnode)
3962  return jtnode;
3963  jtnode = find_jointree_node_for_rel(j->rarg, relid);
3964  if (jtnode)
3965  return jtnode;
3966  }
3967  else
3968  elog(ERROR, "unrecognized node type: %d",
3969  (int) nodeTag(jtnode));
3970  return NULL;
3971 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
int j
Definition: isn.c:74
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define lfirst(lc)
Definition: pg_list.h:172
static Node * find_jointree_node_for_rel(Node *jtnode, int relid)
List * fromlist
Definition: primnodes.h:2304

References elog, ERROR, FromExpr::fromlist, IsA, j, lfirst, and nodeTag.

Referenced by get_relids_for_join().

◆ fix_append_rel_relids()

static void fix_append_rel_relids ( PlannerInfo root,
int  varno,
Relids  subrelids 
)
static

Definition at line 3809 of file prepjointree.c.

3810 {
3811  ListCell *l;
3812  int subvarno = -1;
3813 
3814  /*
3815  * We only want to extract the member relid once, but we mustn't fail
3816  * immediately if there are multiple members; it could be that none of the
3817  * AppendRelInfo nodes refer to it. So compute it on first use. Note that
3818  * bms_singleton_member will complain if set is not singleton.
3819  */
3820  foreach(l, root->append_rel_list)
3821  {
3822  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3823 
3824  /* The parent_relid shouldn't ever be a pullup target */
3825  Assert(appinfo->parent_relid != varno);
3826 
3827  if (appinfo->child_relid == varno)
3828  {
3829  if (subvarno < 0)
3830  subvarno = bms_singleton_member(subrelids);
3831  appinfo->child_relid = subvarno;
3832  }
3833 
3834  /* Also fix up any PHVs in its translated vars */
3835  if (root->glob->lastPHId != 0)
3837  varno, subrelids);
3838  }
3839 }
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:672
static void substitute_phv_relids(Node *node, int varno, Relids subrelids)
Index child_relid
Definition: pathnodes.h:2970
List * translated_vars
Definition: pathnodes.h:2997
Index parent_relid
Definition: pathnodes.h:2969

References Assert, bms_singleton_member(), AppendRelInfo::child_relid, lfirst, AppendRelInfo::parent_relid, root, substitute_phv_relids(), and AppendRelInfo::translated_vars.

Referenced by pull_up_simple_subquery(), and remove_result_refs().

◆ flatten_simple_union_all()

void flatten_simple_union_all ( PlannerInfo root)

Definition at line 2586 of file prepjointree.c.

2587 {
2588  Query *parse = root->parse;
2589  SetOperationStmt *topop;
2590  Node *leftmostjtnode;
2591  int leftmostRTI;
2592  RangeTblEntry *leftmostRTE;
2593  int childRTI;
2594  RangeTblEntry *childRTE;
2595  RangeTblRef *rtr;
2596 
2597  /* Shouldn't be called unless query has setops */
2598  topop = castNode(SetOperationStmt, parse->setOperations);
2599  Assert(topop);
2600 
2601  /* Can't optimize away a recursive UNION */
2602  if (root->hasRecursion)
2603  return;
2604 
2605  /*
2606  * Recursively check the tree of set operations. If not all UNION ALL
2607  * with identical column types, punt.
2608  */
2609  if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
2610  return;
2611 
2612  /*
2613  * Locate the leftmost leaf query in the setops tree. The upper query's
2614  * Vars all refer to this RTE (see transformSetOperationStmt).
2615  */
2616  leftmostjtnode = topop->larg;
2617  while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
2618  leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
2619  Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
2620  leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
2621  leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
2622  Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
2623 
2624  /*
2625  * Make a copy of the leftmost RTE and add it to the rtable. This copy
2626  * will represent the leftmost leaf query in its capacity as a member of
2627  * the appendrel. The original will represent the appendrel as a whole.
2628  * (We must do things this way because the upper query's Vars have to be
2629  * seen as referring to the whole appendrel.)
2630  */
2631  childRTE = copyObject(leftmostRTE);
2632  parse->rtable = lappend(parse->rtable, childRTE);
2633  childRTI = list_length(parse->rtable);
2634 
2635  /* Modify the setops tree to reference the child copy */
2636  ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
2637 
2638  /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
2639  leftmostRTE->inh = true;
2640 
2641  /*
2642  * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
2643  * Query of a setops tree should have had an empty FromClause initially.
2644  */
2645  rtr = makeNode(RangeTblRef);
2646  rtr->rtindex = leftmostRTI;
2647  Assert(parse->jointree->fromlist == NIL);
2648  parse->jointree->fromlist = list_make1(rtr);
2649 
2650  /*
2651  * Now pretend the query has no setops. We must do this before trying to
2652  * do subquery pullup, because of Assert in pull_up_simple_subquery.
2653  */
2654  parse->setOperations = NULL;
2655 
2656  /*
2657  * Build AppendRelInfo information, and apply pull_up_subqueries to the
2658  * leaf queries of the UNION ALL. (We must do that now because they
2659  * weren't previously referenced by the jointree, and so were missed by
2660  * the main invocation of pull_up_subqueries.)
2661  */
2662  pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
2663 }
List * lappend(List *list, void *datum)
Definition: list.c:339
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ RTE_SUBQUERY
Definition: parsenodes.h:1029
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex, Query *setOpQuery, int childRToffset)
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715
RTEKind rtekind
Definition: parsenodes.h:1057

References Assert, castNode, copyObject, RangeTblEntry::inh, is_simple_union_all_recurse(), IsA, lappend(), SetOperationStmt::larg, list_length(), list_make1, makeNode, NIL, parse(), pull_up_union_leaf_queries(), root, rt_fetch, RTE_SUBQUERY, RangeTblEntry::rtekind, and RangeTblRef::rtindex.

Referenced by subquery_planner().

◆ get_relids_for_join()

Relids get_relids_for_join ( Query query,
int  joinrelid 
)

Definition at line 3914 of file prepjointree.c.

3915 {
3916  Node *jtnode;
3917 
3918  jtnode = find_jointree_node_for_rel((Node *) query->jointree,
3919  joinrelid);
3920  if (!jtnode)
3921  elog(ERROR, "could not find join node %d", joinrelid);
3922  return get_relids_in_jointree(jtnode, true, false);
3923 }
FromExpr * jointree
Definition: parsenodes.h:175

References elog, ERROR, find_jointree_node_for_rel(), get_relids_in_jointree(), and Query::jointree.

Referenced by add_nullingrels_if_needed(), and alias_relid_set().

◆ get_relids_in_jointree()

Relids get_relids_in_jointree ( Node jtnode,
bool  include_outer_joins,
bool  include_inner_joins 
)

Definition at line 3853 of file prepjointree.c.

3855 {
3856  Relids result = NULL;
3857 
3858  if (jtnode == NULL)
3859  return result;
3860  if (IsA(jtnode, RangeTblRef))
3861  {
3862  int varno = ((RangeTblRef *) jtnode)->rtindex;
3863 
3864  result = bms_make_singleton(varno);
3865  }
3866  else if (IsA(jtnode, FromExpr))
3867  {
3868  FromExpr *f = (FromExpr *) jtnode;
3869  ListCell *l;
3870 
3871  foreach(l, f->fromlist)
3872  {
3873  result = bms_join(result,
3875  include_outer_joins,
3876  include_inner_joins));
3877  }
3878  }
3879  else if (IsA(jtnode, JoinExpr))
3880  {
3881  JoinExpr *j = (JoinExpr *) jtnode;
3882 
3883  result = get_relids_in_jointree(j->larg,
3884  include_outer_joins,
3885  include_inner_joins);
3886  result = bms_join(result,
3887  get_relids_in_jointree(j->rarg,
3888  include_outer_joins,
3889  include_inner_joins));
3890  if (j->rtindex)
3891  {
3892  if (j->jointype == JOIN_INNER)
3893  {
3894  if (include_inner_joins)
3895  result = bms_add_member(result, j->rtindex);
3896  }
3897  else
3898  {
3899  if (include_outer_joins)
3900  result = bms_add_member(result, j->rtindex);
3901  }
3902  }
3903  }
3904  else
3905  elog(ERROR, "unrecognized node type: %d",
3906  (int) nodeTag(jtnode));
3907  return result;
3908 }
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
@ JOIN_INNER
Definition: nodes.h:293

References bms_add_member(), bms_join(), bms_make_singleton(), elog, ERROR, FromExpr::fromlist, IsA, j, JOIN_INNER, lfirst, and nodeTag.

Referenced by find_dependent_phvs_in_jointree(), get_relids_for_join(), is_simple_subquery(), preprocess_rowmarks(), pull_up_simple_subquery(), and remove_result_refs().

◆ get_result_relid()

static int get_result_relid ( PlannerInfo root,
Node jtnode 
)
static

Definition at line 3543 of file prepjointree.c.

3544 {
3545  int varno;
3546 
3547  if (!IsA(jtnode, RangeTblRef))
3548  return 0;
3549  varno = ((RangeTblRef *) jtnode)->rtindex;
3550  if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
3551  return 0;
3552  return varno;
3553 }
@ RTE_RESULT
Definition: parsenodes.h:1036

References IsA, root, rt_fetch, and RTE_RESULT.

Referenced by remove_useless_results_recurse().

◆ is_safe_append_member()

static bool is_safe_append_member ( Query subquery)
static

Definition at line 2015 of file prepjointree.c.

2016 {
2017  FromExpr *jtnode;
2018 
2019  /*
2020  * It's only safe to pull up the child if its jointree contains exactly
2021  * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
2022  * could be buried in several levels of FromExpr, however. Also, if the
2023  * child's jointree is completely empty, we can pull up because
2024  * pull_up_simple_subquery will insert a single RTE_RESULT RTE instead.
2025  *
2026  * Also, the child can't have any WHERE quals because there's no place to
2027  * put them in an appendrel. (This is a bit annoying...) If we didn't
2028  * need to check this, we'd just test whether get_relids_in_jointree()
2029  * yields a singleton set, to be more consistent with the coding of
2030  * fix_append_rel_relids().
2031  */
2032  jtnode = subquery->jointree;
2033  Assert(IsA(jtnode, FromExpr));
2034  /* Check the completely-empty case */
2035  if (jtnode->fromlist == NIL && jtnode->quals == NULL)
2036  return true;
2037  /* Check the more general case */
2038  while (IsA(jtnode, FromExpr))
2039  {
2040  if (jtnode->quals != NULL)
2041  return false;
2042  if (list_length(jtnode->fromlist) != 1)
2043  return false;
2044  jtnode = linitial(jtnode->fromlist);
2045  }
2046  if (!IsA(jtnode, RangeTblRef))
2047  return false;
2048 
2049  return true;
2050 }
#define linitial(l)
Definition: pg_list.h:178
Node * quals
Definition: primnodes.h:2305

References Assert, FromExpr::fromlist, IsA, Query::jointree, linitial, list_length(), NIL, and FromExpr::quals.

Referenced by pull_up_simple_subquery(), and pull_up_subqueries_recurse().

◆ is_simple_subquery()

static bool is_simple_subquery ( PlannerInfo root,
Query subquery,
RangeTblEntry rte,
JoinExpr lowest_outer_join 
)
static

Definition at line 1536 of file prepjointree.c.

1538 {
1539  /*
1540  * Let's just make sure it's a valid subselect ...
1541  */
1542  if (!IsA(subquery, Query) ||
1543  subquery->commandType != CMD_SELECT)
1544  elog(ERROR, "subquery is bogus");
1545 
1546  /*
1547  * Can't currently pull up a query with setops (unless it's simple UNION
1548  * ALL, which is handled by a different code path). Maybe after querytree
1549  * redesign...
1550  */
1551  if (subquery->setOperations)
1552  return false;
1553 
1554  /*
1555  * Can't pull up a subquery involving grouping, aggregation, SRFs,
1556  * sorting, limiting, or WITH. (XXX WITH could possibly be allowed later)
1557  *
1558  * We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
1559  * clauses, because pullup would cause the locking to occur semantically
1560  * higher than it should. Implicit FOR UPDATE/SHARE is okay because in
1561  * that case the locking was originally declared in the upper query
1562  * anyway.
1563  */
1564  if (subquery->hasAggs ||
1565  subquery->hasWindowFuncs ||
1566  subquery->hasTargetSRFs ||
1567  subquery->groupClause ||
1568  subquery->groupingSets ||
1569  subquery->havingQual ||
1570  subquery->sortClause ||
1571  subquery->distinctClause ||
1572  subquery->limitOffset ||
1573  subquery->limitCount ||
1574  subquery->hasForUpdate ||
1575  subquery->cteList)
1576  return false;
1577 
1578  /*
1579  * Don't pull up if the RTE represents a security-barrier view; we
1580  * couldn't prevent information leakage once the RTE's Vars are scattered
1581  * about in the upper query.
1582  */
1583  if (rte->security_barrier)
1584  return false;
1585 
1586  /*
1587  * If the subquery is LATERAL, check for pullup restrictions from that.
1588  */
1589  if (rte->lateral)
1590  {
1591  bool restricted;
1592  Relids safe_upper_varnos;
1593 
1594  /*
1595  * The subquery's WHERE and JOIN/ON quals mustn't contain any lateral
1596  * references to rels outside a higher outer join (including the case
1597  * where the outer join is within the subquery itself). In such a
1598  * case, pulling up would result in a situation where we need to
1599  * postpone quals from below an outer join to above it, which is
1600  * probably completely wrong and in any case is a complication that
1601  * doesn't seem worth addressing at the moment.
1602  */
1603  if (lowest_outer_join != NULL)
1604  {
1605  restricted = true;
1606  safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join,
1607  true, true);
1608  }
1609  else
1610  {
1611  restricted = false;
1612  safe_upper_varnos = NULL; /* doesn't matter */
1613  }
1614 
1616  (Node *) subquery->jointree,
1617  restricted, safe_upper_varnos))
1618  return false;
1619 
1620  /*
1621  * If there's an outer join above the LATERAL subquery, also disallow
1622  * pullup if the subquery's targetlist has any references to rels
1623  * outside the outer join, since these might get pulled into quals
1624  * above the subquery (but in or below the outer join) and then lead
1625  * to qual-postponement issues similar to the case checked for above.
1626  * (We wouldn't need to prevent pullup if no such references appear in
1627  * outer-query quals, but we don't have enough info here to check
1628  * that. Also, maybe this restriction could be removed if we forced
1629  * such refs to be wrapped in PlaceHolderVars, even when they're below
1630  * the nearest outer join? But it's a pretty hokey usage, so not
1631  * clear this is worth sweating over.)
1632  */
1633  if (lowest_outer_join != NULL)
1634  {
1635  Relids lvarnos = pull_varnos_of_level(root,
1636  (Node *) subquery->targetList,
1637  1);
1638 
1639  if (!bms_is_subset(lvarnos, safe_upper_varnos))
1640  return false;
1641  }
1642  }
1643 
1644  /*
1645  * Don't pull up a subquery that has any volatile functions in its
1646  * targetlist. Otherwise we might introduce multiple evaluations of these
1647  * functions, if they get copied to multiple places in the upper query,
1648  * leading to surprising results. (Note: the PlaceHolderVar mechanism
1649  * doesn't quite guarantee single evaluation; else we could pull up anyway
1650  * and just wrap such items in PlaceHolderVars ...)
1651  */
1652  if (contain_volatile_functions((Node *) subquery->targetList))
1653  return false;
1654 
1655  return true;
1656 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:538
@ CMD_SELECT
Definition: nodes.h:265
static bool jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode, bool restricted, Relids safe_upper_varnos)
Node * limitCount
Definition: parsenodes.h:214
Node * setOperations
Definition: parsenodes.h:219
List * cteList
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:200
Node * havingQual
Definition: parsenodes.h:205
Node * limitOffset
Definition: parsenodes.h:213
CmdType commandType
Definition: parsenodes.h:121
List * targetList
Definition: parsenodes.h:191
List * groupingSets
Definition: parsenodes.h:203
List * distinctClause
Definition: parsenodes.h:209
List * sortClause
Definition: parsenodes.h:211
Relids pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
Definition: var.c:134

References bms_is_subset(), CMD_SELECT, Query::commandType, contain_volatile_functions(), Query::cteList, Query::distinctClause, elog, ERROR, get_relids_in_jointree(), Query::groupClause, Query::groupingSets, Query::havingQual, IsA, Query::jointree, jointree_contains_lateral_outer_refs(), Query::limitCount, Query::limitOffset, pull_varnos_of_level(), root, Query::setOperations, Query::sortClause, and Query::targetList.

Referenced by pull_up_simple_subquery(), and pull_up_subqueries_recurse().

◆ is_simple_union_all()

static bool is_simple_union_all ( Query subquery)
static

Definition at line 1944 of file prepjointree.c.

1945 {
1946  SetOperationStmt *topop;
1947 
1948  /* Let's just make sure it's a valid subselect ... */
1949  if (!IsA(subquery, Query) ||
1950  subquery->commandType != CMD_SELECT)
1951  elog(ERROR, "subquery is bogus");
1952 
1953  /* Is it a set-operation query at all? */
1954  topop = castNode(SetOperationStmt, subquery->setOperations);
1955  if (!topop)
1956  return false;
1957 
1958  /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
1959  if (subquery->sortClause ||
1960  subquery->limitOffset ||
1961  subquery->limitCount ||
1962  subquery->rowMarks ||
1963  subquery->cteList)
1964  return false;
1965 
1966  /* Recursively check the tree of set operations */
1967  return is_simple_union_all_recurse((Node *) topop, subquery,
1968  topop->colTypes);
1969 }
List * rowMarks
Definition: parsenodes.h:217

References castNode, CMD_SELECT, Query::commandType, Query::cteList, elog, ERROR, is_simple_union_all_recurse(), IsA, Query::limitCount, Query::limitOffset, Query::rowMarks, Query::setOperations, and Query::sortClause.

Referenced by pull_up_subqueries_recurse().

◆ is_simple_union_all_recurse()

static bool is_simple_union_all_recurse ( Node setOp,
Query setOpQuery,
List colTypes 
)
static

Definition at line 1972 of file prepjointree.c.

1973 {
1974  /* Since this function recurses, it could be driven to stack overflow. */
1976 
1977  if (IsA(setOp, RangeTblRef))
1978  {
1979  RangeTblRef *rtr = (RangeTblRef *) setOp;
1980  RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
1981  Query *subquery = rte->subquery;
1982 
1983  Assert(subquery != NULL);
1984 
1985  /* Leaf nodes are OK if they match the toplevel column types */
1986  /* We don't have to compare typmods or collations here */
1987  return tlist_same_datatypes(subquery->targetList, colTypes, true);
1988  }
1989  else if (IsA(setOp, SetOperationStmt))
1990  {
1991  SetOperationStmt *op = (SetOperationStmt *) setOp;
1992 
1993  /* Must be UNION ALL */
1994  if (op->op != SETOP_UNION || !op->all)
1995  return false;
1996 
1997  /* Recurse to check inputs */
1998  return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
1999  is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
2000  }
2001  else
2002  {
2003  elog(ERROR, "unrecognized node type: %d",
2004  (int) nodeTag(setOp));
2005  return false; /* keep compiler quiet */
2006  }
2007 }
@ SETOP_UNION
Definition: parsenodes.h:2114
void check_stack_depth(void)
Definition: postgres.c:3530
List * rtable
Definition: parsenodes.h:168
Query * subquery
Definition: parsenodes.h:1114
SetOperation op
Definition: parsenodes.h:2191
bool tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK)
Definition: tlist.c:248

References SetOperationStmt::all, Assert, check_stack_depth(), elog, ERROR, IsA, SetOperationStmt::larg, nodeTag, SetOperationStmt::op, SetOperationStmt::rarg, rt_fetch, Query::rtable, RangeTblRef::rtindex, SETOP_UNION, RangeTblEntry::subquery, Query::targetList, and tlist_same_datatypes().

Referenced by flatten_simple_union_all(), and is_simple_union_all().

◆ is_simple_values()

static bool is_simple_values ( PlannerInfo root,
RangeTblEntry rte 
)
static

Definition at line 1768 of file prepjointree.c.

1769 {
1770  Assert(rte->rtekind == RTE_VALUES);
1771 
1772  /*
1773  * There must be exactly one VALUES list, else it's not semantically
1774  * correct to replace the VALUES RTE with a RESULT RTE, nor would we have
1775  * a unique set of expressions to substitute into the parent query.
1776  */
1777  if (list_length(rte->values_lists) != 1)
1778  return false;
1779 
1780  /*
1781  * Because VALUES can't appear under an outer join (or at least, we won't
1782  * try to pull it up if it does), we need not worry about LATERAL, nor
1783  * about validity of PHVs for the VALUES' outputs.
1784  */
1785 
1786  /*
1787  * Don't pull up a VALUES that contains any set-returning or volatile
1788  * functions. The considerations here are basically identical to the
1789  * restrictions on a pull-able subquery's targetlist.
1790  */
1791  if (expression_returns_set((Node *) rte->values_lists) ||
1793  return false;
1794 
1795  /*
1796  * Do not pull up a VALUES that's not the only RTE in its parent query.
1797  * This is actually the only case that the parser will generate at the
1798  * moment, and assuming this is true greatly simplifies
1799  * pull_up_simple_values().
1800  */
1801  if (list_length(root->parse->rtable) != 1 ||
1802  rte != (RangeTblEntry *) linitial(root->parse->rtable))
1803  return false;
1804 
1805  return true;
1806 }
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:758
@ RTE_VALUES
Definition: parsenodes.h:1033
List * values_lists
Definition: parsenodes.h:1200

References Assert, contain_volatile_functions(), expression_returns_set(), linitial, list_length(), root, RTE_VALUES, RangeTblEntry::rtekind, and RangeTblEntry::values_lists.

Referenced by pull_up_subqueries_recurse().

◆ jointree_contains_lateral_outer_refs()

static bool jointree_contains_lateral_outer_refs ( PlannerInfo root,
Node jtnode,
bool  restricted,
Relids  safe_upper_varnos 
)
static

Definition at line 2063 of file prepjointree.c.

2066 {
2067  if (jtnode == NULL)
2068  return false;
2069  if (IsA(jtnode, RangeTblRef))
2070  return false;
2071  else if (IsA(jtnode, FromExpr))
2072  {
2073  FromExpr *f = (FromExpr *) jtnode;
2074  ListCell *l;
2075 
2076  /* First, recurse to check child joins */
2077  foreach(l, f->fromlist)
2078  {
2080  lfirst(l),
2081  restricted,
2082  safe_upper_varnos))
2083  return true;
2084  }
2085 
2086  /* Then check the top-level quals */
2087  if (restricted &&
2089  safe_upper_varnos))
2090  return true;
2091  }
2092  else if (IsA(jtnode, JoinExpr))
2093  {
2094  JoinExpr *j = (JoinExpr *) jtnode;
2095 
2096  /*
2097  * If this is an outer join, we mustn't allow any upper lateral
2098  * references in or below it.
2099  */
2100  if (j->jointype != JOIN_INNER)
2101  {
2102  restricted = true;
2103  safe_upper_varnos = NULL;
2104  }
2105 
2106  /* Check the child joins */
2108  j->larg,
2109  restricted,
2110  safe_upper_varnos))
2111  return true;
2113  j->rarg,
2114  restricted,
2115  safe_upper_varnos))
2116  return true;
2117 
2118  /* Check the JOIN's qual clauses */
2119  if (restricted &&
2121  safe_upper_varnos))
2122  return true;
2123  }
2124  else
2125  elog(ERROR, "unrecognized node type: %d",
2126  (int) nodeTag(jtnode));
2127  return false;
2128 }

References bms_is_subset(), elog, ERROR, FromExpr::fromlist, IsA, j, JOIN_INNER, lfirst, nodeTag, pull_varnos_of_level(), FromExpr::quals, and root.

Referenced by is_simple_subquery().

◆ make_setop_translation_list()

static void make_setop_translation_list ( Query query,
int  newvarno,
AppendRelInfo appinfo 
)
static

Definition at line 1498 of file prepjointree.c.

1500 {
1501  List *vars = NIL;
1502  AttrNumber *pcolnos;
1503  ListCell *l;
1504 
1505  /* Initialize reverse-translation array with all entries zero */
1506  /* (entries for resjunk columns will stay that way) */
1507  appinfo->num_child_cols = list_length(query->targetList);
1508  appinfo->parent_colnos = pcolnos =
1509  (AttrNumber *) palloc0(appinfo->num_child_cols * sizeof(AttrNumber));
1510 
1511  foreach(l, query->targetList)
1512  {
1513  TargetEntry *tle = (TargetEntry *) lfirst(l);
1514 
1515  if (tle->resjunk)
1516  continue;
1517 
1518  vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
1519  pcolnos[tle->resno - 1] = tle->resno;
1520  }
1521 
1522  appinfo->translated_vars = vars;
1523 }
int16 AttrNumber
Definition: attnum.h:21
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:105
void * palloc0(Size size)
Definition: mcxt.c:1347
int num_child_cols
Definition: pathnodes.h:3005
Definition: pg_list.h:54
AttrNumber resno
Definition: primnodes.h:2188
Definition: regcomp.c:281

References lappend(), lfirst, list_length(), makeVarFromTargetEntry(), NIL, AppendRelInfo::num_child_cols, palloc0(), TargetEntry::resno, Query::targetList, and AppendRelInfo::translated_vars.

Referenced by pull_up_union_leaf_queries().

◆ perform_pullup_replace_vars()

static void perform_pullup_replace_vars ( PlannerInfo root,
pullup_replace_vars_context rvcontext,
AppendRelInfo containing_appendrel 
)
static

Definition at line 2138 of file prepjointree.c.

2141 {
2142  Query *parse = root->parse;
2143  ListCell *lc;
2144 
2145  /*
2146  * If we are considering an appendrel child subquery (that is, a UNION ALL
2147  * member query that we're pulling up), then the only part of the upper
2148  * query that could reference the child yet is the translated_vars list of
2149  * the associated AppendRelInfo. Furthermore, we do not want to force use
2150  * of PHVs in the AppendRelInfo --- there isn't any outer join between.
2151  */
2152  if (containing_appendrel)
2153  {
2154  bool save_wrap_non_vars = rvcontext->wrap_non_vars;
2155 
2156  rvcontext->wrap_non_vars = false;
2157  containing_appendrel->translated_vars = (List *)
2158  pullup_replace_vars((Node *) containing_appendrel->translated_vars,
2159  rvcontext);
2160  rvcontext->wrap_non_vars = save_wrap_non_vars;
2161  return;
2162  }
2163 
2164  /*
2165  * Replace all of the top query's references to the subquery's outputs
2166  * with copies of the adjusted subtlist items, being careful not to
2167  * replace any of the jointree structure. (This'd be a lot cleaner if we
2168  * could use query_tree_mutator.) We have to use PHVs in the targetList,
2169  * returningList, and havingQual, since those are certainly above any
2170  * outer join. replace_vars_in_jointree tracks its location in the
2171  * jointree and uses PHVs or not appropriately.
2172  */
2173  parse->targetList = (List *)
2174  pullup_replace_vars((Node *) parse->targetList, rvcontext);
2175  parse->returningList = (List *)
2176  pullup_replace_vars((Node *) parse->returningList, rvcontext);
2177 
2178  if (parse->onConflict)
2179  {
2180  parse->onConflict->onConflictSet = (List *)
2181  pullup_replace_vars((Node *) parse->onConflict->onConflictSet,
2182  rvcontext);
2183  parse->onConflict->onConflictWhere =
2184  pullup_replace_vars(parse->onConflict->onConflictWhere,
2185  rvcontext);
2186 
2187  /*
2188  * We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist
2189  * can't contain any references to a subquery.
2190  */
2191  }
2192  if (parse->mergeActionList)
2193  {
2194  foreach(lc, parse->mergeActionList)
2195  {
2196  MergeAction *action = lfirst(lc);
2197 
2198  action->qual = pullup_replace_vars(action->qual, rvcontext);
2199  action->targetList = (List *)
2200  pullup_replace_vars((Node *) action->targetList, rvcontext);
2201  }
2202  }
2203  parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition,
2204  rvcontext);
2205  replace_vars_in_jointree((Node *) parse->jointree, rvcontext);
2206  Assert(parse->setOperations == NULL);
2207  parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
2208 
2209  /*
2210  * Replace references in the translated_vars lists of appendrels.
2211  */
2212  foreach(lc, root->append_rel_list)
2213  {
2214  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
2215 
2216  appinfo->translated_vars = (List *)
2217  pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext);
2218  }
2219 
2220  /*
2221  * Replace references in the joinaliasvars lists of join RTEs.
2222  */
2223  foreach(lc, parse->rtable)
2224  {
2225  RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
2226 
2227  if (otherrte->rtekind == RTE_JOIN)
2228  otherrte->joinaliasvars = (List *)
2229  pullup_replace_vars((Node *) otherrte->joinaliasvars,
2230  rvcontext);
2231  }
2232 }
@ RTE_JOIN
Definition: parsenodes.h:1030
static void replace_vars_in_jointree(Node *jtnode, pullup_replace_vars_context *context)
static Node * pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)

References generate_unaccent_rules::action, Assert, lfirst, parse(), pullup_replace_vars(), replace_vars_in_jointree(), root, RTE_JOIN, RangeTblEntry::rtekind, AppendRelInfo::translated_vars, and pullup_replace_vars_context::wrap_non_vars.

Referenced by pull_up_constant_function(), pull_up_simple_subquery(), and pull_up_simple_values().

◆ preprocess_function_rtes()

void preprocess_function_rtes ( PlannerInfo root)

Definition at line 776 of file prepjointree.c.

777 {
778  ListCell *rt;
779 
780  foreach(rt, root->parse->rtable)
781  {
782  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
783 
784  if (rte->rtekind == RTE_FUNCTION)
785  {
786  Query *funcquery;
787 
788  /* Apply const-simplification */
789  rte->functions = (List *)
791 
792  /* Check safety of expansion, and expand if possible */
793  funcquery = inline_set_returning_function(root, rte);
794  if (funcquery)
795  {
796  /* Successful expansion, convert the RTE to a subquery */
797  rte->rtekind = RTE_SUBQUERY;
798  rte->subquery = funcquery;
799  rte->security_barrier = false;
800  /* Clear fields that should not be set in a subquery RTE */
801  rte->functions = NIL;
802  rte->funcordinality = false;
803  }
804  }
805  }
806 }
Query * inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
Definition: clauses.c:5053
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2254
@ RTE_FUNCTION
Definition: parsenodes.h:1031
bool funcordinality
Definition: parsenodes.h:1189
List * functions
Definition: parsenodes.h:1187

References eval_const_expressions(), RangeTblEntry::funcordinality, RangeTblEntry::functions, inline_set_returning_function(), lfirst, NIL, root, RTE_FUNCTION, RTE_SUBQUERY, RangeTblEntry::rtekind, and RangeTblEntry::subquery.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ pull_up_constant_function()

static Node * pull_up_constant_function ( PlannerInfo root,
Node jtnode,
RangeTblEntry rte,
AppendRelInfo containing_appendrel 
)
static

Definition at line 1827 of file prepjointree.c.

1830 {
1831  Query *parse = root->parse;
1832  RangeTblFunction *rtf;
1833  TypeFuncClass functypclass;
1834  Oid funcrettype;
1835  TupleDesc tupdesc;
1836  pullup_replace_vars_context rvcontext;
1837 
1838  /* Fail if the RTE has ORDINALITY - we don't implement that here. */
1839  if (rte->funcordinality)
1840  return jtnode;
1841 
1842  /* Fail if RTE isn't a single, simple Const expr */
1843  if (list_length(rte->functions) != 1)
1844  return jtnode;
1846  if (!IsA(rtf->funcexpr, Const))
1847  return jtnode;
1848 
1849  /*
1850  * If the function's result is not a scalar, we punt. In principle we
1851  * could break the composite constant value apart into per-column
1852  * constants, but for now it seems not worth the work.
1853  */
1854  if (rtf->funccolcount != 1)
1855  return jtnode; /* definitely composite */
1856 
1857  /* If it has a coldeflist, it certainly returns RECORD */
1858  if (rtf->funccolnames != NIL)
1859  return jtnode; /* must be a one-column RECORD type */
1860 
1861  functypclass = get_expr_result_type(rtf->funcexpr,
1862  &funcrettype,
1863  &tupdesc);
1864  if (functypclass != TYPEFUNC_SCALAR)
1865  return jtnode; /* must be a one-column composite type */
1866 
1867  /* Create context for applying pullup_replace_vars */
1868  rvcontext.root = root;
1869  rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr,
1870  1, /* resno */
1871  NULL, /* resname */
1872  false)); /* resjunk */
1873  rvcontext.target_rte = rte;
1874 
1875  /*
1876  * Since this function was reduced to a Const, it doesn't contain any
1877  * lateral references, even if it's marked as LATERAL. This means we
1878  * don't need to fill relids.
1879  */
1880  rvcontext.relids = NULL;
1881 
1882  rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1883  rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex;
1884  /* this flag will be set below, if needed */
1885  rvcontext.wrap_non_vars = false;
1886  /* initialize cache array with indexes 0 .. length(tlist) */
1887  rvcontext.rv_cache = palloc0((list_length(rvcontext.targetlist) + 1) *
1888  sizeof(Node *));
1889 
1890  /*
1891  * If we are dealing with an appendrel member then anything that's not a
1892  * simple Var has to be turned into a PlaceHolderVar. (See comments in
1893  * pull_up_simple_subquery().)
1894  */
1895  if (containing_appendrel != NULL)
1896  rvcontext.wrap_non_vars = true;
1897 
1898  /*
1899  * If the parent query uses grouping sets, we need a PlaceHolderVar for
1900  * anything that's not a simple Var.
1901  */
1902  if (parse->groupingSets)
1903  rvcontext.wrap_non_vars = true;
1904 
1905  /*
1906  * Replace all of the top query's references to the RTE's output with
1907  * copies of the funcexpr, being careful not to replace any of the
1908  * jointree structure.
1909  */
1910  perform_pullup_replace_vars(root, &rvcontext,
1911  containing_appendrel);
1912 
1913  /*
1914  * We don't need to bother with changing PlaceHolderVars in the parent
1915  * query. Their references to the RT index are still good for now, and
1916  * will get removed later if we're able to drop the RTE_RESULT.
1917  */
1918 
1919  /*
1920  * Convert the RTE to be RTE_RESULT type, signifying that we don't need to
1921  * scan it anymore, and zero out RTE_FUNCTION-specific fields. Also make
1922  * sure the RTE is not marked LATERAL, since elsewhere we don't expect
1923  * RTE_RESULTs to be LATERAL.
1924  */
1925  rte->rtekind = RTE_RESULT;
1926  rte->functions = NIL;
1927  rte->lateral = false;
1928 
1929  /*
1930  * We can reuse the RangeTblRef node.
1931  */
1932  return jtnode;
1933 }
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:299
TypeFuncClass
Definition: funcapi.h:147
@ TYPEFUNC_SCALAR
Definition: funcapi.h:148
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
#define linitial_node(type, l)
Definition: pg_list.h:181
unsigned int Oid
Definition: postgres_ext.h:31
static void perform_pullup_replace_vars(PlannerInfo *root, pullup_replace_vars_context *rvcontext, AppendRelInfo *containing_appendrel)
RangeTblEntry * target_rte
Definition: prepjointree.c:49

References RangeTblFunction::funcexpr, RangeTblEntry::funcordinality, RangeTblEntry::functions, get_expr_result_type(), IsA, linitial_node, list_length(), list_make1, makeTargetEntry(), NIL, pullup_replace_vars_context::outer_hasSubLinks, palloc0(), parse(), perform_pullup_replace_vars(), pullup_replace_vars_context::relids, pullup_replace_vars_context::root, root, RTE_RESULT, RangeTblEntry::rtekind, pullup_replace_vars_context::rv_cache, pullup_replace_vars_context::target_rte, pullup_replace_vars_context::targetlist, TYPEFUNC_SCALAR, pullup_replace_vars_context::varno, and pullup_replace_vars_context::wrap_non_vars.

Referenced by pull_up_subqueries_recurse().

◆ pull_up_simple_subquery()

static Node * pull_up_simple_subquery ( PlannerInfo root,
Node jtnode,
RangeTblEntry rte,
JoinExpr lowest_outer_join,
AppendRelInfo containing_appendrel 
)
static

Definition at line 1006 of file prepjointree.c.

1009 {
1010  Query *parse = root->parse;
1011  int varno = ((RangeTblRef *) jtnode)->rtindex;
1012  Query *subquery;
1013  PlannerInfo *subroot;
1014  int rtoffset;
1015  pullup_replace_vars_context rvcontext;
1016  ListCell *lc;
1017 
1018  /*
1019  * Make a modifiable copy of the subquery to hack on, so that the RTE will
1020  * be left unchanged in case we decide below that we can't pull it up
1021  * after all.
1022  */
1023  subquery = copyObject(rte->subquery);
1024 
1025  /*
1026  * Create a PlannerInfo data structure for this subquery.
1027  *
1028  * NOTE: the next few steps should match the first processing in
1029  * subquery_planner(). Can we refactor to avoid code duplication, or
1030  * would that just make things uglier?
1031  */
1032  subroot = makeNode(PlannerInfo);
1033  subroot->parse = subquery;
1034  subroot->glob = root->glob;
1035  subroot->query_level = root->query_level;
1036  subroot->parent_root = root->parent_root;
1037  subroot->plan_params = NIL;
1038  subroot->outer_params = NULL;
1039  subroot->planner_cxt = CurrentMemoryContext;
1040  subroot->init_plans = NIL;
1041  subroot->cte_plan_ids = NIL;
1042  subroot->multiexpr_params = NIL;
1043  subroot->join_domains = NIL;
1044  subroot->eq_classes = NIL;
1045  subroot->ec_merging_done = false;
1046  subroot->last_rinfo_serial = 0;
1047  subroot->all_result_relids = NULL;
1048  subroot->leaf_result_relids = NULL;
1049  subroot->append_rel_list = NIL;
1050  subroot->row_identity_vars = NIL;
1051  subroot->rowMarks = NIL;
1052  memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
1053  memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
1054  subroot->processed_groupClause = NIL;
1055  subroot->processed_distinctClause = NIL;
1056  subroot->processed_tlist = NIL;
1057  subroot->update_colnos = NIL;
1058  subroot->grouping_map = NULL;
1059  subroot->minmax_aggs = NIL;
1060  subroot->qual_security_level = 0;
1061  subroot->placeholdersFrozen = false;
1062  subroot->hasRecursion = false;
1063  subroot->wt_param_id = -1;
1064  subroot->non_recursive_path = NULL;
1065  /* We don't currently need a top JoinDomain for the subroot */
1066 
1067  /* No CTEs to worry about */
1068  Assert(subquery->cteList == NIL);
1069 
1070  /*
1071  * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
1072  * that we don't need so many special cases to deal with that situation.
1073  */
1074  replace_empty_jointree(subquery);
1075 
1076  /*
1077  * Pull up any SubLinks within the subquery's quals, so that we don't
1078  * leave unoptimized SubLinks behind.
1079  */
1080  if (subquery->hasSubLinks)
1081  pull_up_sublinks(subroot);
1082 
1083  /*
1084  * Similarly, preprocess its function RTEs to inline any set-returning
1085  * functions in its rangetable.
1086  */
1087  preprocess_function_rtes(subroot);
1088 
1089  /*
1090  * Recursively pull up the subquery's subqueries, so that
1091  * pull_up_subqueries' processing is complete for its jointree and
1092  * rangetable.
1093  *
1094  * Note: it's okay that the subquery's recursion starts with NULL for
1095  * containing-join info, even if we are within an outer join in the upper
1096  * query; the lower query starts with a clean slate for outer-join
1097  * semantics. Likewise, we needn't pass down appendrel state.
1098  */
1099  pull_up_subqueries(subroot);
1100 
1101  /*
1102  * Now we must recheck whether the subquery is still simple enough to pull
1103  * up. If not, abandon processing it.
1104  *
1105  * We don't really need to recheck all the conditions involved, but it's
1106  * easier just to keep this "if" looking the same as the one in
1107  * pull_up_subqueries_recurse.
1108  */
1109  if (is_simple_subquery(root, subquery, rte, lowest_outer_join) &&
1110  (containing_appendrel == NULL || is_safe_append_member(subquery)))
1111  {
1112  /* good to go */
1113  }
1114  else
1115  {
1116  /*
1117  * Give up, return unmodified RangeTblRef.
1118  *
1119  * Note: The work we just did will be redone when the subquery gets
1120  * planned on its own. Perhaps we could avoid that by storing the
1121  * modified subquery back into the rangetable, but I'm not gonna risk
1122  * it now.
1123  */
1124  return jtnode;
1125  }
1126 
1127  /*
1128  * We must flatten any join alias Vars in the subquery's targetlist,
1129  * because pulling up the subquery's subqueries might have changed their
1130  * expansions into arbitrary expressions, which could affect
1131  * pullup_replace_vars' decisions about whether PlaceHolderVar wrappers
1132  * are needed for tlist entries. (Likely it'd be better to do
1133  * flatten_join_alias_vars on the whole query tree at some earlier stage,
1134  * maybe even in the rewriter; but for now let's just fix this case here.)
1135  */
1136  subquery->targetList = (List *)
1137  flatten_join_alias_vars(subroot, subroot->parse,
1138  (Node *) subquery->targetList);
1139 
1140  /*
1141  * Adjust level-0 varnos in subquery so that we can append its rangetable
1142  * to upper query's. We have to fix the subquery's append_rel_list as
1143  * well.
1144  */
1145  rtoffset = list_length(parse->rtable);
1146  OffsetVarNodes((Node *) subquery, rtoffset, 0);
1147  OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
1148 
1149  /*
1150  * Upper-level vars in subquery are now one level closer to their parent
1151  * than before.
1152  */
1153  IncrementVarSublevelsUp((Node *) subquery, -1, 1);
1154  IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
1155 
1156  /*
1157  * The subquery's targetlist items are now in the appropriate form to
1158  * insert into the top query, except that we may need to wrap them in
1159  * PlaceHolderVars. Set up required context data for pullup_replace_vars.
1160  * (Note that we should include the subquery's inner joins in relids,
1161  * since it may include join alias vars referencing them.)
1162  */
1163  rvcontext.root = root;
1164  rvcontext.targetlist = subquery->targetList;
1165  rvcontext.target_rte = rte;
1166  if (rte->lateral)
1167  rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
1168  true, true);
1169  else /* won't need relids */
1170  rvcontext.relids = NULL;
1171  rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1172  rvcontext.varno = varno;
1173  /* this flag will be set below, if needed */
1174  rvcontext.wrap_non_vars = false;
1175  /* initialize cache array with indexes 0 .. length(tlist) */
1176  rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
1177  sizeof(Node *));
1178 
1179  /*
1180  * If we are dealing with an appendrel member then anything that's not a
1181  * simple Var has to be turned into a PlaceHolderVar. We force this to
1182  * ensure that what we pull up doesn't get merged into a surrounding
1183  * expression during later processing and then fail to match the
1184  * expression actually available from the appendrel.
1185  */
1186  if (containing_appendrel != NULL)
1187  rvcontext.wrap_non_vars = true;
1188 
1189  /*
1190  * If the parent query uses grouping sets, we need a PlaceHolderVar for
1191  * anything that's not a simple Var. Again, this ensures that expressions
1192  * retain their separate identity so that they will match grouping set
1193  * columns when appropriate. (It'd be sufficient to wrap values used in
1194  * grouping set columns, and do so only in non-aggregated portions of the
1195  * tlist and havingQual, but that would require a lot of infrastructure
1196  * that pullup_replace_vars hasn't currently got.)
1197  */
1198  if (parse->groupingSets)
1199  rvcontext.wrap_non_vars = true;
1200 
1201  /*
1202  * Replace all of the top query's references to the subquery's outputs
1203  * with copies of the adjusted subtlist items, being careful not to
1204  * replace any of the jointree structure.
1205  */
1206  perform_pullup_replace_vars(root, &rvcontext,
1207  containing_appendrel);
1208 
1209  /*
1210  * If the subquery had a LATERAL marker, propagate that to any of its
1211  * child RTEs that could possibly now contain lateral cross-references.
1212  * The children might or might not contain any actual lateral
1213  * cross-references, but we have to mark the pulled-up child RTEs so that
1214  * later planner stages will check for such.
1215  */
1216  if (rte->lateral)
1217  {
1218  foreach(lc, subquery->rtable)
1219  {
1220  RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
1221 
1222  switch (child_rte->rtekind)
1223  {
1224  case RTE_RELATION:
1225  if (child_rte->tablesample)
1226  child_rte->lateral = true;
1227  break;
1228  case RTE_SUBQUERY:
1229  case RTE_FUNCTION:
1230  case RTE_VALUES:
1231  case RTE_TABLEFUNC:
1232  child_rte->lateral = true;
1233  break;
1234  case RTE_JOIN:
1235  case RTE_CTE:
1236  case RTE_NAMEDTUPLESTORE:
1237  case RTE_RESULT:
1238  /* these can't contain any lateral references */
1239  break;
1240  }
1241  }
1242  }
1243 
1244  /*
1245  * Now append the adjusted rtable entries and their perminfos to upper
1246  * query. (We hold off until after fixing the upper rtable entries; no
1247  * point in running that code on the subquery ones too.)
1248  */
1249  CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1250  subquery->rtable, subquery->rteperminfos);
1251 
1252  /*
1253  * Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already
1254  * adjusted the marker rtindexes, so just concat the lists.)
1255  */
1256  parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
1257 
1258  /*
1259  * We also have to fix the relid sets of any PlaceHolderVar nodes in the
1260  * parent query. (This could perhaps be done by pullup_replace_vars(),
1261  * but it seems cleaner to use two passes.) Note in particular that any
1262  * PlaceHolderVar nodes just created by pullup_replace_vars() will be
1263  * adjusted, so having created them with the subquery's varno is correct.
1264  *
1265  * Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
1266  * already checked that this won't require introducing multiple subrelids
1267  * into the single-slot AppendRelInfo structs.
1268  */
1269  if (root->glob->lastPHId != 0 || root->append_rel_list)
1270  {
1271  Relids subrelids;
1272 
1273  subrelids = get_relids_in_jointree((Node *) subquery->jointree,
1274  true, false);
1275  if (root->glob->lastPHId != 0)
1276  substitute_phv_relids((Node *) parse, varno, subrelids);
1277  fix_append_rel_relids(root, varno, subrelids);
1278  }
1279 
1280  /*
1281  * And now add subquery's AppendRelInfos to our list.
1282  */
1283  root->append_rel_list = list_concat(root->append_rel_list,
1284  subroot->append_rel_list);
1285 
1286  /*
1287  * We don't have to do the equivalent bookkeeping for outer-join info,
1288  * because that hasn't been set up yet. placeholder_list likewise.
1289  */
1290  Assert(root->join_info_list == NIL);
1291  Assert(subroot->join_info_list == NIL);
1292  Assert(root->placeholder_list == NIL);
1293  Assert(subroot->placeholder_list == NIL);
1294 
1295  /*
1296  * We no longer need the RTE's copy of the subquery's query tree. Getting
1297  * rid of it saves nothing in particular so far as this level of query is
1298  * concerned; but if this query level is in turn pulled up into a parent,
1299  * we'd waste cycles copying the now-unused query tree.
1300  */
1301  rte->subquery = NULL;
1302 
1303  /*
1304  * Miscellaneous housekeeping.
1305  *
1306  * Although replace_rte_variables() faithfully updated parse->hasSubLinks
1307  * if it copied any SubLinks out of the subquery's targetlist, we still
1308  * could have SubLinks added to the query in the expressions of FUNCTION
1309  * and VALUES RTEs copied up from the subquery. So it's necessary to copy
1310  * subquery->hasSubLinks anyway. Perhaps this can be improved someday.
1311  */
1312  parse->hasSubLinks |= subquery->hasSubLinks;
1313 
1314  /* If subquery had any RLS conditions, now main query does too */
1315  parse->hasRowSecurity |= subquery->hasRowSecurity;
1316 
1317  /*
1318  * subquery won't be pulled up if it hasAggs, hasWindowFuncs, or
1319  * hasTargetSRFs, so no work needed on those flags
1320  */
1321 
1322  /*
1323  * Return the adjusted subquery jointree to replace the RangeTblRef entry
1324  * in parent's jointree; or, if the FromExpr is degenerate, just return
1325  * its single member.
1326  */
1327  Assert(IsA(subquery->jointree, FromExpr));
1328  Assert(subquery->jointree->fromlist != NIL);
1329  if (subquery->jointree->quals == NULL &&
1330  list_length(subquery->jointree->fromlist) == 1)
1331  return (Node *) linitial(subquery->jointree->fromlist);
1332 
1333  return (Node *) subquery->jointree;
1334 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
@ RTE_CTE
Definition: parsenodes.h:1034
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1035
@ RTE_TABLEFUNC
Definition: parsenodes.h:1032
@ RTE_RELATION
Definition: parsenodes.h:1028
void preprocess_function_rtes(PlannerInfo *root)
Definition: prepjointree.c:776
static bool is_simple_subquery(PlannerInfo *root, Query *subquery, RangeTblEntry *rte, JoinExpr *lowest_outer_join)
void pull_up_sublinks(PlannerInfo *root)
Definition: prepjointree.c:342
void replace_empty_jointree(Query *parse)
Definition: prepjointree.c:284
static void fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids)
void pull_up_subqueries(PlannerInfo *root)
Definition: prepjointree.c:817
static bool is_safe_append_member(Query *subquery)
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:480
void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos)
Definition: rewriteManip.c:350
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:849
List * minmax_aggs
Definition: pathnodes.h:478
List * processed_tlist
Definition: pathnodes.h:462
bool hasRecursion
Definition: pathnodes.h:510
List * cte_plan_ids
Definition: pathnodes.h:305
int last_rinfo_serial
Definition: pathnodes.h:343
Index qual_security_level
Definition: pathnodes.h:495
List * init_plans
Definition: pathnodes.h:299
List * multiexpr_params
Definition: pathnodes.h:308
List * row_identity_vars
Definition: pathnodes.h:368
bool ec_merging_done
Definition: pathnodes.h:317
Bitmapset * outer_params
Definition: pathnodes.h:221
Index query_level
Definition: pathnodes.h:208
List * append_rel_list
Definition: pathnodes.h:365
struct Path * non_recursive_path
Definition: pathnodes.h:532
List * placeholder_list
Definition: pathnodes.h:374
PlannerGlobal * glob
Definition: pathnodes.h:205
List * join_domains
Definition: pathnodes.h:311
List * eq_classes
Definition: pathnodes.h:314
int wt_param_id
Definition: pathnodes.h:530
List * plan_params
Definition: pathnodes.h:220
List * processed_groupClause
Definition: pathnodes.h:439
List * processed_distinctClause
Definition: pathnodes.h:451
Query * parse
Definition: pathnodes.h:202
List * rowMarks
Definition: pathnodes.h:371
List * update_colnos
Definition: pathnodes.h:470
bool placeholdersFrozen
Definition: pathnodes.h:508
List * join_info_list
Definition: pathnodes.h:340
Relids all_result_relids
Definition: pathnodes.h:354
Relids leaf_result_relids
Definition: pathnodes.h:356
struct TableSampleClause * tablesample
Definition: parsenodes.h:1108
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition: var.c:744

References PlannerInfo::all_result_relids, PlannerInfo::append_rel_list, Assert, CombineRangeTables(), copyObject, PlannerInfo::cte_plan_ids, Query::cteList, CurrentMemoryContext, PlannerInfo::ec_merging_done, PlannerInfo::eq_classes, fix_append_rel_relids(), flatten_join_alias_vars(), FromExpr::fromlist, get_relids_in_jointree(), PlannerInfo::glob, PlannerInfo::hasRecursion, IncrementVarSublevelsUp(), PlannerInfo::init_plans, is_safe_append_member(), is_simple_subquery(), IsA, PlannerInfo::join_domains, PlannerInfo::join_info_list, Query::jointree, PlannerInfo::last_rinfo_serial, PlannerInfo::leaf_result_relids, lfirst, linitial, list_concat(), list_length(), makeNode, PlannerInfo::minmax_aggs, PlannerInfo::multiexpr_params, NIL, PlannerInfo::non_recursive_path, OffsetVarNodes(), pullup_replace_vars_context::outer_hasSubLinks, PlannerInfo::outer_params, palloc0(), parse(), PlannerInfo::parse, perform_pullup_replace_vars(), PlannerInfo::placeholder_list, PlannerInfo::placeholdersFrozen, PlannerInfo::plan_params, preprocess_function_rtes(), PlannerInfo::processed_distinctClause, PlannerInfo::processed_groupClause, PlannerInfo::processed_tlist, pull_up_sublinks(), pull_up_subqueries(), PlannerInfo::qual_security_level, FromExpr::quals, PlannerInfo::query_level, pullup_replace_vars_context::relids, replace_empty_jointree(), pullup_replace_vars_context::root, root, PlannerInfo::row_identity_vars, Query::rowMarks, PlannerInfo::rowMarks, Query::rtable, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, pullup_replace_vars_context::rv_cache, RangeTblEntry::subquery, substitute_phv_relids(), RangeTblEntry::tablesample, pullup_replace_vars_context::target_rte, pullup_replace_vars_context::targetlist, Query::targetList, PlannerInfo::update_colnos, pullup_replace_vars_context::varno, pullup_replace_vars_context::wrap_non_vars, and PlannerInfo::wt_param_id.

Referenced by pull_up_subqueries_recurse().

◆ pull_up_simple_union_all()

static Node * pull_up_simple_union_all ( PlannerInfo root,
Node jtnode,
RangeTblEntry rte 
)
static

Definition at line 1346 of file prepjointree.c.

1347 {
1348  int varno = ((RangeTblRef *) jtnode)->rtindex;
1349  Query *subquery = rte->subquery;
1350  int rtoffset = list_length(root->parse->rtable);
1351  List *rtable;
1352 
1353  /*
1354  * Make a modifiable copy of the subquery's rtable, so we can adjust
1355  * upper-level Vars in it. There are no such Vars in the setOperations
1356  * tree proper, so fixing the rtable should be sufficient.
1357  */
1358  rtable = copyObject(subquery->rtable);
1359 
1360  /*
1361  * Upper-level vars in subquery are now one level closer to their parent
1362  * than before. We don't have to worry about offsetting varnos, though,
1363  * because the UNION leaf queries can't cross-reference each other.
1364  */
1365  IncrementVarSublevelsUp_rtable(rtable, -1, 1);
1366 
1367  /*
1368  * If the UNION ALL subquery had a LATERAL marker, propagate that to all
1369  * its children. The individual children might or might not contain any
1370  * actual lateral cross-references, but we have to mark the pulled-up
1371  * child RTEs so that later planner stages will check for such.
1372  */
1373  if (rte->lateral)
1374  {
1375  ListCell *rt;
1376 
1377  foreach(rt, rtable)
1378  {
1379  RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt);
1380 
1381  Assert(child_rte->rtekind == RTE_SUBQUERY);
1382  child_rte->lateral = true;
1383  }
1384  }
1385 
1386  /*
1387  * Append child RTEs (and their perminfos) to parent rtable.
1388  */
1389  CombineRangeTables(&root->parse->rtable, &root->parse->rteperminfos,
1390  rtable, subquery->rteperminfos);
1391 
1392  /*
1393  * Recursively scan the subquery's setOperations tree and add
1394  * AppendRelInfo nodes for leaf subqueries to the parent's
1395  * append_rel_list. Also apply pull_up_subqueries to the leaf subqueries.
1396  */
1397  Assert(subquery->setOperations);
1398  pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
1399  rtoffset);
1400 
1401  /*
1402  * Mark the parent as an append relation.
1403  */
1404  rte->inh = true;
1405 
1406  return jtnode;
1407 }
void IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:872

References Assert, CombineRangeTables(), copyObject, IncrementVarSublevelsUp_rtable(), RangeTblEntry::inh, lfirst, list_length(), pull_up_union_leaf_queries(), root, Query::rtable, RTE_SUBQUERY, RangeTblEntry::rtekind, Query::setOperations, and RangeTblEntry::subquery.

Referenced by pull_up_subqueries_recurse().

◆ pull_up_simple_values()

static Node * pull_up_simple_values ( PlannerInfo root,
Node jtnode,
RangeTblEntry rte 
)
static

Definition at line 1673 of file prepjointree.c.

1674 {
1675  Query *parse = root->parse;
1676  int varno = ((RangeTblRef *) jtnode)->rtindex;
1677  List *values_list;
1678  List *tlist;
1679  AttrNumber attrno;
1680  pullup_replace_vars_context rvcontext;
1681  ListCell *lc;
1682 
1683  Assert(rte->rtekind == RTE_VALUES);
1684  Assert(list_length(rte->values_lists) == 1);
1685 
1686  /*
1687  * Need a modifiable copy of the VALUES list to hack on, just in case it's
1688  * multiply referenced.
1689  */
1690  values_list = copyObject(linitial(rte->values_lists));
1691 
1692  /*
1693  * The VALUES RTE can't contain any Vars of level zero, let alone any that
1694  * are join aliases, so no need to flatten join alias Vars.
1695  */
1696  Assert(!contain_vars_of_level((Node *) values_list, 0));
1697 
1698  /*
1699  * Set up required context data for pullup_replace_vars. In particular,
1700  * we have to make the VALUES list look like a subquery targetlist.
1701  */
1702  tlist = NIL;
1703  attrno = 1;
1704  foreach(lc, values_list)
1705  {
1706  tlist = lappend(tlist,
1707  makeTargetEntry((Expr *) lfirst(lc),
1708  attrno,
1709  NULL,
1710  false));
1711  attrno++;
1712  }
1713  rvcontext.root = root;
1714  rvcontext.targetlist = tlist;
1715  rvcontext.target_rte = rte;
1716  rvcontext.relids = NULL;
1717  rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1718  rvcontext.varno = varno;
1719  rvcontext.wrap_non_vars = false;
1720  /* initialize cache array with indexes 0 .. length(tlist) */
1721  rvcontext.rv_cache = palloc0((list_length(tlist) + 1) *
1722  sizeof(Node *));
1723 
1724  /*
1725  * Replace all of the top query's references to the RTE's outputs with
1726  * copies of the adjusted VALUES expressions, being careful not to replace
1727  * any of the jointree structure. We can assume there's no outer joins or
1728  * appendrels in the dummy Query that surrounds a VALUES RTE.
1729  */
1730  perform_pullup_replace_vars(root, &rvcontext, NULL);
1731 
1732  /*
1733  * There should be no appendrels to fix, nor any outer joins and hence no
1734  * PlaceHolderVars.
1735  */
1736  Assert(root->append_rel_list == NIL);
1737  Assert(root->join_info_list == NIL);
1738  Assert(root->placeholder_list == NIL);
1739 
1740  /*
1741  * Replace the VALUES RTE with a RESULT RTE. The VALUES RTE is the only
1742  * rtable entry in the current query level, so this is easy.
1743  */
1744  Assert(list_length(parse->rtable) == 1);
1745 
1746  /* Create suitable RTE */
1747  rte = makeNode(RangeTblEntry);
1748  rte->rtekind = RTE_RESULT;
1749  rte->eref = makeAlias("*RESULT*", NIL);
1750 
1751  /* Replace rangetable */
1752  parse->rtable = list_make1(rte);
1753 
1754  /* We could manufacture a new RangeTblRef, but the one we have is fine */
1755  Assert(varno == 1);
1756 
1757  return jtnode;
1758 }
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:389
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:441

References Assert, contain_vars_of_level(), copyObject, lappend(), lfirst, linitial, list_length(), list_make1, makeAlias(), makeNode, makeTargetEntry(), NIL, pullup_replace_vars_context::outer_hasSubLinks, palloc0(), parse(), perform_pullup_replace_vars(), pullup_replace_vars_context::relids, pullup_replace_vars_context::root, root, RTE_RESULT, RTE_VALUES, RangeTblEntry::rtekind, pullup_replace_vars_context::rv_cache, pullup_replace_vars_context::target_rte, pullup_replace_vars_context::targetlist, RangeTblEntry::values_lists, pullup_replace_vars_context::varno, and pullup_replace_vars_context::wrap_non_vars.

Referenced by pull_up_subqueries_recurse().

◆ pull_up_sublinks()

void pull_up_sublinks ( PlannerInfo root)

Definition at line 342 of file prepjointree.c.

343 {
344  Node *jtnode;
345  Relids relids;
346 
347  /* Begin recursion through the jointree */
349  (Node *) root->parse->jointree,
350  &relids);
351 
352  /*
353  * root->parse->jointree must always be a FromExpr, so insert a dummy one
354  * if we got a bare RangeTblRef or JoinExpr out of the recursion.
355  */
356  if (IsA(jtnode, FromExpr))
357  root->parse->jointree = (FromExpr *) jtnode;
358  else
359  root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
360 }
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:287
static Node * pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode, Relids *relids)
Definition: prepjointree.c:369

References IsA, list_make1, makeFromExpr(), pull_up_sublinks_jointree_recurse(), and root.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ pull_up_sublinks_jointree_recurse()

static Node * pull_up_sublinks_jointree_recurse ( PlannerInfo root,
Node jtnode,
Relids relids 
)
static

Definition at line 369 of file prepjointree.c.

371 {
372  /* Since this function recurses, it could be driven to stack overflow. */
374 
375  if (jtnode == NULL)
376  {
377  *relids = NULL;
378  }
379  else if (IsA(jtnode, RangeTblRef))
380  {
381  int varno = ((RangeTblRef *) jtnode)->rtindex;
382 
383  *relids = bms_make_singleton(varno);
384  /* jtnode is returned unmodified */
385  }
386  else if (IsA(jtnode, FromExpr))
387  {
388  FromExpr *f = (FromExpr *) jtnode;
389  List *newfromlist = NIL;
390  Relids frelids = NULL;
391  FromExpr *newf;
392  Node *jtlink;
393  ListCell *l;
394 
395  /* First, recurse to process children and collect their relids */
396  foreach(l, f->fromlist)
397  {
398  Node *newchild;
399  Relids childrelids;
400 
402  lfirst(l),
403  &childrelids);
404  newfromlist = lappend(newfromlist, newchild);
405  frelids = bms_join(frelids, childrelids);
406  }
407  /* Build the replacement FromExpr; no quals yet */
408  newf = makeFromExpr(newfromlist, NULL);
409  /* Set up a link representing the rebuilt jointree */
410  jtlink = (Node *) newf;
411  /* Now process qual --- all children are available for use */
413  &jtlink, frelids,
414  NULL, NULL);
415 
416  /*
417  * Note that the result will be either newf, or a stack of JoinExprs
418  * with newf at the base. We rely on subsequent optimization steps to
419  * flatten this and rearrange the joins as needed.
420  *
421  * Although we could include the pulled-up subqueries in the returned
422  * relids, there's no need since upper quals couldn't refer to their
423  * outputs anyway.
424  */
425  *relids = frelids;
426  jtnode = jtlink;
427  }
428  else if (IsA(jtnode, JoinExpr))
429  {
430  JoinExpr *j;
431  Relids leftrelids;
432  Relids rightrelids;
433  Node *jtlink;
434 
435  /*
436  * Make a modifiable copy of join node, but don't bother copying its
437  * subnodes (yet).
438  */
439  j = (JoinExpr *) palloc(sizeof(JoinExpr));
440  memcpy(j, jtnode, sizeof(JoinExpr));
441  jtlink = (Node *) j;
442 
443  /* Recurse to process children and collect their relids */
444  j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
445  &leftrelids);
446  j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
447  &rightrelids);
448 
449  /*
450  * Now process qual, showing appropriate child relids as available,
451  * and attach any pulled-up jointree items at the right place. In the
452  * inner-join case we put new JoinExprs above the existing one (much
453  * as for a FromExpr-style join). In outer-join cases the new
454  * JoinExprs must go into the nullable side of the outer join. The
455  * point of the available_rels machinations is to ensure that we only
456  * pull up quals for which that's okay.
457  *
458  * We don't expect to see any pre-existing JOIN_SEMI, JOIN_ANTI,
459  * JOIN_RIGHT_SEMI, or JOIN_RIGHT_ANTI jointypes here.
460  */
461  switch (j->jointype)
462  {
463  case JOIN_INNER:
464  j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
465  &jtlink,
466  bms_union(leftrelids,
467  rightrelids),
468  NULL, NULL);
469  break;
470  case JOIN_LEFT:
471  j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
472  &j->rarg,
473  rightrelids,
474  NULL, NULL);
475  break;
476  case JOIN_FULL:
477  /* can't do anything with full-join quals */
478  break;
479  case JOIN_RIGHT:
480  j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
481  &j->larg,
482  leftrelids,
483  NULL, NULL);
484  break;
485  default:
486  elog(ERROR, "unrecognized join type: %d",
487  (int) j->jointype);
488  break;
489  }
490 
491  /*
492  * Although we could include the pulled-up subqueries in the returned
493  * relids, there's no need since upper quals couldn't refer to their
494  * outputs anyway. But we *do* need to include the join's own rtindex
495  * because we haven't yet collapsed join alias variables, so upper
496  * levels would mistakenly think they couldn't use references to this
497  * join.
498  */
499  *relids = bms_join(leftrelids, rightrelids);
500  if (j->rtindex)
501  *relids = bms_add_member(*relids, j->rtindex);
502  jtnode = jtlink;
503  }
504  else
505  elog(ERROR, "unrecognized node type: %d",
506  (int) nodeTag(jtnode));
507  return jtnode;
508 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
void * palloc(Size size)
Definition: mcxt.c:1317
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
static Node * pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node, Node **jtlink1, Relids available_rels1, Node **jtlink2, Relids available_rels2)
Definition: prepjointree.c:526

References bms_add_member(), bms_join(), bms_make_singleton(), bms_union(), check_stack_depth(), elog, ERROR, FromExpr::fromlist, IsA, j, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, lappend(), lfirst, makeFromExpr(), NIL, nodeTag, palloc(), pull_up_sublinks_qual_recurse(), FromExpr::quals, and root.

Referenced by pull_up_sublinks(), and pull_up_sublinks_qual_recurse().

◆ pull_up_sublinks_qual_recurse()

static Node * pull_up_sublinks_qual_recurse ( PlannerInfo root,
Node node,
Node **  jtlink1,
Relids  available_rels1,
Node **  jtlink2,
Relids  available_rels2 
)
static

Definition at line 526 of file prepjointree.c.

529 {
530  if (node == NULL)
531  return NULL;
532  if (IsA(node, SubLink))
533  {
534  SubLink *sublink = (SubLink *) node;
535  JoinExpr *j;
536  Relids child_rels;
537 
538  /* Is it a convertible ANY or EXISTS clause? */
539  if (sublink->subLinkType == ANY_SUBLINK)
540  {
541  if ((j = convert_ANY_sublink_to_join(root, sublink,
542  available_rels1)) != NULL)
543  {
544  /* Yes; insert the new join node into the join tree */
545  j->larg = *jtlink1;
546  *jtlink1 = (Node *) j;
547  /* Recursively process pulled-up jointree nodes */
549  j->rarg,
550  &child_rels);
551 
552  /*
553  * Now recursively process the pulled-up quals. Any inserted
554  * joins can get stacked onto either j->larg or j->rarg,
555  * depending on which rels they reference.
556  */
558  j->quals,
559  &j->larg,
560  available_rels1,
561  &j->rarg,
562  child_rels);
563  /* Return NULL representing constant TRUE */
564  return NULL;
565  }
566  if (available_rels2 != NULL &&
567  (j = convert_ANY_sublink_to_join(root, sublink,
568  available_rels2)) != NULL)
569  {
570  /* Yes; insert the new join node into the join tree */
571  j->larg = *jtlink2;
572  *jtlink2 = (Node *) j;
573  /* Recursively process pulled-up jointree nodes */
575  j->rarg,
576  &child_rels);
577 
578  /*
579  * Now recursively process the pulled-up quals. Any inserted
580  * joins can get stacked onto either j->larg or j->rarg,
581  * depending on which rels they reference.
582  */
584  j->quals,
585  &j->larg,
586  available_rels2,
587  &j->rarg,
588  child_rels);
589  /* Return NULL representing constant TRUE */
590  return NULL;
591  }
592  }
593  else if (sublink->subLinkType == EXISTS_SUBLINK)
594  {
595  if ((j = convert_EXISTS_sublink_to_join(root, sublink, false,
596  available_rels1)) != NULL)
597  {
598  /* Yes; insert the new join node into the join tree */
599  j->larg = *jtlink1;
600  *jtlink1 = (Node *) j;
601  /* Recursively process pulled-up jointree nodes */
603  j->rarg,
604  &child_rels);
605 
606  /*
607  * Now recursively process the pulled-up quals. Any inserted
608  * joins can get stacked onto either j->larg or j->rarg,
609  * depending on which rels they reference.
610  */
612  j->quals,
613  &j->larg,
614  available_rels1,
615  &j->rarg,
616  child_rels);
617  /* Return NULL representing constant TRUE */
618  return NULL;
619  }
620  if (available_rels2 != NULL &&
621  (j = convert_EXISTS_sublink_to_join(root, sublink, false,
622  available_rels2)) != NULL)
623  {
624  /* Yes; insert the new join node into the join tree */
625  j->larg = *jtlink2;
626  *jtlink2 = (Node *) j;
627  /* Recursively process pulled-up jointree nodes */
629  j->rarg,
630  &child_rels);
631 
632  /*
633  * Now recursively process the pulled-up quals. Any inserted
634  * joins can get stacked onto either j->larg or j->rarg,
635  * depending on which rels they reference.
636  */
638  j->quals,
639  &j->larg,
640  available_rels2,
641  &j->rarg,
642  child_rels);
643  /* Return NULL representing constant TRUE */
644  return NULL;
645  }
646  }
647  /* Else return it unmodified */
648  return node;
649  }
650  if (is_notclause(node))
651  {
652  /* If the immediate argument of NOT is EXISTS, try to convert */
653  SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
654  JoinExpr *j;
655  Relids child_rels;
656 
657  if (sublink && IsA(sublink, SubLink))
658  {
659  if (sublink->subLinkType == EXISTS_SUBLINK)
660  {
661  if ((j = convert_EXISTS_sublink_to_join(root, sublink, true,
662  available_rels1)) != NULL)
663  {
664  /* Yes; insert the new join node into the join tree */
665  j->larg = *jtlink1;
666  *jtlink1 = (Node *) j;
667  /* Recursively process pulled-up jointree nodes */
669  j->rarg,
670  &child_rels);
671 
672  /*
673  * Now recursively process the pulled-up quals. Because
674  * we are underneath a NOT, we can't pull up sublinks that
675  * reference the left-hand stuff, but it's still okay to
676  * pull up sublinks referencing j->rarg.
677  */
679  j->quals,
680  &j->rarg,
681  child_rels,
682  NULL, NULL);
683  /* Return NULL representing constant TRUE */
684  return NULL;
685  }
686  if (available_rels2 != NULL &&
687  (j = convert_EXISTS_sublink_to_join(root, sublink, true,
688  available_rels2)) != NULL)
689  {
690  /* Yes; insert the new join node into the join tree */
691  j->larg = *jtlink2;
692  *jtlink2 = (Node *) j;
693  /* Recursively process pulled-up jointree nodes */
695  j->rarg,
696  &child_rels);
697 
698  /*
699  * Now recursively process the pulled-up quals. Because
700  * we are underneath a NOT, we can't pull up sublinks that
701  * reference the left-hand stuff, but it's still okay to
702  * pull up sublinks referencing j->rarg.
703  */
705  j->quals,
706  &j->rarg,
707  child_rels,
708  NULL, NULL);
709  /* Return NULL representing constant TRUE */
710  return NULL;
711  }
712  }
713  }
714  /* Else return it unmodified */
715  return node;
716  }
717  if (is_andclause(node))
718  {
719  /* Recurse into AND clause */
720  List *newclauses = NIL;
721  ListCell *l;
722 
723  foreach(l, ((BoolExpr *) node)->args)
724  {
725  Node *oldclause = (Node *) lfirst(l);
726  Node *newclause;
727 
729  oldclause,
730  jtlink1,
731  available_rels1,
732  jtlink2,
733  available_rels2);
734  if (newclause)
735  newclauses = lappend(newclauses, newclause);
736  }
737  /* We might have got back fewer clauses than we started with */
738  if (newclauses == NIL)
739  return NULL;
740  else if (list_length(newclauses) == 1)
741  return (Node *) linitial(newclauses);
742  else
743  return (Node *) make_andclause(newclauses);
744  }
745  /* Stop if not an AND */
746  return node;
747 }
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:654
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:105
static Expr * get_notclausearg(const void *notclause)
Definition: nodeFuncs.h:132
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:123
@ ANY_SUBLINK
Definition: primnodes.h:999
@ EXISTS_SUBLINK
Definition: primnodes.h:997
JoinExpr * convert_ANY_sublink_to_join(PlannerInfo *root, SubLink *sublink, Relids available_rels)
Definition: subselect.c:1254
JoinExpr * convert_EXISTS_sublink_to_join(PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
Definition: subselect.c:1371

References ANY_SUBLINK, generate_unaccent_rules::args, convert_ANY_sublink_to_join(), convert_EXISTS_sublink_to_join(), EXISTS_SUBLINK, get_notclausearg(), is_andclause(), is_notclause(), IsA, j, lappend(), lfirst, linitial, list_length(), make_andclause(), NIL, pull_up_sublinks_jointree_recurse(), root, and SubLink::subLinkType.

Referenced by pull_up_sublinks_jointree_recurse().

◆ pull_up_subqueries()

void pull_up_subqueries ( PlannerInfo root)

Definition at line 817 of file prepjointree.c.

818 {
819  /* Top level of jointree must always be a FromExpr */
820  Assert(IsA(root->parse->jointree, FromExpr));
821  /* Recursion starts with no containing join nor appendrel */
822  root->parse->jointree = (FromExpr *)
823  pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
824  NULL, NULL);
825  /* We should still have a FromExpr */
826  Assert(IsA(root->parse->jointree, FromExpr));
827 }
static Node * pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
Definition: prepjointree.c:861

References Assert, IsA, pull_up_subqueries_recurse(), and root.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ pull_up_subqueries_recurse()

static Node * pull_up_subqueries_recurse ( PlannerInfo root,
Node jtnode,
JoinExpr lowest_outer_join,
AppendRelInfo containing_appendrel 
)
static

Definition at line 861 of file prepjointree.c.

864 {
865  /* Since this function recurses, it could be driven to stack overflow. */
867  /* Also, since it's a bit expensive, let's check for query cancel. */
869 
870  Assert(jtnode != NULL);
871  if (IsA(jtnode, RangeTblRef))
872  {
873  int varno = ((RangeTblRef *) jtnode)->rtindex;
874  RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
875 
876  /*
877  * Is this a subquery RTE, and if so, is the subquery simple enough to
878  * pull up?
879  *
880  * If we are looking at an append-relation member, we can't pull it up
881  * unless is_safe_append_member says so.
882  */
883  if (rte->rtekind == RTE_SUBQUERY &&
884  is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) &&
885  (containing_appendrel == NULL ||
887  return pull_up_simple_subquery(root, jtnode, rte,
888  lowest_outer_join,
889  containing_appendrel);
890 
891  /*
892  * Alternatively, is it a simple UNION ALL subquery? If so, flatten
893  * into an "append relation".
894  *
895  * It's safe to do this regardless of whether this query is itself an
896  * appendrel member. (If you're thinking we should try to flatten the
897  * two levels of appendrel together, you're right; but we handle that
898  * in set_append_rel_pathlist, not here.)
899  */
900  if (rte->rtekind == RTE_SUBQUERY &&
902  return pull_up_simple_union_all(root, jtnode, rte);
903 
904  /*
905  * Or perhaps it's a simple VALUES RTE?
906  *
907  * We don't allow VALUES pullup below an outer join nor into an
908  * appendrel (such cases are impossible anyway at the moment).
909  */
910  if (rte->rtekind == RTE_VALUES &&
911  lowest_outer_join == NULL &&
912  containing_appendrel == NULL &&
913  is_simple_values(root, rte))
914  return pull_up_simple_values(root, jtnode, rte);
915 
916  /*
917  * Or perhaps it's a FUNCTION RTE that we could inline?
918  */
919  if (rte->rtekind == RTE_FUNCTION)
920  return pull_up_constant_function(root, jtnode, rte,
921  containing_appendrel);
922 
923  /* Otherwise, do nothing at this node. */
924  }
925  else if (IsA(jtnode, FromExpr))
926  {
927  FromExpr *f = (FromExpr *) jtnode;
928  ListCell *l;
929 
930  Assert(containing_appendrel == NULL);
931  /* Recursively transform all the child nodes */
932  foreach(l, f->fromlist)
933  {
935  lowest_outer_join,
936  NULL);
937  }
938  }
939  else if (IsA(jtnode, JoinExpr))
940  {
941  JoinExpr *j = (JoinExpr *) jtnode;
942 
943  Assert(containing_appendrel == NULL);
944  /* Recurse, being careful to tell myself when inside outer join */
945  switch (j->jointype)
946  {
947  case JOIN_INNER:
948  j->larg = pull_up_subqueries_recurse(root, j->larg,
949  lowest_outer_join,
950  NULL);
951  j->rarg = pull_up_subqueries_recurse(root, j->rarg,
952  lowest_outer_join,
953  NULL);
954  break;
955  case JOIN_LEFT:
956  case JOIN_SEMI:
957  case JOIN_ANTI:
958  j->larg = pull_up_subqueries_recurse(root, j->larg,
959  j,
960  NULL);
961  j->rarg = pull_up_subqueries_recurse(root, j->rarg,
962  j,
963  NULL);
964  break;
965  case JOIN_FULL:
966  j->larg = pull_up_subqueries_recurse(root, j->larg,
967  j,
968  NULL);
969  j->rarg = pull_up_subqueries_recurse(root, j->rarg,
970  j,
971  NULL);
972  break;
973  case JOIN_RIGHT:
974  j->larg = pull_up_subqueries_recurse(root, j->larg,
975  j,
976  NULL);
977  j->rarg = pull_up_subqueries_recurse(root, j->rarg,
978  j,
979  NULL);
980  break;
981  default:
982  elog(ERROR, "unrecognized join type: %d",
983  (int) j->jointype);
984  break;
985  }
986  }
987  else
988  elog(ERROR, "unrecognized node type: %d",
989  (int) nodeTag(jtnode));
990  return jtnode;
991 }
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_ANTI
Definition: nodes.h:308
static Node * pull_up_constant_function(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, AppendRelInfo *containing_appendrel)
static Node * pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte)
static Node * pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
static Node * pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
static bool is_simple_union_all(Query *subquery)

References Assert, CHECK_FOR_INTERRUPTS, check_stack_depth(), elog, ERROR, FromExpr::fromlist, is_safe_append_member(), is_simple_subquery(), is_simple_union_all(), is_simple_values(), IsA, j, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JOIN_SEMI, lfirst, nodeTag, pull_up_constant_function(), pull_up_simple_subquery(), pull_up_simple_union_all(), pull_up_simple_values(), root, rt_fetch, RTE_FUNCTION, RTE_SUBQUERY, RTE_VALUES, RangeTblEntry::rtekind, and RangeTblEntry::subquery.

Referenced by pull_up_subqueries(), and pull_up_union_leaf_queries().

◆ pull_up_union_leaf_queries()

static void pull_up_union_leaf_queries ( Node setOp,
PlannerInfo root,
int  parentRTindex,
Query setOpQuery,
int  childRToffset 
)
static

Definition at line 1428 of file prepjointree.c.

1430 {
1431  if (IsA(setOp, RangeTblRef))
1432  {
1433  RangeTblRef *rtr = (RangeTblRef *) setOp;
1434  int childRTindex;
1435  AppendRelInfo *appinfo;
1436 
1437  /*
1438  * Calculate the index in the parent's range table
1439  */
1440  childRTindex = childRToffset + rtr->rtindex;
1441 
1442  /*
1443  * Build a suitable AppendRelInfo, and attach to parent's list.
1444  */
1445  appinfo = makeNode(AppendRelInfo);
1446  appinfo->parent_relid = parentRTindex;
1447  appinfo->child_relid = childRTindex;
1448  appinfo->parent_reltype = InvalidOid;
1449  appinfo->child_reltype = InvalidOid;
1450  make_setop_translation_list(setOpQuery, childRTindex, appinfo);
1451  appinfo->parent_reloid = InvalidOid;
1452  root->append_rel_list = lappend(root->append_rel_list, appinfo);
1453 
1454  /*
1455  * Recursively apply pull_up_subqueries to the new child RTE. (We
1456  * must build the AppendRelInfo first, because this will modify it;
1457  * indeed, that's the only part of the upper query where Vars
1458  * referencing childRTindex can exist at this point.)
1459  *
1460  * Note that we can pass NULL for containing-join info even if we're
1461  * actually under an outer join, because the child's expressions
1462  * aren't going to propagate up to the join. Also, we ignore the
1463  * possibility that pull_up_subqueries_recurse() returns a different
1464  * jointree node than what we pass it; if it does, the important thing
1465  * is that it replaced the child relid in the AppendRelInfo node.
1466  */
1467  rtr = makeNode(RangeTblRef);
1468  rtr->rtindex = childRTindex;
1469  (void) pull_up_subqueries_recurse(root, (Node *) rtr,
1470  NULL, appinfo);
1471  }
1472  else if (IsA(setOp, SetOperationStmt))
1473  {
1474  SetOperationStmt *op = (SetOperationStmt *) setOp;
1475 
1476  /* Recurse to reach leaf queries */
1477  pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
1478  childRToffset);
1479  pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
1480  childRToffset);
1481  }
1482  else
1483  {
1484  elog(ERROR, "unrecognized node type: %d",
1485  (int) nodeTag(setOp));
1486  }
1487 }
#define InvalidOid
Definition: postgres_ext.h:36
static void make_setop_translation_list(Query *query, int newvarno, AppendRelInfo *appinfo)
Oid parent_reltype
Definition: pathnodes.h:2978

References AppendRelInfo::child_relid, AppendRelInfo::child_reltype, elog, ERROR, InvalidOid, IsA, lappend(), SetOperationStmt::larg, make_setop_translation_list(), makeNode, nodeTag, AppendRelInfo::parent_relid, AppendRelInfo::parent_reloid, AppendRelInfo::parent_reltype, pull_up_subqueries_recurse(), SetOperationStmt::rarg, root, and RangeTblRef::rtindex.

Referenced by flatten_simple_union_all(), and pull_up_simple_union_all().

◆ pullup_replace_vars()

static Node * pullup_replace_vars ( Node expr,
pullup_replace_vars_context context 
)
static

Definition at line 2346 of file prepjointree.c.

2347 {
2348  return replace_rte_variables(expr,
2349  context->varno, 0,
2351  (void *) context,
2352  context->outer_hasSubLinks);
2353 }
static Node * pullup_replace_vars_callback(Var *var, replace_rte_variables_context *context)
Node * replace_rte_variables(Node *node, int target_varno, int sublevels_up, replace_rte_variables_callback callback, void *callback_arg, bool *outer_hasSubLinks)

References context, pullup_replace_vars_callback(), and replace_rte_variables().

Referenced by perform_pullup_replace_vars(), and replace_vars_in_jointree().

◆ pullup_replace_vars_callback()

static Node * pullup_replace_vars_callback ( Var var,
replace_rte_variables_context context 
)
static

Definition at line 2356 of file prepjointree.c.

2358 {
2360  int varattno = var->varattno;
2361  bool need_phv;
2362  Node *newnode;
2363 
2364  /*
2365  * We need a PlaceHolderVar if the Var-to-be-replaced has nonempty
2366  * varnullingrels (unless we find below that the replacement expression is
2367  * a Var or PlaceHolderVar that we can just add the nullingrels to). We
2368  * also need one if the caller has instructed us that all non-Var/PHV
2369  * replacements need to be wrapped for identification purposes.
2370  */
2371  need_phv = (var->varnullingrels != NULL) || rcon->wrap_non_vars;
2372 
2373  /*
2374  * If PlaceHolderVars are needed, we cache the modified expressions in
2375  * rcon->rv_cache[]. This is not in hopes of any material speed gain
2376  * within this function, but to avoid generating identical PHVs with
2377  * different IDs. That would result in duplicate evaluations at runtime,
2378  * and possibly prevent optimizations that rely on recognizing different
2379  * references to the same subquery output as being equal(). So it's worth
2380  * a bit of extra effort to avoid it.
2381  *
2382  * The cached items have phlevelsup = 0 and phnullingrels = NULL; we'll
2383  * copy them and adjust those values for this reference site below.
2384  */
2385  if (need_phv &&
2386  varattno >= InvalidAttrNumber &&
2387  varattno <= list_length(rcon->targetlist) &&
2388  rcon->rv_cache[varattno] != NULL)
2389  {
2390  /* Just copy the entry and fall through to adjust phlevelsup etc */
2391  newnode = copyObject(rcon->rv_cache[varattno]);
2392  }
2393  else if (varattno == InvalidAttrNumber)
2394  {
2395  /* Must expand whole-tuple reference into RowExpr */
2396  RowExpr *rowexpr;
2397  List *colnames;
2398  List *fields;
2399  bool save_wrap_non_vars = rcon->wrap_non_vars;
2400  int save_sublevelsup = context->sublevels_up;
2401 
2402  /*
2403  * If generating an expansion for a var of a named rowtype (ie, this
2404  * is a plain relation RTE), then we must include dummy items for
2405  * dropped columns. If the var is RECORD (ie, this is a JOIN), then
2406  * omit dropped columns. In the latter case, attach column names to
2407  * the RowExpr for use of the executor and ruleutils.c.
2408  *
2409  * In order to be able to cache the results, we always generate the
2410  * expansion with varlevelsup = 0, and then adjust below if needed.
2411  */
2412  expandRTE(rcon->target_rte,
2413  var->varno, 0 /* not varlevelsup */ , var->location,
2414  (var->vartype != RECORDOID),
2415  &colnames, &fields);
2416  /* Expand the generated per-field Vars, but don't insert PHVs there */
2417  rcon->wrap_non_vars = false;
2418  context->sublevels_up = 0; /* to match the expandRTE output */
2419  fields = (List *) replace_rte_variables_mutator((Node *) fields,
2420  context);
2421  rcon->wrap_non_vars = save_wrap_non_vars;
2422  context->sublevels_up = save_sublevelsup;
2423 
2424  rowexpr = makeNode(RowExpr);
2425  rowexpr->args = fields;
2426  rowexpr->row_typeid = var->vartype;
2427  rowexpr->row_format = COERCE_IMPLICIT_CAST;
2428  rowexpr->colnames = (var->vartype == RECORDOID) ? colnames : NIL;
2429  rowexpr->location = var->location;
2430  newnode = (Node *) rowexpr;
2431 
2432  /*
2433  * Insert PlaceHolderVar if needed. Notice that we are wrapping one
2434  * PlaceHolderVar around the whole RowExpr, rather than putting one
2435  * around each element of the row. This is because we need the
2436  * expression to yield NULL, not ROW(NULL,NULL,...) when it is forced
2437  * to null by an outer join.
2438  */
2439  if (need_phv)
2440  {
2441  newnode = (Node *)
2443  (Expr *) newnode,
2444  bms_make_singleton(rcon->varno));
2445  /* cache it with the PHV, and with phlevelsup etc not set yet */
2446  rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
2447  }
2448  }
2449  else
2450  {
2451  /* Normal case referencing one targetlist element */
2452  TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
2453 
2454  if (tle == NULL) /* shouldn't happen */
2455  elog(ERROR, "could not find attribute %d in subquery targetlist",
2456  varattno);
2457 
2458  /* Make a copy of the tlist item to return */
2459  newnode = (Node *) copyObject(tle->expr);
2460 
2461  /* Insert PlaceHolderVar if needed */
2462  if (need_phv)
2463  {
2464  bool wrap;
2465 
2466  if (newnode && IsA(newnode, Var) &&
2467  ((Var *) newnode)->varlevelsup == 0)
2468  {
2469  /*
2470  * Simple Vars always escape being wrapped, unless they are
2471  * lateral references to something outside the subquery being
2472  * pulled up. (Even then, we could omit the PlaceHolderVar if
2473  * the referenced rel is under the same lowest outer join, but
2474  * it doesn't seem worth the trouble to check that.)
2475  */
2476  if (rcon->target_rte->lateral &&
2477  !bms_is_member(((Var *) newnode)->varno, rcon->relids))
2478  wrap = true;
2479  else
2480  wrap = false;
2481  }
2482  else if (newnode && IsA(newnode, PlaceHolderVar) &&
2483  ((PlaceHolderVar *) newnode)->phlevelsup == 0)
2484  {
2485  /* The same rules apply for a PlaceHolderVar */
2486  if (rcon->target_rte->lateral &&
2487  !bms_is_subset(((PlaceHolderVar *) newnode)->phrels,
2488  rcon->relids))
2489  wrap = true;
2490  else
2491  wrap = false;
2492  }
2493  else
2494  {
2495  /*
2496  * Must wrap, either because we need a place to insert
2497  * varnullingrels or because caller told us to wrap
2498  * everything.
2499  */
2500  wrap = true;
2501  }
2502 
2503  if (wrap)
2504  {
2505  newnode = (Node *)
2507  (Expr *) newnode,
2508  bms_make_singleton(rcon->varno));
2509 
2510  /*
2511  * Cache it if possible (ie, if the attno is in range, which
2512  * it probably always should be).
2513  */
2514  if (varattno > InvalidAttrNumber &&
2515  varattno <= list_length(rcon->targetlist))
2516  rcon->rv_cache[varattno] = copyObject(newnode);
2517  }
2518  }
2519  }
2520 
2521  /* Must adjust varlevelsup if replaced Var is within a subquery */
2522  if (var->varlevelsup > 0)
2523  IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
2524 
2525  /* Propagate any varnullingrels into the replacement Var or PHV */
2526  if (var->varnullingrels != NULL)
2527  {
2528  if (IsA(newnode, Var))
2529  {
2530  Var *newvar = (Var *) newnode;
2531 
2532  Assert(newvar->varlevelsup == var->varlevelsup);
2533  newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
2534  var->varnullingrels);
2535  }
2536  else if (IsA(newnode, PlaceHolderVar))
2537  {
2538  PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
2539 
2540  Assert(newphv->phlevelsup == var->varlevelsup);
2541  newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
2542  var->varnullingrels);
2543  }
2544  else
2545  elog(ERROR, "failed to wrap a non-Var");
2546  }
2547 
2548  return newnode;
2549 }
#define InvalidAttrNumber
Definition: attnum.h:23
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
void expandRTE(RangeTblEntry *rte, int rtindex, int sublevels_up, int location, bool include_dropped, List **colnames, List **colvars)
PlaceHolderVar * make_placeholder_expr(PlannerInfo *root, Expr *expr, Relids phrels)
Definition: placeholder.c:54
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
Node * replace_rte_variables_mutator(Node *node, replace_rte_variables_context *context)
Relids phnullingrels
Definition: pathnodes.h:2791
List * args
Definition: primnodes.h:1411
ParseLoc location
Definition: primnodes.h:1435
Expr * expr
Definition: primnodes.h:2186
Definition: primnodes.h:248
ParseLoc location
Definition: primnodes.h:293
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280

References RowExpr::args, Assert, bms_add_members(), bms_is_member(), bms_is_subset(), bms_make_singleton(), COERCE_IMPLICIT_CAST, context, copyObject, elog, ERROR, expandRTE(), TargetEntry::expr, get_tle_by_resno(), IncrementVarSublevelsUp(), InvalidAttrNumber, IsA, list_length(), Var::location, RowExpr::location, make_placeholder_expr(), makeNode, NIL, PlaceHolderVar::phlevelsup, PlaceHolderVar::phnullingrels, pullup_replace_vars_context::relids, replace_rte_variables_mutator(), pullup_replace_vars_context::root, pullup_replace_vars_context::rv_cache, pullup_replace_vars_context::target_rte, pullup_replace_vars_context::targetlist, Var::varattno, Var::varlevelsup, pullup_replace_vars_context::varno, Var::varno, and pullup_replace_vars_context::wrap_non_vars.

Referenced by pullup_replace_vars(), and pullup_replace_vars_subquery().

◆ pullup_replace_vars_subquery()

static Query * pullup_replace_vars_subquery ( Query query,
pullup_replace_vars_context context 
)
static

Definition at line 2559 of file prepjointree.c.

2561 {
2562  Assert(IsA(query, Query));
2563  return (Query *) replace_rte_variables((Node *) query,
2564  context->varno, 1,
2566  (void *) context,
2567  NULL);
2568 }

References Assert, context, IsA, pullup_replace_vars_callback(), and replace_rte_variables().

Referenced by replace_vars_in_jointree().

◆ reduce_outer_joins()

void reduce_outer_joins ( PlannerInfo root)

Definition at line 2705 of file prepjointree.c.

2706 {
2709  ListCell *lc;
2710 
2711  /*
2712  * To avoid doing strictness checks on more quals than necessary, we want
2713  * to stop descending the jointree as soon as there are no outer joins
2714  * below our current point. This consideration forces a two-pass process.
2715  * The first pass gathers information about which base rels appear below
2716  * each side of each join clause, and about whether there are outer
2717  * join(s) below each side of each join clause. The second pass examines
2718  * qual clauses and changes join types as it descends the tree.
2719  */
2720  state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
2721 
2722  /* planner.c shouldn't have called me if no outer joins */
2723  if (state1 == NULL || !state1->contains_outer)
2724  elog(ERROR, "so where are the outer joins?");
2725 
2726  state2.inner_reduced = NULL;
2727  state2.partial_reduced = NIL;
2728 
2729  reduce_outer_joins_pass2((Node *) root->parse->jointree,
2730  state1, &state2,
2731  root, NULL, NIL);
2732 
2733  /*
2734  * If we successfully reduced the strength of any outer joins, we must
2735  * remove references to those joins as nulling rels. This is handled as
2736  * an additional pass, for simplicity and because we can handle all
2737  * fully-reduced joins in a single pass over the parse tree.
2738  */
2739  if (!bms_is_empty(state2.inner_reduced))
2740  {
2741  root->parse = (Query *)
2742  remove_nulling_relids((Node *) root->parse,
2743  state2.inner_reduced,
2744  NULL);
2745  /* There could be references in the append_rel_list, too */
2746  root->append_rel_list = (List *)
2747  remove_nulling_relids((Node *) root->append_rel_list,
2748  state2.inner_reduced,
2749  NULL);
2750  }
2751 
2752  /*
2753  * Partially-reduced full joins have to be done one at a time, since
2754  * they'll each need a different setting of except_relids.
2755  */
2756  foreach(lc, state2.partial_reduced)
2757  {
2759  Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
2760 
2761  root->parse = (Query *)
2762  remove_nulling_relids((Node *) root->parse,
2763  full_join_relids,
2764  statep->unreduced_side);
2765  root->append_rel_list = (List *)
2766  remove_nulling_relids((Node *) root->append_rel_list,
2767  full_join_relids,
2768  statep->unreduced_side);
2769  }
2770 }
#define bms_is_empty(a)
Definition: bitmapset.h:118
static void reduce_outer_joins_pass2(Node *jtnode, reduce_outer_joins_pass1_state *state1, reduce_outer_joins_pass2_state *state2, PlannerInfo *root, Relids nonnullable_rels, List *forced_null_vars)
static reduce_outer_joins_pass1_state * reduce_outer_joins_pass1(Node *jtnode)
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)

References bms_is_empty, bms_make_singleton(), reduce_outer_joins_pass1_state::contains_outer, elog, ERROR, reduce_outer_joins_partial_state::full_join_rti, reduce_outer_joins_pass2_state::inner_reduced, lfirst, NIL, reduce_outer_joins_pass2_state::partial_reduced, reduce_outer_joins_pass1(), reduce_outer_joins_pass2(), remove_nulling_relids(), root, and reduce_outer_joins_partial_state::unreduced_side.

Referenced by subquery_planner().

◆ reduce_outer_joins_pass1()

static reduce_outer_joins_pass1_state * reduce_outer_joins_pass1 ( Node jtnode)
static

Definition at line 2778 of file prepjointree.c.

2779 {
2781 
2782  result = (reduce_outer_joins_pass1_state *)
2784  result->relids = NULL;
2785  result->contains_outer = false;
2786  result->sub_states = NIL;
2787 
2788  if (jtnode == NULL)
2789  return result;
2790  if (IsA(jtnode, RangeTblRef))
2791  {
2792  int varno = ((RangeTblRef *) jtnode)->rtindex;
2793 
2794  result->relids = bms_make_singleton(varno);
2795  }
2796  else if (IsA(jtnode, FromExpr))
2797  {
2798  FromExpr *f = (FromExpr *) jtnode;
2799  ListCell *l;
2800 
2801  foreach(l, f->fromlist)
2802  {
2803  reduce_outer_joins_pass1_state *sub_state;
2804 
2805  sub_state = reduce_outer_joins_pass1(lfirst(l));
2806  result->relids = bms_add_members(result->relids,
2807  sub_state->relids);
2808  result->contains_outer |= sub_state->contains_outer;
2809  result->sub_states = lappend(result->sub_states, sub_state);
2810  }
2811  }
2812  else if (IsA(jtnode, JoinExpr))
2813  {
2814  JoinExpr *j = (JoinExpr *) jtnode;
2815  reduce_outer_joins_pass1_state *sub_state;
2816 
2817  /* join's own RT index is not wanted in result->relids */
2818  if (IS_OUTER_JOIN(j->jointype))
2819  result->contains_outer = true;
2820 
2821  sub_state = reduce_outer_joins_pass1(j->larg);
2822  result->relids = bms_add_members(result->relids,
2823  sub_state->relids);
2824  result->contains_outer |= sub_state->contains_outer;
2825  result->sub_states = lappend(result->sub_states, sub_state);
2826 
2827  sub_state = reduce_outer_joins_pass1(j->rarg);
2828  result->relids = bms_add_members(result->relids,
2829  sub_state->relids);
2830  result->contains_outer |= sub_state->contains_outer;
2831  result->sub_states = lappend(result->sub_states, sub_state);
2832  }
2833  else
2834  elog(ERROR, "unrecognized node type: %d",
2835  (int) nodeTag(jtnode));
2836  return result;
2837 }
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:338

References bms_add_members(), bms_make_singleton(), reduce_outer_joins_pass1_state::contains_outer, elog, ERROR, FromExpr::fromlist, IS_OUTER_JOIN, IsA, j, lappend(), lfirst, NIL, nodeTag, palloc(), reduce_outer_joins_pass1_state::relids, and reduce_outer_joins_pass1_state::sub_states.

Referenced by reduce_outer_joins().

◆ reduce_outer_joins_pass2()

static void reduce_outer_joins_pass2 ( Node jtnode,
reduce_outer_joins_pass1_state state1,
reduce_outer_joins_pass2_state state2,
PlannerInfo root,
Relids  nonnullable_rels,
List forced_null_vars 
)
static

Definition at line 2856 of file prepjointree.c.

2862 {
2863  /*
2864  * pass 2 should never descend as far as an empty subnode or base rel,
2865  * because it's only called on subtrees marked as contains_outer.
2866  */
2867  if (jtnode == NULL)
2868  elog(ERROR, "reached empty jointree");
2869  if (IsA(jtnode, RangeTblRef))
2870  elog(ERROR, "reached base rel");
2871  else if (IsA(jtnode, FromExpr))
2872  {
2873  FromExpr *f = (FromExpr *) jtnode;
2874  ListCell *l;
2875  ListCell *s;
2876  Relids pass_nonnullable_rels;
2877  List *pass_forced_null_vars;
2878 
2879  /* Scan quals to see if we can add any constraints */
2880  pass_nonnullable_rels = find_nonnullable_rels(f->quals);
2881  pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
2882  nonnullable_rels);
2883  pass_forced_null_vars = find_forced_null_vars(f->quals);
2884  pass_forced_null_vars = mbms_add_members(pass_forced_null_vars,
2885  forced_null_vars);
2886  /* And recurse --- but only into interesting subtrees */
2888  forboth(l, f->fromlist, s, state1->sub_states)
2889  {
2890  reduce_outer_joins_pass1_state *sub_state = lfirst(s);
2891 
2892  if (sub_state->contains_outer)
2893  reduce_outer_joins_pass2(lfirst(l), sub_state,
2894  state2, root,
2895  pass_nonnullable_rels,
2896  pass_forced_null_vars);
2897  }
2898  bms_free(pass_nonnullable_rels);
2899  /* can't so easily clean up var lists, unfortunately */
2900  }
2901  else if (IsA(jtnode, JoinExpr))
2902  {
2903  JoinExpr *j = (JoinExpr *) jtnode;
2904  int rtindex = j->rtindex;
2905  JoinType jointype = j->jointype;
2906  reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states);
2907  reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states);
2908 
2909  /* Can we simplify this join? */
2910  switch (jointype)
2911  {
2912  case JOIN_INNER:
2913  break;
2914  case JOIN_LEFT:
2915  if (bms_overlap(nonnullable_rels, right_state->relids))
2916  jointype = JOIN_INNER;
2917  break;
2918  case JOIN_RIGHT:
2919  if (bms_overlap(nonnullable_rels, left_state->relids))
2920  jointype = JOIN_INNER;
2921  break;
2922  case JOIN_FULL:
2923  if (bms_overlap(nonnullable_rels, left_state->relids))
2924  {
2925  if (bms_overlap(nonnullable_rels, right_state->relids))
2926  jointype = JOIN_INNER;
2927  else
2928  {
2929  jointype = JOIN_LEFT;
2930  /* Also report partial reduction in state2 */
2931  report_reduced_full_join(state2, rtindex,
2932  right_state->relids);
2933  }
2934  }
2935  else
2936  {
2937  if (bms_overlap(nonnullable_rels, right_state->relids))
2938  {
2939  jointype = JOIN_RIGHT;
2940  /* Also report partial reduction in state2 */
2941  report_reduced_full_join(state2, rtindex,
2942  left_state->relids);
2943  }
2944  }
2945  break;
2946  case JOIN_SEMI:
2947  case JOIN_ANTI:
2948 
2949  /*
2950  * These could only have been introduced by pull_up_sublinks,
2951  * so there's no way that upper quals could refer to their
2952  * righthand sides, and no point in checking. We don't expect
2953  * to see JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI yet.
2954  */
2955  break;
2956  default:
2957  elog(ERROR, "unrecognized join type: %d",
2958  (int) jointype);
2959  break;
2960  }
2961 
2962  /*
2963  * Convert JOIN_RIGHT to JOIN_LEFT. Note that in the case where we
2964  * reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
2965  * longer matches the internal ordering of any CoalesceExpr's built to
2966  * represent merged join variables. We don't care about that at
2967  * present, but be wary of it ...
2968  */
2969  if (jointype == JOIN_RIGHT)
2970  {
2971  Node *tmparg;
2972 
2973  tmparg = j->larg;
2974  j->larg = j->rarg;
2975  j->rarg = tmparg;
2976  jointype = JOIN_LEFT;
2977  right_state = linitial(state1->sub_states);
2978  left_state = lsecond(state1->sub_states);
2979  }
2980 
2981  /*
2982  * See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
2983  * the join's own quals are strict for any var that was forced null by
2984  * higher qual levels. NOTE: there are other ways that we could
2985  * detect an anti-join, in particular if we were to check whether Vars
2986  * coming from the RHS must be non-null because of table constraints.
2987  * That seems complicated and expensive though (in particular, one
2988  * would have to be wary of lower outer joins). For the moment this
2989  * seems sufficient.
2990  */
2991  if (jointype == JOIN_LEFT)
2992  {
2993  List *nonnullable_vars;
2994  Bitmapset *overlap;
2995 
2996  /* Find Vars in j->quals that must be non-null in joined rows */
2997  nonnullable_vars = find_nonnullable_vars(j->quals);
2998 
2999  /*
3000  * It's not sufficient to check whether nonnullable_vars and
3001  * forced_null_vars overlap: we need to know if the overlap
3002  * includes any RHS variables.
3003  */
3004  overlap = mbms_overlap_sets(nonnullable_vars, forced_null_vars);
3005  if (bms_overlap(overlap, right_state->relids))
3006  jointype = JOIN_ANTI;
3007  }
3008 
3009  /*
3010  * Apply the jointype change, if any, to both jointree node and RTE.
3011  * Also, if we changed an RTE to INNER, add its RTI to inner_reduced.
3012  */
3013  if (rtindex && jointype != j->jointype)
3014  {
3015  RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
3016 
3017  Assert(rte->rtekind == RTE_JOIN);
3018  Assert(rte->jointype == j->jointype);
3019  rte->jointype = jointype;
3020  if (jointype == JOIN_INNER)
3021  state2->inner_reduced = bms_add_member(state2->inner_reduced,
3022  rtindex);
3023  }
3024  j->jointype = jointype;
3025 
3026  /* Only recurse if there's more to do below here */
3027  if (left_state->contains_outer || right_state->contains_outer)
3028  {
3029  Relids local_nonnullable_rels;
3030  List *local_forced_null_vars;
3031  Relids pass_nonnullable_rels;
3032  List *pass_forced_null_vars;
3033 
3034  /*
3035  * If this join is (now) inner, we can add any constraints its
3036  * quals provide to those we got from above. But if it is outer,
3037  * we can pass down the local constraints only into the nullable
3038  * side, because an outer join never eliminates any rows from its
3039  * non-nullable side. Also, there is no point in passing upper
3040  * constraints into the nullable side, since if there were any
3041  * we'd have been able to reduce the join. (In the case of upper
3042  * forced-null constraints, we *must not* pass them into the
3043  * nullable side --- they either applied here, or not.) The upshot
3044  * is that we pass either the local or the upper constraints,
3045  * never both, to the children of an outer join.
3046  *
3047  * Note that a SEMI join works like an inner join here: it's okay
3048  * to pass down both local and upper constraints. (There can't be
3049  * any upper constraints affecting its inner side, but it's not
3050  * worth having a separate code path to avoid passing them.)
3051  *
3052  * At a FULL join we just punt and pass nothing down --- is it
3053  * possible to be smarter?
3054  */
3055  if (jointype != JOIN_FULL)
3056  {
3057  local_nonnullable_rels = find_nonnullable_rels(j->quals);
3058  local_forced_null_vars = find_forced_null_vars(j->quals);
3059  if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3060  {
3061  /* OK to merge upper and local constraints */
3062  local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
3063  nonnullable_rels);
3064  local_forced_null_vars = mbms_add_members(local_forced_null_vars,
3065  forced_null_vars);
3066  }
3067  }
3068  else
3069  {
3070  /* no use in calculating these */
3071  local_nonnullable_rels = NULL;
3072  local_forced_null_vars = NIL;
3073  }
3074 
3075  if (left_state->contains_outer)
3076  {
3077  if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3078  {
3079  /* pass union of local and upper constraints */
3080  pass_nonnullable_rels = local_nonnullable_rels;
3081  pass_forced_null_vars = local_forced_null_vars;
3082  }
3083  else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
3084  {
3085  /* can't pass local constraints to non-nullable side */
3086  pass_nonnullable_rels = nonnullable_rels;
3087  pass_forced_null_vars = forced_null_vars;
3088  }
3089  else
3090  {
3091  /* no constraints pass through JOIN_FULL */
3092  pass_nonnullable_rels = NULL;
3093  pass_forced_null_vars = NIL;
3094  }
3095  reduce_outer_joins_pass2(j->larg, left_state,
3096  state2, root,
3097  pass_nonnullable_rels,
3098  pass_forced_null_vars);
3099  }
3100 
3101  if (right_state->contains_outer)
3102  {
3103  if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
3104  {
3105  /* pass appropriate constraints, per comment above */
3106  pass_nonnullable_rels = local_nonnullable_rels;
3107  pass_forced_null_vars = local_forced_null_vars;
3108  }
3109  else
3110  {
3111  /* no constraints pass through JOIN_FULL */
3112  pass_nonnullable_rels = NULL;
3113  pass_forced_null_vars = NIL;
3114  }
3115  reduce_outer_joins_pass2(j->rarg, right_state,
3116  state2, root,
3117  pass_nonnullable_rels,
3118  pass_forced_null_vars);
3119  }
3120  bms_free(local_nonnullable_rels);
3121  }
3122  }
3123  else
3124  elog(ERROR, "unrecognized node type: %d",
3125  (int) nodeTag(jtnode));
3126 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
List * find_forced_null_vars(Node *node)
Definition: clauses.c:1916
Relids find_nonnullable_rels(Node *clause)
Definition: clauses.c:1456
List * find_nonnullable_vars(Node *clause)
Definition: clauses.c:1707
Bitmapset * mbms_overlap_sets(const List *a, const List *b)
List * mbms_add_members(List *a, const List *b)
JoinType
Definition: nodes.h:288
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define lsecond(l)
Definition: pg_list.h:183
static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2, int rtindex, Relids relids)
JoinType jointype
Definition: parsenodes.h:1161

References Assert, bms_add_member(), bms_add_members(), bms_free(), bms_overlap(), reduce_outer_joins_pass1_state::contains_outer, elog, ERROR, find_forced_null_vars(), find_nonnullable_rels(), find_nonnullable_vars(), forboth, FromExpr::fromlist, reduce_outer_joins_pass2_state::inner_reduced, IsA, j, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JOIN_SEMI, RangeTblEntry::jointype, lfirst, linitial, list_length(), lsecond, mbms_add_members(), mbms_overlap_sets(), NIL, nodeTag, FromExpr::quals, reduce_outer_joins_pass1_state::relids, report_reduced_full_join(), root, rt_fetch, RTE_JOIN, RangeTblEntry::rtekind, and reduce_outer_joins_pass1_state::sub_states.

Referenced by reduce_outer_joins().

◆ remove_result_refs()

static void remove_result_refs ( PlannerInfo root,
int  varno,
Node newjtloc 
)
static

Definition at line 3573 of file prepjointree.c.

3574 {
3575  /* Fix up PlaceHolderVars as needed */
3576  /* If there are no PHVs anywhere, we can skip this bit */
3577  if (root->glob->lastPHId != 0)
3578  {
3579  Relids subrelids;
3580 
3581  subrelids = get_relids_in_jointree(newjtloc, true, false);
3582  Assert(!bms_is_empty(subrelids));
3583  substitute_phv_relids((Node *) root->parse, varno, subrelids);
3584  fix_append_rel_relids(root, varno, subrelids);
3585  }
3586 
3587  /*
3588  * We also need to remove any PlanRowMark referencing the RTE, but we
3589  * postpone that work until we return to remove_useless_result_rtes.
3590  */
3591 }

References Assert, bms_is_empty, fix_append_rel_relids(), get_relids_in_jointree(), root, and substitute_phv_relids().

Referenced by remove_useless_results_recurse().

◆ remove_useless_result_rtes()

void remove_useless_result_rtes ( PlannerInfo root)

Definition at line 3199 of file prepjointree.c.

3200 {
3201  Relids dropped_outer_joins = NULL;
3202  ListCell *cell;
3203 
3204  /* Top level of jointree must always be a FromExpr */
3205  Assert(IsA(root->parse->jointree, FromExpr));
3206  /* Recurse ... */
3207  root->parse->jointree = (FromExpr *)
3209  (Node *) root->parse->jointree,
3210  NULL,
3211  &dropped_outer_joins);
3212  /* We should still have a FromExpr */
3213  Assert(IsA(root->parse->jointree, FromExpr));
3214 
3215  /*
3216  * If we removed any outer-join nodes from the jointree, run around and
3217  * remove references to those joins as nulling rels. (There could be such
3218  * references in PHVs that we pulled up out of the original subquery that
3219  * the RESULT rel replaced. This is kosher on the grounds that we now
3220  * know that such an outer join wouldn't really have nulled anything.) We
3221  * don't do this during the main recursion, for simplicity and because we
3222  * can handle all such joins in a single pass over the parse tree.
3223  */
3224  if (!bms_is_empty(dropped_outer_joins))
3225  {
3226  root->parse = (Query *)
3227  remove_nulling_relids((Node *) root->parse,
3228  dropped_outer_joins,
3229  NULL);
3230  /* There could be references in the append_rel_list, too */
3231  root->append_rel_list = (List *)
3232  remove_nulling_relids((Node *) root->append_rel_list,
3233  dropped_outer_joins,
3234  NULL);
3235  }
3236 
3237  /*
3238  * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
3239  * must do that for any RTE_RESULT that we just removed. But one for a
3240  * RTE that we did not remove can be dropped anyway: since the RTE has
3241  * only one possible output row, there is no need for EPQ to mark and
3242  * restore that row.
3243  *
3244  * It's necessary, not optional, to remove the PlanRowMark for a surviving
3245  * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
3246  * RTE_RESULT, which the executor has no support for.
3247  */
3248  foreach(cell, root->rowMarks)
3249  {
3250  PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
3251 
3252  if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
3253  root->rowMarks = foreach_delete_current(root->rowMarks, cell);
3254  }
3255 }
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
static Node * remove_useless_results_recurse(PlannerInfo *root, Node *jtnode, Node **parent_quals, Relids *dropped_outer_joins)

References Assert, bms_is_empty, foreach_delete_current, IsA, lfirst, remove_nulling_relids(), remove_useless_results_recurse(), root, rt_fetch, RTE_RESULT, and PlanRowMark::rti.

Referenced by subquery_planner().

◆ remove_useless_results_recurse()

static Node * remove_useless_results_recurse ( PlannerInfo root,
Node jtnode,
Node **  parent_quals,
Relids dropped_outer_joins 
)
static

Definition at line 3272 of file prepjointree.c.

3275 {
3276  Assert(jtnode != NULL);
3277  if (IsA(jtnode, RangeTblRef))
3278  {
3279  /* Can't immediately do anything with a RangeTblRef */
3280  }
3281  else if (IsA(jtnode, FromExpr))
3282  {
3283  FromExpr *f = (FromExpr *) jtnode;
3284  Relids result_relids = NULL;
3285  ListCell *cell;
3286 
3287  /*
3288  * We can drop RTE_RESULT rels from the fromlist so long as at least
3289  * one child remains, since joining to a one-row table changes
3290  * nothing. (But we can't drop a RTE_RESULT that computes PHV(s) that
3291  * are needed by some sibling. The cleanup transformation below would
3292  * reassign the PHVs to be computed at the join, which is too late for
3293  * the sibling's use.) The easiest way to mechanize this rule is to
3294  * modify the list in-place.
3295  */
3296  foreach(cell, f->fromlist)
3297  {
3298  Node *child = (Node *) lfirst(cell);
3299  int varno;
3300 
3301  /* Recursively transform child, allowing it to push up quals ... */
3302  child = remove_useless_results_recurse(root, child,
3303  &f->quals,
3304  dropped_outer_joins);
3305  /* ... and stick it back into the tree */
3306  lfirst(cell) = child;
3307 
3308  /*
3309  * If it's an RTE_RESULT with at least one sibling, and no sibling
3310  * references dependent PHVs, we can drop it. We don't yet know
3311  * what the inner join's final relid set will be, so postpone
3312  * cleanup of PHVs etc till after this loop.
3313  */
3314  if (list_length(f->fromlist) > 1 &&
3315  (varno = get_result_relid(root, child)) != 0 &&
3316  !find_dependent_phvs_in_jointree(root, (Node *) f, varno))
3317  {
3318  f->fromlist = foreach_delete_current(f->fromlist, cell);
3319  result_relids = bms_add_member(result_relids, varno);
3320  }
3321  }
3322 
3323  /*
3324  * Clean up if we dropped any RTE_RESULT RTEs. This is a bit
3325  * inefficient if there's more than one, but it seems better to
3326  * optimize the support code for the single-relid case.
3327  */
3328  if (result_relids)
3329  {
3330  int varno = -1;
3331 
3332  while ((varno = bms_next_member(result_relids, varno)) >= 0)
3333  remove_result_refs(root, varno, (Node *) f);
3334  }
3335 
3336  /*
3337  * If the FromExpr now has only one child, see if we can elide it.
3338  * This is always valid if there are no quals, except at the top of
3339  * the jointree (since Query.jointree is required to point to a
3340  * FromExpr). Otherwise, we can do it if we can push the quals up to
3341  * the parent node.
3342  *
3343  * Note: while it would not be terribly hard to generalize this
3344  * transformation to merge multi-child FromExprs into their parent
3345  * FromExpr, that risks making the parent join too expensive to plan.
3346  * We leave it to later processing to decide heuristically whether
3347  * that's a good idea. Pulling up a single child is always OK,
3348  * however.
3349  */
3350  if (list_length(f->fromlist) == 1 &&
3351  f != root->parse->jointree &&
3352  (f->quals == NULL || parent_quals != NULL))
3353  {
3354  /*
3355  * Merge any quals up to parent. They should be in implicit-AND
3356  * format by now, so we just need to concatenate lists. Put the
3357  * child quals at the front, on the grounds that they should
3358  * nominally be evaluated earlier.
3359  */
3360  if (f->quals != NULL)
3361  *parent_quals = (Node *)
3363  castNode(List, *parent_quals));
3364  return (Node *) linitial(f->fromlist);
3365  }
3366  }
3367  else if (IsA(jtnode, JoinExpr))
3368  {
3369  JoinExpr *j = (JoinExpr *) jtnode;
3370  int varno;
3371 
3372  /*
3373  * First, recurse. We can absorb pushed-up FromExpr quals from either
3374  * child into this node if the jointype is INNER, since then this is
3375  * equivalent to a FromExpr. When the jointype is LEFT, we can absorb
3376  * quals from the RHS child into the current node, as they're
3377  * essentially degenerate quals of the outer join. Moreover, if we've
3378  * been passed down a parent_quals pointer then we can allow quals of
3379  * the LHS child to be absorbed into the parent. (This is important
3380  * to ensure we remove single-child FromExprs immediately below
3381  * commutable left joins.) For other jointypes, we can't move child
3382  * quals up, or at least there's no particular reason to.
3383  */
3384  j->larg = remove_useless_results_recurse(root, j->larg,
3385  (j->jointype == JOIN_INNER) ?
3386  &j->quals :
3387  (j->jointype == JOIN_LEFT) ?
3388  parent_quals : NULL,
3389  dropped_outer_joins);
3390  j->rarg = remove_useless_results_recurse(root, j->rarg,
3391  (j->jointype == JOIN_INNER ||
3392  j->jointype == JOIN_LEFT) ?
3393  &j->quals : NULL,
3394  dropped_outer_joins);
3395 
3396  /* Apply join-type-specific optimization rules */
3397  switch (j->jointype)
3398  {
3399  case JOIN_INNER:
3400 
3401  /*
3402  * An inner join is equivalent to a FromExpr, so if either
3403  * side was simplified to an RTE_RESULT rel, we can replace
3404  * the join with a FromExpr with just the other side.
3405  * Furthermore, we can elide that FromExpr according to the
3406  * same rules as above.
3407  *
3408  * Just as in the FromExpr case, we can't simplify if the
3409  * other input rel references any PHVs that are marked as to
3410  * be evaluated at the RTE_RESULT rel, because we can't
3411  * postpone their evaluation in that case. But we only have
3412  * to check this in cases where it's syntactically legal for
3413  * the other input to have a LATERAL reference to the
3414  * RTE_RESULT rel. Only RHSes of inner and left joins are
3415  * allowed to have such refs.
3416  */
3417  if ((varno = get_result_relid(root, j->larg)) != 0 &&
3418  !find_dependent_phvs_in_jointree(root, j->rarg, varno))
3419  {
3420  remove_result_refs(root, varno, j->rarg);
3421  if (j->quals != NULL && parent_quals == NULL)
3422  jtnode = (Node *)
3423  makeFromExpr(list_make1(j->rarg), j->quals);
3424  else
3425  {
3426  /* Merge any quals up to parent */
3427  if (j->quals != NULL)
3428  *parent_quals = (Node *)
3429  list_concat(castNode(List, j->quals),
3430  castNode(List, *parent_quals));
3431  jtnode = j->rarg;
3432  }
3433  }
3434  else if ((varno = get_result_relid(root, j->rarg)) != 0)
3435  {
3436  remove_result_refs(root, varno, j->larg);
3437  if (j->quals != NULL && parent_quals == NULL)
3438  jtnode = (Node *)
3439  makeFromExpr(list_make1(j->larg), j->quals);
3440  else
3441  {
3442  /* Merge any quals up to parent */
3443  if (j->quals != NULL)
3444  *parent_quals = (Node *)
3445  list_concat(castNode(List, j->quals),
3446  castNode(List, *parent_quals));
3447  jtnode = j->larg;
3448  }
3449  }
3450  break;
3451  case JOIN_LEFT:
3452 
3453  /*
3454  * We can simplify this case if the RHS is an RTE_RESULT, with
3455  * two different possibilities:
3456  *
3457  * If the qual is empty (JOIN ON TRUE), then the join can be
3458  * strength-reduced to a plain inner join, since each LHS row
3459  * necessarily has exactly one join partner. So we can always
3460  * discard the RHS, much as in the JOIN_INNER case above.
3461  * (Again, the LHS could not contain a lateral reference to
3462  * the RHS.)
3463  *
3464  * Otherwise, it's still true that each LHS row should be
3465  * returned exactly once, and since the RHS returns no columns
3466  * (unless there are PHVs that have to be evaluated there), we
3467  * don't much care if it's null-extended or not. So in this
3468  * case also, we can just ignore the qual and discard the left
3469  * join.
3470  */
3471  if ((varno = get_result_relid(root, j->rarg)) != 0 &&
3472  (j->quals == NULL ||
3473  !find_dependent_phvs(root, varno)))
3474  {
3475  remove_result_refs(root, varno, j->larg);
3476  *dropped_outer_joins = bms_add_member(*dropped_outer_joins,
3477  j->rtindex);
3478  jtnode = j->larg;
3479  }
3480  break;
3481  case JOIN_SEMI:
3482 
3483  /*
3484  * We may simplify this case if the RHS is an RTE_RESULT; the
3485  * join qual becomes effectively just a filter qual for the
3486  * LHS, since we should either return the LHS row or not. The
3487  * filter clause must go into a new FromExpr if we can't push
3488  * it up to the parent.
3489  *
3490  * There is a fine point about PHVs that are supposed to be
3491  * evaluated at the RHS. Such PHVs could only appear in the
3492  * semijoin's qual, since the rest of the query cannot
3493  * reference any outputs of the semijoin's RHS. Therefore,
3494  * they can't actually go to null before being examined, and
3495  * it'd be OK to just remove the PHV wrapping. We don't have
3496  * infrastructure for that, but remove_result_refs() will
3497  * relabel them as to be evaluated at the LHS, which is fine.
3498  *
3499  * Also, we don't need to worry about removing traces of the
3500  * join's rtindex, since it hasn't got one.
3501  */
3502  if ((varno = get_result_relid(root, j->rarg)) != 0)
3503  {
3504  Assert(j->rtindex == 0);
3505  remove_result_refs(root, varno, j->larg);
3506  if (j->quals != NULL && parent_quals == NULL)
3507  jtnode = (Node *)
3508  makeFromExpr(list_make1(j->larg), j->quals);
3509  else
3510  {
3511  /* Merge any quals up to parent */
3512  if (j->quals != NULL)
3513  *parent_quals = (Node *)
3514  list_concat(castNode(List, j->quals),
3515  castNode(List, *parent_quals));
3516  jtnode = j->larg;
3517  }
3518  }
3519  break;
3520  case JOIN_FULL:
3521  case JOIN_ANTI:
3522  /* We have no special smarts for these cases */
3523  break;
3524  default:
3525  /* Note: JOIN_RIGHT should be gone at this point */
3526  elog(ERROR, "unrecognized join type: %d",
3527  (int) j->jointype);
3528  break;
3529  }
3530  }
3531  else
3532  elog(ERROR, "unrecognized node type: %d",
3533  (int) nodeTag(jtnode));
3534  return jtnode;
3535 }
static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
static int get_result_relid(PlannerInfo *root, Node *jtnode)
static bool find_dependent_phvs(PlannerInfo *root, int varno)
static bool find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno)

References Assert, bms_add_member(), bms_next_member(), castNode, elog, ERROR, find_dependent_phvs(), find_dependent_phvs_in_jointree(), foreach_delete_current, FromExpr::fromlist, get_result_relid(), IsA, j, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, lfirst, linitial, list_concat(), list_length(), list_make1, makeFromExpr(), nodeTag, FromExpr::quals, remove_result_refs(), and root.

Referenced by remove_useless_result_rtes().

◆ replace_empty_jointree()

void replace_empty_jointree ( Query parse)

Definition at line 284 of file prepjointree.c.

285 {
286  RangeTblEntry *rte;
287  Index rti;
288  RangeTblRef *rtr;
289 
290  /* Nothing to do if jointree is already nonempty */
291  if (parse->jointree->fromlist != NIL)
292  return;
293 
294  /* We mustn't change it in the top level of a setop tree, either */
295  if (parse->setOperations)
296  return;
297 
298  /* Create suitable RTE */
299  rte = makeNode(RangeTblEntry);
300  rte->rtekind = RTE_RESULT;
301  rte->eref = makeAlias("*RESULT*", NIL);
302 
303  /* Add it to rangetable */
304  parse->rtable = lappend(parse->rtable, rte);
305  rti = list_length(parse->rtable);
306 
307  /* And jam a reference into the jointree */
308  rtr = makeNode(RangeTblRef);
309  rtr->rtindex = rti;
310  parse->jointree->fromlist = list_make1(rtr);
311 }
unsigned int Index
Definition: c.h:614

References lappend(), list_length(), list_make1, makeAlias(), makeNode, NIL, parse(), RTE_RESULT, RangeTblEntry::rtekind, and RangeTblRef::rtindex.

Referenced by convert_EXISTS_sublink_to_join(), pull_up_simple_subquery(), and subquery_planner().

◆ replace_vars_in_jointree()

static void replace_vars_in_jointree ( Node jtnode,
pullup_replace_vars_context context 
)
static

Definition at line 2240 of file prepjointree.c.

2242 {
2243  if (jtnode == NULL)
2244  return;
2245  if (IsA(jtnode, RangeTblRef))
2246  {
2247  /*
2248  * If the RangeTblRef refers to a LATERAL subquery (that isn't the
2249  * same subquery we're pulling up), it might contain references to the
2250  * target subquery, which we must replace. We drive this from the
2251  * jointree scan, rather than a scan of the rtable, so that we can
2252  * avoid processing no-longer-referenced RTEs.
2253  */
2254  int varno = ((RangeTblRef *) jtnode)->rtindex;
2255 
2256  if (varno != context->varno) /* ignore target subquery itself */
2257  {
2258  RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
2259 
2260  Assert(rte != context->target_rte);
2261  if (rte->lateral)
2262  {
2263  switch (rte->rtekind)
2264  {
2265  case RTE_RELATION:
2266  /* shouldn't be marked LATERAL unless tablesample */
2267  Assert(rte->tablesample);
2268  rte->tablesample = (TableSampleClause *)
2270  context);
2271  break;
2272  case RTE_SUBQUERY:
2273  rte->subquery =
2275  context);
2276  break;
2277  case RTE_FUNCTION:
2278  rte->functions = (List *)
2280  context);
2281  break;
2282  case RTE_TABLEFUNC:
2283  rte->tablefunc = (TableFunc *)
2285  context);
2286  break;
2287  case RTE_VALUES:
2288  rte->values_lists = (List *)
2290  context);
2291  break;
2292  case RTE_JOIN:
2293  case RTE_CTE:
2294  case RTE_NAMEDTUPLESTORE:
2295  case RTE_RESULT:
2296  /* these shouldn't be marked LATERAL */
2297  Assert(false);
2298  break;
2299  }
2300  }
2301  }
2302  }
2303  else if (IsA(jtnode, FromExpr))
2304  {
2305  FromExpr *f = (FromExpr *) jtnode;
2306  ListCell *l;
2307 
2308  foreach(l, f->fromlist)
2311  }
2312  else if (IsA(jtnode, JoinExpr))
2313  {
2314  JoinExpr *j = (JoinExpr *) jtnode;
2315  bool save_wrap_non_vars = context->wrap_non_vars;
2316 
2319 
2320  /*
2321  * Use PHVs within the join quals of a full join. Otherwise, we
2322  * cannot identify which side of the join a pulled-up var-free
2323  * expression came from, which can lead to failure to make a plan at
2324  * all because none of the quals appear to be mergeable or hashable
2325  * conditions.
2326  */
2327  if (j->jointype == JOIN_FULL)
2328  context->wrap_non_vars = true;
2329 
2330  j->quals = pullup_replace_vars(j->quals, context);
2331 
2332  context->wrap_non_vars = save_wrap_non_vars;
2333  }
2334  else
2335  elog(ERROR, "unrecognized node type: %d",
2336  (int) nodeTag(jtnode));
2337 }
static Query * pullup_replace_vars_subquery(Query *query, pullup_replace_vars_context *context)
TableFunc * tablefunc
Definition: parsenodes.h:1194

References Assert, context, elog, ERROR, FromExpr::fromlist, RangeTblEntry::functions, IsA, j, JOIN_FULL, lfirst, nodeTag, pullup_replace_vars(), pullup_replace_vars_subquery(), FromExpr::quals, rt_fetch, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, RangeTblEntry::tablefunc, RangeTblEntry::tablesample, and RangeTblEntry::values_lists.

Referenced by perform_pullup_replace_vars().

◆ report_reduced_full_join()

static void report_reduced_full_join ( reduce_outer_joins_pass2_state state2,
int  rtindex,
Relids  relids 
)
static

Definition at line 3130 of file prepjointree.c.

3132 {
3134 
3135  statep = palloc(sizeof(reduce_outer_joins_partial_state));
3136  statep->full_join_rti = rtindex;
3137  statep->unreduced_side = relids;
3138  state2->partial_reduced = lappend(state2->partial_reduced, statep);
3139 }

References reduce_outer_joins_partial_state::full_join_rti, lappend(), palloc(), reduce_outer_joins_pass2_state::partial_reduced, and reduce_outer_joins_partial_state::unreduced_side.

Referenced by reduce_outer_joins_pass2().

◆ substitute_phv_relids()

static void substitute_phv_relids ( Node node,
int  varno,
Relids  subrelids 
)
static

Definition at line 3781 of file prepjointree.c.

3782 {
3784 
3785  context.varno = varno;
3786  context.sublevels_up = 0;
3787  context.subrelids = subrelids;
3788 
3789  /*
3790  * Must be prepared to start with a Query or a bare expression tree.
3791  */
3794  (void *) &context,
3795  0);
3796 }
#define query_or_expression_tree_walker(n, w, c, f)
Definition: nodeFuncs.h:169
static bool substitute_phv_relids_walker(Node *node, substitute_phv_relids_context *context)

References context, query_or_expression_tree_walker, and substitute_phv_relids_walker().

Referenced by fix_append_rel_relids(), pull_up_simple_subquery(), and remove_result_refs().

◆ substitute_phv_relids_walker()

static bool substitute_phv_relids_walker ( Node node,
substitute_phv_relids_context context 
)
static

Definition at line 3737 of file prepjointree.c.

3739 {
3740  if (node == NULL)
3741  return false;
3742  if (IsA(node, PlaceHolderVar))
3743  {
3744  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3745 
3746  if (phv->phlevelsup == context->sublevels_up &&
3747  bms_is_member(context->varno, phv->phrels))
3748  {
3749  phv->phrels = bms_union(phv->phrels,
3750  context->subrelids);
3751  phv->phrels = bms_del_member(phv->phrels,
3752  context->varno);
3753  /* Assert we haven't broken the PHV */
3754  Assert(!bms_is_empty(phv->phrels));
3755  }
3756  /* fall through to examine children */
3757  }
3758  if (IsA(node, Query))
3759  {
3760  /* Recurse into subselects */
3761  bool result;
3762 
3763  context->sublevels_up++;
3764  result = query_tree_walker((Query *) node,
3766  (void *) context, 0);
3767  context->sublevels_up--;
3768  return result;
3769  }
3770  /* Shouldn't need to handle planner auxiliary nodes here */
3771  Assert(!IsA(node, SpecialJoinInfo));
3772  Assert(!IsA(node, AppendRelInfo));
3773  Assert(!IsA(node, PlaceHolderInfo));
3774  Assert(!IsA(node, MinMaxAggInfo));
3775 
3777  (void *) context);
3778 }
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:868

References Assert, bms_del_member(), bms_is_empty, bms_is_member(), bms_union(), context, expression_tree_walker, IsA, PlaceHolderVar::phlevelsup, and query_tree_walker.

Referenced by substitute_phv_relids().

◆ transform_MERGE_to_join()

void transform_MERGE_to_join ( Query parse)

Definition at line 152 of file prepjointree.c.

153 {
154  RangeTblEntry *joinrte;
155  JoinExpr *joinexpr;
156  bool have_action[NUM_MERGE_MATCH_KINDS];
157  JoinType jointype;
158  int joinrti;
159  List *vars;
160  RangeTblRef *rtr;
161 
162  if (parse->commandType != CMD_MERGE)
163  return;
164 
165  /* XXX probably bogus */
166  vars = NIL;
167 
168  /*
169  * Work out what kind of join is required. If there any WHEN NOT MATCHED
170  * BY SOURCE/TARGET actions, an outer join is required so that we process
171  * all unmatched tuples from the source and/or target relations.
172  * Otherwise, we can use an inner join.
173  */
174  have_action[MERGE_WHEN_MATCHED] = false;
175  have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false;
176  have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false;
177 
178  foreach_node(MergeAction, action, parse->mergeActionList)
179  {
180  if (action->commandType != CMD_NOTHING)
181  have_action[action->matchKind] = true;
182  }
183 
184  if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
186  jointype = JOIN_FULL;
187  else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
188  jointype = JOIN_LEFT;
189  else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
190  jointype = JOIN_RIGHT;
191  else
192  jointype = JOIN_INNER;
193 
194  /* Manufacture a join RTE to use. */
195  joinrte = makeNode(RangeTblEntry);
196  joinrte->rtekind = RTE_JOIN;
197  joinrte->jointype = jointype;
198  joinrte->joinmergedcols = 0;
199  joinrte->joinaliasvars = vars;
200  joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */
201  joinrte->joinrightcols = NIL; /* ditto */
202  joinrte->join_using_alias = NULL;
203 
204  joinrte->alias = NULL;
205  joinrte->eref = makeAlias("*MERGE*", NIL);
206  joinrte->lateral = false;
207  joinrte->inh = false;
208  joinrte->inFromCl = true;
209 
210  /*
211  * Add completed RTE to pstate's range table list, so that we know its
212  * index.
213  */
214  parse->rtable = lappend(parse->rtable, joinrte);
215  joinrti = list_length(parse->rtable);
216 
217  /*
218  * Create a JOIN between the target and the source relation.
219  *
220  * Here the target is identified by parse->mergeTargetRelation. For a
221  * regular table, this will equal parse->resultRelation, but for a
222  * trigger-updatable view, it will be the expanded view subquery that we
223  * need to pull data from.
224  *
225  * The source relation is in parse->jointree->fromlist, but any quals in
226  * parse->jointree->quals are restrictions on the target relation (if the
227  * target relation is an auto-updatable view).
228  */
229  rtr = makeNode(RangeTblRef);
230  rtr->rtindex = parse->mergeTargetRelation;
231  joinexpr = makeNode(JoinExpr);
232  joinexpr->jointype = jointype;
233  joinexpr->isNatural = false;
234  joinexpr->larg = (Node *) makeFromExpr(list_make1(rtr), parse->jointree->quals);
235  joinexpr->rarg = linitial(parse->jointree->fromlist); /* source rel */
236  joinexpr->usingClause = NIL;
237  joinexpr->join_using_alias = NULL;
238  joinexpr->quals = parse->mergeJoinCondition;
239  joinexpr->alias = NULL;
240  joinexpr->rtindex = joinrti;
241 
242  /* Make the new join be the sole entry in the query's jointree */
243  parse->jointree->fromlist = list_make1(joinexpr);
244  parse->jointree->quals = NULL;
245 
246  /*
247  * If necessary, mark parse->targetlist entries that refer to the target
248  * as nullable by the join. Normally the targetlist will be empty for a
249  * MERGE, but if the target is a trigger-updatable view, it will contain a
250  * whole-row Var referring to the expanded view query.
251  */
252  if (parse->targetList != NIL &&
253  (jointype == JOIN_RIGHT || jointype == JOIN_FULL))
254  parse->targetList = (List *)
255  add_nulling_relids((Node *) parse->targetList,
256  bms_make_singleton(parse->mergeTargetRelation),
257  bms_make_singleton(joinrti));
258 
259  /*
260  * If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will
261  * use the join condition to distinguish between MATCHED and NOT MATCHED
262  * BY SOURCE cases. Otherwise, it's no longer needed, and we set it to
263  * NULL, saving cycles during planning and execution.
264  */
265  if (!have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
266  parse->mergeJoinCondition = NULL;
267 }
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_NOTHING
Definition: nodes.h:272
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
#define NUM_MERGE_MATCH_KINDS
Definition: primnodes.h:1997
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:1994
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:1993
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:1992
Node * add_nulling_relids(Node *node, const Bitmapset *target_relids, const Bitmapset *added_relids)
Node * quals
Definition: primnodes.h:2285
JoinType jointype
Definition: primnodes.h:2276
int rtindex
Definition: primnodes.h:2289
Node * larg
Definition: primnodes.h:2278
bool isNatural
Definition: primnodes.h:2277
Node * rarg
Definition: primnodes.h:2279

References generate_unaccent_rules::action, add_nulling_relids(), bms_make_singleton(), CMD_MERGE, CMD_NOTHING, foreach_node, RangeTblEntry::inh, JoinExpr::isNatural, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, RangeTblEntry::jointype, JoinExpr::jointype, lappend(), JoinExpr::larg, linitial, list_length(), list_make1, makeAlias(), makeFromExpr(), makeNode, MERGE_WHEN_MATCHED, MERGE_WHEN_NOT_MATCHED_BY_SOURCE, MERGE_WHEN_NOT_MATCHED_BY_TARGET, NIL, NUM_MERGE_MATCH_KINDS, parse(), JoinExpr::quals, JoinExpr::rarg, RTE_JOIN, RangeTblEntry::rtekind, RangeTblRef::rtindex, and JoinExpr::rtindex.

Referenced by subquery_planner().