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, Path *path, PlannerInfo *subroot, List *plan_params, SubLinkType subLinkType, int subLinkId, Node *testexpr, List *testexpr_paramids, bool unknownEqFalse)
 
static Listgenerate_subquery_params (PlannerInfo *root, List *tlist, List **paramIds)
 
static Listgenerate_subquery_vars (PlannerInfo *root, List *tlist, Index varno)
 
static Nodeconvert_testexpr (PlannerInfo *root, Node *testexpr, List *subst_nodes)
 
static Nodeconvert_testexpr_mutator (Node *node, convert_testexpr_context *context)
 
static bool subplan_is_hashable (Plan *plan)
 
static bool subpath_is_hashable (Path *path)
 
static bool testexpr_is_hashable (Node *testexpr, List *param_ids)
 
static bool test_opexpr_is_hashable (OpExpr *testexpr, List *param_ids)
 
static bool hash_ok_operator (OpExpr *expr)
 
static bool contain_dml (Node *node)
 
static bool contain_dml_walker (Node *node, void *context)
 
static bool contain_outer_selfref (Node *node)
 
static bool contain_outer_selfref_walker (Node *node, Index *depth)
 
static void inline_cte (PlannerInfo *root, CommonTableExpr *cte)
 
static bool inline_cte_walker (Node *node, inline_cte_walker_context *context)
 
static bool simplify_EXISTS_query (PlannerInfo *root, Query *query)
 
static Queryconvert_EXISTS_to_ANY (PlannerInfo *root, Query *subselect, Node **testexpr, List **paramIds)
 
static Nodereplace_correlation_vars_mutator (Node *node, PlannerInfo *root)
 
static Nodeprocess_sublinks_mutator (Node *node, process_sublinks_context *context)
 
static Bitmapsetfinalize_plan (PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
 
static bool finalize_primnode (Node *node, finalize_primnode_context *context)
 
static bool finalize_agg_primnode (Node *node, finalize_primnode_context *context)
 
static void get_first_col_type (Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
 
static Nodemake_subplan (PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual)
 
void SS_process_ctes (PlannerInfo *root)
 
JoinExprconvert_ANY_sublink_to_join (PlannerInfo *root, SubLink *sublink, Relids available_rels)
 
JoinExprconvert_EXISTS_sublink_to_join (PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
 
NodeSS_replace_correlation_vars (PlannerInfo *root, Node *expr)
 
NodeSS_process_sublinks (PlannerInfo *root, Node *expr, bool isQual)
 
void SS_identify_outer_params (PlannerInfo *root)
 
void SS_charge_for_initplans (PlannerInfo *root, RelOptInfo *final_rel)
 
void SS_compute_initplan_cost (List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
 
void SS_attach_initplans (PlannerInfo *root, Plan *plan)
 
void SS_finalize_plan (PlannerInfo *root, Plan *plan)
 
ParamSS_make_initplan_output_param (PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
 
void SS_make_initplan_from_plan (PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
 

Typedef Documentation

◆ convert_testexpr_context

◆ finalize_primnode_context

◆ inline_cte_walker_context

◆ process_sublinks_context

Function Documentation

◆ build_subplan()

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

Definition at line 319 of file subselect.c.

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

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

Referenced by make_subplan().

◆ contain_dml()

static bool contain_dml ( Node node)
static

Definition at line 1056 of file subselect.c.

1057{
1058 return contain_dml_walker(node, NULL);
1059}
static bool contain_dml_walker(Node *node, void *context)
Definition: subselect.c:1062

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

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

References CMD_SELECT, Query::commandType, contain_dml_walker(), expression_tree_walker, IsA, NIL, query_tree_walker, and Query::rowMarks.

Referenced by contain_dml(), and contain_dml_walker().

◆ contain_outer_selfref()

static bool contain_outer_selfref ( Node node)
static

Definition at line 1083 of file subselect.c.

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

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

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

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

Referenced by contain_outer_selfref(), and contain_outer_selfref_walker().

◆ convert_ANY_sublink_to_join()

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

Definition at line 1253 of file subselect.c.

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

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

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_EXISTS_sublink_to_join()

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

Definition at line 1370 of file subselect.c.

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

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

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_EXISTS_to_ANY()

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

Definition at line 1651 of file subselect.c.

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

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

Referenced by make_subplan().

◆ convert_testexpr()

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

Definition at line 644 of file subselect.c.

647{
649
650 context.root = root;
651 context.subst_nodes = subst_nodes;
652 return convert_testexpr_mutator(testexpr, &context);
653}
PlannerInfo * root
Definition: subselect.c:44
static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context)
Definition: subselect.c:656

References convert_testexpr_mutator(), convert_testexpr_context::root, 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 656 of file subselect.c.

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

References convert_testexpr_mutator(), 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(), and convert_testexpr_mutator().

◆ finalize_agg_primnode()

static bool finalize_agg_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 3007 of file subselect.c.

3008{
3009 if (node == NULL)
3010 return false;
3011 if (IsA(node, Aggref))
3012 {
3013 Aggref *agg = (Aggref *) node;
3014
3015 /* we should not consider the direct arguments, if any */
3016 finalize_primnode((Node *) agg->args, context);
3017 finalize_primnode((Node *) agg->aggfilter, context);
3018 return false; /* there can't be any Aggrefs below here */
3019 }
3020 return expression_tree_walker(node, finalize_agg_primnode, context);
3021}
List * args
Definition: primnodes.h:485
Expr * aggfilter
Definition: primnodes.h:494
static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:3007
static bool finalize_primnode(Node *node, finalize_primnode_context *context)
Definition: subselect.c:2924

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

Referenced by finalize_agg_primnode(), and 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 2326 of file subselect.c.

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

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_plan(), finalize_primnode(), find_base_rel(), RangeTblFunction::funcexpr, FunctionScan::functions, lfirst, lfirst_int, list_length(), list_nth(), nodeTag, ModifyTable::onConflictSet, ModifyTable::onConflictWhere, PlannerInfo::outer_params, finalize_primnode_context::paramids, NestLoopParam::paramno, Agg::plan, plan, planner_subplan_get_plan, Plan::qual, ModifyTable::returningLists, finalize_primnode_context::root, root, SubqueryScan::scan, Scan::scanrelid, SubPlan::setParam, SubqueryScan::subplan, RelOptInfo::subroot, and Plan::targetlist.

Referenced by finalize_plan(), and SS_finalize_plan().

◆ finalize_primnode()

static bool finalize_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 2924 of file subselect.c.

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

References SubPlan::args, bms_add_member(), bms_copy(), bms_del_member(), bms_join(), expression_tree_walker, finalize_primnode(), 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(), finalize_plan(), and finalize_primnode().

◆ generate_subquery_params()

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

Definition at line 582 of file subselect.c.

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

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

Referenced by build_subplan().

◆ generate_subquery_vars()

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

Definition at line 615 of file subselect.c.

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

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

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

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

Referenced by convert_EXISTS_to_ANY(), and test_opexpr_is_hashable().

◆ inline_cte()

static void inline_cte ( PlannerInfo root,
CommonTableExpr cte 
)
static

Definition at line 1137 of file subselect.c.

1138{
1139 struct inline_cte_walker_context context;
1140
1141 context.ctename = cte->ctename;
1142 /* Start at levelsup = -1 because we'll immediately increment it */
1143 context.levelsup = -1;
1144 context.ctequery = castNode(Query, cte->ctequery);
1145
1146 (void) inline_cte_walker((Node *) root->parse, &context);
1147}
#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:1150

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 root.

Referenced by SS_process_ctes().

◆ inline_cte_walker()

static bool inline_cte_walker ( Node node,
inline_cte_walker_context context 
)
static

Definition at line 1150 of file subselect.c.

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

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

Referenced by inline_cte(), and inline_cte_walker().

◆ make_subplan()

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

Definition at line 162 of file subselect.c.

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

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

Referenced by process_sublinks_mutator().

◆ process_sublinks_mutator()

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

Definition at line 1956 of file subselect.c.

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

Referenced by process_sublinks_mutator(), and SS_process_sublinks().

◆ replace_correlation_vars_mutator()

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

Definition at line 1898 of file subselect.c.

1899{
1900 if (node == NULL)
1901 return NULL;
1902 if (IsA(node, Var))
1903 {
1904 if (((Var *) node)->varlevelsup > 0)
1905 return (Node *) replace_outer_var(root, (Var *) node);
1906 }
1907 if (IsA(node, PlaceHolderVar))
1908 {
1909 if (((PlaceHolderVar *) node)->phlevelsup > 0)
1911 (PlaceHolderVar *) node);
1912 }
1913 if (IsA(node, Aggref))
1914 {
1915 if (((Aggref *) node)->agglevelsup > 0)
1916 return (Node *) replace_outer_agg(root, (Aggref *) node);
1917 }
1918 if (IsA(node, GroupingFunc))
1919 {
1920 if (((GroupingFunc *) node)->agglevelsup > 0)
1921 return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
1922 }
1923 if (IsA(node, MergeSupportFunc))
1924 {
1925 if (root->parse->commandType != CMD_MERGE)
1927 (MergeSupportFunc *) node);
1928 }
1929 if (IsA(node, ReturningExpr))
1930 {
1931 if (((ReturningExpr *) node)->retlevelsup > 0)
1933 (ReturningExpr *) node);
1934 }
1936}
@ CMD_MERGE
Definition: nodes.h:269
Param * replace_outer_merge_support(PlannerInfo *root, MergeSupportFunc *msf)
Definition: paramassign.c:318
Param * replace_outer_agg(PlannerInfo *root, Aggref *agg)
Definition: paramassign.c:225
Param * replace_outer_returning(PlannerInfo *root, ReturningExpr *rexpr)
Definition: paramassign.c:368
Param * replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp)
Definition: paramassign.c:271
Param * replace_outer_var(PlannerInfo *root, Var *var)
Definition: paramassign.c:121
Param * replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
Definition: paramassign.c:198
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1898

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

Referenced by replace_correlation_vars_mutator(), and SS_replace_correlation_vars().

◆ simplify_EXISTS_query()

static bool simplify_EXISTS_query ( PlannerInfo root,
Query query 
)
static

Definition at line 1539 of file subselect.c.

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

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

Referenced by convert_EXISTS_sublink_to_join(), and make_subplan().

◆ SS_attach_initplans()

void SS_attach_initplans ( PlannerInfo root,
Plan plan 
)

Definition at line 2273 of file subselect.c.

2274{
2275 plan->initPlan = root->init_plans;
2276}

References plan, and root.

Referenced by create_plan().

◆ SS_charge_for_initplans()

void SS_charge_for_initplans ( PlannerInfo root,
RelOptInfo final_rel 
)

Definition at line 2168 of file subselect.c.

2169{
2170 Cost initplan_cost;
2171 bool unsafe_initplans;
2172 ListCell *lc;
2173
2174 /* Nothing to do if no initPlans */
2175 if (root->init_plans == NIL)
2176 return;
2177
2178 /*
2179 * Compute the cost increment just once, since it will be the same for all
2180 * Paths. Also check for parallel-unsafe initPlans.
2181 */
2182 SS_compute_initplan_cost(root->init_plans,
2183 &initplan_cost, &unsafe_initplans);
2184
2185 /*
2186 * Now adjust the costs and parallel_safe flags.
2187 */
2188 foreach(lc, final_rel->pathlist)
2189 {
2190 Path *path = (Path *) lfirst(lc);
2191
2192 path->startup_cost += initplan_cost;
2193 path->total_cost += initplan_cost;
2194 if (unsafe_initplans)
2195 path->parallel_safe = false;
2196 }
2197
2198 /*
2199 * Adjust partial paths' costs too, or forget them entirely if we must
2200 * consider the rel parallel-unsafe.
2201 */
2202 if (unsafe_initplans)
2203 {
2204 final_rel->partial_pathlist = NIL;
2205 final_rel->consider_parallel = false;
2206 }
2207 else
2208 {
2209 foreach(lc, final_rel->partial_pathlist)
2210 {
2211 Path *path = (Path *) lfirst(lc);
2212
2213 path->startup_cost += initplan_cost;
2214 path->total_cost += initplan_cost;
2215 }
2216 }
2217
2218 /* We needn't do set_cheapest() here, caller will do it */
2219}
double Cost
Definition: nodes.h:251
Cost startup_cost
Definition: pathnodes.h:1697
Cost total_cost
Definition: pathnodes.h:1698
bool parallel_safe
Definition: pathnodes.h:1690
bool consider_parallel
Definition: pathnodes.h:911
List * pathlist
Definition: pathnodes.h:922
List * partial_pathlist
Definition: pathnodes.h:924
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2232

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

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_compute_initplan_cost()

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

Definition at line 2232 of file subselect.c.

2235{
2236 Cost initplan_cost;
2237 bool unsafe_initplans;
2238 ListCell *lc;
2239
2240 /*
2241 * We assume each initPlan gets run once during top plan startup. This is
2242 * a conservative overestimate, since in fact an initPlan might be
2243 * executed later than plan startup, or even not at all.
2244 */
2245 initplan_cost = 0;
2246 unsafe_initplans = false;
2247 foreach(lc, init_plans)
2248 {
2249 SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2250
2251 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2252 if (!initsubplan->parallel_safe)
2253 unsafe_initplans = true;
2254 }
2255 *initplan_cost_p = initplan_cost;
2256 *unsafe_initplans_p = unsafe_initplans;
2257}
bool parallel_safe
Definition: primnodes.h:1101
Cost startup_cost
Definition: primnodes.h:1110
Cost per_call_cost
Definition: primnodes.h:1111

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

2289{
2290 /* No setup needed, just recurse through plan tree. */
2291 (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2292}

References finalize_plan(), plan, and root.

Referenced by standard_planner().

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2104 of file subselect.c.

2105{
2106 Bitmapset *outer_params;
2107 PlannerInfo *proot;
2108 ListCell *l;
2109
2110 /*
2111 * If no parameters have been assigned anywhere in the tree, we certainly
2112 * don't need to do anything here.
2113 */
2114 if (root->glob->paramExecTypes == NIL)
2115 return;
2116
2117 /*
2118 * Scan all query levels above this one to see which parameters are due to
2119 * be available from them, either because lower query levels have
2120 * requested them (via plan_params) or because they will be available from
2121 * initPlans of those levels.
2122 */
2123 outer_params = NULL;
2124 for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2125 {
2126 /*
2127 * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
2128 */
2129 foreach(l, proot->plan_params)
2130 {
2132
2133 outer_params = bms_add_member(outer_params, pitem->paramId);
2134 }
2135 /* Include any outputs of outer-level initPlans */
2136 foreach(l, proot->init_plans)
2137 {
2138 SubPlan *initsubplan = (SubPlan *) lfirst(l);
2139 ListCell *l2;
2140
2141 foreach(l2, initsubplan->setParam)
2142 {
2143 outer_params = bms_add_member(outer_params, lfirst_int(l2));
2144 }
2145 }
2146 /* Include worktable ID, if a recursive query is being planned */
2147 if (proot->wt_param_id >= 0)
2148 outer_params = bms_add_member(outer_params, proot->wt_param_id);
2149 }
2150 root->outer_params = outer_params;
2151}
List * init_plans
Definition: pathnodes.h:320
int wt_param_id
Definition: pathnodes.h:557
List * plan_params
Definition: pathnodes.h:241

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

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_make_initplan_from_plan()

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

Definition at line 3049 of file subselect.c.

3052{
3053 SubPlan *node;
3054
3055 /*
3056 * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3057 * the global lists. Ideally we'd save a real path, but right now our
3058 * sole caller doesn't build a path that exactly matches the plan. Since
3059 * we're not currently going to need the path for an initplan, it's not
3060 * worth requiring construction of such a path.
3061 */
3062 root->glob->subplans = lappend(root->glob->subplans, plan);
3063 root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3064 root->glob->subroots = lappend(root->glob->subroots, subroot);
3065
3066 /*
3067 * Create a SubPlan node and add it to the outer list of InitPlans. Note
3068 * it has to appear after any other InitPlans it might depend on (see
3069 * comments in ExecReScan).
3070 */
3071 node = makeNode(SubPlan);
3072 node->subLinkType = EXPR_SUBLINK;
3073 node->plan_id = list_length(root->glob->subplans);
3074 node->plan_name = psprintf("InitPlan %d", node->plan_id);
3076 &node->firstColCollation);
3077 node->parallel_safe = plan->parallel_safe;
3078 node->setParam = list_make1_int(prm->paramid);
3079
3080 root->init_plans = lappend(root->init_plans, node);
3081
3082 /*
3083 * The node can't have any inputs (since it's an initplan), so the
3084 * parParam and args lists remain empty.
3085 */
3086
3087 /* Set costs of SubPlan using info from the plan tree */
3088 cost_subplan(subroot, node, plan);
3089}
int plan_id
Definition: primnodes.h:1087
char * plan_name
Definition: primnodes.h:1089
int32 firstColTypmod
Definition: primnodes.h:1092
Oid firstColCollation
Definition: primnodes.h:1093
SubLinkType subLinkType
Definition: primnodes.h:1082
Oid firstColType
Definition: primnodes.h:1091

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

Referenced by create_minmaxagg_plan().

◆ SS_make_initplan_output_param()

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

Definition at line 3033 of file subselect.c.

3036{
3037 return generate_new_exec_param(root, resulttype,
3038 resulttypmod, resultcollation);
3039}

References generate_new_exec_param(), and root.

Referenced by preprocess_minmax_aggregates().

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 880 of file subselect.c.

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

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

Referenced by subquery_planner().

◆ SS_process_sublinks()

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

Definition at line 1946 of file subselect.c.

1947{
1949
1950 context.root = root;
1951 context.isTopQual = isQual;
1952 return process_sublinks_mutator(expr, &context);
1953}

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

Referenced by build_subplan(), and preprocess_expression().

◆ SS_replace_correlation_vars()

Node * SS_replace_correlation_vars ( PlannerInfo root,
Node expr 
)

Definition at line 1891 of file subselect.c.

1892{
1893 /* No setup needed for tree walk, so away we go */
1895}

References replace_correlation_vars_mutator(), and root.

Referenced by preprocess_expression().

◆ subpath_is_hashable()

static bool subpath_is_hashable ( Path path)
static

Definition at line 736 of file subselect.c.

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

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

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

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

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

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

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

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

Referenced by build_subplan().