PostgreSQL Source Code  git master
subselect.h File Reference
#include "nodes/pathnodes.h"
#include "nodes/plannodes.h"
Include dependency graph for subselect.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void SS_process_ctes (PlannerInfo *root)
 
JoinExprconvert_ANY_sublink_to_join (PlannerInfo *root, SubLink *sublink, Relids available_rels)
 
JoinExprconvert_EXISTS_sublink_to_join (PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
 
NodeSS_replace_correlation_vars (PlannerInfo *root, Node *expr)
 
NodeSS_process_sublinks (PlannerInfo *root, Node *expr, bool isQual)
 
void SS_identify_outer_params (PlannerInfo *root)
 
void SS_charge_for_initplans (PlannerInfo *root, RelOptInfo *final_rel)
 
void SS_attach_initplans (PlannerInfo *root, Plan *plan)
 
void SS_finalize_plan (PlannerInfo *root, Plan *plan)
 
ParamSS_make_initplan_output_param (PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
 
void SS_make_initplan_from_plan (PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
 

Function Documentation

◆ convert_ANY_sublink_to_join()

JoinExpr* convert_ANY_sublink_to_join ( PlannerInfo root,
SubLink sublink,
Relids  available_rels 
)

Definition at line 1274 of file subselect.c.

References addRangeTableEntryForSubquery(), JoinExpr::alias, ANY_SUBLINK, Assert, bms_is_empty(), bms_is_subset(), contain_vars_of_level(), contain_volatile_functions(), convert_testexpr(), generate_subquery_vars(), JoinExpr::isNatural, JOIN_SEMI, JoinExpr::join_using_alias, JoinExpr::jointype, lappend(), JoinExpr::larg, list_length(), make_parsestate(), makeAlias(), makeNode, NIL, parse(), PlannerInfo::parse, pull_varnos(), JoinExpr::quals, JoinExpr::rarg, Query::rtable, JoinExpr::rtindex, SubLink::subLinkType, SubLink::subselect, SubLink::testexpr, and JoinExpr::usingClause.

Referenced by pull_up_sublinks_qual_recurse().

1276 {
1277  JoinExpr *result;
1278  Query *parse = root->parse;
1279  Query *subselect = (Query *) sublink->subselect;
1280  Relids upper_varnos;
1281  int rtindex;
1282  ParseNamespaceItem *nsitem;
1283  RangeTblEntry *rte;
1284  RangeTblRef *rtr;
1285  List *subquery_vars;
1286  Node *quals;
1287  ParseState *pstate;
1288 
1289  Assert(sublink->subLinkType == ANY_SUBLINK);
1290 
1291  /*
1292  * The sub-select must not refer to any Vars of the parent query. (Vars of
1293  * higher levels should be okay, though.)
1294  */
1295  if (contain_vars_of_level((Node *) subselect, 1))
1296  return NULL;
1297 
1298  /*
1299  * The test expression must contain some Vars of the parent query, else
1300  * it's not gonna be a join. (Note that it won't have Vars referring to
1301  * the subquery, rather Params.)
1302  */
1303  upper_varnos = pull_varnos(root, sublink->testexpr);
1304  if (bms_is_empty(upper_varnos))
1305  return NULL;
1306 
1307  /*
1308  * However, it can't refer to anything outside available_rels.
1309  */
1310  if (!bms_is_subset(upper_varnos, available_rels))
1311  return NULL;
1312 
1313  /*
1314  * The combining operators and left-hand expressions mustn't be volatile.
1315  */
1316  if (contain_volatile_functions(sublink->testexpr))
1317  return NULL;
1318 
1319  /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1320  pstate = make_parsestate(NULL);
1321 
1322  /*
1323  * Okay, pull up the sub-select into upper range table.
1324  *
1325  * We rely here on the assumption that the outer query has no references
1326  * to the inner (necessarily true, other than the Vars that we build
1327  * below). Therefore this is a lot easier than what pull_up_subqueries has
1328  * to go through.
1329  */
1330  nsitem = addRangeTableEntryForSubquery(pstate,
1331  subselect,
1332  makeAlias("ANY_subquery", NIL),
1333  false,
1334  false);
1335  rte = nsitem->p_rte;
1336  parse->rtable = lappend(parse->rtable, rte);
1337  rtindex = list_length(parse->rtable);
1338 
1339  /*
1340  * Form a RangeTblRef for the pulled-up sub-select.
1341  */
1342  rtr = makeNode(RangeTblRef);
1343  rtr->rtindex = rtindex;
1344 
1345  /*
1346  * Build a list of Vars representing the subselect outputs.
1347  */
1348  subquery_vars = generate_subquery_vars(root,
1349  subselect->targetList,
1350  rtindex);
1351 
1352  /*
1353  * Build the new join's qual expression, replacing Params with these Vars.
1354  */
1355  quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1356 
1357  /*
1358  * And finally, build the JoinExpr node.
1359  */
1360  result = makeNode(JoinExpr);
1361  result->jointype = JOIN_SEMI;
1362  result->isNatural = false;
1363  result->larg = NULL; /* caller must fill this in */
1364  result->rarg = (Node *) rtr;
1365  result->usingClause = NIL;
1366  result->join_using_alias = NULL;
1367  result->quals = quals;
1368  result->alias = NULL;
1369  result->rtindex = 0; /* we don't need an RTE for it */
1370 
1371  return result;
1372 }
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:654
#define NIL
Definition: pg_list.h:65
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
Query * parse
Definition: pathnodes.h:162
Definition: nodes.h:537
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:452
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
Node * larg
Definition: primnodes.h:1543
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
List * rtable
Definition: parsenodes.h:147
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Alias * join_using_alias
Definition: primnodes.h:1546
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:625
List * lappend(List *list, void *datum)
Definition: list.c:336
bool isNatural
Definition: primnodes.h:1542
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
List * usingClause
Definition: primnodes.h:1545
Node * quals
Definition: primnodes.h:1547
#define makeNode(_type_)
Definition: nodes.h:585
Node * rarg
Definition: primnodes.h:1544
Alias * alias
Definition: primnodes.h:1548
JoinType jointype
Definition: primnodes.h:1541
#define Assert(condition)
Definition: c.h:804
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:431
static int list_length(const List *l)
Definition: pg_list.h:149
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
int rtindex
Definition: primnodes.h:1549
Definition: pg_list.h:50
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ convert_EXISTS_sublink_to_join()

JoinExpr* convert_EXISTS_sublink_to_join ( PlannerInfo root,
SubLink sublink,
bool  under_not,
Relids  available_rels 
)

Definition at line 1382 of file subselect.c.

References JoinExpr::alias, Assert, bms_add_member(), bms_first_member(), bms_free(), bms_is_empty(), bms_is_subset(), contain_vars_of_level(), contain_volatile_functions(), copyObject, Query::cteList, EXISTS_SUBLINK, IncrementVarSublevelsUp(), JoinExpr::isNatural, JOIN_ANTI, JOIN_SEMI, JoinExpr::join_using_alias, Query::jointree, JoinExpr::jointype, JoinExpr::larg, linitial, list_concat(), list_length(), makeNode, NIL, OffsetVarNodes(), parse(), PlannerInfo::parse, pull_varnos(), JoinExpr::quals, FromExpr::quals, JoinExpr::rarg, replace_empty_jointree(), Query::rtable, JoinExpr::rtindex, simplify_EXISTS_query(), SubLink::subLinkType, SubLink::subselect, and JoinExpr::usingClause.

Referenced by pull_up_sublinks_qual_recurse().

1384 {
1385  JoinExpr *result;
1386  Query *parse = root->parse;
1387  Query *subselect = (Query *) sublink->subselect;
1388  Node *whereClause;
1389  int rtoffset;
1390  int varno;
1391  Relids clause_varnos;
1392  Relids upper_varnos;
1393 
1394  Assert(sublink->subLinkType == EXISTS_SUBLINK);
1395 
1396  /*
1397  * Can't flatten if it contains WITH. (We could arrange to pull up the
1398  * WITH into the parent query's cteList, but that risks changing the
1399  * semantics, since a WITH ought to be executed once per associated query
1400  * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1401  * this case, since it just produces a subquery RTE that doesn't have to
1402  * get flattened into the parent query.
1403  */
1404  if (subselect->cteList)
1405  return NULL;
1406 
1407  /*
1408  * Copy the subquery so we can modify it safely (see comments in
1409  * make_subplan).
1410  */
1411  subselect = copyObject(subselect);
1412 
1413  /*
1414  * See if the subquery can be simplified based on the knowledge that it's
1415  * being used in EXISTS(). If we aren't able to get rid of its
1416  * targetlist, we have to fail, because the pullup operation leaves us
1417  * with noplace to evaluate the targetlist.
1418  */
1419  if (!simplify_EXISTS_query(root, subselect))
1420  return NULL;
1421 
1422  /*
1423  * Separate out the WHERE clause. (We could theoretically also remove
1424  * top-level plain JOIN/ON clauses, but it's probably not worth the
1425  * trouble.)
1426  */
1427  whereClause = subselect->jointree->quals;
1428  subselect->jointree->quals = NULL;
1429 
1430  /*
1431  * The rest of the sub-select must not refer to any Vars of the parent
1432  * query. (Vars of higher levels should be okay, though.)
1433  */
1434  if (contain_vars_of_level((Node *) subselect, 1))
1435  return NULL;
1436 
1437  /*
1438  * On the other hand, the WHERE clause must contain some Vars of the
1439  * parent query, else it's not gonna be a join.
1440  */
1441  if (!contain_vars_of_level(whereClause, 1))
1442  return NULL;
1443 
1444  /*
1445  * We don't risk optimizing if the WHERE clause is volatile, either.
1446  */
1447  if (contain_volatile_functions(whereClause))
1448  return NULL;
1449 
1450  /*
1451  * The subquery must have a nonempty jointree, but we can make it so.
1452  */
1453  replace_empty_jointree(subselect);
1454 
1455  /*
1456  * Prepare to pull up the sub-select into top range table.
1457  *
1458  * We rely here on the assumption that the outer query has no references
1459  * to the inner (necessarily true). Therefore this is a lot easier than
1460  * what pull_up_subqueries has to go through.
1461  *
1462  * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1463  * do. The machinations of simplify_EXISTS_query ensured that there is
1464  * nothing interesting in the subquery except an rtable and jointree, and
1465  * even the jointree FromExpr no longer has quals. So we can just append
1466  * the rtable to our own and use the FromExpr in our jointree. But first,
1467  * adjust all level-zero varnos in the subquery to account for the rtable
1468  * merger.
1469  */
1470  rtoffset = list_length(parse->rtable);
1471  OffsetVarNodes((Node *) subselect, rtoffset, 0);
1472  OffsetVarNodes(whereClause, rtoffset, 0);
1473 
1474  /*
1475  * Upper-level vars in subquery will now be one level closer to their
1476  * parent than before; in particular, anything that had been level 1
1477  * becomes level zero.
1478  */
1479  IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1480  IncrementVarSublevelsUp(whereClause, -1, 1);
1481 
1482  /*
1483  * Now that the WHERE clause is adjusted to match the parent query
1484  * environment, we can easily identify all the level-zero rels it uses.
1485  * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1486  * not.
1487  */
1488  clause_varnos = pull_varnos(root, whereClause);
1489  upper_varnos = NULL;
1490  while ((varno = bms_first_member(clause_varnos)) >= 0)
1491  {
1492  if (varno <= rtoffset)
1493  upper_varnos = bms_add_member(upper_varnos, varno);
1494  }
1495  bms_free(clause_varnos);
1496  Assert(!bms_is_empty(upper_varnos));
1497 
1498  /*
1499  * Now that we've got the set of upper-level varnos, we can make the last
1500  * check: only available_rels can be referenced.
1501  */
1502  if (!bms_is_subset(upper_varnos, available_rels))
1503  return NULL;
1504 
1505  /* Now we can attach the modified subquery rtable to the parent */
1506  parse->rtable = list_concat(parse->rtable, subselect->rtable);
1507 
1508  /*
1509  * And finally, build the JoinExpr node.
1510  */
1511  result = makeNode(JoinExpr);
1512  result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1513  result->isNatural = false;
1514  result->larg = NULL; /* caller must fill this in */
1515  /* flatten out the FromExpr node if it's useless */
1516  if (list_length(subselect->jointree->fromlist) == 1)
1517  result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1518  else
1519  result->rarg = (Node *) subselect->jointree;
1520  result->usingClause = NIL;
1521  result->join_using_alias = NULL;
1522  result->quals = whereClause;
1523  result->alias = NULL;
1524  result->rtindex = 0; /* we don't need an RTE for it */
1525 
1526  return result;
1527 }
#define NIL
Definition: pg_list.h:65
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
int bms_first_member(Bitmapset *a)
Definition: bitmapset.c:996
Query * parse
Definition: pathnodes.h:162
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:425
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:776
FromExpr * jointree
Definition: parsenodes.h:148
Definition: nodes.h:537
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:452
static bool simplify_EXISTS_query(PlannerInfo *root, Query *query)
Definition: subselect.c:1546
void replace_empty_jointree(Query *parse)
Definition: prepjointree.c:150
Node * quals
Definition: primnodes.h:1565
Node * larg
Definition: primnodes.h:1543
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:147
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
Alias * join_using_alias
Definition: primnodes.h:1546
bool isNatural
Definition: primnodes.h:1542
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
List * usingClause
Definition: primnodes.h:1545
Node * quals
Definition: primnodes.h:1547
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define makeNode(_type_)
Definition: nodes.h:585
Node * rarg
Definition: primnodes.h:1544
Alias * alias
Definition: primnodes.h:1548
JoinType jointype
Definition: primnodes.h:1541
#define Assert(condition)
Definition: c.h:804
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:431
static int list_length(const List *l)
Definition: pg_list.h:149
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
List * cteList
Definition: parsenodes.h:145
#define copyObject(obj)
Definition: nodes.h:653
int rtindex
Definition: primnodes.h:1549
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:673

◆ SS_attach_initplans()

void SS_attach_initplans ( PlannerInfo root,
Plan plan 
)

Definition at line 2184 of file subselect.c.

References PlannerInfo::init_plans, and Plan::initPlan.

Referenced by create_plan().

2185 {
2186  plan->initPlan = root->init_plans;
2187 }
List * init_plans
Definition: pathnodes.h:242
List * initPlan
Definition: plannodes.h:145

◆ SS_charge_for_initplans()

void SS_charge_for_initplans ( PlannerInfo root,
RelOptInfo final_rel 
)

Definition at line 2127 of file subselect.c.

References RelOptInfo::consider_parallel, PlannerInfo::init_plans, lfirst, NIL, Path::parallel_safe, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, SubPlan::per_call_cost, SubPlan::startup_cost, Path::startup_cost, and Path::total_cost.

Referenced by build_minmax_path(), and subquery_planner().

2128 {
2129  Cost initplan_cost;
2130  ListCell *lc;
2131 
2132  /* Nothing to do if no initPlans */
2133  if (root->init_plans == NIL)
2134  return;
2135 
2136  /*
2137  * Compute the cost increment just once, since it will be the same for all
2138  * Paths. We assume each initPlan gets run once during top plan startup.
2139  * This is a conservative overestimate, since in fact an initPlan might be
2140  * executed later than plan startup, or even not at all.
2141  */
2142  initplan_cost = 0;
2143  foreach(lc, root->init_plans)
2144  {
2145  SubPlan *initsubplan = (SubPlan *) lfirst(lc);
2146 
2147  initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2148  }
2149 
2150  /*
2151  * Now adjust the costs and parallel_safe flags.
2152  */
2153  foreach(lc, final_rel->pathlist)
2154  {
2155  Path *path = (Path *) lfirst(lc);
2156 
2157  path->startup_cost += initplan_cost;
2158  path->total_cost += initplan_cost;
2159  path->parallel_safe = false;
2160  }
2161 
2162  /*
2163  * Forget about any partial paths and clear consider_parallel, too;
2164  * they're not usable if we attached an initPlan.
2165  */
2166  final_rel->partial_pathlist = NIL;
2167  final_rel->consider_parallel = false;
2168 
2169  /* We needn't do set_cheapest() here, caller will do it */
2170 }
#define NIL
Definition: pg_list.h:65
List * partial_pathlist
Definition: pathnodes.h:697
Cost startup_cost
Definition: pathnodes.h:1193
List * init_plans
Definition: pathnodes.h:242
Cost per_call_cost
Definition: primnodes.h:776
Cost total_cost
Definition: pathnodes.h:1194
#define lfirst(lc)
Definition: pg_list.h:169
bool parallel_safe
Definition: pathnodes.h:1188
bool consider_parallel
Definition: pathnodes.h:689
Cost startup_cost
Definition: primnodes.h:775
List * pathlist
Definition: pathnodes.h:695
double Cost
Definition: nodes.h:671

◆ SS_finalize_plan()

void SS_finalize_plan ( PlannerInfo root,
Plan plan 
)

Definition at line 2199 of file subselect.c.

References finalize_plan(), and PlannerInfo::outer_params.

Referenced by standard_planner().

2200 {
2201  /* No setup needed, just recurse through plan tree. */
2202  (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2203 }
static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
Definition: subselect.c:2237
Bitmapset * outer_params
Definition: pathnodes.h:177

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2065 of file subselect.c.

References bms_add_member(), PlannerInfo::glob, PlannerInfo::init_plans, lfirst, lfirst_int, NIL, PlannerInfo::outer_params, PlannerGlobal::paramExecTypes, PlannerParamItem::paramId, PlannerInfo::parent_root, PlannerInfo::plan_params, SubPlan::setParam, and PlannerInfo::wt_param_id.

Referenced by build_minmax_path(), and subquery_planner().

2066 {
2067  Bitmapset *outer_params;
2068  PlannerInfo *proot;
2069  ListCell *l;
2070 
2071  /*
2072  * If no parameters have been assigned anywhere in the tree, we certainly
2073  * don't need to do anything here.
2074  */
2075  if (root->glob->paramExecTypes == NIL)
2076  return;
2077 
2078  /*
2079  * Scan all query levels above this one to see which parameters are due to
2080  * be available from them, either because lower query levels have
2081  * requested them (via plan_params) or because they will be available from
2082  * initPlans of those levels.
2083  */
2084  outer_params = NULL;
2085  for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2086  {
2087  /* Include ordinary Var/PHV/Aggref params */
2088  foreach(l, proot->plan_params)
2089  {
2090  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
2091 
2092  outer_params = bms_add_member(outer_params, pitem->paramId);
2093  }
2094  /* Include any outputs of outer-level initPlans */
2095  foreach(l, proot->init_plans)
2096  {
2097  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2098  ListCell *l2;
2099 
2100  foreach(l2, initsubplan->setParam)
2101  {
2102  outer_params = bms_add_member(outer_params, lfirst_int(l2));
2103  }
2104  }
2105  /* Include worktable ID, if a recursive query is being planned */
2106  if (proot->wt_param_id >= 0)
2107  outer_params = bms_add_member(outer_params, proot->wt_param_id);
2108  }
2109  root->outer_params = outer_params;
2110 }
#define NIL
Definition: pg_list.h:65
List * plan_params
Definition: pathnodes.h:176
PlannerInfo * parent_root
Definition: pathnodes.h:168
int wt_param_id
Definition: pathnodes.h:364
List * paramExecTypes
Definition: pathnodes.h:114
#define lfirst_int(lc)
Definition: pg_list.h:170
PlannerGlobal * glob
Definition: pathnodes.h:164
List * init_plans
Definition: pathnodes.h:242
#define lfirst(lc)
Definition: pg_list.h:169
List * setParam
Definition: primnodes.h:770
Bitmapset * outer_params
Definition: pathnodes.h:177
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736

◆ SS_make_initplan_from_plan()

void SS_make_initplan_from_plan ( PlannerInfo root,
PlannerInfo subroot,
Plan plan,
Param prm 
)

Definition at line 2956 of file subselect.c.

References cost_subplan(), EXPR_SUBLINK, SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), PlannerInfo::glob, PlannerInfo::init_plans, lappend(), list_length(), list_make1_int, makeNode, Param::paramid, SubPlan::plan_id, SubPlan::plan_name, psprintf(), SubPlan::setParam, SubPlan::subLinkType, PlannerGlobal::subplans, and PlannerGlobal::subroots.

Referenced by create_minmaxagg_plan().

2959 {
2960  SubPlan *node;
2961 
2962  /*
2963  * Add the subplan and its PlannerInfo to the global lists.
2964  */
2965  root->glob->subplans = lappend(root->glob->subplans, plan);
2966  root->glob->subroots = lappend(root->glob->subroots, subroot);
2967 
2968  /*
2969  * Create a SubPlan node and add it to the outer list of InitPlans. Note
2970  * it has to appear after any other InitPlans it might depend on (see
2971  * comments in ExecReScan).
2972  */
2973  node = makeNode(SubPlan);
2974  node->subLinkType = EXPR_SUBLINK;
2975  node->plan_id = list_length(root->glob->subplans);
2976  node->plan_name = psprintf("InitPlan %d (returns $%d)",
2977  node->plan_id, prm->paramid);
2978  get_first_col_type(plan, &node->firstColType, &node->firstColTypmod,
2979  &node->firstColCollation);
2980  node->setParam = list_make1_int(prm->paramid);
2981 
2982  root->init_plans = lappend(root->init_plans, node);
2983 
2984  /*
2985  * The node can't have any inputs (since it's an initplan), so the
2986  * parParam and args lists remain empty.
2987  */
2988 
2989  /* Set costs of SubPlan using info from the plan tree */
2990  cost_subplan(subroot, node, plan);
2991 }
Oid firstColType
Definition: primnodes.h:756
int plan_id
Definition: primnodes.h:752
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:119
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
SubLinkType subLinkType
Definition: primnodes.h:747
List * subplans
Definition: pathnodes.h:96
PlannerGlobal * glob
Definition: pathnodes.h:164
#define list_make1_int(x1)
Definition: pg_list.h:221
List * lappend(List *list, void *datum)
Definition: list.c:336
List * init_plans
Definition: pathnodes.h:242
int32 firstColTypmod
Definition: primnodes.h:757
#define makeNode(_type_)
Definition: nodes.h:585
char * plan_name
Definition: primnodes.h:754
List * setParam
Definition: primnodes.h:770
int paramid
Definition: primnodes.h:268
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4103
static int list_length(const List *l)
Definition: pg_list.h:149
List * subroots
Definition: pathnodes.h:98
Oid firstColCollation
Definition: primnodes.h:758

◆ SS_make_initplan_output_param()

Param* SS_make_initplan_output_param ( PlannerInfo root,
Oid  resulttype,
int32  resulttypmod,
Oid  resultcollation 
)

Definition at line 2940 of file subselect.c.

References generate_new_exec_param().

Referenced by preprocess_minmax_aggregates().

2943 {
2944  return generate_new_exec_param(root, resulttype,
2945  resulttypmod, resultcollation);
2946 }
Param * generate_new_exec_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation)
Definition: paramassign.c:557

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 892 of file subselect.c.

References SubPlan::args, Assert, assign_special_exec_param(), RelOptInfo::cheapest_total_path, CMD_SELECT, contain_dml(), contain_outer_selfref(), contain_volatile_functions(), copyObject, cost_subplan(), create_plan(), PlannerInfo::cte_plan_ids, CTE_SUBLINK, Query::cteList, CommonTableExpr::ctematerialized, CTEMaterializeDefault, CTEMaterializeNever, CommonTableExpr::ctename, CommonTableExpr::ctequery, CommonTableExpr::cterecursive, CommonTableExpr::cterefcount, elog, ERROR, fetch_upper_rel(), SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), PlannerInfo::glob, PlannerInfo::init_plans, inline_cte(), lappend(), lappend_int(), lfirst, list_length(), list_make1_int, makeNode, NIL, SubPlan::parallel_safe, SubPlan::paramIds, SubPlan::parParam, PlannerInfo::parse, SubPlan::plan_id, SubPlan::plan_name, PlannerInfo::plan_params, psprintf(), SubPlan::setParam, splan, SubPlan::subLinkType, PlannerGlobal::subplans, subquery_planner(), PlannerGlobal::subroots, SubPlan::testexpr, SubPlan::unknownEqFalse, UPPERREL_FINAL, and SubPlan::useHashTable.

Referenced by subquery_planner().

893 {
894  ListCell *lc;
895 
896  Assert(root->cte_plan_ids == NIL);
897 
898  foreach(lc, root->parse->cteList)
899  {
900  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
901  CmdType cmdType = ((Query *) cte->ctequery)->commandType;
902  Query *subquery;
903  PlannerInfo *subroot;
904  RelOptInfo *final_rel;
905  Path *best_path;
906  Plan *plan;
907  SubPlan *splan;
908  int paramid;
909 
910  /*
911  * Ignore SELECT CTEs that are not actually referenced anywhere.
912  */
913  if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
914  {
915  /* Make a dummy entry in cte_plan_ids */
916  root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
917  continue;
918  }
919 
920  /*
921  * Consider inlining the CTE (creating RTE_SUBQUERY RTE(s)) instead of
922  * implementing it as a separately-planned CTE.
923  *
924  * We cannot inline if any of these conditions hold:
925  *
926  * 1. The user said not to (the CTEMaterializeAlways option).
927  *
928  * 2. The CTE is recursive.
929  *
930  * 3. The CTE has side-effects; this includes either not being a plain
931  * SELECT, or containing volatile functions. Inlining might change
932  * the side-effects, which would be bad.
933  *
934  * 4. The CTE is multiply-referenced and contains a self-reference to
935  * a recursive CTE outside itself. Inlining would result in multiple
936  * recursive self-references, which we don't support.
937  *
938  * Otherwise, we have an option whether to inline or not. That should
939  * always be a win if there's just a single reference, but if the CTE
940  * is multiply-referenced then it's unclear: inlining adds duplicate
941  * computations, but the ability to absorb restrictions from the outer
942  * query level could outweigh that. We do not have nearly enough
943  * information at this point to tell whether that's true, so we let
944  * the user express a preference. Our default behavior is to inline
945  * only singly-referenced CTEs, but a CTE marked CTEMaterializeNever
946  * will be inlined even if multiply referenced.
947  *
948  * Note: we check for volatile functions last, because that's more
949  * expensive than the other tests needed.
950  */
951  if ((cte->ctematerialized == CTEMaterializeNever ||
953  cte->cterefcount == 1)) &&
954  !cte->cterecursive &&
955  cmdType == CMD_SELECT &&
956  !contain_dml(cte->ctequery) &&
957  (cte->cterefcount <= 1 ||
960  {
961  inline_cte(root, cte);
962  /* Make a dummy entry in cte_plan_ids */
963  root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
964  continue;
965  }
966 
967  /*
968  * Copy the source Query node. Probably not necessary, but let's keep
969  * this similar to make_subplan.
970  */
971  subquery = (Query *) copyObject(cte->ctequery);
972 
973  /* plan_params should not be in use in current query level */
974  Assert(root->plan_params == NIL);
975 
976  /*
977  * Generate Paths for the CTE query. Always plan for full retrieval
978  * --- we don't have enough info to predict otherwise.
979  */
980  subroot = subquery_planner(root->glob, subquery,
981  root,
982  cte->cterecursive, 0.0);
983 
984  /*
985  * Since the current query level doesn't yet contain any RTEs, it
986  * should not be possible for the CTE to have requested parameters of
987  * this level.
988  */
989  if (root->plan_params)
990  elog(ERROR, "unexpected outer reference in CTE query");
991 
992  /*
993  * Select best Path and turn it into a Plan. At least for now, there
994  * seems no reason to postpone doing that.
995  */
996  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
997  best_path = final_rel->cheapest_total_path;
998 
999  plan = create_plan(subroot, best_path);
1000 
1001  /*
1002  * Make a SubPlan node for it. This is just enough unlike
1003  * build_subplan that we can't share code.
1004  *
1005  * Note plan_id, plan_name, and cost fields are set further down.
1006  */
1007  splan = makeNode(SubPlan);
1008  splan->subLinkType = CTE_SUBLINK;
1009  splan->testexpr = NULL;
1010  splan->paramIds = NIL;
1011  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
1012  &splan->firstColCollation);
1013  splan->useHashTable = false;
1014  splan->unknownEqFalse = false;
1015 
1016  /*
1017  * CTE scans are not considered for parallelism (cf
1018  * set_rel_consider_parallel), and even if they were, initPlans aren't
1019  * parallel-safe.
1020  */
1021  splan->parallel_safe = false;
1022  splan->setParam = NIL;
1023  splan->parParam = NIL;
1024  splan->args = NIL;
1025 
1026  /*
1027  * The node can't have any inputs (since it's an initplan), so the
1028  * parParam and args lists remain empty. (It could contain references
1029  * to earlier CTEs' output param IDs, but CTE outputs are not
1030  * propagated via the args list.)
1031  */
1032 
1033  /*
1034  * Assign a param ID to represent the CTE's output. No ordinary
1035  * "evaluation" of this param slot ever happens, but we use the param
1036  * ID for setParam/chgParam signaling just as if the CTE plan were
1037  * returning a simple scalar output. (Also, the executor abuses the
1038  * ParamExecData slot for this param ID for communication among
1039  * multiple CteScan nodes that might be scanning this CTE.)
1040  */
1041  paramid = assign_special_exec_param(root);
1042  splan->setParam = list_make1_int(paramid);
1043 
1044  /*
1045  * Add the subplan and its PlannerInfo to the global lists.
1046  */
1047  root->glob->subplans = lappend(root->glob->subplans, plan);
1048  root->glob->subroots = lappend(root->glob->subroots, subroot);
1049  splan->plan_id = list_length(root->glob->subplans);
1050 
1051  root->init_plans = lappend(root->init_plans, splan);
1052 
1053  root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
1054 
1055  /* Label the subplan for EXPLAIN purposes */
1056  splan->plan_name = psprintf("CTE %s", cte->ctename);
1057 
1058  /* Lastly, fill in the cost estimates for use later */
1059  cost_subplan(root, splan, plan);
1060  }
1061 }
#define NIL
Definition: pg_list.h:65
Oid firstColType
Definition: primnodes.h:756
Query * parse
Definition: pathnodes.h:162
int plan_id
Definition: primnodes.h:752
List * plan_params
Definition: pathnodes.h:176
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:119
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
SubLinkType subLinkType
Definition: primnodes.h:747
List * paramIds
Definition: primnodes.h:750
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:452
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:584
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:332
#define ERROR
Definition: elog.h:46
static void inline_cte(PlannerInfo *root, CommonTableExpr *cte)
Definition: subselect.c:1151
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1210
struct Path * cheapest_total_path
Definition: pathnodes.h:699
List * subplans
Definition: pathnodes.h:96
PlannerGlobal * glob
Definition: pathnodes.h:164
static SPIPlanPtr splan
Definition: regress.c:263
#define list_make1_int(x1)
Definition: pg_list.h:221
List * lappend_int(List *list, int datum)
Definition: list.c:354
List * lappend(List *list, void *datum)
Definition: list.c:336
List * cte_plan_ids
Definition: pathnodes.h:244
Node * testexpr
Definition: primnodes.h:749
List * init_plans
Definition: pathnodes.h:242
static bool contain_dml(Node *node)
Definition: subselect.c:1069
static bool contain_outer_selfref(Node *node)
Definition: subselect.c:1096
int32 firstColTypmod
Definition: primnodes.h:757
#define makeNode(_type_)
Definition: nodes.h:585
char * plan_name
Definition: primnodes.h:754
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
CTEMaterialize ctematerialized
Definition: parsenodes.h:1514
List * setParam
Definition: primnodes.h:770
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4103
bool unknownEqFalse
Definition: primnodes.h:763
static int list_length(const List *l)
Definition: pg_list.h:149
List * subroots
Definition: pathnodes.h:98
List * parParam
Definition: primnodes.h:772
bool parallel_safe
Definition: primnodes.h:766
List * cteList
Definition: parsenodes.h:145
#define elog(elevel,...)
Definition: elog.h:232
bool useHashTable
Definition: primnodes.h:761
Oid firstColCollation
Definition: primnodes.h:758
#define copyObject(obj)
Definition: nodes.h:653
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:596
CmdType
Definition: nodes.h:681
List * args
Definition: primnodes.h:773

◆ SS_process_sublinks()

Node* SS_process_sublinks ( PlannerInfo root,
Node expr,
bool  isQual 
)

Definition at line 1918 of file subselect.c.

References process_sublinks_context::isTopQual, process_sublinks_mutator(), convert_testexpr_context::root, and process_sublinks_context::root.

Referenced by build_subplan(), and preprocess_expression().

1919 {
1920  process_sublinks_context context;
1921 
1922  context.root = root;
1923  context.isTopQual = isQual;
1924  return process_sublinks_mutator(expr, &context);
1925 }
static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context)
Definition: subselect.c:1928

◆ SS_replace_correlation_vars()

Node* SS_replace_correlation_vars ( PlannerInfo root,
Node expr 
)

Definition at line 1873 of file subselect.c.

References replace_correlation_vars_mutator().

Referenced by preprocess_expression().

1874 {
1875  /* No setup needed for tree walk, so away we go */
1876  return replace_correlation_vars_mutator(expr, root);
1877 }
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1880