PostgreSQL Source Code  git master
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, 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,
PlannerInfo subroot,
List plan_params,
SubLinkType  subLinkType,
int  subLinkId,
Node testexpr,
List testexpr_paramids,
bool  unknownEqFalse 
)
static

Definition at line 320 of file subselect.c.

325 {
326  Node *result;
327  SubPlan *splan;
328  bool isInitPlan;
329  ListCell *lc;
330 
331  /*
332  * Initialize the SubPlan node. Note plan_id, plan_name, and cost fields
333  * are set further down.
334  */
336  splan->subLinkType = subLinkType;
337  splan->testexpr = NULL;
338  splan->paramIds = NIL;
339  get_first_col_type(plan, &splan->firstColType, &splan->firstColTypmod,
340  &splan->firstColCollation);
341  splan->useHashTable = false;
342  splan->unknownEqFalse = unknownEqFalse;
343  splan->parallel_safe = plan->parallel_safe;
344  splan->setParam = NIL;
345  splan->parParam = NIL;
346  splan->args = NIL;
347 
348  /*
349  * Make parParam and args lists of param IDs and expressions that current
350  * query level will pass to this child plan.
351  */
352  foreach(lc, plan_params)
353  {
354  PlannerParamItem *pitem = (PlannerParamItem *) lfirst(lc);
355  Node *arg = pitem->item;
356 
357  /*
358  * The Var, PlaceHolderVar, Aggref or GroupingFunc has already been
359  * adjusted to have the correct varlevelsup, phlevelsup, or
360  * agglevelsup.
361  *
362  * If it's a PlaceHolderVar, Aggref or GroupingFunc, its arguments
363  * might contain SubLinks, which have not yet been processed (see the
364  * comments for SS_replace_correlation_vars). Do that now.
365  */
366  if (IsA(arg, PlaceHolderVar) ||
367  IsA(arg, Aggref) ||
368  IsA(arg, GroupingFunc))
369  arg = SS_process_sublinks(root, arg, false);
370 
371  splan->parParam = lappend_int(splan->parParam, pitem->paramId);
372  splan->args = lappend(splan->args, arg);
373  }
374 
375  /*
376  * Un-correlated or undirect correlated plans of EXISTS, EXPR, ARRAY,
377  * ROWCOMPARE, or MULTIEXPR types can be used as initPlans. For EXISTS,
378  * EXPR, or ARRAY, we return a Param referring to the result of evaluating
379  * the initPlan. For ROWCOMPARE, we must modify the testexpr tree to
380  * contain PARAM_EXEC Params instead of the PARAM_SUBLINK Params emitted
381  * by the parser, and then return that tree. For MULTIEXPR, we return a
382  * null constant: the resjunk targetlist item containing the SubLink does
383  * not need to return anything useful, since the referencing Params are
384  * elsewhere.
385  */
386  if (splan->parParam == NIL && subLinkType == EXISTS_SUBLINK)
387  {
388  Param *prm;
389 
390  Assert(testexpr == NULL);
391  prm = generate_new_exec_param(root, BOOLOID, -1, InvalidOid);
392  splan->setParam = list_make1_int(prm->paramid);
393  isInitPlan = true;
394  result = (Node *) prm;
395  }
396  else if (splan->parParam == NIL && subLinkType == EXPR_SUBLINK)
397  {
398  TargetEntry *te = linitial(plan->targetlist);
399  Param *prm;
400 
401  Assert(!te->resjunk);
402  Assert(testexpr == NULL);
403  prm = generate_new_exec_param(root,
404  exprType((Node *) te->expr),
405  exprTypmod((Node *) te->expr),
406  exprCollation((Node *) te->expr));
407  splan->setParam = list_make1_int(prm->paramid);
408  isInitPlan = true;
409  result = (Node *) prm;
410  }
411  else if (splan->parParam == NIL && subLinkType == ARRAY_SUBLINK)
412  {
413  TargetEntry *te = linitial(plan->targetlist);
414  Oid arraytype;
415  Param *prm;
416 
417  Assert(!te->resjunk);
418  Assert(testexpr == NULL);
419  arraytype = get_promoted_array_type(exprType((Node *) te->expr));
420  if (!OidIsValid(arraytype))
421  elog(ERROR, "could not find array type for datatype %s",
422  format_type_be(exprType((Node *) te->expr)));
423  prm = generate_new_exec_param(root,
424  arraytype,
425  exprTypmod((Node *) te->expr),
426  exprCollation((Node *) te->expr));
427  splan->setParam = list_make1_int(prm->paramid);
428  isInitPlan = true;
429  result = (Node *) prm;
430  }
431  else if (splan->parParam == NIL && subLinkType == ROWCOMPARE_SUBLINK)
432  {
433  /* Adjust the Params */
434  List *params;
435 
436  Assert(testexpr != NULL);
437  params = generate_subquery_params(root,
438  plan->targetlist,
439  &splan->paramIds);
440  result = convert_testexpr(root,
441  testexpr,
442  params);
443  splan->setParam = list_copy(splan->paramIds);
444  isInitPlan = true;
445 
446  /*
447  * The executable expression is returned to become part of the outer
448  * plan's expression tree; it is not kept in the initplan node.
449  */
450  }
451  else if (subLinkType == MULTIEXPR_SUBLINK)
452  {
453  /*
454  * Whether it's an initplan or not, it needs to set a PARAM_EXEC Param
455  * for each output column.
456  */
457  List *params;
458 
459  Assert(testexpr == NULL);
460  params = generate_subquery_params(root,
461  plan->targetlist,
462  &splan->setParam);
463 
464  /*
465  * Save the list of replacement Params in the n'th cell of
466  * root->multiexpr_params; setrefs.c will use it to replace
467  * PARAM_MULTIEXPR Params.
468  */
469  while (list_length(root->multiexpr_params) < subLinkId)
471  lc = list_nth_cell(root->multiexpr_params, subLinkId - 1);
472  Assert(lfirst(lc) == NIL);
473  lfirst(lc) = params;
474 
475  /* It can be an initplan if there are no parParams. */
476  if (splan->parParam == NIL)
477  {
478  isInitPlan = true;
479  result = (Node *) makeNullConst(RECORDOID, -1, InvalidOid);
480  }
481  else
482  {
483  isInitPlan = false;
484  result = (Node *) splan;
485  }
486  }
487  else
488  {
489  /*
490  * Adjust the Params in the testexpr, unless caller already took care
491  * of it (as indicated by passing a list of Param IDs).
492  */
493  if (testexpr && testexpr_paramids == NIL)
494  {
495  List *params;
496 
497  params = generate_subquery_params(root,
498  plan->targetlist,
499  &splan->paramIds);
500  splan->testexpr = convert_testexpr(root,
501  testexpr,
502  params);
503  }
504  else
505  {
506  splan->testexpr = testexpr;
507  splan->paramIds = testexpr_paramids;
508  }
509 
510  /*
511  * We can't convert subplans of ALL_SUBLINK or ANY_SUBLINK types to
512  * initPlans, even when they are uncorrelated or undirect correlated,
513  * because we need to scan the output of the subplan for each outer
514  * tuple. But if it's a not-direct-correlated IN (= ANY) test, we
515  * might be able to use a hashtable to avoid comparing all the tuples.
516  */
517  if (subLinkType == ANY_SUBLINK &&
518  splan->parParam == NIL &&
520  testexpr_is_hashable(splan->testexpr, splan->paramIds))
521  splan->useHashTable = true;
522 
523  /*
524  * Otherwise, we have the option to tack a Material node onto the top
525  * of the subplan, to reduce the cost of reading it repeatedly. This
526  * is pointless for a direct-correlated subplan, since we'd have to
527  * recompute its results each time anyway. For uncorrelated/undirect
528  * correlated subplans, we add Material unless the subplan's top plan
529  * node would materialize its output anyway. Also, if enable_material
530  * is false, then the user does not want us to materialize anything
531  * unnecessarily, so we don't.
532  */
533  else if (splan->parParam == NIL && enable_material &&
536 
537  result = (Node *) splan;
538  isInitPlan = false;
539  }
540 
541  /*
542  * Add the subplan and its PlannerInfo to the global lists.
543  */
544  root->glob->subplans = lappend(root->glob->subplans, plan);
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)
560  splan->plan_id);
561 
562  /* Label the subplan for EXPLAIN purposes */
563  splan->plan_name = palloc(32 + 12 * list_length(splan->setParam));
564  sprintf(splan->plan_name, "%s %d",
565  isInitPlan ? "InitPlan" : "SubPlan",
566  splan->plan_id);
567  if (splan->setParam)
568  {
569  char *ptr = splan->plan_name + strlen(splan->plan_name);
570 
571  ptr += sprintf(ptr, " (returns ");
572  foreach(lc, splan->setParam)
573  {
574  ptr += sprintf(ptr, "$%d%s",
575  lfirst_int(lc),
576  lnext(splan->setParam, lc) ? "," : ")");
577  }
578  }
579 
580  /* Lastly, fill in the cost estimates for use later */
581  cost_subplan(root, splan, plan);
582 
583  return result;
584 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:828
#define OidIsValid(objectId)
Definition: c.h:764
bool enable_material
Definition: costsize.c:144
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4436
Plan * materialize_finished_plan(Plan *subplan)
Definition: createplan.c:6508
#define ERROR
Definition: elog.h:39
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:637
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
Assert(fmt[strlen(fmt) - 1] !='\n')
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:2766
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:340
void * palloc(Size size)
Definition: mcxt.c:1201
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:282
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:786
#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:586
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
#define lfirst_int(lc)
Definition: pg_list.h:173
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:277
#define linitial(l)
Definition: pg_list.h:178
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define list_make1_int(x1)
Definition: pg_list.h:227
#define plan(x)
Definition: pg_regress.c:162
#define sprintf
Definition: port.h:240
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ ARRAY_SUBLINK
Definition: primnodes.h:938
@ ANY_SUBLINK
Definition: primnodes.h:934
@ MULTIEXPR_SUBLINK
Definition: primnodes.h:937
@ EXPR_SUBLINK
Definition: primnodes.h:936
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:935
@ EXISTS_SUBLINK
Definition: primnodes.h:932
static SPIPlanPtr splan
Definition: regress.c:270
Definition: pg_list.h:54
Definition: nodes.h:129
int paramid
Definition: primnodes.h:363
List * subplans
Definition: pathnodes.h:105
Bitmapset * rewindPlanIDs
Definition: pathnodes.h:111
List * init_plans
Definition: pathnodes.h:296
List * multiexpr_params
Definition: pathnodes.h:305
PlannerGlobal * glob
Definition: pathnodes.h:202
Expr * expr
Definition: primnodes.h:1922
static bool testexpr_is_hashable(Node *testexpr, List *param_ids)
Definition: subselect.c:774
static List * generate_subquery_params(PlannerInfo *root, List *tlist, List **paramIds)
Definition: subselect.c:593
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:655
static bool subplan_is_hashable(Plan *plan)
Definition: subselect.c:725
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:1925

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(), PlannerInfo::glob, PlannerInfo::init_plans, InvalidOid, IsA, PlannerParamItem::item, lappend(), lappend_int(), lfirst, lfirst_int, linitial, list_copy(), list_length(), list_make1_int, list_nth_cell(), lnext(), makeNode, makeNullConst(), materialize_finished_plan(), PlannerInfo::multiexpr_params, MULTIEXPR_SUBLINK, NIL, nodeTag, OidIsValid, palloc(), PlannerParamItem::paramId, Param::paramid, plan, PlannerGlobal::rewindPlanIDs, ROWCOMPARE_SUBLINK, splan, sprintf, SS_process_sublinks(), subplan_is_hashable(), PlannerGlobal::subplans, and testexpr_is_hashable().

Referenced by make_subplan().

◆ contain_dml()

static bool contain_dml ( Node node)
static

Definition at line 1069 of file subselect.c.

1070 {
1071  return contain_dml_walker(node, NULL);
1072 }
static bool contain_dml_walker(Node *node, void *context)
Definition: subselect.c:1075

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 1075 of file subselect.c.

1076 {
1077  if (node == NULL)
1078  return false;
1079  if (IsA(node, Query))
1080  {
1081  Query *query = (Query *) node;
1082 
1083  if (query->commandType != CMD_SELECT ||
1084  query->rowMarks != NIL)
1085  return true;
1086 
1087  return query_tree_walker(query, contain_dml_walker, context, 0);
1088  }
1089  return expression_tree_walker(node, contain_dml_walker, context);
1090 }
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:156
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
@ CMD_SELECT
Definition: nodes.h:255
List * rowMarks
Definition: parsenodes.h:207
CmdType commandType
Definition: parsenodes.h:120

References CMD_SELECT, Query::commandType, 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 1096 of file subselect.c.

1097 {
1098  Index depth = 0;
1099 
1100  /*
1101  * We should be starting with a Query, so that depth will be 1 while
1102  * examining its immediate contents.
1103  */
1104  Assert(IsA(node, Query));
1105 
1106  return contain_outer_selfref_walker(node, &depth);
1107 }
unsigned int Index
Definition: c.h:603
static bool contain_outer_selfref_walker(Node *node, Index *depth)
Definition: subselect.c:1110

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 1110 of file subselect.c.

1111 {
1112  if (node == NULL)
1113  return false;
1114  if (IsA(node, RangeTblEntry))
1115  {
1116  RangeTblEntry *rte = (RangeTblEntry *) node;
1117 
1118  /*
1119  * Check for a self-reference to a CTE that's above the Query that our
1120  * search started at.
1121  */
1122  if (rte->rtekind == RTE_CTE &&
1123  rte->self_reference &&
1124  rte->ctelevelsup >= *depth)
1125  return true;
1126  return false; /* allow range_table_walker to continue */
1127  }
1128  if (IsA(node, Query))
1129  {
1130  /* Recurse into subquery, tracking nesting depth properly */
1131  Query *query = (Query *) node;
1132  bool result;
1133 
1134  (*depth)++;
1135 
1137  (void *) depth, QTW_EXAMINE_RTES_BEFORE);
1138 
1139  (*depth)--;
1140 
1141  return result;
1142  }
1144  (void *) depth);
1145 }
#define QTW_EXAMINE_RTES_BEFORE
Definition: nodeFuncs.h:27
@ RTE_CTE
Definition: parsenodes.h:1012
bool self_reference
Definition: parsenodes.h:1158
Index ctelevelsup
Definition: parsenodes.h:1157
RTEKind rtekind
Definition: parsenodes.h:1025

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

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 1267 of file subselect.c.

1269 {
1270  JoinExpr *result;
1271  Query *parse = root->parse;
1272  Query *subselect = (Query *) sublink->subselect;
1273  Relids upper_varnos;
1274  int rtindex;
1275  ParseNamespaceItem *nsitem;
1276  RangeTblEntry *rte;
1277  RangeTblRef *rtr;
1278  List *subquery_vars;
1279  Node *quals;
1280  ParseState *pstate;
1281  Relids sub_ref_outer_relids;
1282  bool use_lateral;
1283 
1284  Assert(sublink->subLinkType == ANY_SUBLINK);
1285 
1286  /*
1287  * If the sub-select refers to any Vars of the parent query, we so let's
1288  * considering it as LATERAL. (Vars of higher levels don't matter here.)
1289  */
1290  sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
1291  use_lateral = !bms_is_empty(sub_ref_outer_relids);
1292 
1293  /*
1294  * Check that sub-select refers nothing outside of available_rels of the
1295  * parent query.
1296  */
1297  if (!bms_is_subset(sub_ref_outer_relids, available_rels))
1298  return NULL;
1299 
1300  /*
1301  * The test expression must contain some Vars of the parent query, else
1302  * it's not gonna be a join. (Note that it won't have Vars referring to
1303  * the subquery, rather Params.)
1304  */
1305  upper_varnos = pull_varnos(root, sublink->testexpr);
1306  if (bms_is_empty(upper_varnos))
1307  return NULL;
1308 
1309  /*
1310  * However, it can't refer to anything outside available_rels.
1311  */
1312  if (!bms_is_subset(upper_varnos, available_rels))
1313  return NULL;
1314 
1315  /*
1316  * The combining operators and left-hand expressions mustn't be volatile.
1317  */
1318  if (contain_volatile_functions(sublink->testexpr))
1319  return NULL;
1320 
1321  /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1322  pstate = make_parsestate(NULL);
1323 
1324  /*
1325  * Okay, pull up the sub-select into upper range table.
1326  *
1327  * We rely here on the assumption that the outer query has no references
1328  * to the inner (necessarily true, other than the Vars that we build
1329  * below). Therefore this is a lot easier than what pull_up_subqueries has
1330  * to go through.
1331  */
1332  nsitem = addRangeTableEntryForSubquery(pstate,
1333  subselect,
1334  makeAlias("ANY_subquery", NIL),
1335  use_lateral,
1336  false);
1337  rte = nsitem->p_rte;
1338  parse->rtable = lappend(parse->rtable, rte);
1339  rtindex = list_length(parse->rtable);
1340 
1341  /*
1342  * Form a RangeTblRef for the pulled-up sub-select.
1343  */
1344  rtr = makeNode(RangeTblRef);
1345  rtr->rtindex = rtindex;
1346 
1347  /*
1348  * Build a list of Vars representing the subselect outputs.
1349  */
1350  subquery_vars = generate_subquery_vars(root,
1351  subselect->targetList,
1352  rtindex);
1353 
1354  /*
1355  * Build the new join's qual expression, replacing Params with these Vars.
1356  */
1357  quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1358 
1359  /*
1360  * And finally, build the JoinExpr node.
1361  */
1362  result = makeNode(JoinExpr);
1363  result->jointype = JOIN_SEMI;
1364  result->isNatural = false;
1365  result->larg = NULL; /* caller must fill this in */
1366  result->rarg = (Node *) rtr;
1367  result->usingClause = NIL;
1368  result->join_using_alias = NULL;
1369  result->quals = quals;
1370  result->alias = NULL;
1371  result->rtindex = 0; /* we don't need an RTE for it */
1372 
1373  return result;
1374 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:425
#define bms_is_empty(a)
Definition: bitmapset.h:105
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:521
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:390
@ JOIN_SEMI
Definition: nodes.h:297
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
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:715
Node * quals
Definition: primnodes.h:2021
JoinType jointype
Definition: primnodes.h:2012
int rtindex
Definition: primnodes.h:2025
Node * larg
Definition: primnodes.h:2014
bool isNatural
Definition: primnodes.h:2013
Node * rarg
Definition: primnodes.h:2015
Query * parse
Definition: pathnodes.h:199
List * targetList
Definition: parsenodes.h:181
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:626
Relids pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
Definition: var.c:134
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108

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(), PlannerInfo::parse, pull_varnos(), pull_varnos_of_level(), JoinExpr::quals, JoinExpr::rarg, 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 1384 of file subselect.c.

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

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(), PlannerInfo::parse, pull_varnos(), JoinExpr::quals, FromExpr::quals, JoinExpr::rarg, replace_empty_jointree(), 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 1641 of file subselect.c.

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

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, PlannerInfo::parse, FromExpr::quals, and Query::targetList.

Referenced by make_subplan().

◆ convert_testexpr()

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

Definition at line 655 of file subselect.c.

658 {
659  convert_testexpr_context context;
660 
661  context.root = root;
662  context.subst_nodes = subst_nodes;
663  return convert_testexpr_mutator(testexpr, &context);
664 }
PlannerInfo * root
Definition: subselect.c:44
static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context)
Definition: subselect.c:667

References convert_testexpr_mutator(), convert_testexpr_context::root, and convert_testexpr_context::subst_nodes.

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 667 of file subselect.c.

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

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

Referenced by convert_testexpr().

◆ finalize_agg_primnode()

static bool finalize_agg_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 2980 of file subselect.c.

2981 {
2982  if (node == NULL)
2983  return false;
2984  if (IsA(node, Aggref))
2985  {
2986  Aggref *agg = (Aggref *) node;
2987 
2988  /* we should not consider the direct arguments, if any */
2989  finalize_primnode((Node *) agg->args, context);
2990  finalize_primnode((Node *) agg->aggfilter, context);
2991  return false; /* there can't be any Aggrefs below here */
2992  }
2994  (void *) context);
2995 }
List * args
Definition: primnodes.h:454
Expr * aggfilter
Definition: primnodes.h:463
static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2980
static bool finalize_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2896

References Aggref::aggfilter, Aggref::args, 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 2298 of file subselect.c.

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

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(), 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, PlannerInfo::glob, 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, SubqueryScan::scan, Scan::scanrelid, SubPlan::setParam, SubqueryScan::subplan, PlannerGlobal::subplans, 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 2896 of file subselect.c.

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

References SubPlan::args, bms_add_member(), bms_copy(), bms_del_member(), bms_join(), expression_tree_walker, find_minmax_agg_replacement_param(), IsA, lfirst_int, PARAM_EXEC, Param::paramid, finalize_primnode_context::paramids, SubPlan::paramIds, SubPlan::parParam, plan, planner_subplan_get_plan, finalize_primnode_context::root, 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 593 of file subselect.c.

594 {
595  List *result;
596  List *ids;
597  ListCell *lc;
598 
599  result = ids = NIL;
600  foreach(lc, tlist)
601  {
602  TargetEntry *tent = (TargetEntry *) lfirst(lc);
603  Param *param;
604 
605  if (tent->resjunk)
606  continue;
607 
608  param = generate_new_exec_param(root,
609  exprType((Node *) tent->expr),
610  exprTypmod((Node *) tent->expr),
611  exprCollation((Node *) tent->expr));
612  result = lappend(result, param);
613  ids = lappend_int(ids, param->paramid);
614  }
615 
616  *paramIds = ids;
617  return result;
618 }

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

Referenced by build_subplan().

◆ generate_subquery_vars()

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

Definition at line 626 of file subselect.c.

627 {
628  List *result;
629  ListCell *lc;
630 
631  result = NIL;
632  foreach(lc, tlist)
633  {
634  TargetEntry *tent = (TargetEntry *) lfirst(lc);
635  Var *var;
636 
637  if (tent->resjunk)
638  continue;
639 
640  var = makeVarFromTargetEntry(varno, tent);
641  result = lappend(result, var);
642  }
643 
644  return result;
645 }
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:106
Definition: primnodes.h:234

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 845 of file subselect.c.

846 {
847  Oid opid = expr->opno;
848 
849  /* quick out if not a binary operator */
850  if (list_length(expr->args) != 2)
851  return false;
852  if (opid == ARRAY_EQ_OP ||
853  opid == RECORD_EQ_OP)
854  {
855  /* these are strict, but must check input type to ensure hashable */
856  Node *leftarg = linitial(expr->args);
857 
858  return op_hashjoinable(opid, exprType(leftarg));
859  }
860  else
861  {
862  /* else must look up the operator properties */
863  HeapTuple tup;
864  Form_pg_operator optup;
865 
866  tup = SearchSysCache1(OPEROID, ObjectIdGetDatum(opid));
867  if (!HeapTupleIsValid(tup))
868  elog(ERROR, "cache lookup failed for operator %u", opid);
869  optup = (Form_pg_operator) GETSTRUCT(tup);
870  if (!optup->oprcanhash || !func_strict(optup->oprcode))
871  {
872  ReleaseSysCache(tup);
873  return false;
874  }
875  ReleaseSysCache(tup);
876  return true;
877  }
878 }
#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:1414
bool func_strict(Oid funcid)
Definition: lsyscache.c:1738
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:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219

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 1151 of file subselect.c.

1152 {
1153  struct inline_cte_walker_context context;
1154 
1155  context.ctename = cte->ctename;
1156  /* Start at levelsup = -1 because we'll immediately increment it */
1157  context.levelsup = -1;
1158  context.ctequery = castNode(Query, cte->ctequery);
1159 
1160  (void) inline_cte_walker((Node *) root->parse, &context);
1161 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
const char * ctename
Definition: subselect.c:62
static bool inline_cte_walker(Node *node, inline_cte_walker_context *context)
Definition: subselect.c:1164

References castNode, inline_cte_walker_context::ctename, CommonTableExpr::ctename, inline_cte_walker_context::ctequery, CommonTableExpr::ctequery, inline_cte_walker(), inline_cte_walker_context::levelsup, and PlannerInfo::parse.

Referenced by SS_process_ctes().

◆ inline_cte_walker()

static bool inline_cte_walker ( Node node,
inline_cte_walker_context context 
)
static

Definition at line 1164 of file subselect.c.

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

References RangeTblEntry::colcollations, RangeTblEntry::coltypes, RangeTblEntry::coltypmods, copyObject, RangeTblEntry::ctelevelsup, inline_cte_walker_context::ctename, RangeTblEntry::ctename, inline_cte_walker_context::ctequery, expression_tree_walker, IncrementVarSublevelsUp(), IsA, inline_cte_walker_context::levelsup, NIL, QTW_EXAMINE_RTES_AFTER, query_tree_walker, RTE_CTE, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblEntry::security_barrier, RangeTblEntry::self_reference, 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,
222  root,
223  false, tuple_fraction);
224 
225  /* Isolate the params needed by this specific subplan */
226  plan_params = root->plan_params;
227  root->plan_params = NIL;
228 
229  /*
230  * Select best Path and turn it into a Plan. At least for now, there
231  * seems no reason to postpone doing that.
232  */
233  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
234  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
235 
236  plan = create_plan(subroot, best_path);
237 
238  /* And convert to SubPlan or InitPlan format. */
239  result = build_subplan(root, plan, 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,
269  root,
270  false, 0.0);
271 
272  /* Isolate the params needed by this specific subplan */
273  plan_params = root->plan_params;
274  root->plan_params = NIL;
275 
276  /* Select best Path */
277  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
278  best_path = final_rel->cheapest_total_path;
279 
280  /* Now we can check if it'll fit in hash_mem */
281  if (subpath_is_hashable(best_path))
282  {
283  SubPlan *hashplan;
284  AlternativeSubPlan *asplan;
285 
286  /* OK, finish planning the ANY subquery */
287  plan = create_plan(subroot, best_path);
288 
289  /* ... and convert to SubPlan format */
290  hashplan = castNode(SubPlan,
291  build_subplan(root, plan, subroot,
292  plan_params,
293  ANY_SUBLINK, 0,
294  newtestexpr,
295  paramIds,
296  true));
297  /* Check we got what we expected */
298  Assert(hashplan->parParam == NIL);
299  Assert(hashplan->useHashTable);
300 
301  /* Leave it to setrefs.c to decide which plan to use */
302  asplan = makeNode(AlternativeSubPlan);
303  asplan->subplans = list_make2(result, hashplan);
304  result = (Node *) asplan;
305  root->hasAlternativeSubPlans = true;
306  }
307  }
308  }
309 
310  return result;
311 }
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:335
@ 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)
Definition: planner.c:625
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:6248
@ ALL_SUBLINK
Definition: primnodes.h:933
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1463
List * plan_params
Definition: pathnodes.h:217
bool hasAlternativeSubPlans
Definition: pathnodes.h:497
struct Path * cheapest_total_path
Definition: pathnodes.h:887
bool useHashTable
Definition: primnodes.h:1014
static Node * build_subplan(PlannerInfo *root, Plan *plan, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, List *testexpr_paramids, bool unknownEqFalse)
Definition: subselect.c:320
static Query * convert_EXISTS_to_ANY(PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds)
Definition: subselect.c:1641
static bool subpath_is_hashable(Path *path)
Definition: subselect.c:749

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(), PlannerInfo::glob, PlannerInfo::hasAlternativeSubPlans, IsA, list_make2, makeNode, NIL, SubPlan::parParam, plan, PlannerInfo::plan_params, 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 1935 of file subselect.c.

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

1888 {
1889  if (node == NULL)
1890  return NULL;
1891  if (IsA(node, Var))
1892  {
1893  if (((Var *) node)->varlevelsup > 0)
1894  return (Node *) replace_outer_var(root, (Var *) node);
1895  }
1896  if (IsA(node, PlaceHolderVar))
1897  {
1898  if (((PlaceHolderVar *) node)->phlevelsup > 0)
1899  return (Node *) replace_outer_placeholdervar(root,
1900  (PlaceHolderVar *) node);
1901  }
1902  if (IsA(node, Aggref))
1903  {
1904  if (((Aggref *) node)->agglevelsup > 0)
1905  return (Node *) replace_outer_agg(root, (Aggref *) node);
1906  }
1907  if (IsA(node, GroupingFunc))
1908  {
1909  if (((GroupingFunc *) node)->agglevelsup > 0)
1910  return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
1911  }
1912  return expression_tree_mutator(node,
1914  (void *) root);
1915 }
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_agg(PlannerInfo *root, Aggref *agg)
Definition: paramassign.c:224
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1887

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

Referenced by SS_replace_correlation_vars().

◆ simplify_EXISTS_query()

static bool simplify_EXISTS_query ( PlannerInfo root,
Query query 
)
static

Definition at line 1553 of file subselect.c.

1554 {
1555  /*
1556  * We don't try to simplify at all if the query uses set operations,
1557  * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1558  * UPDATE/SHARE; none of these seem likely in normal usage and their
1559  * possible effects are complex. (Note: we could ignore an "OFFSET 0"
1560  * clause, but that traditionally is used as an optimization fence, so we
1561  * don't.)
1562  */
1563  if (query->commandType != CMD_SELECT ||
1564  query->setOperations ||
1565  query->hasAggs ||
1566  query->groupingSets ||
1567  query->hasWindowFuncs ||
1568  query->hasTargetSRFs ||
1569  query->hasModifyingCTE ||
1570  query->havingQual ||
1571  query->limitOffset ||
1572  query->rowMarks)
1573  return false;
1574 
1575  /*
1576  * LIMIT with a constant positive (or NULL) value doesn't affect the
1577  * semantics of EXISTS, so let's ignore such clauses. This is worth doing
1578  * because people accustomed to certain other DBMSes may be in the habit
1579  * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a
1580  * LIMIT with anything else as argument, though, we can't simplify.
1581  */
1582  if (query->limitCount)
1583  {
1584  /*
1585  * The LIMIT clause has not yet been through eval_const_expressions,
1586  * so we have to apply that here. It might seem like this is a waste
1587  * of cycles, since the only case plausibly worth worrying about is
1588  * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1589  * so we have to fold constants or we're not going to recognize it.
1590  */
1591  Node *node = eval_const_expressions(root, query->limitCount);
1592  Const *limit;
1593 
1594  /* Might as well update the query if we simplified the clause. */
1595  query->limitCount = node;
1596 
1597  if (!IsA(node, Const))
1598  return false;
1599 
1600  limit = (Const *) node;
1601  Assert(limit->consttype == INT8OID);
1602  if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1603  return false;
1604 
1605  /* Whether or not the targetlist is safe, we can drop the LIMIT. */
1606  query->limitCount = NULL;
1607  }
1608 
1609  /*
1610  * Otherwise, we can throw away the targetlist, as well as any GROUP,
1611  * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1612  * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1613  * since our parsetree representation of these clauses depends on the
1614  * targetlist, we'd better throw them away if we drop the targetlist.)
1615  */
1616  query->targetList = NIL;
1617  query->groupClause = NIL;
1618  query->windowClause = NIL;
1619  query->distinctClause = NIL;
1620  query->sortClause = NIL;
1621  query->hasDistinctOn = false;
1622 
1623  return true;
1624 }
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:385
Oid consttype
Definition: primnodes.h:298
Node * limitCount
Definition: parsenodes.h:204
Node * setOperations
Definition: parsenodes.h:209
List * groupClause
Definition: parsenodes.h:190
Node * havingQual
Definition: parsenodes.h:195
Node * limitOffset
Definition: parsenodes.h:203
List * windowClause
Definition: parsenodes.h:197
List * groupingSets
Definition: parsenodes.h:193
List * distinctClause
Definition: parsenodes.h:199
List * sortClause
Definition: parsenodes.h:201

References Assert(), CMD_SELECT, Query::commandType, Const::consttype, DatumGetInt64(), Query::distinctClause, eval_const_expressions(), Query::groupClause, Query::groupingSets, Query::havingQual, IsA, Query::limitCount, Query::limitOffset, NIL, Query::rowMarks, 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 2245 of file subselect.c.

2246 {
2247  plan->initPlan = root->init_plans;
2248 }

References PlannerInfo::init_plans, and plan.

Referenced by create_plan().

◆ SS_charge_for_initplans()

void SS_charge_for_initplans ( PlannerInfo root,
RelOptInfo final_rel 
)

Definition at line 2140 of file subselect.c.

2141 {
2142  Cost initplan_cost;
2143  bool unsafe_initplans;
2144  ListCell *lc;
2145 
2146  /* Nothing to do if no initPlans */
2147  if (root->init_plans == NIL)
2148  return;
2149 
2150  /*
2151  * Compute the cost increment just once, since it will be the same for all
2152  * Paths. Also check for parallel-unsafe initPlans.
2153  */
2155  &initplan_cost, &unsafe_initplans);
2156 
2157  /*
2158  * Now adjust the costs and parallel_safe flags.
2159  */
2160  foreach(lc, final_rel->pathlist)
2161  {
2162  Path *path = (Path *) lfirst(lc);
2163 
2164  path->startup_cost += initplan_cost;
2165  path->total_cost += initplan_cost;
2166  if (unsafe_initplans)
2167  path->parallel_safe = false;
2168  }
2169 
2170  /*
2171  * Adjust partial paths' costs too, or forget them entirely if we must
2172  * consider the rel parallel-unsafe.
2173  */
2174  if (unsafe_initplans)
2175  {
2176  final_rel->partial_pathlist = NIL;
2177  final_rel->consider_parallel = false;
2178  }
2179  else
2180  {
2181  foreach(lc, final_rel->partial_pathlist)
2182  {
2183  Path *path = (Path *) lfirst(lc);
2184 
2185  path->startup_cost += initplan_cost;
2186  path->total_cost += initplan_cost;
2187  }
2188  }
2189 
2190  /* We needn't do set_cheapest() here, caller will do it */
2191 }
double Cost
Definition: nodes.h:241
Cost startup_cost
Definition: pathnodes.h:1641
Cost total_cost
Definition: pathnodes.h:1642
bool parallel_safe
Definition: pathnodes.h:1635
bool consider_parallel
Definition: pathnodes.h:872
List * pathlist
Definition: pathnodes.h:883
List * partial_pathlist
Definition: pathnodes.h:885
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2204

References RelOptInfo::consider_parallel, PlannerInfo::init_plans, lfirst, NIL, Path::parallel_safe, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, 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 2204 of file subselect.c.

2207 {
2208  Cost initplan_cost;
2209  bool unsafe_initplans;
2210  ListCell *lc;
2211 
2212  /*
2213  * We assume each initPlan gets run once during top plan startup. This is
2214  * a conservative overestimate, since in fact an initPlan might be
2215  * executed later than plan startup, or even not at all.
2216  */
2217  initplan_cost = 0;
2218  unsafe_initplans = false;
2219  foreach(lc, init_plans)
2220  {
2221  SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2222 
2223  initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2224  if (!initsubplan->parallel_safe)
2225  unsafe_initplans = true;
2226  }
2227  *initplan_cost_p = initplan_cost;
2228  *unsafe_initplans_p = unsafe_initplans;
2229 }
#define lfirst_node(type, lc)
Definition: pg_list.h:176
bool parallel_safe
Definition: primnodes.h:1019
Cost startup_cost
Definition: primnodes.h:1028
Cost per_call_cost
Definition: primnodes.h:1029

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 2260 of file subselect.c.

2261 {
2262  /* No setup needed, just recurse through plan tree. */
2263  (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2264 }

References finalize_plan(), PlannerInfo::outer_params, and plan.

Referenced by standard_planner().

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2078 of file subselect.c.

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

References bms_add_member(), PlannerInfo::glob, PlannerInfo::init_plans, lfirst, lfirst_int, NIL, PlannerInfo::outer_params, PlannerGlobal::paramExecTypes, PlannerParamItem::paramId, PlannerInfo::plan_params, 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 3023 of file subselect.c.

3026 {
3027  SubPlan *node;
3028 
3029  /*
3030  * Add the subplan and its PlannerInfo to the global lists.
3031  */
3032  root->glob->subplans = lappend(root->glob->subplans, plan);
3033  root->glob->subroots = lappend(root->glob->subroots, subroot);
3034 
3035  /*
3036  * Create a SubPlan node and add it to the outer list of InitPlans. Note
3037  * it has to appear after any other InitPlans it might depend on (see
3038  * comments in ExecReScan).
3039  */
3040  node = makeNode(SubPlan);
3041  node->subLinkType = EXPR_SUBLINK;
3042  node->plan_id = list_length(root->glob->subplans);
3043  node->plan_name = psprintf("InitPlan %d (returns $%d)",
3044  node->plan_id, prm->paramid);
3046  &node->firstColCollation);
3047  node->parallel_safe = plan->parallel_safe;
3048  node->setParam = list_make1_int(prm->paramid);
3049 
3050  root->init_plans = lappend(root->init_plans, node);
3051 
3052  /*
3053  * The node can't have any inputs (since it's an initplan), so the
3054  * parParam and args lists remain empty.
3055  */
3056 
3057  /* Set costs of SubPlan using info from the plan tree */
3058  cost_subplan(subroot, node, plan);
3059 }
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int plan_id
Definition: primnodes.h:1005
char * plan_name
Definition: primnodes.h:1007
int32 firstColTypmod
Definition: primnodes.h:1010
Oid firstColCollation
Definition: primnodes.h:1011
SubLinkType subLinkType
Definition: primnodes.h:1000
Oid firstColType
Definition: primnodes.h:1009

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

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

3010 {
3011  return generate_new_exec_param(root, resulttype,
3012  resulttypmod, resultcollation);
3013 }

References generate_new_exec_param().

Referenced by preprocess_minmax_aggregates().

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 893 of file subselect.c.

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

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(), PlannerInfo::cte_plan_ids, CTE_SUBLINK, Query::cteList, CommonTableExpr::ctematerialized, CTEMaterializeDefault, CTEMaterializeNever, CommonTableExpr::ctename, CommonTableExpr::ctequery, elog(), ERROR, fetch_upper_rel(), get_first_col_type(), PlannerInfo::glob, PlannerInfo::init_plans, inline_cte(), lappend(), lappend_int(), lfirst, list_length(), list_make1_int, makeNode, NIL, PlannerInfo::parse, plan, PlannerInfo::plan_params, psprintf(), splan, PlannerGlobal::subplans, 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 1925 of file subselect.c.

1926 {
1927  process_sublinks_context context;
1928 
1929  context.root = root;
1930  context.isTopQual = isQual;
1931  return process_sublinks_mutator(expr, &context);
1932 }

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

Referenced by build_subplan(), and preprocess_expression().

◆ SS_replace_correlation_vars()

Node* SS_replace_correlation_vars ( PlannerInfo root,
Node expr 
)

Definition at line 1880 of file subselect.c.

1881 {
1882  /* No setup needed for tree walk, so away we go */
1883  return replace_correlation_vars_mutator(expr, root);
1884 }

References replace_correlation_vars_mutator().

Referenced by preprocess_expression().

◆ subpath_is_hashable()

static bool subpath_is_hashable ( Path path)
static

Definition at line 749 of file subselect.c.

750 {
751  double subquery_size;
752 
753  /*
754  * The estimated size of the subquery result must fit in hash_mem. (Note:
755  * we use heap tuple overhead here even though the tuples will actually be
756  * stored as MinimalTuples; this provides some fudge factor for hashtable
757  * overhead.)
758  */
759  subquery_size = path->rows *
760  (MAXALIGN(path->pathtarget->width) + MAXALIGN(SizeofHeapTupleHeader));
761  if (subquery_size > get_hash_memory_limit())
762  return false;
763 
764  return true;
765 }
#define MAXALIGN(LEN)
Definition: c.h:800
#define SizeofHeapTupleHeader
Definition: htup_details.h:185
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3596
Cardinality rows
Definition: pathnodes.h:1640

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 725 of file subselect.c.

726 {
727  double subquery_size;
728 
729  /*
730  * The estimated size of the subquery result must fit in hash_mem. (Note:
731  * we use heap tuple overhead here even though the tuples will actually be
732  * stored as MinimalTuples; this provides some fudge factor for hashtable
733  * overhead.)
734  */
735  subquery_size = plan->plan_rows *
736  (MAXALIGN(plan->plan_width) + MAXALIGN(SizeofHeapTupleHeader));
737  if (subquery_size > get_hash_memory_limit())
738  return false;
739 
740  return true;
741 }

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 805 of file subselect.c.

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

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 774 of file subselect.c.

775 {
776  /*
777  * The testexpr must be a single OpExpr, or an AND-clause containing only
778  * OpExprs, each of which satisfy test_opexpr_is_hashable().
779  */
780  if (testexpr && IsA(testexpr, OpExpr))
781  {
782  if (test_opexpr_is_hashable((OpExpr *) testexpr, param_ids))
783  return true;
784  }
785  else if (is_andclause(testexpr))
786  {
787  ListCell *l;
788 
789  foreach(l, ((BoolExpr *) testexpr)->args)
790  {
791  Node *andarg = (Node *) lfirst(l);
792 
793  if (!IsA(andarg, OpExpr))
794  return false;
795  if (!test_opexpr_is_hashable((OpExpr *) andarg, param_ids))
796  return false;
797  }
798  return true;
799  }
800 
801  return false;
802 }
static bool test_opexpr_is_hashable(OpExpr *testexpr, List *param_ids)
Definition: subselect.c:805

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

Referenced by build_subplan().