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

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

◆ convert_EXISTS_sublink_to_join()

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

Definition at line 1383 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, 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().

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

◆ 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:253
List * initPlan
Definition: plannodes.h:140

◆ 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:682
Cost startup_cost
Definition: pathnodes.h:1159
List * init_plans
Definition: pathnodes.h:253
Cost per_call_cost
Definition: primnodes.h:754
Cost total_cost
Definition: pathnodes.h:1160
#define lfirst(lc)
Definition: pg_list.h:169
bool parallel_safe
Definition: pathnodes.h:1154
bool consider_parallel
Definition: pathnodes.h:674
Cost startup_cost
Definition: primnodes.h:753
List * pathlist
Definition: pathnodes.h:680
double Cost
Definition: nodes.h:662

◆ 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:188

◆ 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:187
PlannerInfo * parent_root
Definition: pathnodes.h:179
int wt_param_id
Definition: pathnodes.h:357
List * paramExecTypes
Definition: pathnodes.h:125
#define lfirst_int(lc)
Definition: pg_list.h:170
PlannerGlobal * glob
Definition: pathnodes.h:175
List * init_plans
Definition: pathnodes.h:253
#define lfirst(lc)
Definition: pg_list.h:169
List * setParam
Definition: primnodes.h:748
Bitmapset * outer_params
Definition: pathnodes.h:188
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:734
int plan_id
Definition: primnodes.h:730
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:725
List * subplans
Definition: pathnodes.h:107
PlannerGlobal * glob
Definition: pathnodes.h:175
#define list_make1_int(x1)
Definition: pg_list.h:217
List * lappend(List *list, void *datum)
Definition: list.c:321
List * init_plans
Definition: pathnodes.h:253
int32 firstColTypmod
Definition: primnodes.h:735
#define makeNode(_type_)
Definition: nodes.h:576
char * plan_name
Definition: primnodes.h:732
List * setParam
Definition: primnodes.h:748
int paramid
Definition: primnodes.h:263
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:3866
static int list_length(const List *l)
Definition: pg_list.h:149
List * subroots
Definition: pathnodes.h:109
Oid firstColCollation
Definition: primnodes.h:736

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

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

◆ 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