PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
subselect.c File Reference
Include dependency graph for subselect.c:

Go to the source code of this file.

Data Structures

struct  convert_testexpr_context
 
struct  process_sublinks_context
 
struct  finalize_primnode_context
 
struct  inline_cte_walker_context
 

Typedefs

typedef struct convert_testexpr_context convert_testexpr_context
 
typedef struct process_sublinks_context process_sublinks_context
 
typedef struct finalize_primnode_context finalize_primnode_context
 
typedef struct inline_cte_walker_context inline_cte_walker_context
 

Functions

static Nodebuild_subplan (PlannerInfo *root, Plan *plan, Path *path, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, List *testexpr_paramids, bool unknownEqFalse)
 
static Listgenerate_subquery_params (PlannerInfo *root, List *tlist, List **paramIds)
 
static Listgenerate_subquery_vars (PlannerInfo *root, List *tlist, Index varno)
 
static Nodeconvert_testexpr (PlannerInfo *root, Node *testexpr, List *subst_nodes)
 
static Nodeconvert_testexpr_mutator (Node *node, convert_testexpr_context *context)
 
static bool subplan_is_hashable (Plan *plan)
 
static bool subpath_is_hashable (Path *path)
 
static bool testexpr_is_hashable (Node *testexpr, List *param_ids)
 
static bool test_opexpr_is_hashable (OpExpr *testexpr, List *param_ids)
 
static bool hash_ok_operator (OpExpr *expr)
 
static bool contain_dml (Node *node)
 
static bool contain_dml_walker (Node *node, void *context)
 
static bool contain_outer_selfref (Node *node)
 
static bool contain_outer_selfref_walker (Node *node, Index *depth)
 
static void inline_cte (PlannerInfo *root, CommonTableExpr *cte)
 
static bool inline_cte_walker (Node *node, inline_cte_walker_context *context)
 
static bool simplify_EXISTS_query (PlannerInfo *root, Query *query)
 
static Queryconvert_EXISTS_to_ANY (PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds)
 
static Nodereplace_correlation_vars_mutator (Node *node, PlannerInfo *root)
 
static Nodeprocess_sublinks_mutator (Node *node, process_sublinks_context *context)
 
static Bitmapsetfinalize_plan (PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
 
static bool finalize_primnode (Node *node, finalize_primnode_context *context)
 
static bool finalize_agg_primnode (Node *node, finalize_primnode_context *context)
 
static void get_first_col_type (Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
 
static Nodemake_subplan (PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual)
 
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_compute_initplan_cost (List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
 
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)
 

Typedef Documentation

◆ convert_testexpr_context

◆ finalize_primnode_context

◆ inline_cte_walker_context

◆ process_sublinks_context

Function Documentation

◆ build_subplan()

static Node * build_subplan ( PlannerInfo root,
Plan plan,
Path path,
PlannerInfo subroot,
List plan_params,
SubLinkType  subLinkType,
int  subLinkId,
Node testexpr,
List testexpr_paramids,
bool  unknownEqFalse 
)
static

Definition at line 319 of file subselect.c.

324 {
325  Node *result;
326  SubPlan *splan;
327  bool isInitPlan;
328  ListCell *lc;
329 
330  /*
331  * Initialize the SubPlan node. Note plan_id, plan_name, and cost fields
332  * are set further down.
333  */
335  splan->subLinkType = subLinkType;
336  splan->testexpr = NULL;
337  splan->paramIds = NIL;
338  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
339  &splan->firstColCollation);
340  splan->useHashTable = false;
341  splan->unknownEqFalse = unknownEqFalse;
342  splan->parallel_safe = plan->parallel_safe;
343  splan->setParam = NIL;
344  splan->parParam = NIL;
345  splan->args = NIL;
346 
347  /*
348  * Make parParam and args lists of param IDs and expressions that current
349  * query level will pass to this child plan.
350  */
351  foreach(lc, plan_params)
352  {
353  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
354  Node *arg = pitem->item;
355 
356  /*
357  * The Var, PlaceHolderVar, Aggref or GroupingFunc has already been
358  * adjusted to have the correct varlevelsup, phlevelsup, or
359  * agglevelsup.
360  *
361  * If it's a PlaceHolderVar, Aggref or GroupingFunc, its arguments
362  * might contain SubLinks, which have not yet been processed (see the
363  * comments for SS_replace_correlation_vars). Do that now.
364  */
365  if (IsA(arg, PlaceHolderVar) ||
366  IsA(arg, Aggref) ||
367  IsA(arg, GroupingFunc))
368  arg = SS_process_sublinks(root, arg, false);
369 
370  splan->parParam = lappend_int(splan->parParam, pitem->paramId);
371  splan->args = lappend(splan->args, arg);
372  }
373 
374  /*
375  * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
376  * ROWCOMPARE, or MULTIEXPR types can be used as initPlans. For EXISTS,
377  * EXPR, or ARRAY, we return a Param referring to the result of evaluating
378  * the initPlan. For ROWCOMPARE, we must modify the testexpr tree to
379  * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
380  * by the parser, and then return that tree. For MULTIEXPR, we return a
381  * null constant: the resjunk targetlist item containing the SubLink does
382  * not need to return anything useful, since the referencing Params are
383  * elsewhere.
384  */
385  if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
386  {
387  Param *prm;
388 
389  Assert(testexpr == NULL);
390  prm = generate_new_exec_param(root, BOOLOID, -1, InvalidOid);
391  splan->setParam = list_make1_int(prm->paramid);
392  isInitPlan = true;
393  result = (Node *) prm;
394  }
395  else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
396  {
397  TargetEntry *te = linitial(plan->targetlist);
398  Param *prm;
399 
400  Assert(!te->resjunk);
401  Assert(testexpr == NULL);
403  exprType((Node *) te->expr),
404  exprTypmod((Node *) te->expr),
405  exprCollation((Node *) te->expr));
406  splan->setParam = list_make1_int(prm->paramid);
407  isInitPlan = true;
408  result = (Node *) prm;
409  }
410  else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
411  {
412  TargetEntry *te = linitial(plan->targetlist);
413  Oid arraytype;
414  Param *prm;
415 
416  Assert(!te->resjunk);
417  Assert(testexpr == NULL);
418  arraytype = get_promoted_array_type(exprType((Node *) te->expr));
419  if (!OidIsValid(arraytype))
420  elog(ERROR, "could not find array type for datatype %s",
421  format_type_be(exprType((Node *) te->expr)));
423  arraytype,
424  exprTypmod((Node *) te->expr),
425  exprCollation((Node *) te->expr));
426  splan->setParam = list_make1_int(prm->paramid);
427  isInitPlan = true;
428  result = (Node *) prm;
429  }
430  else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
431  {
432  /* Adjust the Params */
433  List *params;
434 
435  Assert(testexpr != NULL);
437  plan->targetlist,
438  &splan->paramIds);
439  result = convert_testexpr(root,
440  testexpr,
441  params);
442  splan->setParam = list_copy(splan->paramIds);
443  isInitPlan = true;
444 
445  /*
446  * The executable expression is returned to become part of the outer
447  * plan's expression tree; it is not kept in the initplan node.
448  */
449  }
450  else if (subLinkType == MULTIEXPR_SUBLINK)
451  {
452  /*
453  * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
454  * for each output column.
455  */
456  List *params;
457 
458  Assert(testexpr == NULL);
460  plan->targetlist,
461  &splan->setParam);
462 
463  /*
464  * Save the list of replacement Params in the n'th cell of
465  * root->multiexpr_params; setrefs.c will use it to replace
466  * PARAM_MULTIEXPR Params.
467  */
468  while (list_length(root->multiexpr_params) < subLinkId)
469  root->multiexpr_params = lappend(root->multiexpr_params, NIL);
470  lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
471  Assert(lfirst(lc) == NIL);
472  lfirst(lc) = params;
473 
474  /* It can be an initplan if there are no parParams. */
475  if (splan->parParam == NIL)
476  {
477  isInitPlan = true;
478  result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
479  }
480  else
481  {
482  isInitPlan = false;
483  result = (Node *) splan;
484  }
485  }
486  else
487  {
488  /*
489  * Adjust the Params in the testexpr, unless caller already took care
490  * of it (as indicated by passing a list of Param IDs).
491  */
492  if (testexpr && testexpr_paramids == NIL)
493  {
494  List *params;
495 
497  plan->targetlist,
498  &splan->paramIds);
499  splan->testexpr = convert_testexpr(root,
500  testexpr,
501  params);
502  }
503  else
504  {
505  splan->testexpr = testexpr;
506  splan->paramIds = testexpr_paramids;
507  }
508 
509  /*
510  * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
511  * initPlans, even when they are uncorrelated or undirect correlated,
512  * because we need to scan the output of the subplan for each outer
513  * tuple. But if it's a not-direct-correlated IN (= ANY) test, we
514  * might be able to use a hashtable to avoid comparing all the tuples.
515  */
516  if (subLinkType == ANY_SUBLINK &&
517  splan->parParam == NIL &&
519  testexpr_is_hashable(splan->testexpr, splan->paramIds))
520  splan->useHashTable = true;
521 
522  /*
523  * Otherwise, we have the option to tack a Material node onto the top
524  * of the subplan, to reduce the cost of reading it repeatedly. This
525  * is pointless for a direct-correlated subplan, since we'd have to
526  * recompute its results each time anyway. For uncorrelated/undirect
527  * correlated subplans, we add Material unless the subplan's top plan
528  * node would materialize its output anyway. Also, if enable_material
529  * is false, then the user does not want us to materialize anything
530  * unnecessarily, so we don't.
531  */
532  else if (splan->parParam == NIL && enable_material &&
535 
536  result = (Node *) splan;
537  isInitPlan = false;
538  }
539 
540  /*
541  * Add the subplan, its path, and its PlannerInfo to the global lists.
542  */
543  root->glob->subplans = lappend(root->glob->subplans, plan);
544  root->glob->subpaths = lappend(root->glob->subpaths, path);
545  root->glob->subroots = lappend(root->glob->subroots, subroot);
546  splan->plan_id = list_length(root->glob->subplans);
547 
548  if (isInitPlan)
549  root->init_plans = lappend(root->init_plans, splan);
550 
551  /*
552  * A parameterless subplan (not initplan) should be prepared to handle
553  * REWIND efficiently. If it has direct parameters then there's no point
554  * since it'll be reset on each scan anyway; and if it's an initplan then
555  * there's no point since it won't get re-run without parameter changes
556  * anyway. The input of a hashed subplan doesn't need REWIND either.
557  */
558  if (splan->parParam == NIL && !isInitPlan && !splan->useHashTable)
559  root->glob->rewindPlanIDs = bms_add_member(root->glob->rewindPlanIDs,
560  splan->plan_id);
561 
562  /* Label the subplan for EXPLAIN purposes */
563  splan->plan_name = psprintf("%s %d",
564  isInitPlan ? "InitPlan" : "SubPlan",
565  splan->plan_id);
566 
567  /* Lastly, fill in the cost estimates for use later */
569 
570  return result;
571 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define Assert(condition)
Definition: c.h:837
#define OidIsValid(objectId)
Definition: c.h:754
bool enable_material
Definition: costsize.c:154
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4524
Plan * materialize_finished_plan(Plan *subplan)
Definition: createplan.c:6600
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:635
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_int(List *list, int datum)
Definition: list.c:357
List * list_copy(const List *oldlist)
Definition: list.c:1573
Oid get_promoted_array_type(Oid typid)
Definition: lsyscache.c:2811
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:339
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define makeNode(_type_)
Definition: nodes.h:155
Param * generate_new_exec_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation)
Definition: paramassign.c:637
void * arg
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:277
#define linitial(l)
Definition: pg_list.h:178
#define list_make1_int(x1)
Definition: pg_list.h:227
#define plan(x)
Definition: pg_regress.c:161
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ ARRAY_SUBLINK
Definition: primnodes.h:1003
@ ANY_SUBLINK
Definition: primnodes.h:999
@ MULTIEXPR_SUBLINK
Definition: primnodes.h:1002
@ EXPR_SUBLINK
Definition: primnodes.h:1001
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:1000
@ EXISTS_SUBLINK
Definition: primnodes.h:997
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
tree ctl root
Definition: radixtree.h:1886
static SPIPlanPtr splan
Definition: regress.c:267
Definition: pg_list.h:54
Definition: nodes.h:129
int paramid
Definition: primnodes.h:377
Expr * expr
Definition: primnodes.h:2190
static bool testexpr_is_hashable(Node *testexpr, List *param_ids)
Definition: subselect.c:759
static List * generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
Definition: subselect.c:580
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:642
static bool subplan_is_hashable(Plan *plan)
Definition: subselect.c:710
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:118
Node * SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual)
Definition: subselect.c:1938

References ANY_SUBLINK, arg, ARRAY_SUBLINK, Assert, bms_add_member(), convert_testexpr(), cost_subplan(), elog, enable_material, ERROR, ExecMaterializesOutput(), EXISTS_SUBLINK, TargetEntry::expr, EXPR_SUBLINK, exprCollation(), exprType(), exprTypmod(), format_type_be(), generate_new_exec_param(), generate_subquery_params(), get_first_col_type(), get_promoted_array_type(), InvalidOid, IsA, PlannerParamItem::item, lappend(), lappend_int(), lfirst, linitial, list_copy(), list_length(), list_make1_int, list_nth_cell(), makeNode, makeNullConst(), materialize_finished_plan(), MULTIEXPR_SUBLINK, NIL, nodeTag, OidIsValid, PlannerParamItem::paramId, Param::paramid, plan, psprintf(), root, ROWCOMPARE_SUBLINK, splan, SS_process_sublinks(), subplan_is_hashable(), and testexpr_is_hashable().

Referenced by make_subplan().

◆ contain_dml()

static bool contain_dml ( Node node)
static

Definition at line 1054 of file subselect.c.

1055 {
1056  return contain_dml_walker(node, NULL);
1057 }
static bool contain_dml_walker(Node *node, void *context)
Definition: subselect.c:1060

References contain_dml_walker().

Referenced by SS_process_ctes().

◆ contain_dml_walker()

static bool contain_dml_walker ( Node node,
void *  context 
)
static

Definition at line 1060 of file subselect.c.

1061 {
1062  if (node == NULL)
1063  return false;
1064  if (IsA(node, Query))
1065  {
1066  Query *query = (Query *) node;
1067 
1068  if (query->commandType != CMD_SELECT ||
1069  query->rowMarks != NIL)
1070  return true;
1071 
1072  return query_tree_walker(query, contain_dml_walker, context, 0);
1073  }
1075 }
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
@ CMD_SELECT
Definition: nodes.h:265
tree context
Definition: radixtree.h:1835
List * rowMarks
Definition: parsenodes.h:219
CmdType commandType
Definition: parsenodes.h:121

References CMD_SELECT, Query::commandType, context, expression_tree_walker, IsA, NIL, query_tree_walker, and Query::rowMarks.

Referenced by contain_dml().

◆ contain_outer_selfref()

static bool contain_outer_selfref ( Node node)
static

Definition at line 1081 of file subselect.c.

1082 {
1083  Index depth = 0;
1084 
1085  /*
1086  * We should be starting with a Query, so that depth will be 1 while
1087  * examining its immediate contents.
1088  */
1089  Assert(IsA(node, Query));
1090 
1091  return contain_outer_selfref_walker(node, &depth);
1092 }
unsigned int Index
Definition: c.h:593
static bool contain_outer_selfref_walker(Node *node, Index *depth)
Definition: subselect.c:1095

References Assert, contain_outer_selfref_walker(), and IsA.

Referenced by SS_process_ctes().

◆ contain_outer_selfref_walker()

static bool contain_outer_selfref_walker ( Node node,
Index depth 
)
static

Definition at line 1095 of file subselect.c.

1096 {
1097  if (node == NULL)
1098  return false;
1099  if (IsA(node, RangeTblEntry))
1100  {
1101  RangeTblEntry *rte = (RangeTblEntry *) node;
1102 
1103  /*
1104  * Check for a self-reference to a CTE that's above the Query that our
1105  * search started at.
1106  */
1107  if (rte->rtekind == RTE_CTE &&
1108  rte->self_reference &&
1109  rte->ctelevelsup >= *depth)
1110  return true;
1111  return false; /* allow range_table_walker to continue */
1112  }
1113  if (IsA(node, Query))
1114  {
1115  /* Recurse into subquery, tracking nesting depth properly */
1116  Query *query = (Query *) node;
1117  bool result;
1118 
1119  (*depth)++;
1120 
1122  depth, QTW_EXAMINE_RTES_BEFORE);
1123 
1124  (*depth)--;
1125 
1126  return result;
1127  }
1129 }
#define QTW_EXAMINE_RTES_BEFORE
Definition: nodeFuncs.h:27
@ RTE_CTE
Definition: parsenodes.h:1023
Index ctelevelsup
Definition: parsenodes.h:1198
RTEKind rtekind
Definition: parsenodes.h:1047

References RangeTblEntry::ctelevelsup, expression_tree_walker, IsA, QTW_EXAMINE_RTES_BEFORE, query_tree_walker, RTE_CTE, and RangeTblEntry::rtekind.

Referenced by contain_outer_selfref().

◆ convert_ANY_sublink_to_join()

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

Definition at line 1251 of file subselect.c.

1253 {
1254  JoinExpr *result;
1255  Query *parse = root->parse;
1256  Query *subselect = (Query *) sublink->subselect;
1257  Relids upper_varnos;
1258  int rtindex;
1259  ParseNamespaceItem *nsitem;
1260  RangeTblEntry *rte;
1261  RangeTblRef *rtr;
1262  List *subquery_vars;
1263  Node *quals;
1264  ParseState *pstate;
1265  Relids sub_ref_outer_relids;
1266  bool use_lateral;
1267 
1268  Assert(sublink->subLinkType == ANY_SUBLINK);
1269 
1270  /*
1271  * If the sub-select contains any Vars of the parent query, we treat it as
1272  * LATERAL. (Vars from higher levels don't matter here.)
1273  */
1274  sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
1275  use_lateral = !bms_is_empty(sub_ref_outer_relids);
1276 
1277  /*
1278  * Can't convert if the sub-select contains parent-level Vars of relations
1279  * not in available_rels.
1280  */
1281  if (!bms_is_subset(sub_ref_outer_relids, available_rels))
1282  return NULL;
1283 
1284  /*
1285  * The test expression must contain some Vars of the parent query, else
1286  * it's not gonna be a join. (Note that it won't have Vars referring to
1287  * the subquery, rather Params.)
1288  */
1289  upper_varnos = pull_varnos(root, sublink->testexpr);
1290  if (bms_is_empty(upper_varnos))
1291  return NULL;
1292 
1293  /*
1294  * However, it can't refer to anything outside available_rels.
1295  */
1296  if (!bms_is_subset(upper_varnos, available_rels))
1297  return NULL;
1298 
1299  /*
1300  * The combining operators and left-hand expressions mustn't be volatile.
1301  */
1302  if (contain_volatile_functions(sublink->testexpr))
1303  return NULL;
1304 
1305  /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1306  pstate = make_parsestate(NULL);
1307 
1308  /*
1309  * Okay, pull up the sub-select into upper range table.
1310  *
1311  * We rely here on the assumption that the outer query has no references
1312  * to the inner (necessarily true, other than the Vars that we build
1313  * below). Therefore this is a lot easier than what pull_up_subqueries has
1314  * to go through.
1315  */
1316  nsitem = addRangeTableEntryForSubquery(pstate,
1317  subselect,
1318  makeAlias("ANY_subquery", NIL),
1319  use_lateral,
1320  false);
1321  rte = nsitem->p_rte;
1322  parse->rtable = lappend(parse->rtable, rte);
1323  rtindex = list_length(parse->rtable);
1324 
1325  /*
1326  * Form a RangeTblRef for the pulled-up sub-select.
1327  */
1328  rtr = makeNode(RangeTblRef);
1329  rtr->rtindex = rtindex;
1330 
1331  /*
1332  * Build a list of Vars representing the subselect outputs.
1333  */
1334  subquery_vars = generate_subquery_vars(root,
1335  subselect->targetList,
1336  rtindex);
1337 
1338  /*
1339  * Build the new join's qual expression, replacing Params with these Vars.
1340  */
1341  quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1342 
1343  /*
1344  * And finally, build the JoinExpr node.
1345  */
1346  result = makeNode(JoinExpr);
1347  result->jointype = JOIN_SEMI;
1348  result->isNatural = false;
1349  result->larg = NULL; /* caller must fill this in */
1350  result->rarg = (Node *) rtr;
1351  result->usingClause = NIL;
1352  result->join_using_alias = NULL;
1353  result->quals = quals;
1354  result->alias = NULL;
1355  result->rtindex = 0; /* we don't need an RTE for it */
1356 
1357  return result;
1358 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
#define bms_is_empty(a)
Definition: bitmapset.h:118
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:537
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:389
@ JOIN_SEMI
Definition: nodes.h:307
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
Node * quals
Definition: primnodes.h:2289
JoinType jointype
Definition: primnodes.h:2280
int rtindex
Definition: primnodes.h:2293
Node * larg
Definition: primnodes.h:2282
bool isNatural
Definition: primnodes.h:2281
Node * rarg
Definition: primnodes.h:2283
List * targetList
Definition: parsenodes.h:193
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:613
Relids pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
Definition: var.c:139
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:113

References addRangeTableEntryForSubquery(), ANY_SUBLINK, Assert, bms_is_empty, bms_is_subset(), 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(), pull_varnos(), pull_varnos_of_level(), JoinExpr::quals, JoinExpr::rarg, root, JoinExpr::rtindex, SubLink::subLinkType, SubLink::subselect, Query::targetList, and SubLink::testexpr.

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_EXISTS_sublink_to_join()

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

Definition at line 1368 of file subselect.c.

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

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

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_EXISTS_to_ANY()

static Query * convert_EXISTS_to_ANY ( PlannerInfo root,
Query subselect,
Node **  testexpr,
List **  paramIds 
)
static

Definition at line 1649 of file subselect.c.

1651 {
1652  Node *whereClause;
1653  List *leftargs,
1654  *rightargs,
1655  *opids,
1656  *opcollations,
1657  *newWhere,
1658  *tlist,
1659  *testlist,
1660  *paramids;
1661  ListCell *lc,
1662  *rc,
1663  *oc,
1664  *cc;
1665  AttrNumber resno;
1666 
1667  /*
1668  * Query must not require a targetlist, since we have to insert a new one.
1669  * Caller should have dealt with the case already.
1670  */
1671  Assert(subselect->targetList == NIL);
1672 
1673  /*
1674  * Separate out the WHERE clause. (We could theoretically also remove
1675  * top-level plain JOIN/ON clauses, but it's probably not worth the
1676  * trouble.)
1677  */
1678  whereClause = subselect->jointree->quals;
1679  subselect->jointree->quals = NULL;
1680 
1681  /*
1682  * The rest of the sub-select must not refer to any Vars of the parent
1683  * query. (Vars of higher levels should be okay, though.)
1684  *
1685  * Note: we need not check for Aggrefs separately because we know the
1686  * sub-select is as yet unoptimized; any uplevel Aggref must therefore
1687  * contain an uplevel Var reference. This is not the case below ...
1688  */
1689  if (contain_vars_of_level((Node *) subselect, 1))
1690  return NULL;
1691 
1692  /*
1693  * We don't risk optimizing if the WHERE clause is volatile, either.
1694  */
1695  if (contain_volatile_functions(whereClause))
1696  return NULL;
1697 
1698  /*
1699  * Clean up the WHERE clause by doing const-simplification etc on it.
1700  * Aside from simplifying the processing we're about to do, this is
1701  * important for being able to pull chunks of the WHERE clause up into the
1702  * parent query. Since we are invoked partway through the parent's
1703  * preprocess_expression() work, earlier steps of preprocess_expression()
1704  * wouldn't get applied to the pulled-up stuff unless we do them here. For
1705  * the parts of the WHERE clause that get put back into the child query,
1706  * this work is partially duplicative, but it shouldn't hurt.
1707  *
1708  * Note: we do not run flatten_join_alias_vars. This is OK because any
1709  * parent aliases were flattened already, and we're not going to pull any
1710  * child Vars (of any description) into the parent.
1711  *
1712  * Note: passing the parent's root to eval_const_expressions is
1713  * technically wrong, but we can get away with it since only the
1714  * boundParams (if any) are used, and those would be the same in a
1715  * subroot.
1716  */
1717  whereClause = eval_const_expressions(root, whereClause);
1718  whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
1719  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1720 
1721  /*
1722  * We now have a flattened implicit-AND list of clauses, which we try to
1723  * break apart into "outervar = innervar" hash clauses. Anything that
1724  * can't be broken apart just goes back into the newWhere list. Note that
1725  * we aren't trying hard yet to ensure that we have only outer or only
1726  * inner on each side; we'll check that if we get to the end.
1727  */
1728  leftargs = rightargs = opids = opcollations = newWhere = NIL;
1729  foreach(lc, (List *) whereClause)
1730  {
1731  OpExpr *expr = (OpExpr *) lfirst(lc);
1732 
1733  if (IsA(expr, OpExpr) &&
1734  hash_ok_operator(expr))
1735  {
1736  Node *leftarg = (Node *) linitial(expr->args);
1737  Node *rightarg = (Node *) lsecond(expr->args);
1738 
1739  if (contain_vars_of_level(leftarg, 1))
1740  {
1741  leftargs = lappend(leftargs, leftarg);
1742  rightargs = lappend(rightargs, rightarg);
1743  opids = lappend_oid(opids, expr->opno);
1744  opcollations = lappend_oid(opcollations, expr->inputcollid);
1745  continue;
1746  }
1747  if (contain_vars_of_level(rightarg, 1))
1748  {
1749  /*
1750  * We must commute the clause to put the outer var on the
1751  * left, because the hashing code in nodeSubplan.c expects
1752  * that. This probably shouldn't ever fail, since hashable
1753  * operators ought to have commutators, but be paranoid.
1754  */
1755  expr->opno = get_commutator(expr->opno);
1756  if (OidIsValid(expr->opno) && hash_ok_operator(expr))
1757  {
1758  leftargs = lappend(leftargs, rightarg);
1759  rightargs = lappend(rightargs, leftarg);
1760  opids = lappend_oid(opids, expr->opno);
1761  opcollations = lappend_oid(opcollations, expr->inputcollid);
1762  continue;
1763  }
1764  /* If no commutator, no chance to optimize the WHERE clause */
1765  return NULL;
1766  }
1767  }
1768  /* Couldn't handle it as a hash clause */
1769  newWhere = lappend(newWhere, expr);
1770  }
1771 
1772  /*
1773  * If we didn't find anything we could convert, fail.
1774  */
1775  if (leftargs == NIL)
1776  return NULL;
1777 
1778  /*
1779  * There mustn't be any parent Vars or Aggs in the stuff that we intend to
1780  * put back into the child query. Note: you might think we don't need to
1781  * check for Aggs separately, because an uplevel Agg must contain an
1782  * uplevel Var in its argument. But it is possible that the uplevel Var
1783  * got optimized away by eval_const_expressions. Consider
1784  *
1785  * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
1786  */
1787  if (contain_vars_of_level((Node *) newWhere, 1) ||
1788  contain_vars_of_level((Node *) rightargs, 1))
1789  return NULL;
1790  if (root->parse->hasAggs &&
1791  (contain_aggs_of_level((Node *) newWhere, 1) ||
1792  contain_aggs_of_level((Node *) rightargs, 1)))
1793  return NULL;
1794 
1795  /*
1796  * And there can't be any child Vars in the stuff we intend to pull up.
1797  * (Note: we'd need to check for child Aggs too, except we know the child
1798  * has no aggs at all because of simplify_EXISTS_query's check. The same
1799  * goes for window functions.)
1800  */
1801  if (contain_vars_of_level((Node *) leftargs, 0))
1802  return NULL;
1803 
1804  /*
1805  * Also reject sublinks in the stuff we intend to pull up. (It might be
1806  * possible to support this, but doesn't seem worth the complication.)
1807  */
1808  if (contain_subplans((Node *) leftargs))
1809  return NULL;
1810 
1811  /*
1812  * Okay, adjust the sublevelsup in the stuff we're pulling up.
1813  */
1814  IncrementVarSublevelsUp((Node *) leftargs, -1, 1);
1815 
1816  /*
1817  * Put back any child-level-only WHERE clauses.
1818  */
1819  if (newWhere)
1820  subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
1821 
1822  /*
1823  * Build a new targetlist for the child that emits the expressions we
1824  * need. Concurrently, build a testexpr for the parent using Params to
1825  * reference the child outputs. (Since we generate Params directly here,
1826  * there will be no need to convert the testexpr in build_subplan.)
1827  */
1828  tlist = testlist = paramids = NIL;
1829  resno = 1;
1830  forfour(lc, leftargs, rc, rightargs, oc, opids, cc, opcollations)
1831  {
1832  Node *leftarg = (Node *) lfirst(lc);
1833  Node *rightarg = (Node *) lfirst(rc);
1834  Oid opid = lfirst_oid(oc);
1835  Oid opcollation = lfirst_oid(cc);
1836  Param *param;
1837 
1838  param = generate_new_exec_param(root,
1839  exprType(rightarg),
1840  exprTypmod(rightarg),
1841  exprCollation(rightarg));
1842  tlist = lappend(tlist,
1843  makeTargetEntry((Expr *) rightarg,
1844  resno++,
1845  NULL,
1846  false));
1847  testlist = lappend(testlist,
1848  make_opclause(opid, BOOLOID, false,
1849  (Expr *) leftarg, (Expr *) param,
1850  InvalidOid, opcollation));
1851  paramids = lappend_int(paramids, param->paramid);
1852  }
1853 
1854  /* Put everything where it should go, and we're done */
1855  subselect->targetList = tlist;
1856  *testexpr = (Node *) make_ands_explicit(testlist);
1857  *paramIds = paramids;
1858 
1859  return subselect;
1860 }
int16 AttrNumber
Definition: attnum.h:21
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2253
bool contain_subplans(Node *clause)
Definition: clauses.c:329
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1509
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: makefuncs.c:651
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:760
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
Expr * make_ands_explicit(List *andclauses)
Definition: makefuncs.c:749
#define lsecond(l)
Definition: pg_list.h:183
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:575
#define lfirst_oid(lc)
Definition: pg_list.h:174
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:293
bool contain_aggs_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:85
Oid opno
Definition: primnodes.h:818
List * args
Definition: primnodes.h:836
static bool hash_ok_operator(OpExpr *expr)
Definition: subselect.c:830

References OpExpr::args, Assert, canonicalize_qual(), contain_aggs_of_level(), contain_subplans(), contain_vars_of_level(), contain_volatile_functions(), eval_const_expressions(), exprCollation(), exprType(), exprTypmod(), forfour, generate_new_exec_param(), get_commutator(), hash_ok_operator(), IncrementVarSublevelsUp(), InvalidOid, IsA, Query::jointree, lappend(), lappend_int(), lappend_oid(), lfirst, lfirst_oid, linitial, lsecond, make_ands_explicit(), make_ands_implicit(), make_opclause(), makeTargetEntry(), NIL, OidIsValid, OpExpr::opno, Param::paramid, FromExpr::quals, root, and Query::targetList.

Referenced by make_subplan().

◆ convert_testexpr()

static Node * convert_testexpr ( PlannerInfo root,
Node testexpr,
List subst_nodes 
)
static

Definition at line 642 of file subselect.c.

645 {
647 
648  context.root = root;
649  context.subst_nodes = subst_nodes;
650  return convert_testexpr_mutator(testexpr, &context);
651 }
static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context)
Definition: subselect.c:654

References context, convert_testexpr_mutator(), and root.

Referenced by build_subplan(), and convert_ANY_sublink_to_join().

◆ convert_testexpr_mutator()

static Node * convert_testexpr_mutator ( Node node,
convert_testexpr_context context 
)
static

Definition at line 654 of file subselect.c.

656 {
657  if (node == NULL)
658  return NULL;
659  if (IsA(node, Param))
660  {
661  Param *param = (Param *) node;
662 
663  if (param->paramkind == PARAM_SUBLINK)
664  {
665  if (param->paramid <= 0 ||
666  param->paramid > list_length(context->subst_nodes))
667  elog(ERROR, "unexpected PARAM_SUBLINK ID: %d", param->paramid);
668 
669  /*
670  * We copy the list item to avoid having doubly-linked
671  * substructure in the modified parse tree. This is probably
672  * unnecessary when it's a Param, but be safe.
673  */
674  return (Node *) copyObject(list_nth(context->subst_nodes,
675  param->paramid - 1));
676  }
677  }
678  if (IsA(node, SubLink))
679  {
680  /*
681  * If we come across a nested SubLink, it is neither necessary nor
682  * correct to recurse into it: any PARAM_SUBLINKs we might find inside
683  * belong to the inner SubLink not the outer. So just return it as-is.
684  *
685  * This reasoning depends on the assumption that nothing will pull
686  * subexpressions into or out of the testexpr field of a SubLink, at
687  * least not without replacing PARAM_SUBLINKs first. If we did want
688  * to do that we'd need to rethink the parser-output representation
689  * altogether, since currently PARAM_SUBLINKs are only unique per
690  * SubLink not globally across the query. The whole point of
691  * replacing them with Vars or PARAM_EXEC nodes is to make them
692  * globally unique before they escape from the SubLink's testexpr.
693  *
694  * Note: this can't happen when called during SS_process_sublinks,
695  * because that recursively processes inner SubLinks first. It can
696  * happen when called from convert_ANY_sublink_to_join, though.
697  */
698  return node;
699  }
701 }
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
@ PARAM_SUBLINK
Definition: primnodes.h:369
ParamKind paramkind
Definition: primnodes.h:376

References context, copyObject, elog, ERROR, expression_tree_mutator, IsA, list_length(), list_nth(), PARAM_SUBLINK, Param::paramid, and Param::paramkind.

Referenced by convert_testexpr().

◆ finalize_agg_primnode()

static bool finalize_agg_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 2992 of file subselect.c.

2993 {
2994  if (node == NULL)
2995  return false;
2996  if (IsA(node, Aggref))
2997  {
2998  Aggref *agg = (Aggref *) node;
2999 
3000  /* we should not consider the direct arguments, if any */
3001  finalize_primnode((Node *) agg->args, context);
3003  return false; /* there can't be any Aggrefs below here */
3004  }
3006 }
List * args
Definition: primnodes.h:468
Expr * aggfilter
Definition: primnodes.h:477
static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2992
static bool finalize_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2909

References Aggref::aggfilter, Aggref::args, context, expression_tree_walker, finalize_primnode(), and IsA.

Referenced by finalize_plan().

◆ finalize_plan()

static Bitmapset * finalize_plan ( PlannerInfo root,
Plan plan,
int  gather_param,
Bitmapset valid_params,
Bitmapset scan_params 
)
static

Definition at line 2311 of file subselect.c.

2315 {
2317  int locally_added_param;
2318  Bitmapset *nestloop_params;
2319  Bitmapset *initExtParam;
2320  Bitmapset *initSetParam;
2321  Bitmapset *child_params;
2322  ListCell *l;
2323 
2324  if (plan == NULL)
2325  return NULL;
2326 
2327  context.root = root;
2328  context.paramids = NULL; /* initialize set to empty */
2329  locally_added_param = -1; /* there isn't one */
2330  nestloop_params = NULL; /* there aren't any */
2331 
2332  /*
2333  * Examine any initPlans to determine the set of external params they
2334  * reference and the set of output params they supply. (We assume
2335  * SS_finalize_plan was run on them already.)
2336  */
2337  initExtParam = initSetParam = NULL;
2338  foreach(l, plan->initPlan)
2339  {
2340  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2341  Plan *initplan = planner_subplan_get_plan(root, initsubplan);
2342  ListCell *l2;
2343 
2344  initExtParam = bms_add_members(initExtParam, initplan->extParam);
2345  foreach(l2, initsubplan->setParam)
2346  {
2347  initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2348  }
2349  }
2350 
2351  /* Any setParams are validly referenceable in this node and children */
2352  if (initSetParam)
2353  valid_params = bms_union(valid_params, initSetParam);
2354 
2355  /*
2356  * When we call finalize_primnode, context.paramids sets are automatically
2357  * merged together. But when recursing to self, we have to do it the hard
2358  * way. We want the paramids set to include params in subplans as well as
2359  * at this level.
2360  */
2361 
2362  /* Find params in targetlist and qual */
2363  finalize_primnode((Node *) plan->targetlist, &context);
2364  finalize_primnode((Node *) plan->qual, &context);
2365 
2366  /*
2367  * If it's a parallel-aware scan node, mark it as dependent on the parent
2368  * Gather/GatherMerge's rescan Param.
2369  */
2370  if (plan->parallel_aware)
2371  {
2372  if (gather_param < 0)
2373  elog(ERROR, "parallel-aware plan node is not below a Gather");
2374  context.paramids =
2375  bms_add_member(context.paramids, gather_param);
2376  }
2377 
2378  /* Check additional node-type-specific fields */
2379  switch (nodeTag(plan))
2380  {
2381  case T_Result:
2382  finalize_primnode(((Result *) plan)->resconstantqual,
2383  &context);
2384  break;
2385 
2386  case T_SeqScan:
2387  context.paramids = bms_add_members(context.paramids, scan_params);
2388  break;
2389 
2390  case T_SampleScan:
2391  finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
2392  &context);
2393  context.paramids = bms_add_members(context.paramids, scan_params);
2394  break;
2395 
2396  case T_IndexScan:
2397  finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2398  &context);
2399  finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2400  &context);
2401 
2402  /*
2403  * we need not look at indexqualorig, since it will have the same
2404  * param references as indexqual. Likewise, we can ignore
2405  * indexorderbyorig.
2406  */
2407  context.paramids = bms_add_members(context.paramids, scan_params);
2408  break;
2409 
2410  case T_IndexOnlyScan:
2411  finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2412  &context);
2413  finalize_primnode((Node *) ((IndexOnlyScan *) plan)->recheckqual,
2414  &context);
2415  finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2416  &context);
2417 
2418  /*
2419  * we need not look at indextlist, since it cannot contain Params.
2420  */
2421  context.paramids = bms_add_members(context.paramids, scan_params);
2422  break;
2423 
2424  case T_BitmapIndexScan:
2425  finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2426  &context);
2427 
2428  /*
2429  * we need not look at indexqualorig, since it will have the same
2430  * param references as indexqual.
2431  */
2432  break;
2433 
2434  case T_BitmapHeapScan:
2435  finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2436  &context);
2437  context.paramids = bms_add_members(context.paramids, scan_params);
2438  break;
2439 
2440  case T_TidScan:
2441  finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2442  &context);
2443  context.paramids = bms_add_members(context.paramids, scan_params);
2444  break;
2445 
2446  case T_TidRangeScan:
2447  finalize_primnode((Node *) ((TidRangeScan *) plan)->tidrangequals,
2448  &context);
2449  context.paramids = bms_add_members(context.paramids, scan_params);
2450  break;
2451 
2452  case T_SubqueryScan:
2453  {
2454  SubqueryScan *sscan = (SubqueryScan *) plan;
2455  RelOptInfo *rel;
2456  Bitmapset *subquery_params;
2457 
2458  /* We must run finalize_plan on the subquery */
2459  rel = find_base_rel(root, sscan->scan.scanrelid);
2460  subquery_params = rel->subroot->outer_params;
2461  if (gather_param >= 0)
2462  subquery_params = bms_add_member(bms_copy(subquery_params),
2463  gather_param);
2464  finalize_plan(rel->subroot, sscan->subplan, gather_param,
2465  subquery_params, NULL);
2466 
2467  /* Now we can add its extParams to the parent's params */
2468  context.paramids = bms_add_members(context.paramids,
2469  sscan->subplan->extParam);
2470  /* We need scan_params too, though */
2471  context.paramids = bms_add_members(context.paramids,
2472  scan_params);
2473  }
2474  break;
2475 
2476  case T_FunctionScan:
2477  {
2478  FunctionScan *fscan = (FunctionScan *) plan;
2479  ListCell *lc;
2480 
2481  /*
2482  * Call finalize_primnode independently on each function
2483  * expression, so that we can record which params are
2484  * referenced in each, in order to decide which need
2485  * re-evaluating during rescan.
2486  */
2487  foreach(lc, fscan->functions)
2488  {
2489  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
2490  finalize_primnode_context funccontext;
2491 
2492  funccontext = context;
2493  funccontext.paramids = NULL;
2494 
2495  finalize_primnode(rtfunc->funcexpr, &funccontext);
2496 
2497  /* remember results for execution */
2498  rtfunc->funcparams = funccontext.paramids;
2499 
2500  /* add the function's params to the overall set */
2501  context.paramids = bms_add_members(context.paramids,
2502  funccontext.paramids);
2503  }
2504 
2505  context.paramids = bms_add_members(context.paramids,
2506  scan_params);
2507  }
2508  break;
2509 
2510  case T_TableFuncScan:
2511  finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
2512  &context);
2513  context.paramids = bms_add_members(context.paramids, scan_params);
2514  break;
2515 
2516  case T_ValuesScan:
2517  finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2518  &context);
2519  context.paramids = bms_add_members(context.paramids, scan_params);
2520  break;
2521 
2522  case T_CteScan:
2523  {
2524  /*
2525  * You might think we should add the node's cteParam to
2526  * paramids, but we shouldn't because that param is just a
2527  * linkage mechanism for multiple CteScan nodes for the same
2528  * CTE; it is never used for changed-param signaling. What we
2529  * have to do instead is to find the referenced CTE plan and
2530  * incorporate its external paramids, so that the correct
2531  * things will happen if the CTE references outer-level
2532  * variables. See test cases for bug #4902. (We assume
2533  * SS_finalize_plan was run on the CTE plan already.)
2534  */
2535  int plan_id = ((CteScan *) plan)->ctePlanId;
2536  Plan *cteplan;
2537 
2538  /* so, do this ... */
2539  if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2540  elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2541  plan_id);
2542  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2543  context.paramids =
2544  bms_add_members(context.paramids, cteplan->extParam);
2545 
2546 #ifdef NOT_USED
2547  /* ... but not this */
2548  context.paramids =
2549  bms_add_member(context.paramids,
2550  ((CteScan *) plan)->cteParam);
2551 #endif
2552 
2553  context.paramids = bms_add_members(context.paramids,
2554  scan_params);
2555  }
2556  break;
2557 
2558  case T_WorkTableScan:
2559  context.paramids =
2560  bms_add_member(context.paramids,
2561  ((WorkTableScan *) plan)->wtParam);
2562  context.paramids = bms_add_members(context.paramids, scan_params);
2563  break;
2564 
2565  case T_NamedTuplestoreScan:
2566  context.paramids = bms_add_members(context.paramids, scan_params);
2567  break;
2568 
2569  case T_ForeignScan:
2570  {
2571  ForeignScan *fscan = (ForeignScan *) plan;
2572 
2573  finalize_primnode((Node *) fscan->fdw_exprs,
2574  &context);
2576  &context);
2577 
2578  /* We assume fdw_scan_tlist cannot contain Params */
2579  context.paramids = bms_add_members(context.paramids,
2580  scan_params);
2581  }
2582  break;
2583 
2584  case T_CustomScan:
2585  {
2586  CustomScan *cscan = (CustomScan *) plan;
2587  ListCell *lc;
2588 
2589  finalize_primnode((Node *) cscan->custom_exprs,
2590  &context);
2591  /* We assume custom_scan_tlist cannot contain Params */
2592  context.paramids =
2593  bms_add_members(context.paramids, scan_params);
2594 
2595  /* child nodes if any */
2596  foreach(lc, cscan->custom_plans)
2597  {
2598  context.paramids =
2599  bms_add_members(context.paramids,
2601  (Plan *) lfirst(lc),
2602  gather_param,
2603  valid_params,
2604  scan_params));
2605  }
2606  }
2607  break;
2608 
2609  case T_ModifyTable:
2610  {
2611  ModifyTable *mtplan = (ModifyTable *) plan;
2612 
2613  /* Force descendant scan nodes to reference epqParam */
2614  locally_added_param = mtplan->epqParam;
2615  valid_params = bms_add_member(bms_copy(valid_params),
2616  locally_added_param);
2617  scan_params = bms_add_member(bms_copy(scan_params),
2618  locally_added_param);
2620  &context);
2621  finalize_primnode((Node *) mtplan->onConflictSet,
2622  &context);
2624  &context);
2625  /* exclRelTlist contains only Vars, doesn't need examination */
2626  }
2627  break;
2628 
2629  case T_Append:
2630  {
2631  foreach(l, ((Append *) plan)->appendplans)
2632  {
2633  context.paramids =
2634  bms_add_members(context.paramids,
2636  (Plan *) lfirst(l),
2637  gather_param,
2638  valid_params,
2639  scan_params));
2640  }
2641  }
2642  break;
2643 
2644  case T_MergeAppend:
2645  {
2646  foreach(l, ((MergeAppend *) plan)->mergeplans)
2647  {
2648  context.paramids =
2649  bms_add_members(context.paramids,
2651  (Plan *) lfirst(l),
2652  gather_param,
2653  valid_params,
2654  scan_params));
2655  }
2656  }
2657  break;
2658 
2659  case T_BitmapAnd:
2660  {
2661  foreach(l, ((BitmapAnd *) plan)->bitmapplans)
2662  {
2663  context.paramids =
2664  bms_add_members(context.paramids,
2666  (Plan *) lfirst(l),
2667  gather_param,
2668  valid_params,
2669  scan_params));
2670  }
2671  }
2672  break;
2673 
2674  case T_BitmapOr:
2675  {
2676  foreach(l, ((BitmapOr *) plan)->bitmapplans)
2677  {
2678  context.paramids =
2679  bms_add_members(context.paramids,
2681  (Plan *) lfirst(l),
2682  gather_param,
2683  valid_params,
2684  scan_params));
2685  }
2686  }
2687  break;
2688 
2689  case T_NestLoop:
2690  {
2691  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2692  &context);
2693  /* collect set of params that will be passed to right child */
2694  foreach(l, ((NestLoop *) plan)->nestParams)
2695  {
2696  NestLoopParam *nlp = (NestLoopParam *) lfirst(l);
2697 
2698  nestloop_params = bms_add_member(nestloop_params,
2699  nlp->paramno);
2700  }
2701  }
2702  break;
2703 
2704  case T_MergeJoin:
2705  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2706  &context);
2707  finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
2708  &context);
2709  break;
2710 
2711  case T_HashJoin:
2712  finalize_primnode((Node *) ((Join *) plan)->joinqual,
2713  &context);
2714  finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
2715  &context);
2716  break;
2717 
2718  case T_Hash:
2719  finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
2720  &context);
2721  break;
2722 
2723  case T_Limit:
2724  finalize_primnode(((Limit *) plan)->limitOffset,
2725  &context);
2726  finalize_primnode(((Limit *) plan)->limitCount,
2727  &context);
2728  break;
2729 
2730  case T_RecursiveUnion:
2731  /* child nodes are allowed to reference wtParam */
2732  locally_added_param = ((RecursiveUnion *) plan)->wtParam;
2733  valid_params = bms_add_member(bms_copy(valid_params),
2734  locally_added_param);
2735  /* wtParam does *not* get added to scan_params */
2736  break;
2737 
2738  case T_LockRows:
2739  /* Force descendant scan nodes to reference epqParam */
2740  locally_added_param = ((LockRows *) plan)->epqParam;
2741  valid_params = bms_add_member(bms_copy(valid_params),
2742  locally_added_param);
2743  scan_params = bms_add_member(bms_copy(scan_params),
2744  locally_added_param);
2745  break;
2746 
2747  case T_Agg:
2748  {
2749  Agg *agg = (Agg *) plan;
2750 
2751  /*
2752  * AGG_HASHED plans need to know which Params are referenced
2753  * in aggregate calls. Do a separate scan to identify them.
2754  */
2755  if (agg->aggstrategy == AGG_HASHED)
2756  {
2757  finalize_primnode_context aggcontext;
2758 
2759  aggcontext.root = root;
2760  aggcontext.paramids = NULL;
2762  &aggcontext);
2764  &aggcontext);
2765  agg->aggParams = aggcontext.paramids;
2766  }
2767  }
2768  break;
2769 
2770  case T_WindowAgg:
2771  finalize_primnode(((WindowAgg *) plan)->startOffset,
2772  &context);
2773  finalize_primnode(((WindowAgg *) plan)->endOffset,
2774  &context);
2775  break;
2776 
2777  case T_Gather:
2778  /* child nodes are allowed to reference rescan_param, if any */
2779  locally_added_param = ((Gather *) plan)->rescan_param;
2780  if (locally_added_param >= 0)
2781  {
2782  valid_params = bms_add_member(bms_copy(valid_params),
2783  locally_added_param);
2784 
2785  /*
2786  * We currently don't support nested Gathers. The issue so
2787  * far as this function is concerned would be how to identify
2788  * which child nodes depend on which Gather.
2789  */
2790  Assert(gather_param < 0);
2791  /* Pass down rescan_param to child parallel-aware nodes */
2792  gather_param = locally_added_param;
2793  }
2794  /* rescan_param does *not* get added to scan_params */
2795  break;
2796 
2797  case T_GatherMerge:
2798  /* child nodes are allowed to reference rescan_param, if any */
2799  locally_added_param = ((GatherMerge *) plan)->rescan_param;
2800  if (locally_added_param >= 0)
2801  {
2802  valid_params = bms_add_member(bms_copy(valid_params),
2803  locally_added_param);
2804 
2805  /*
2806  * We currently don't support nested Gathers. The issue so
2807  * far as this function is concerned would be how to identify
2808  * which child nodes depend on which Gather.
2809  */
2810  Assert(gather_param < 0);
2811  /* Pass down rescan_param to child parallel-aware nodes */
2812  gather_param = locally_added_param;
2813  }
2814  /* rescan_param does *not* get added to scan_params */
2815  break;
2816 
2817  case T_Memoize:
2818  finalize_primnode((Node *) ((Memoize *) plan)->param_exprs,
2819  &context);
2820  break;
2821 
2822  case T_ProjectSet:
2823  case T_Material:
2824  case T_Sort:
2825  case T_IncrementalSort:
2826  case T_Unique:
2827  case T_SetOp:
2828  case T_Group:
2829  /* no node-type-specific fields need fixing */
2830  break;
2831 
2832  default:
2833  elog(ERROR, "unrecognized node type: %d",
2834  (int) nodeTag(plan));
2835  }
2836 
2837  /* Process left and right child plans, if any */
2838  child_params = finalize_plan(root,
2839  plan->lefttree,
2840  gather_param,
2841  valid_params,
2842  scan_params);
2843  context.paramids = bms_add_members(context.paramids, child_params);
2844 
2845  if (nestloop_params)
2846  {
2847  /* right child can reference nestloop_params as well as valid_params */
2848  child_params = finalize_plan(root,
2849  plan->righttree,
2850  gather_param,
2851  bms_union(nestloop_params, valid_params),
2852  scan_params);
2853  /* ... and they don't count as parameters used at my level */
2854  child_params = bms_difference(child_params, nestloop_params);
2855  bms_free(nestloop_params);
2856  }
2857  else
2858  {
2859  /* easy case */
2860  child_params = finalize_plan(root,
2861  plan->righttree,
2862  gather_param,
2863  valid_params,
2864  scan_params);
2865  }
2866  context.paramids = bms_add_members(context.paramids, child_params);
2867 
2868  /*
2869  * Any locally generated parameter doesn't count towards its generating
2870  * plan node's external dependencies. (Note: if we changed valid_params
2871  * and/or scan_params, we leak those bitmapsets; not worth the notational
2872  * trouble to clean them up.)
2873  */
2874  if (locally_added_param >= 0)
2875  {
2876  context.paramids = bms_del_member(context.paramids,
2877  locally_added_param);
2878  }
2879 
2880  /* Now we have all the paramids referenced in this node and children */
2881 
2882  if (!bms_is_subset(context.paramids, valid_params))
2883  elog(ERROR, "plan should not reference subplan's variable");
2884 
2885  /*
2886  * The plan node's allParam and extParam fields should include all its
2887  * referenced paramids, plus contributions from any child initPlans.
2888  * However, any setParams of the initPlans should not be present in the
2889  * parent node's extParams, only in its allParams. (It's possible that
2890  * some initPlans have extParams that are setParams of other initPlans.)
2891  */
2892 
2893  /* allParam must include initplans' extParams and setParams */
2894  plan->allParam = bms_union(context.paramids, initExtParam);
2895  plan->allParam = bms_add_members(plan->allParam, initSetParam);
2896  /* extParam must include any initplan extParams */
2897  plan->extParam = bms_union(context.paramids, initExtParam);
2898  /* but not any initplan setParams */
2899  plan->extParam = bms_del_members(plan->extParam, initSetParam);
2900 
2901  return plan->allParam;
2902 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:346
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1161
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:868
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
@ AGG_HASHED
Definition: nodes.h:356
#define planner_subplan_get_plan(root, subplan)
Definition: pathnodes.h:169
#define lfirst_int(lc)
Definition: pg_list.h:173
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414
Definition: plannodes.h:998
Bitmapset * aggParams
Definition: plannodes.h:1024
Plan plan
Definition: plannodes.h:999
AggStrategy aggstrategy
Definition: plannodes.h:1002
List * custom_exprs
Definition: plannodes.h:746
List * custom_plans
Definition: plannodes.h:745
List * fdw_exprs
Definition: plannodes.h:716
List * fdw_recheck_quals
Definition: plannodes.h:719
List * functions
Definition: plannodes.h:613
int epqParam
Definition: plannodes.h:245
List * onConflictSet
Definition: plannodes.h:248
List * returningLists
Definition: plannodes.h:241
Node * onConflictWhere
Definition: plannodes.h:250
Bitmapset * extParam
Definition: plannodes.h:171
List * qual
Definition: plannodes.h:154
List * targetlist
Definition: plannodes.h:153
Bitmapset * outer_params
Definition: pathnodes.h:221
PlannerInfo * subroot
Definition: pathnodes.h:953
Index scanrelid
Definition: plannodes.h:390
List * setParam
Definition: primnodes.h:1088
Plan * subplan
Definition: plannodes.h:602
PlannerInfo * root
Definition: subselect.c:56
static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
Definition: subselect.c:2311

References AGG_HASHED, Agg::aggParams, Agg::aggstrategy, Assert, bms_add_member(), bms_add_members(), bms_copy(), bms_del_member(), bms_del_members(), bms_difference(), bms_free(), bms_is_subset(), bms_union(), context, CustomScan::custom_exprs, CustomScan::custom_plans, elog, ModifyTable::epqParam, ERROR, Plan::extParam, ForeignScan::fdw_exprs, ForeignScan::fdw_recheck_quals, finalize_agg_primnode(), finalize_primnode(), find_base_rel(), RangeTblFunction::funcexpr, FunctionScan::functions, lfirst, lfirst_int, list_length(), list_nth(), nodeTag, ModifyTable::onConflictSet, ModifyTable::onConflictWhere, PlannerInfo::outer_params, finalize_primnode_context::paramids, NestLoopParam::paramno, Agg::plan, plan, planner_subplan_get_plan, Plan::qual, ModifyTable::returningLists, finalize_primnode_context::root, root, SubqueryScan::scan, Scan::scanrelid, SubPlan::setParam, SubqueryScan::subplan, RelOptInfo::subroot, and Plan::targetlist.

Referenced by SS_finalize_plan().

◆ finalize_primnode()

static bool finalize_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 2909 of file subselect.c.

2910 {
2911  if (node == NULL)
2912  return false;
2913  if (IsA(node, Param))
2914  {
2915  if (((Param *) node)->paramkind == PARAM_EXEC)
2916  {
2917  int paramid = ((Param *) node)->paramid;
2918 
2919  context->paramids = bms_add_member(context->paramids, paramid);
2920  }
2921  return false; /* no more to do here */
2922  }
2923  else if (IsA(node, Aggref))
2924  {
2925  /*
2926  * Check to see if the aggregate will be replaced by a Param
2927  * referencing a subquery output during setrefs.c. If so, we must
2928  * account for that Param here. (For various reasons, it's not
2929  * convenient to perform that substitution earlier than setrefs.c, nor
2930  * to perform this processing after setrefs.c. Thus we need a wart
2931  * here.)
2932  */
2933  Aggref *aggref = (Aggref *) node;
2934  Param *aggparam;
2935 
2936  aggparam = find_minmax_agg_replacement_param(context->root, aggref);
2937  if (aggparam != NULL)
2938  context->paramids = bms_add_member(context->paramids,
2939  aggparam->paramid);
2940  /* Fall through to examine the agg's arguments */
2941  }
2942  else if (IsA(node, SubPlan))
2943  {
2944  SubPlan *subplan = (SubPlan *) node;
2945  Plan *plan = planner_subplan_get_plan(context->root, subplan);
2946  ListCell *lc;
2947  Bitmapset *subparamids;
2948 
2949  /* Recurse into the testexpr, but not into the Plan */
2950  finalize_primnode(subplan->testexpr, context);
2951 
2952  /*
2953  * Remove any param IDs of output parameters of the subplan that were
2954  * referenced in the testexpr. These are not interesting for
2955  * parameter change signaling since we always re-evaluate the subplan.
2956  * Note that this wouldn't work too well if there might be uses of the
2957  * same param IDs elsewhere in the plan, but that can't happen because
2958  * generate_new_exec_param never tries to merge params.
2959  */
2960  foreach(lc, subplan->paramIds)
2961  {
2962  context->paramids = bms_del_member(context->paramids,
2963  lfirst_int(lc));
2964  }
2965 
2966  /* Also examine args list */
2967  finalize_primnode((Node *) subplan->args, context);
2968 
2969  /*
2970  * Add params needed by the subplan to paramids, but excluding those
2971  * we will pass down to it. (We assume SS_finalize_plan was run on
2972  * the subplan already.)
2973  */
2974  subparamids = bms_copy(plan->extParam);
2975  foreach(lc, subplan->parParam)
2976  {
2977  subparamids = bms_del_member(subparamids, lfirst_int(lc));
2978  }
2979  context->paramids = bms_join(context->paramids, subparamids);
2980 
2981  return false; /* no more to do here */
2982  }
2984 }
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
@ PARAM_EXEC
Definition: primnodes.h:368
Param * find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
Definition: setrefs.c:3443
List * args
Definition: primnodes.h:1091
List * paramIds
Definition: primnodes.h:1068
Node * testexpr
Definition: primnodes.h:1067
List * parParam
Definition: primnodes.h:1090

References SubPlan::args, bms_add_member(), bms_copy(), bms_del_member(), bms_join(), context, expression_tree_walker, find_minmax_agg_replacement_param(), IsA, lfirst_int, PARAM_EXEC, Param::paramid, SubPlan::paramIds, SubPlan::parParam, plan, planner_subplan_get_plan, and SubPlan::testexpr.

Referenced by finalize_agg_primnode(), and finalize_plan().

◆ generate_subquery_params()

static List * generate_subquery_params ( PlannerInfo root,
List tlist,
List **  paramIds 
)
static

Definition at line 580 of file subselect.c.

581 {
582  List *result;
583  List *ids;
584  ListCell *lc;
585 
586  result = ids = NIL;
587  foreach(lc, tlist)
588  {
589  TargetEntry *tent = (TargetEntry *) lfirst(lc);
590  Param *param;
591 
592  if (tent->resjunk)
593  continue;
594 
596  exprType((Node *) tent->expr),
597  exprTypmod((Node *) tent->expr),
598  exprCollation((Node *) tent->expr));
599  result = lappend(result, param);
600  ids = lappend_int(ids, param->paramid);
601  }
602 
603  *paramIds = ids;
604  return result;
605 }

References TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), generate_new_exec_param(), lappend(), lappend_int(), lfirst, NIL, Param::paramid, and root.

Referenced by build_subplan().

◆ generate_subquery_vars()

static List * generate_subquery_vars ( PlannerInfo root,
List tlist,
Index  varno 
)
static

Definition at line 613 of file subselect.c.

614 {
615  List *result;
616  ListCell *lc;
617 
618  result = NIL;
619  foreach(lc, tlist)
620  {
621  TargetEntry *tent = (TargetEntry *) lfirst(lc);
622  Var *var;
623 
624  if (tent->resjunk)
625  continue;
626 
627  var = makeVarFromTargetEntry(varno, tent);
628  result = lappend(result, var);
629  }
630 
631  return result;
632 }
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:105
Definition: primnodes.h:248

References lappend(), lfirst, makeVarFromTargetEntry(), and NIL.

Referenced by convert_ANY_sublink_to_join().

◆ get_first_col_type()

static void get_first_col_type ( Plan plan,
Oid coltype,
int32 coltypmod,
Oid colcollation 
)
static

Definition at line 118 of file subselect.c.

120 {
121  /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
122  if (plan->targetlist)
123  {
124  TargetEntry *tent = linitial_node(TargetEntry, plan->targetlist);
125 
126  if (!tent->resjunk)
127  {
128  *coltype = exprType((Node *) tent->expr);
129  *coltypmod = exprTypmod((Node *) tent->expr);
130  *colcollation = exprCollation((Node *) tent->expr);
131  return;
132  }
133  }
134  *coltype = VOIDOID;
135  *coltypmod = -1;
136  *colcollation = InvalidOid;
137 }
#define linitial_node(type, l)
Definition: pg_list.h:181

References TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), InvalidOid, linitial_node, and plan.

Referenced by build_subplan(), SS_make_initplan_from_plan(), and SS_process_ctes().

◆ hash_ok_operator()

static bool hash_ok_operator ( OpExpr expr)
static

Definition at line 830 of file subselect.c.

831 {
832  Oid opid = expr->opno;
833 
834  /* quick out if not a binary operator */
835  if (list_length(expr->args) != 2)
836  return false;
837  if (opid == ARRAY_EQ_OP ||
838  opid == RECORD_EQ_OP)
839  {
840  /* these are strict, but must check input type to ensure hashable */
841  Node *leftarg = linitial(expr->args);
842 
843  return op_hashjoinable(opid, exprType(leftarg));
844  }
845  else
846  {
847  /* else must look up the operator properties */
848  HeapTuple tup;
849  Form_pg_operator optup;
850 
851  tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
852  if (!HeapTupleIsValid(tup))
853  elog(ERROR, "cache lookup failed for operator %u", opid);
854  optup = (Form_pg_operator) GETSTRUCT(tup);
855  if (!optup->oprcanhash || !func_strict(optup->oprcode))
856  {
857  ReleaseSysCache(tup);
858  return false;
859  }
860  ReleaseSysCache(tup);
861  return true;
862  }
863 }
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition: lsyscache.c:1437
bool func_strict(Oid funcid)
Definition: lsyscache.c:1761
FormData_pg_operator * Form_pg_operator
Definition: pg_operator.h:83
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

References OpExpr::args, elog, ERROR, exprType(), func_strict(), GETSTRUCT, HeapTupleIsValid, linitial, list_length(), ObjectIdGetDatum(), op_hashjoinable(), OpExpr::opno, ReleaseSysCache(), and SearchSysCache1().

Referenced by convert_EXISTS_to_ANY(), and test_opexpr_is_hashable().

◆ inline_cte()

static void inline_cte ( PlannerInfo root,
CommonTableExpr cte 
)
static

Definition at line 1135 of file subselect.c.

1136 {
1138 
1139  context.ctename = cte->ctename;
1140  /* Start at levelsup = -1 because we'll immediately increment it */
1141  context.levelsup = -1;
1142  context.ctequery = castNode(Query, cte->ctequery);
1143 
1144  (void) inline_cte_walker((Node *) root->parse, &context);
1145 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
static bool inline_cte_walker(Node *node, inline_cte_walker_context *context)
Definition: subselect.c:1148

References castNode, context, CommonTableExpr::ctename, CommonTableExpr::ctequery, inline_cte_walker(), and root.

Referenced by SS_process_ctes().

◆ inline_cte_walker()

static bool inline_cte_walker ( Node node,
inline_cte_walker_context context 
)
static

Definition at line 1148 of file subselect.c.

1149 {
1150  if (node == NULL)
1151  return false;
1152  if (IsA(node, Query))
1153  {
1154  Query *query = (Query *) node;
1155 
1156  context->levelsup++;
1157 
1158  /*
1159  * Visit the query's RTE nodes after their contents; otherwise
1160  * query_tree_walker would descend into the newly inlined CTE query,
1161  * which we don't want.
1162  */
1165 
1166  context->levelsup--;
1167 
1168  return false;
1169  }
1170  else if (IsA(node, RangeTblEntry))
1171  {
1172  RangeTblEntry *rte = (RangeTblEntry *) node;
1173 
1174  if (rte->rtekind == RTE_CTE &&
1175  strcmp(rte->ctename, context->ctename) == 0 &&
1176  rte->ctelevelsup == context->levelsup)
1177  {
1178  /*
1179  * Found a reference to replace. Generate a copy of the CTE query
1180  * with appropriate level adjustment for outer references (e.g.,
1181  * to other CTEs).
1182  */
1183  Query *newquery = copyObject(context->ctequery);
1184 
1185  if (context->levelsup > 0)
1186  IncrementVarSublevelsUp((Node *) newquery, context->levelsup, 1);
1187 
1188  /*
1189  * Convert the RTE_CTE RTE into a RTE_SUBQUERY.
1190  *
1191  * Historically, a FOR UPDATE clause has been treated as extending
1192  * into views and subqueries, but not into CTEs. We preserve this
1193  * distinction by not trying to push rowmarks into the new
1194  * subquery.
1195  */
1196  rte->rtekind = RTE_SUBQUERY;
1197  rte->subquery = newquery;
1198  rte->security_barrier = false;
1199 
1200  /* Zero out CTE-specific fields */
1201  rte->ctename = NULL;
1202  rte->ctelevelsup = 0;
1203  rte->self_reference = false;
1204  rte->coltypes = NIL;
1205  rte->coltypmods = NIL;
1206  rte->colcollations = NIL;
1207  }
1208 
1209  return false;
1210  }
1211 
1213 }
#define QTW_EXAMINE_RTES_AFTER
Definition: nodeFuncs.h:28
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
char * ctename
Definition: parsenodes.h:1196
Query * subquery
Definition: parsenodes.h:1104

References context, copyObject, RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, expression_tree_walker, IncrementVarSublevelsUp(), IsA, NIL, QTW_EXAMINE_RTES_AFTER, query_tree_walker, RTE_CTE, RTE_SUBQUERY, RangeTblEntry::rtekind, and RangeTblEntry::subquery.

Referenced by inline_cte().

◆ make_subplan()

static Node* make_subplan ( PlannerInfo root,
Query orig_subquery,
SubLinkType  subLinkType,
int  subLinkId,
Node testexpr,
bool  isTopQual 
)
static

Definition at line 162 of file subselect.c.

165 {
166  Query *subquery;
167  bool simple_exists = false;
168  double tuple_fraction;
169  PlannerInfo *subroot;
170  RelOptInfo *final_rel;
171  Path *best_path;
172  Plan *plan;
173  List *plan_params;
174  Node *result;
175 
176  /*
177  * Copy the source Query node. This is a quick and dirty kluge to resolve
178  * the fact that the parser can generate trees with multiple links to the
179  * same sub-Query node, but the planner wants to scribble on the Query.
180  * Try to clean this up when we do querytree redesign...
181  */
182  subquery = copyObject(orig_subquery);
183 
184  /*
185  * If it's an EXISTS subplan, we might be able to simplify it.
186  */
187  if (subLinkType == EXISTS_SUBLINK)
188  simple_exists = simplify_EXISTS_query(root, subquery);
189 
190  /*
191  * For an EXISTS subplan, tell lower-level planner to expect that only the
192  * first tuple will be retrieved. For ALL and ANY subplans, we will be
193  * able to stop evaluating if the test condition fails or matches, so very
194  * often not all the tuples will be retrieved; for lack of a better idea,
195  * specify 50% retrieval. For EXPR, MULTIEXPR, and ROWCOMPARE subplans,
196  * use default behavior (we're only expecting one row out, anyway).
197  *
198  * NOTE: if you change these numbers, also change cost_subplan() in
199  * path/costsize.c.
200  *
201  * XXX If an ANY subplan is uncorrelated, build_subplan may decide to hash
202  * its output. In that case it would've been better to specify full
203  * retrieval. At present, however, we can only check hashability after
204  * we've made the subplan :-(. (Determining whether it'll fit in hash_mem
205  * is the really hard part.) Therefore, we don't want to be too
206  * optimistic about the percentage of tuples retrieved, for fear of
207  * selecting a plan that's bad for the materialization case.
208  */
209  if (subLinkType == EXISTS_SUBLINK)
210  tuple_fraction = 1.0; /* just like a LIMIT 1 */
211  else if (subLinkType == ALL_SUBLINK ||
212  subLinkType == ANY_SUBLINK)
213  tuple_fraction = 0.5; /* 50% */
214  else
215  tuple_fraction = 0.0; /* default behavior */
216 
217  /* plan_params should not be in use in current query level */
218  Assert(root->plan_params == NIL);
219 
220  /* Generate Paths for the subquery */
221  subroot = subquery_planner(root->glob, subquery, root, false,
222  tuple_fraction, NULL);
223 
224  /* Isolate the params needed by this specific subplan */
225  plan_params = root->plan_params;
226  root->plan_params = NIL;
227 
228  /*
229  * Select best Path and turn it into a Plan. At least for now, there
230  * seems no reason to postpone doing that.
231  */
232  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
233  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
234 
235  plan = create_plan(subroot, best_path);
236 
237  /* And convert to SubPlan or InitPlan format. */
238  result = build_subplan(root, plan, best_path,
239  subroot, plan_params,
240  subLinkType, subLinkId,
241  testexpr, NIL, isTopQual);
242 
243  /*
244  * If it's a correlated EXISTS with an unimportant targetlist, we might be
245  * able to transform it to the equivalent of an IN and then implement it
246  * by hashing. We don't have enough information yet to tell which way is
247  * likely to be better (it depends on the expected number of executions of
248  * the EXISTS qual, and we are much too early in planning the outer query
249  * to be able to guess that). So we generate both plans, if possible, and
250  * leave it to setrefs.c to decide which to use.
251  */
252  if (simple_exists && IsA(result, SubPlan))
253  {
254  Node *newtestexpr;
255  List *paramIds;
256 
257  /* Make a second copy of the original subquery */
258  subquery = copyObject(orig_subquery);
259  /* and re-simplify */
260  simple_exists = simplify_EXISTS_query(root, subquery);
261  Assert(simple_exists);
262  /* See if it can be converted to an ANY query */
263  subquery = convert_EXISTS_to_ANY(root, subquery,
264  &newtestexpr, &paramIds);
265  if (subquery)
266  {
267  /* Generate Paths for the ANY subquery; we'll need all rows */
268  subroot = subquery_planner(root->glob, subquery, root, false, 0.0,
269  NULL);
270 
271  /* Isolate the params needed by this specific subplan */
272  plan_params = root->plan_params;
273  root->plan_params = NIL;
274 
275  /* Select best Path */
276  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
277  best_path = final_rel->cheapest_total_path;
278 
279  /* Now we can check if it'll fit in hash_mem */
280  if (subpath_is_hashable(best_path))
281  {
282  SubPlan *hashplan;
283  AlternativeSubPlan *asplan;
284 
285  /* OK, finish planning the ANY subquery */
286  plan = create_plan(subroot, best_path);
287 
288  /* ... and convert to SubPlan format */
289  hashplan = castNode(SubPlan,
290  build_subplan(root, plan, best_path,
291  subroot, plan_params,
292  ANY_SUBLINK, 0,
293  newtestexpr,
294  paramIds,
295  true));
296  /* Check we got what we expected */
297  Assert(hashplan->parParam == NIL);
298  Assert(hashplan->useHashTable);
299 
300  /* Leave it to setrefs.c to decide which plan to use */
301  asplan = makeNode(AlternativeSubPlan);
302  asplan->subplans = list_make2(result, hashplan);
303  result = (Node *) asplan;
304  root->hasAlternativeSubPlans = true;
305  }
306  }
307  }
308 
309  return result;
310 }
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:340
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define list_make2(x1, x2)
Definition: pg_list.h:214
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition: planner.c:640
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:6576
@ ALL_SUBLINK
Definition: primnodes.h:998
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1458
struct Path * cheapest_total_path
Definition: pathnodes.h:902
bool useHashTable
Definition: primnodes.h:1079
static Query * convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds)
Definition: subselect.c:1649
static bool subpath_is_hashable(Path *path)
Definition: subselect.c:734
static Node * build_subplan(PlannerInfo *root, Plan *plan, Path *path, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, List *testexpr_paramids, bool unknownEqFalse)
Definition: subselect.c:319

References ALL_SUBLINK, ANY_SUBLINK, Assert, build_subplan(), castNode, RelOptInfo::cheapest_total_path, convert_EXISTS_to_ANY(), copyObject, create_plan(), EXISTS_SUBLINK, fetch_upper_rel(), get_cheapest_fractional_path(), IsA, list_make2, makeNode, NIL, SubPlan::parParam, plan, root, simplify_EXISTS_query(), subpath_is_hashable(), AlternativeSubPlan::subplans, subquery_planner(), UPPERREL_FINAL, and SubPlan::useHashTable.

Referenced by process_sublinks_mutator().

◆ process_sublinks_mutator()

static Node * process_sublinks_mutator ( Node node,
process_sublinks_context context 
)
static

Definition at line 1948 of file subselect.c.

1949 {
1950  process_sublinks_context locContext;
1951 
1952  locContext.root = context->root;
1953 
1954  if (node == NULL)
1955  return NULL;
1956  if (IsA(node, SubLink))
1957  {
1958  SubLink *sublink = (SubLink *) node;
1959  Node *testexpr;
1960 
1961  /*
1962  * First, recursively process the lefthand-side expressions, if any.
1963  * They're not top-level anymore.
1964  */
1965  locContext.isTopQual = false;
1966  testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
1967 
1968  /*
1969  * Now build the SubPlan node and make the expr to return.
1970  */
1971  return make_subplan(context->root,
1972  (Query *) sublink->subselect,
1973  sublink->subLinkType,
1974  sublink->subLinkId,
1975  testexpr,
1976  context->isTopQual);
1977  }
1978 
1979  /*
1980  * Don't recurse into the arguments of an outer PHV, Aggref or
1981  * GroupingFunc here. Any SubLinks in the arguments have to be dealt with
1982  * at the outer query level; they'll be handled when build_subplan
1983  * collects the PHV, Aggref or GroupingFunc into the arguments to be
1984  * passed down to the current subplan.
1985  */
1986  if (IsA(node, PlaceHolderVar))
1987  {
1988  if (((PlaceHolderVar *) node)->phlevelsup > 0)
1989  return node;
1990  }
1991  else if (IsA(node, Aggref))
1992  {
1993  if (((Aggref *) node)->agglevelsup > 0)
1994  return node;
1995  }
1996  else if (IsA(node, GroupingFunc))
1997  {
1998  if (((GroupingFunc *) node)->agglevelsup > 0)
1999  return node;
2000  }
2001 
2002  /*
2003  * We should never see a SubPlan expression in the input (since this is
2004  * the very routine that creates 'em to begin with). We shouldn't find
2005  * ourselves invoked directly on a Query, either.
2006  */
2007  Assert(!IsA(node, SubPlan));
2008  Assert(!IsA(node, AlternativeSubPlan));
2009  Assert(!IsA(node, Query));
2010 
2011  /*
2012  * Because make_subplan() could return an AND or OR clause, we have to
2013  * take steps to preserve AND/OR flatness of a qual. We assume the input
2014  * has been AND/OR flattened and so we need no recursion here.
2015  *
2016  * (Due to the coding here, we will not get called on the List subnodes of
2017  * an AND; and the input is *not* yet in implicit-AND format. So no check
2018  * is needed for a bare List.)
2019  *
2020  * Anywhere within the top-level AND/OR clause structure, we can tell
2021  * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
2022  * propagates down in both cases. (Note that this is unlike the meaning
2023  * of "top level qual" used in most other places in Postgres.)
2024  */
2025  if (is_andclause(node))
2026  {
2027  List *newargs = NIL;
2028  ListCell *l;
2029 
2030  /* Still at qual top-level */
2031  locContext.isTopQual = context->isTopQual;
2032 
2033  foreach(l, ((BoolExpr *) node)->args)
2034  {
2035  Node *newarg;
2036 
2037  newarg = process_sublinks_mutator(lfirst(l), &locContext);
2038  if (is_andclause(newarg))
2039  newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2040  else
2041  newargs = lappend(newargs, newarg);
2042  }
2043  return (Node *) make_andclause(newargs);
2044  }
2045 
2046  if (is_orclause(node))
2047  {
2048  List *newargs = NIL;
2049  ListCell *l;
2050 
2051  /* Still at qual top-level */
2052  locContext.isTopQual = context->isTopQual;
2053 
2054  foreach(l, ((BoolExpr *) node)->args)
2055  {
2056  Node *newarg;
2057 
2058  newarg = process_sublinks_mutator(lfirst(l), &locContext);
2059  if (is_orclause(newarg))
2060  newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2061  else
2062  newargs = lappend(newargs, newarg);
2063  }
2064  return (Node *) make_orclause(newargs);
2065  }
2066 
2067  /*
2068  * If we recurse down through anything other than an AND or OR node, we
2069  * are definitely not at top qual level anymore.
2070  */
2071  locContext.isTopQual = false;
2072 
2073  return expression_tree_mutator(node,
2075  &locContext);
2076 }
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:677
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:693
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:107
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:116
static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context)
Definition: subselect.c:1948
static Node * make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual)
Definition: subselect.c:162

References generate_unaccent_rules::args, Assert, context, expression_tree_mutator, is_andclause(), is_orclause(), IsA, process_sublinks_context::isTopQual, lappend(), lfirst, list_concat(), make_andclause(), make_orclause(), make_subplan(), NIL, process_sublinks_context::root, SubLink::subLinkId, SubLink::subLinkType, SubLink::subselect, and SubLink::testexpr.

Referenced by SS_process_sublinks().

◆ replace_correlation_vars_mutator()

static Node * replace_correlation_vars_mutator ( Node node,
PlannerInfo root 
)
static

Definition at line 1896 of file subselect.c.

1897 {
1898  if (node == NULL)
1899  return NULL;
1900  if (IsA(node, Var))
1901  {
1902  if (((Var *) node)->varlevelsup > 0)
1903  return (Node *) replace_outer_var(root, (Var *) node);
1904  }
1905  if (IsA(node, PlaceHolderVar))
1906  {
1907  if (((PlaceHolderVar *) node)->phlevelsup > 0)
1909  (PlaceHolderVar *) node);
1910  }
1911  if (IsA(node, Aggref))
1912  {
1913  if (((Aggref *) node)->agglevelsup > 0)
1914  return (Node *) replace_outer_agg(root, (Aggref *) node);
1915  }
1916  if (IsA(node, GroupingFunc))
1917  {
1918  if (((GroupingFunc *) node)->agglevelsup > 0)
1919  return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
1920  }
1921  if (IsA(node, MergeSupportFunc))
1922  {
1923  if (root->parse->commandType != CMD_MERGE)
1925  (MergeSupportFunc *) node);
1926  }
1928 }
@ CMD_MERGE
Definition: nodes.h:269
Param * replace_outer_var(PlannerInfo *root, Var *var)
Definition: paramassign.c:120
Param * replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp)
Definition: paramassign.c:270
Param * replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
Definition: paramassign.c:197
Param * replace_outer_merge_support(PlannerInfo *root, MergeSupportFunc *msf)
Definition: paramassign.c:317
Param * replace_outer_agg(PlannerInfo *root, Aggref *agg)
Definition: paramassign.c:224
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1896

References CMD_MERGE, expression_tree_mutator, IsA, replace_outer_agg(), replace_outer_grouping(), replace_outer_merge_support(), replace_outer_placeholdervar(), replace_outer_var(), and root.

Referenced by SS_replace_correlation_vars().

◆ simplify_EXISTS_query()

static bool simplify_EXISTS_query ( PlannerInfo root,
Query query 
)
static

Definition at line 1537 of file subselect.c.

1538 {
1539  ListCell *lc;
1540 
1541  /*
1542  * We don't try to simplify at all if the query uses set operations,
1543  * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1544  * UPDATE/SHARE; none of these seem likely in normal usage and their
1545  * possible effects are complex. (Note: we could ignore an "OFFSET 0"
1546  * clause, but that traditionally is used as an optimization fence, so we
1547  * don't.)
1548  */
1549  if (query->commandType != CMD_SELECT ||
1550  query->setOperations ||
1551  query->hasAggs ||
1552  query->groupingSets ||
1553  query->hasWindowFuncs ||
1554  query->hasTargetSRFs ||
1555  query->hasModifyingCTE ||
1556  query->havingQual ||
1557  query->limitOffset ||
1558  query->rowMarks)
1559  return false;
1560 
1561  /*
1562  * LIMIT with a constant positive (or NULL) value doesn't affect the
1563  * semantics of EXISTS, so let's ignore such clauses. This is worth doing
1564  * because people accustomed to certain other DBMSes may be in the habit
1565  * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a
1566  * LIMIT with anything else as argument, though, we can't simplify.
1567  */
1568  if (query->limitCount)
1569  {
1570  /*
1571  * The LIMIT clause has not yet been through eval_const_expressions,
1572  * so we have to apply that here. It might seem like this is a waste
1573  * of cycles, since the only case plausibly worth worrying about is
1574  * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1575  * so we have to fold constants or we're not going to recognize it.
1576  */
1577  Node *node = eval_const_expressions(root, query->limitCount);
1578  Const *limit;
1579 
1580  /* Might as well update the query if we simplified the clause. */
1581  query->limitCount = node;
1582 
1583  if (!IsA(node, Const))
1584  return false;
1585 
1586  limit = (Const *) node;
1587  Assert(limit->consttype == INT8OID);
1588  if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1589  return false;
1590 
1591  /* Whether or not the targetlist is safe, we can drop the LIMIT. */
1592  query->limitCount = NULL;
1593  }
1594 
1595  /*
1596  * Otherwise, we can throw away the targetlist, as well as any GROUP,
1597  * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1598  * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1599  * since our parsetree representation of these clauses depends on the
1600  * targetlist, we'd better throw them away if we drop the targetlist.)
1601  */
1602  query->targetList = NIL;
1603  query->groupClause = NIL;
1604  query->windowClause = NIL;
1605  query->distinctClause = NIL;
1606  query->sortClause = NIL;
1607  query->hasDistinctOn = false;
1608 
1609  /*
1610  * Since we have thrown away the GROUP BY clauses, we'd better remove the
1611  * RTE_GROUP RTE and clear the hasGroupRTE flag.
1612  */
1613  foreach(lc, query->rtable)
1614  {
1616 
1617  /*
1618  * Remove the RTE_GROUP RTE and clear the hasGroupRTE flag. (Since
1619  * we'll exit the foreach loop immediately, we don't bother with
1620  * foreach_delete_current.)
1621  */
1622  if (rte->rtekind == RTE_GROUP)
1623  {
1624  Assert(query->hasGroupRTE);
1625  query->rtable = list_delete_cell(query->rtable, lc);
1626  query->hasGroupRTE = false;
1627  break;
1628  }
1629  }
1630 
1631  return true;
1632 }
List * list_delete_cell(List *list, ListCell *cell)
Definition: list.c:841
@ RTE_GROUP
Definition: parsenodes.h:1028
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385
Oid consttype
Definition: primnodes.h:312
Node * limitCount
Definition: parsenodes.h:216
Node * setOperations
Definition: parsenodes.h:221
List * groupClause
Definition: parsenodes.h:202
Node * havingQual
Definition: parsenodes.h:207
List * rtable
Definition: parsenodes.h:170
Node * limitOffset
Definition: parsenodes.h:215
List * windowClause
Definition: parsenodes.h:209
List * groupingSets
Definition: parsenodes.h:205
List * distinctClause
Definition: parsenodes.h:211
List * sortClause
Definition: parsenodes.h:213

References Assert, CMD_SELECT, Query::commandType, Const::consttype, DatumGetInt64(), Query::distinctClause, eval_const_expressions(), Query::groupClause, Query::groupingSets, Query::havingQual, IsA, lfirst_node, Query::limitCount, Query::limitOffset, list_delete_cell(), NIL, root, Query::rowMarks, Query::rtable, RTE_GROUP, RangeTblEntry::rtekind, Query::setOperations, Query::sortClause, Query::targetList, and Query::windowClause.

Referenced by convert_EXISTS_sublink_to_join(), and make_subplan().

◆ SS_attach_initplans()

void SS_attach_initplans ( PlannerInfo root,
Plan plan 
)

Definition at line 2258 of file subselect.c.

2259 {
2260  plan->initPlan = root->init_plans;
2261 }

References plan, and root.

Referenced by create_plan().

◆ SS_charge_for_initplans()

void SS_charge_for_initplans ( PlannerInfo root,
RelOptInfo final_rel 
)

Definition at line 2153 of file subselect.c.

2154 {
2155  Cost initplan_cost;
2156  bool unsafe_initplans;
2157  ListCell *lc;
2158 
2159  /* Nothing to do if no initPlans */
2160  if (root->init_plans == NIL)
2161  return;
2162 
2163  /*
2164  * Compute the cost increment just once, since it will be the same for all
2165  * Paths. Also check for parallel-unsafe initPlans.
2166  */
2167  SS_compute_initplan_cost(root->init_plans,
2168  &initplan_cost, &unsafe_initplans);
2169 
2170  /*
2171  * Now adjust the costs and parallel_safe flags.
2172  */
2173  foreach(lc, final_rel->pathlist)
2174  {
2175  Path *path = (Path *) lfirst(lc);
2176 
2177  path->startup_cost += initplan_cost;
2178  path->total_cost += initplan_cost;
2179  if (unsafe_initplans)
2180  path->parallel_safe = false;
2181  }
2182 
2183  /*
2184  * Adjust partial paths' costs too, or forget them entirely if we must
2185  * consider the rel parallel-unsafe.
2186  */
2187  if (unsafe_initplans)
2188  {
2189  final_rel->partial_pathlist = NIL;
2190  final_rel->consider_parallel = false;
2191  }
2192  else
2193  {
2194  foreach(lc, final_rel->partial_pathlist)
2195  {
2196  Path *path = (Path *) lfirst(lc);
2197 
2198  path->startup_cost += initplan_cost;
2199  path->total_cost += initplan_cost;
2200  }
2201  }
2202 
2203  /* We needn't do set_cheapest() here, caller will do it */
2204 }
double Cost
Definition: nodes.h:251
Cost startup_cost
Definition: pathnodes.h:1671
Cost total_cost
Definition: pathnodes.h:1672
bool parallel_safe
Definition: pathnodes.h:1664
bool consider_parallel
Definition: pathnodes.h:887
List * pathlist
Definition: pathnodes.h:898
List * partial_pathlist
Definition: pathnodes.h:900
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2217

References RelOptInfo::consider_parallel, lfirst, NIL, Path::parallel_safe, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, root, SS_compute_initplan_cost(), Path::startup_cost, and Path::total_cost.

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_compute_initplan_cost()

void SS_compute_initplan_cost ( List init_plans,
Cost initplan_cost_p,
bool *  unsafe_initplans_p 
)

Definition at line 2217 of file subselect.c.

2220 {
2221  Cost initplan_cost;
2222  bool unsafe_initplans;
2223  ListCell *lc;
2224 
2225  /*
2226  * We assume each initPlan gets run once during top plan startup. This is
2227  * a conservative overestimate, since in fact an initPlan might be
2228  * executed later than plan startup, or even not at all.
2229  */
2230  initplan_cost = 0;
2231  unsafe_initplans = false;
2232  foreach(lc, init_plans)
2233  {
2234  SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2235 
2236  initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2237  if (!initsubplan->parallel_safe)
2238  unsafe_initplans = true;
2239  }
2240  *initplan_cost_p = initplan_cost;
2241  *unsafe_initplans_p = unsafe_initplans;
2242 }
bool parallel_safe
Definition: primnodes.h:1084
Cost startup_cost
Definition: primnodes.h:1093
Cost per_call_cost
Definition: primnodes.h:1094

References lfirst_node, SubPlan::parallel_safe, SubPlan::per_call_cost, and SubPlan::startup_cost.

Referenced by clean_up_removed_plan_level(), materialize_finished_plan(), SS_charge_for_initplans(), and standard_planner().

◆ SS_finalize_plan()

void SS_finalize_plan ( PlannerInfo root,
Plan plan 
)

Definition at line 2273 of file subselect.c.

2274 {
2275  /* No setup needed, just recurse through plan tree. */
2276  (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2277 }

References finalize_plan(), plan, and root.

Referenced by standard_planner().

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2091 of file subselect.c.

2092 {
2093  Bitmapset *outer_params;
2094  PlannerInfo *proot;
2095  ListCell *l;
2096 
2097  /*
2098  * If no parameters have been assigned anywhere in the tree, we certainly
2099  * don't need to do anything here.
2100  */
2101  if (root->glob->paramExecTypes == NIL)
2102  return;
2103 
2104  /*
2105  * Scan all query levels above this one to see which parameters are due to
2106  * be available from them, either because lower query levels have
2107  * requested them (via plan_params) or because they will be available from
2108  * initPlans of those levels.
2109  */
2110  outer_params = NULL;
2111  for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2112  {
2113  /* Include ordinary Var/PHV/Aggref/GroupingFunc params */
2114  foreach(l, proot->plan_params)
2115  {
2116  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(l);
2117 
2118  outer_params = bms_add_member(outer_params, pitem->paramId);
2119  }
2120  /* Include any outputs of outer-level initPlans */
2121  foreach(l, proot->init_plans)
2122  {
2123  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2124  ListCell *l2;
2125 
2126  foreach(l2, initsubplan->setParam)
2127  {
2128  outer_params = bms_add_member(outer_params, lfirst_int(l2));
2129  }
2130  }
2131  /* Include worktable ID, if a recursive query is being planned */
2132  if (proot->wt_param_id >= 0)
2133  outer_params = bms_add_member(outer_params, proot->wt_param_id);
2134  }
2135  root->outer_params = outer_params;
2136 }
List * init_plans
Definition: pathnodes.h:299
int wt_param_id
Definition: pathnodes.h:536
List * plan_params
Definition: pathnodes.h:220

References bms_add_member(), PlannerInfo::init_plans, lfirst, lfirst_int, NIL, PlannerParamItem::paramId, PlannerInfo::plan_params, root, SubPlan::setParam, and PlannerInfo::wt_param_id.

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_make_initplan_from_plan()

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

Definition at line 3034 of file subselect.c.

3037 {
3038  SubPlan *node;
3039 
3040  /*
3041  * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3042  * the global lists. Ideally we'd save a real path, but right now our
3043  * sole caller doesn't build a path that exactly matches the plan. Since
3044  * we're not currently going to need the path for an initplan, it's not
3045  * worth requiring construction of such a path.
3046  */
3047  root->glob->subplans = lappend(root->glob->subplans, plan);
3048  root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3049  root->glob->subroots = lappend(root->glob->subroots, subroot);
3050 
3051  /*
3052  * Create a SubPlan node and add it to the outer list of InitPlans. Note
3053  * it has to appear after any other InitPlans it might depend on (see
3054  * comments in ExecReScan).
3055  */
3056  node = makeNode(SubPlan);
3057  node->subLinkType = EXPR_SUBLINK;
3058  node->plan_id = list_length(root->glob->subplans);
3059  node->plan_name = psprintf("InitPlan %d", node->plan_id);
3061  &node->firstColCollation);
3062  node->parallel_safe = plan->parallel_safe;
3063  node->setParam = list_make1_int(prm->paramid);
3064 
3065  root->init_plans = lappend(root->init_plans, node);
3066 
3067  /*
3068  * The node can't have any inputs (since it's an initplan), so the
3069  * parParam and args lists remain empty.
3070  */
3071 
3072  /* Set costs of SubPlan using info from the plan tree */
3073  cost_subplan(subroot, node, plan);
3074 }
int plan_id
Definition: primnodes.h:1070
char * plan_name
Definition: primnodes.h:1072
int32 firstColTypmod
Definition: primnodes.h:1075
Oid firstColCollation
Definition: primnodes.h:1076
SubLinkType subLinkType
Definition: primnodes.h:1065
Oid firstColType
Definition: primnodes.h:1074

References cost_subplan(), EXPR_SUBLINK, SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), lappend(), list_length(), list_make1_int, makeNode, SubPlan::parallel_safe, Param::paramid, plan, SubPlan::plan_id, SubPlan::plan_name, psprintf(), root, SubPlan::setParam, and SubPlan::subLinkType.

Referenced by create_minmaxagg_plan().

◆ SS_make_initplan_output_param()

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

Definition at line 3018 of file subselect.c.

3021 {
3022  return generate_new_exec_param(root, resulttype,
3023  resulttypmod, resultcollation);
3024 }

References generate_new_exec_param(), and root.

Referenced by preprocess_minmax_aggregates().

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 878 of file subselect.c.

879 {
880  ListCell *lc;
881 
882  Assert(root->cte_plan_ids == NIL);
883 
884  foreach(lc, root->parse->cteList)
885  {
886  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
887  CmdType cmdType = ((Query *) cte->ctequery)->commandType;
888  Query *subquery;
889  PlannerInfo *subroot;
890  RelOptInfo *final_rel;
891  Path *best_path;
892  Plan *plan;
893  SubPlan *splan;
894  int paramid;
895 
896  /*
897  * Ignore SELECT CTEs that are not actually referenced anywhere.
898  */
899  if (cte->cterefcount == 0 && cmdType == CMD_SELECT)
900  {
901  /* Make a dummy entry in cte_plan_ids */
902  root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
903  continue;
904  }
905 
906  /*
907  * Consider inlining the CTE (creating RTE_SUBQUERY RTE(s)) instead of
908  * implementing it as a separately-planned CTE.
909  *
910  * We cannot inline if any of these conditions hold:
911  *
912  * 1. The user said not to (the CTEMaterializeAlways option).
913  *
914  * 2. The CTE is recursive.
915  *
916  * 3. The CTE has side-effects; this includes either not being a plain
917  * SELECT, or containing volatile functions. Inlining might change
918  * the side-effects, which would be bad.
919  *
920  * 4. The CTE is multiply-referenced and contains a self-reference to
921  * a recursive CTE outside itself. Inlining would result in multiple
922  * recursive self-references, which we don't support.
923  *
924  * Otherwise, we have an option whether to inline or not. That should
925  * always be a win if there's just a single reference, but if the CTE
926  * is multiply-referenced then it's unclear: inlining adds duplicate
927  * computations, but the ability to absorb restrictions from the outer
928  * query level could outweigh that. We do not have nearly enough
929  * information at this point to tell whether that's true, so we let
930  * the user express a preference. Our default behavior is to inline
931  * only singly-referenced CTEs, but a CTE marked CTEMaterializeNever
932  * will be inlined even if multiply referenced.
933  *
934  * Note: we check for volatile functions last, because that's more
935  * expensive than the other tests needed.
936  */
937  if ((cte->ctematerialized == CTEMaterializeNever ||
939  cte->cterefcount == 1)) &&
940  !cte->cterecursive &&
941  cmdType == CMD_SELECT &&
942  !contain_dml(cte->ctequery) &&
943  (cte->cterefcount <= 1 ||
946  {
947  inline_cte(root, cte);
948  /* Make a dummy entry in cte_plan_ids */
949  root->cte_plan_ids = lappend_int(root->cte_plan_ids, -1);
950  continue;
951  }
952 
953  /*
954  * Copy the source Query node. Probably not necessary, but let's keep
955  * this similar to make_subplan.
956  */
957  subquery = (Query *) copyObject(cte->ctequery);
958 
959  /* plan_params should not be in use in current query level */
960  Assert(root->plan_params == NIL);
961 
962  /*
963  * Generate Paths for the CTE query. Always plan for full retrieval
964  * --- we don't have enough info to predict otherwise.
965  */
966  subroot = subquery_planner(root->glob, subquery, root,
967  cte->cterecursive, 0.0, NULL);
968 
969  /*
970  * Since the current query level doesn't yet contain any RTEs, it
971  * should not be possible for the CTE to have requested parameters of
972  * this level.
973  */
974  if (root->plan_params)
975  elog(ERROR, "unexpected outer reference in CTE query");
976 
977  /*
978  * Select best Path and turn it into a Plan. At least for now, there
979  * seems no reason to postpone doing that.
980  */
981  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
982  best_path = final_rel->cheapest_total_path;
983 
984  plan = create_plan(subroot, best_path);
985 
986  /*
987  * Make a SubPlan node for it. This is just enough unlike
988  * build_subplan that we can't share code.
989  *
990  * Note plan_id, plan_name, and cost fields are set further down.
991  */
993  splan->subLinkType = CTE_SUBLINK;
994  splan->testexpr = NULL;
995  splan->paramIds = NIL;
996  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
997  &splan->firstColCollation);
998  splan->useHashTable = false;
999  splan->unknownEqFalse = false;
1000 
1001  /*
1002  * CTE scans are not considered for parallelism (cf
1003  * set_rel_consider_parallel).
1004  */
1005  splan->parallel_safe = false;
1006  splan->setParam = NIL;
1007  splan->parParam = NIL;
1008  splan->args = NIL;
1009 
1010  /*
1011  * The node can't have any inputs (since it's an initplan), so the
1012  * parParam and args lists remain empty. (It could contain references
1013  * to earlier CTEs' output param IDs, but CTE outputs are not
1014  * propagated via the args list.)
1015  */
1016 
1017  /*
1018  * Assign a param ID to represent the CTE's output. No ordinary
1019  * "evaluation" of this param slot ever happens, but we use the param
1020  * ID for setParam/chgParam signaling just as if the CTE plan were
1021  * returning a simple scalar output. (Also, the executor abuses the
1022  * ParamExecData slot for this param ID for communication among
1023  * multiple CteScan nodes that might be scanning this CTE.)
1024  */
1025  paramid = assign_special_exec_param(root);
1026  splan->setParam = list_make1_int(paramid);
1027 
1028  /*
1029  * Add the subplan, its path, and its PlannerInfo to the global lists.
1030  */
1031  root->glob->subplans = lappend(root->glob->subplans, plan);
1032  root->glob->subpaths = lappend(root->glob->subpaths, best_path);
1033  root->glob->subroots = lappend(root->glob->subroots, subroot);
1034  splan->plan_id = list_length(root->glob->subplans);
1035 
1036  root->init_plans = lappend(root->init_plans, splan);
1037 
1038  root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
1039 
1040  /* Label the subplan for EXPLAIN purposes */
1041  splan->plan_name = psprintf("CTE %s", cte->ctename);
1042 
1043  /* Lastly, fill in the cost estimates for use later */
1045  }
1046 }
CmdType
Definition: nodes.h:263
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:664
@ CTEMaterializeNever
Definition: parsenodes.h:1640
@ CTEMaterializeDefault
Definition: parsenodes.h:1638
@ CTE_SUBLINK
Definition: primnodes.h:1004
CTEMaterialize ctematerialized
Definition: parsenodes.h:1679
static bool contain_outer_selfref(Node *node)
Definition: subselect.c:1081
static bool contain_dml(Node *node)
Definition: subselect.c:1054
static void inline_cte(PlannerInfo *root, CommonTableExpr *cte)
Definition: subselect.c:1135

References Assert, assign_special_exec_param(), RelOptInfo::cheapest_total_path, CMD_SELECT, contain_dml(), contain_outer_selfref(), contain_volatile_functions(), copyObject, cost_subplan(), create_plan(), CTE_SUBLINK, CommonTableExpr::ctematerialized, CTEMaterializeDefault, CTEMaterializeNever, CommonTableExpr::ctename, CommonTableExpr::ctequery, elog, ERROR, fetch_upper_rel(), get_first_col_type(), inline_cte(), lappend(), lappend_int(), lfirst, list_length(), list_make1_int, makeNode, NIL, plan, psprintf(), root, splan, subquery_planner(), and UPPERREL_FINAL.

Referenced by subquery_planner().

◆ SS_process_sublinks()

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

Definition at line 1938 of file subselect.c.

1939 {
1941 
1942  context.root = root;
1943  context.isTopQual = isQual;
1944  return process_sublinks_mutator(expr, &context);
1945 }

References context, process_sublinks_mutator(), and root.

Referenced by build_subplan(), and preprocess_expression().

◆ SS_replace_correlation_vars()

Node* SS_replace_correlation_vars ( PlannerInfo root,
Node expr 
)

Definition at line 1889 of file subselect.c.

1890 {
1891  /* No setup needed for tree walk, so away we go */
1892  return replace_correlation_vars_mutator(expr, root);
1893 }

References replace_correlation_vars_mutator(), and root.

Referenced by preprocess_expression().

◆ subpath_is_hashable()

static bool subpath_is_hashable ( Path path)
static

Definition at line 734 of file subselect.c.

735 {
736  double subquery_size;
737 
738  /*
739  * The estimated size of the subquery result must fit in hash_mem. (Note:
740  * we use heap tuple overhead here even though the tuples will actually be
741  * stored as MinimalTuples; this provides some fudge factor for hashtable
742  * overhead.)
743  */
744  subquery_size = path->rows *
745  (MAXALIGN(path->pathtarget->width) + MAXALIGN(SizeofHeapTupleHeader));
746  if (subquery_size > get_hash_memory_limit())
747  return false;
748 
749  return true;
750 }
#define MAXALIGN(LEN)
Definition: c.h:790
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3487
Cardinality rows
Definition: pathnodes.h:1669

References get_hash_memory_limit(), MAXALIGN, Path::rows, and SizeofHeapTupleHeader.

Referenced by make_subplan().

◆ subplan_is_hashable()

static bool subplan_is_hashable ( Plan plan)
static

Definition at line 710 of file subselect.c.

711 {
712  double subquery_size;
713 
714  /*
715  * The estimated size of the subquery result must fit in hash_mem. (Note:
716  * we use heap tuple overhead here even though the tuples will actually be
717  * stored as MinimalTuples; this provides some fudge factor for hashtable
718  * overhead.)
719  */
720  subquery_size = plan->plan_rows *
721  (MAXALIGN(plan->plan_width) + MAXALIGN(SizeofHeapTupleHeader));
722  if (subquery_size > get_hash_memory_limit())
723  return false;
724 
725  return true;
726 }

References get_hash_memory_limit(), MAXALIGN, plan, and SizeofHeapTupleHeader.

Referenced by build_subplan().

◆ test_opexpr_is_hashable()

static bool test_opexpr_is_hashable ( OpExpr testexpr,
List param_ids 
)
static

Definition at line 790 of file subselect.c.

791 {
792  /*
793  * The combining operator must be hashable and strict. The need for
794  * hashability is obvious, since we want to use hashing. Without
795  * strictness, behavior in the presence of nulls is too unpredictable. We
796  * actually must assume even more than plain strictness: it can't yield
797  * NULL for non-null inputs, either (see nodeSubplan.c). However, hash
798  * indexes and hash joins assume that too.
799  */
800  if (!hash_ok_operator(testexpr))
801  return false;
802 
803  /*
804  * The left and right inputs must belong to the outer and inner queries
805  * respectively; hence Params that will be supplied by the subquery must
806  * not appear in the LHS, and Vars of the outer query must not appear in
807  * the RHS. (Ordinarily, this must be true because of the way that the
808  * parser builds an ANY SubLink's testexpr ... but inlining of functions
809  * could have changed the expression's structure, so we have to check.
810  * Such cases do not occur often enough to be worth trying to optimize, so
811  * we don't worry about trying to commute the clause or anything like
812  * that; we just need to be sure not to build an invalid plan.)
813  */
814  if (list_length(testexpr->args) != 2)
815  return false;
816  if (contain_exec_param((Node *) linitial(testexpr->args), param_ids))
817  return false;
818  if (contain_var_clause((Node *) lsecond(testexpr->args)))
819  return false;
820  return true;
821 }
bool contain_exec_param(Node *clause, List *param_ids)
Definition: clauses.c:1136
bool contain_var_clause(Node *node)
Definition: var.c:405

References OpExpr::args, contain_exec_param(), contain_var_clause(), hash_ok_operator(), linitial, list_length(), and lsecond.

Referenced by testexpr_is_hashable().

◆ testexpr_is_hashable()

static bool testexpr_is_hashable ( Node testexpr,
List param_ids 
)
static

Definition at line 759 of file subselect.c.

760 {
761  /*
762  * The testexpr must be a single OpExpr, or an AND-clause containing only
763  * OpExprs, each of which satisfy test_opexpr_is_hashable().
764  */
765  if (testexpr && IsA(testexpr, OpExpr))
766  {
767  if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
768  return true;
769  }
770  else if (is_andclause(testexpr))
771  {
772  ListCell *l;
773 
774  foreach(l, ((BoolExpr *) testexpr)->args)
775  {
776  Node *andarg = (Node *) lfirst(l);
777 
778  if (!IsA(andarg, OpExpr))
779  return false;
780  if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
781  return false;
782  }
783  return true;
784  }
785 
786  return false;
787 }
static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
Definition: subselect.c:790

References generate_unaccent_rules::args, is_andclause(), IsA, lfirst, and test_opexpr_is_hashable().

Referenced by build_subplan().