PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, bool unknownEqFalse)
 
static bool subpath_is_hashable (Path *path, bool unknownEqFalse)
 
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 sublink_testexpr_is_not_nullable (PlannerInfo *root, SubLink *sublink)
 
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 const charsublinktype_to_string (SubLinkType subLinkType)
 
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)
 
ScalarArrayOpExprconvert_VALUES_to_ANY (PlannerInfo *root, Node *testexpr, Query *values)
 
JoinExprconvert_ANY_sublink_to_join (PlannerInfo *root, SubLink *sublink, bool under_not, 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 327 of file subselect.c.

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

References ANY_SUBLINK, arg, SubPlan::args, ARRAY_SUBLINK, Assert, bms_add_member(), convert_testexpr(), cost_subplan(), elog, enable_material, ERROR, ExecMaterializesOutput(), EXISTS_SUBLINK, TargetEntry::expr, EXPR_SUBLINK, exprCollation(), exprType(), exprTypmod(), fb(), SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, format_type_be(), generate_new_exec_param(), generate_subquery_params(), get_first_col_type(), get_promoted_array_type(), InvalidOid, IsA, SubPlan::isInitPlan, 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, SubPlan::parallel_safe, SubPlan::paramIds, SubPlan::parParam, plan, SubPlan::plan_id, PlannerInfo::plan_name, SubPlan::plan_name, root, ROWCOMPARE_SUBLINK, SubPlan::setParam, SS_process_sublinks(), SubPlan::subLinkType, subplan_is_hashable(), SubPlan::testexpr, testexpr_is_hashable(), SubPlan::unknownEqFalse, and SubPlan::useHashTable.

Referenced by make_subplan().

◆ contain_dml()

static bool contain_dml ( Node node)
static

Definition at line 1059 of file subselect.c.

1060{
1061 return contain_dml_walker(node, NULL);
1062}
static bool contain_dml_walker(Node *node, void *context)
Definition subselect.c:1065

References contain_dml_walker(), and fb().

Referenced by SS_process_ctes().

◆ contain_dml_walker()

static bool contain_dml_walker ( Node node,
void context 
)
static

Definition at line 1065 of file subselect.c.

1066{
1067 if (node == NULL)
1068 return false;
1069 if (IsA(node, Query))
1070 {
1071 Query *query = (Query *) node;
1072
1073 if (query->commandType != CMD_SELECT ||
1074 query->rowMarks != NIL)
1075 return true;
1076
1077 return query_tree_walker(query, contain_dml_walker, context, 0);
1078 }
1079 return expression_tree_walker(node, contain_dml_walker, context);
1080}
#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:275
List * rowMarks
Definition parsenodes.h:234
CmdType commandType
Definition parsenodes.h:121

References CMD_SELECT, Query::commandType, contain_dml_walker(), expression_tree_walker, fb(), 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 1086 of file subselect.c.

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

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

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

References contain_outer_selfref_walker(), expression_tree_walker, fb(), IsA, QTW_EXAMINE_RTES_BEFORE, query_tree_walker, and RTE_CTE.

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,
bool  under_not,
Relids  available_rels 
)

Definition at line 1339 of file subselect.c.

1341{
1342 JoinExpr *result;
1343 Query *parse = root->parse;
1344 Query *subselect = (Query *) sublink->subselect;
1346 int rtindex;
1351 Node *quals;
1352 ParseState *pstate;
1354 bool use_lateral;
1355
1356 Assert(sublink->subLinkType == ANY_SUBLINK);
1357
1358 /*
1359 * Per SQL spec, NOT IN is not ordinarily equivalent to an anti-join, so
1360 * that by default we have to fail when under_not. However, if we can
1361 * prove that neither the outer query's expressions nor the sub-select's
1362 * output columns can be NULL, and further that the operator itself cannot
1363 * return NULL for non-null inputs, then the logic is identical and it's
1364 * safe to convert NOT IN to an anti-join.
1365 */
1366 if (under_not &&
1368 !query_outputs_are_not_nullable(subselect)))
1369 return NULL;
1370
1371 /*
1372 * If the sub-select contains any Vars of the parent query, we treat it as
1373 * LATERAL. (Vars from higher levels don't matter here.)
1374 */
1377
1378 /*
1379 * Can't convert if the sub-select contains parent-level Vars of relations
1380 * not in available_rels.
1381 */
1383 return NULL;
1384
1385 /*
1386 * The test expression must contain some Vars of the parent query, else
1387 * it's not gonna be a join. (Note that it won't have Vars referring to
1388 * the subquery, rather Params.)
1389 */
1390 upper_varnos = pull_varnos(root, sublink->testexpr);
1392 return NULL;
1393
1394 /*
1395 * However, it can't refer to anything outside available_rels.
1396 */
1398 return NULL;
1399
1400 /*
1401 * The combining operators and left-hand expressions mustn't be volatile.
1402 */
1403 if (contain_volatile_functions(sublink->testexpr))
1404 return NULL;
1405
1406 /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1407 pstate = make_parsestate(NULL);
1408
1409 /*
1410 * Okay, pull up the sub-select into upper range table.
1411 *
1412 * We rely here on the assumption that the outer query has no references
1413 * to the inner (necessarily true, other than the Vars that we build
1414 * below). Therefore this is a lot easier than what pull_up_subqueries has
1415 * to go through.
1416 */
1418 subselect,
1419 NULL,
1421 false);
1422 rte = nsitem->p_rte;
1423 parse->rtable = lappend(parse->rtable, rte);
1424 rtindex = list_length(parse->rtable);
1425
1426 /*
1427 * Form a RangeTblRef for the pulled-up sub-select.
1428 */
1430 rtr->rtindex = rtindex;
1431
1432 /*
1433 * Build a list of Vars representing the subselect outputs.
1434 */
1436 subselect->targetList,
1437 rtindex);
1438
1439 /*
1440 * Build the new join's qual expression, replacing Params with these Vars.
1441 */
1442 quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1443
1444 /*
1445 * And finally, build the JoinExpr node.
1446 */
1447 result = makeNode(JoinExpr);
1448 result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1449 result->isNatural = false;
1450 result->larg = NULL; /* caller must fill this in */
1451 result->rarg = (Node *) rtr;
1452 result->usingClause = NIL;
1453 result->join_using_alias = NULL;
1454 result->quals = quals;
1455 result->alias = NULL;
1456 result->rtindex = 0; /* we don't need an RTE for it */
1457
1458 return result;
1459}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:412
#define bms_is_empty(a)
Definition bitmapset.h:118
bool query_outputs_are_not_nullable(Query *query)
Definition clauses.c:2049
bool contain_volatile_functions(Node *clause)
Definition clauses.c:549
void parse(int)
Definition parse.c:49
@ JOIN_SEMI
Definition nodes.h:317
@ JOIN_ANTI
Definition nodes.h:318
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
static bool sublink_testexpr_is_not_nullable(PlannerInfo *root, SubLink *sublink)
Definition subselect.c:1483
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition subselect.c:619
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(), fb(), generate_subquery_vars(), JoinExpr::isNatural, JOIN_ANTI, JOIN_SEMI, JoinExpr::jointype, lappend(), JoinExpr::larg, list_length(), make_parsestate(), makeNode, NIL, parse(), pull_varnos(), pull_varnos_of_level(), JoinExpr::quals, query_outputs_are_not_nullable(), JoinExpr::rarg, root, JoinExpr::rtindex, sublink_testexpr_is_not_nullable(), and Query::targetList.

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

1593{
1594 JoinExpr *result;
1595 Query *parse = root->parse;
1596 Query *subselect = (Query *) sublink->subselect;
1597 Node *whereClause;
1598 PlannerInfo subroot;
1599 int rtoffset;
1600 int varno;
1603
1604 Assert(sublink->subLinkType == EXISTS_SUBLINK);
1605
1606 /*
1607 * Can't flatten if it contains WITH. (We could arrange to pull up the
1608 * WITH into the parent query's cteList, but that risks changing the
1609 * semantics, since a WITH ought to be executed once per associated query
1610 * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1611 * this case, since it just produces a subquery RTE that doesn't have to
1612 * get flattened into the parent query.
1613 */
1614 if (subselect->cteList)
1615 return NULL;
1616
1617 /*
1618 * Copy the subquery so we can modify it safely (see comments in
1619 * make_subplan).
1620 */
1621 subselect = copyObject(subselect);
1622
1623 /*
1624 * See if the subquery can be simplified based on the knowledge that it's
1625 * being used in EXISTS(). If we aren't able to get rid of its
1626 * targetlist, we have to fail, because the pullup operation leaves us
1627 * with noplace to evaluate the targetlist.
1628 */
1629 if (!simplify_EXISTS_query(root, subselect))
1630 return NULL;
1631
1632 /*
1633 * Separate out the WHERE clause. (We could theoretically also remove
1634 * top-level plain JOIN/ON clauses, but it's probably not worth the
1635 * trouble.)
1636 */
1637 whereClause = subselect->jointree->quals;
1638 subselect->jointree->quals = NULL;
1639
1640 /*
1641 * The rest of the sub-select must not refer to any Vars of the parent
1642 * query. (Vars of higher levels should be okay, though.)
1643 */
1644 if (contain_vars_of_level((Node *) subselect, 1))
1645 return NULL;
1646
1647 /*
1648 * On the other hand, the WHERE clause must contain some Vars of the
1649 * parent query, else it's not gonna be a join.
1650 */
1651 if (!contain_vars_of_level(whereClause, 1))
1652 return NULL;
1653
1654 /*
1655 * We don't risk optimizing if the WHERE clause is volatile, either.
1656 */
1657 if (contain_volatile_functions(whereClause))
1658 return NULL;
1659
1660 /*
1661 * Scan the rangetable for relation RTEs and retrieve the necessary
1662 * catalog information for each relation. Using this information, clear
1663 * the inh flag for any relation that has no children, collect not-null
1664 * attribute numbers for any relation that has column not-null
1665 * constraints, and expand virtual generated columns for any relation that
1666 * contains them.
1667 *
1668 * Note: we construct up an entirely dummy PlannerInfo for use here. This
1669 * is fine because only the "glob" and "parse" links will be used in this
1670 * case.
1671 *
1672 * Note: we temporarily assign back the WHERE clause so that any virtual
1673 * generated column references within it can be expanded. It should be
1674 * separated out again afterward.
1675 */
1676 MemSet(&subroot, 0, sizeof(subroot));
1677 subroot.type = T_PlannerInfo;
1678 subroot.glob = root->glob;
1679 subroot.parse = subselect;
1680 subselect->jointree->quals = whereClause;
1681 subselect = preprocess_relation_rtes(&subroot);
1682
1683 /*
1684 * Now separate out the WHERE clause again.
1685 */
1686 whereClause = subselect->jointree->quals;
1687 subselect->jointree->quals = NULL;
1688
1689 /*
1690 * The subquery must have a nonempty jointree, but we can make it so.
1691 */
1692 replace_empty_jointree(subselect);
1693
1694 /*
1695 * Prepare to pull up the sub-select into top range table.
1696 *
1697 * We rely here on the assumption that the outer query has no references
1698 * to the inner (necessarily true). Therefore this is a lot easier than
1699 * what pull_up_subqueries has to go through.
1700 *
1701 * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1702 * do. The machinations of simplify_EXISTS_query ensured that there is
1703 * nothing interesting in the subquery except an rtable and jointree, and
1704 * even the jointree FromExpr no longer has quals. So we can just append
1705 * the rtable to our own and use the FromExpr in our jointree. But first,
1706 * adjust all level-zero varnos in the subquery to account for the rtable
1707 * merger.
1708 */
1709 rtoffset = list_length(parse->rtable);
1710 OffsetVarNodes((Node *) subselect, rtoffset, 0);
1711 OffsetVarNodes(whereClause, rtoffset, 0);
1712
1713 /*
1714 * Upper-level vars in subquery will now be one level closer to their
1715 * parent than before; in particular, anything that had been level 1
1716 * becomes level zero.
1717 */
1718 IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1719 IncrementVarSublevelsUp(whereClause, -1, 1);
1720
1721 /*
1722 * Now that the WHERE clause is adjusted to match the parent query
1723 * environment, we can easily identify all the level-zero rels it uses.
1724 * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1725 * not.
1726 */
1727 clause_varnos = pull_varnos(root, whereClause);
1729 varno = -1;
1730 while ((varno = bms_next_member(clause_varnos, varno)) >= 0)
1731 {
1732 if (varno <= rtoffset)
1734 }
1737
1738 /*
1739 * Now that we've got the set of upper-level varnos, we can make the last
1740 * check: only available_rels can be referenced.
1741 */
1743 return NULL;
1744
1745 /*
1746 * Now we can attach the modified subquery rtable to the parent. This also
1747 * adds subquery's RTEPermissionInfos into the upper query.
1748 */
1749 CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1750 subselect->rtable, subselect->rteperminfos);
1751
1752 /*
1753 * And finally, build the JoinExpr node.
1754 */
1755 result = makeNode(JoinExpr);
1756 result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1757 result->isNatural = false;
1758 result->larg = NULL; /* caller must fill this in */
1759 /* flatten out the FromExpr node if it's useless */
1760 if (list_length(subselect->jointree->fromlist) == 1)
1761 result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1762 else
1763 result->rarg = (Node *) subselect->jointree;
1764 result->usingClause = NIL;
1765 result->join_using_alias = NULL;
1766 result->quals = whereClause;
1767 result->alias = NULL;
1768 result->rtindex = 0; /* we don't need an RTE for it */
1769
1770 return result;
1771}
int bms_next_member(const Bitmapset *a, int prevbit)
Definition bitmapset.c:1290
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
#define MemSet(start, val, len)
Definition c.h:1109
#define copyObject(obj)
Definition nodes.h:232
void replace_empty_jointree(Query *parse)
Query * preprocess_relation_rtes(PlannerInfo *root)
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos)
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
PlannerGlobal * glob
Definition pathnodes.h:312
Query * parse
Definition pathnodes.h:309
static bool simplify_EXISTS_query(PlannerInfo *root, Query *query)
Definition subselect.c:1796
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, fb(), FromExpr::fromlist, PlannerInfo::glob, IncrementVarSublevelsUp(), JoinExpr::isNatural, JOIN_ANTI, JOIN_SEMI, Query::jointree, JoinExpr::jointype, JoinExpr::larg, linitial, list_length(), makeNode, MemSet, NIL, OffsetVarNodes(), PlannerInfo::parse, parse(), preprocess_relation_rtes(), pull_varnos(), JoinExpr::quals, FromExpr::quals, JoinExpr::rarg, replace_empty_jointree(), root, Query::rtable, JoinExpr::rtindex, and simplify_EXISTS_query().

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

1910{
1911 Node *whereClause;
1912 PlannerInfo subroot;
1913 List *leftargs,
1914 *rightargs,
1915 *opids,
1916 *opcollations,
1917 *newWhere,
1918 *tlist,
1919 *testlist,
1920 *paramids;
1921 ListCell *lc,
1922 *rc,
1923 *oc,
1924 *cc;
1925 AttrNumber resno;
1926
1927 /*
1928 * Query must not require a targetlist, since we have to insert a new one.
1929 * Caller should have dealt with the case already.
1930 */
1931 Assert(subselect->targetList == NIL);
1932
1933 /*
1934 * Separate out the WHERE clause. (We could theoretically also remove
1935 * top-level plain JOIN/ON clauses, but it's probably not worth the
1936 * trouble.)
1937 */
1938 whereClause = subselect->jointree->quals;
1939 subselect->jointree->quals = NULL;
1940
1941 /*
1942 * The rest of the sub-select must not refer to any Vars of the parent
1943 * query. (Vars of higher levels should be okay, though.)
1944 *
1945 * Note: we need not check for Aggrefs separately because we know the
1946 * sub-select is as yet unoptimized; any uplevel Aggref must therefore
1947 * contain an uplevel Var reference. This is not the case below ...
1948 */
1949 if (contain_vars_of_level((Node *) subselect, 1))
1950 return NULL;
1951
1952 /*
1953 * We don't risk optimizing if the WHERE clause is volatile, either.
1954 */
1955 if (contain_volatile_functions(whereClause))
1956 return NULL;
1957
1958 /*
1959 * Clean up the WHERE clause by doing const-simplification etc on it.
1960 * Aside from simplifying the processing we're about to do, this is
1961 * important for being able to pull chunks of the WHERE clause up into the
1962 * parent query. Since we are invoked partway through the parent's
1963 * preprocess_expression() work, earlier steps of preprocess_expression()
1964 * wouldn't get applied to the pulled-up stuff unless we do them here. For
1965 * the parts of the WHERE clause that get put back into the child query,
1966 * this work is partially duplicative, but it shouldn't hurt.
1967 *
1968 * Note: we do not run flatten_join_alias_vars. This is OK because any
1969 * parent aliases were flattened already, and we're not going to pull any
1970 * child Vars (of any description) into the parent.
1971 *
1972 * Note: we construct up an entirely dummy PlannerInfo to pass to
1973 * eval_const_expressions. This is fine because only the "glob" and
1974 * "parse" links are used by eval_const_expressions.
1975 */
1976 MemSet(&subroot, 0, sizeof(subroot));
1977 subroot.type = T_PlannerInfo;
1978 subroot.glob = root->glob;
1979 subroot.parse = subselect;
1980 whereClause = eval_const_expressions(&subroot, whereClause);
1981 whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
1982 whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
1983
1984 /*
1985 * We now have a flattened implicit-AND list of clauses, which we try to
1986 * break apart into "outervar = innervar" hash clauses. Anything that
1987 * can't be broken apart just goes back into the newWhere list. Note that
1988 * we aren't trying hard yet to ensure that we have only outer or only
1989 * inner on each side; we'll check that if we get to the end.
1990 */
1992 foreach(lc, (List *) whereClause)
1993 {
1994 OpExpr *expr = (OpExpr *) lfirst(lc);
1995
1996 if (IsA(expr, OpExpr) &&
1997 hash_ok_operator(expr))
1998 {
1999 Node *leftarg = (Node *) linitial(expr->args);
2000 Node *rightarg = (Node *) lsecond(expr->args);
2001
2003 {
2006 opids = lappend_oid(opids, expr->opno);
2007 opcollations = lappend_oid(opcollations, expr->inputcollid);
2008 continue;
2009 }
2011 {
2012 /*
2013 * We must commute the clause to put the outer var on the
2014 * left, because the hashing code in nodeSubplan.c expects
2015 * that. This probably shouldn't ever fail, since hashable
2016 * operators ought to have commutators, but be paranoid.
2017 */
2018 expr->opno = get_commutator(expr->opno);
2019 if (OidIsValid(expr->opno) && hash_ok_operator(expr))
2020 {
2023 opids = lappend_oid(opids, expr->opno);
2024 opcollations = lappend_oid(opcollations, expr->inputcollid);
2025 continue;
2026 }
2027 /* If no commutator, no chance to optimize the WHERE clause */
2028 return NULL;
2029 }
2030 }
2031 /* Couldn't handle it as a hash clause */
2032 newWhere = lappend(newWhere, expr);
2033 }
2034
2035 /*
2036 * If we didn't find anything we could convert, fail.
2037 */
2038 if (leftargs == NIL)
2039 return NULL;
2040
2041 /*
2042 * There mustn't be any parent Vars or Aggs in the stuff that we intend to
2043 * put back into the child query. Note: you might think we don't need to
2044 * check for Aggs separately, because an uplevel Agg must contain an
2045 * uplevel Var in its argument. But it is possible that the uplevel Var
2046 * got optimized away by eval_const_expressions. Consider
2047 *
2048 * SUM(CASE WHEN false THEN uplevelvar ELSE 0 END)
2049 */
2050 if (contain_vars_of_level((Node *) newWhere, 1) ||
2052 return NULL;
2053 if (root->parse->hasAggs &&
2056 return NULL;
2057
2058 /*
2059 * And there can't be any child Vars in the stuff we intend to pull up.
2060 * (Note: we'd need to check for child Aggs too, except we know the child
2061 * has no aggs at all because of simplify_EXISTS_query's check. The same
2062 * goes for window functions.)
2063 */
2065 return NULL;
2066
2067 /*
2068 * Also reject sublinks in the stuff we intend to pull up. (It might be
2069 * possible to support this, but doesn't seem worth the complication.)
2070 */
2072 return NULL;
2073
2074 /*
2075 * Okay, adjust the sublevelsup in the stuff we're pulling up.
2076 */
2078
2079 /*
2080 * Put back any child-level-only WHERE clauses.
2081 */
2082 if (newWhere)
2083 subselect->jointree->quals = (Node *) make_ands_explicit(newWhere);
2084
2085 /*
2086 * Build a new targetlist for the child that emits the expressions we
2087 * need. Concurrently, build a testexpr for the parent using Params to
2088 * reference the child outputs. (Since we generate Params directly here,
2089 * there will be no need to convert the testexpr in build_subplan.)
2090 */
2091 tlist = testlist = paramids = NIL;
2092 resno = 1;
2094 {
2095 Node *leftarg = (Node *) lfirst(lc);
2096 Node *rightarg = (Node *) lfirst(rc);
2097 Oid opid = lfirst_oid(oc);
2099 Param *param;
2100
2105 tlist = lappend(tlist,
2107 resno++,
2108 NULL,
2109 false));
2111 make_opclause(opid, BOOLOID, false,
2112 (Expr *) leftarg, (Expr *) param,
2114 paramids = lappend_int(paramids, param->paramid);
2115 }
2116
2117 /* Put everything where it should go, and we're done */
2118 subselect->targetList = tlist;
2119 *testexpr = (Node *) make_ands_explicit(testlist);
2120 *paramIds = paramids;
2121
2122 return subselect;
2123}
int16 AttrNumber
Definition attnum.h:21
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition clauses.c:2498
bool contain_subplans(Node *clause)
Definition clauses.c:341
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
Oid get_commutator(Oid opno)
Definition lsyscache.c:1729
Expr * make_ands_explicit(List *andclauses)
Definition makefuncs.c:799
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition makefuncs.c:701
List * make_ands_implicit(Expr *clause)
Definition makefuncs.c:810
#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)
Node * quals
Definition primnodes.h:2384
Oid opno
Definition primnodes.h:851
List * args
Definition primnodes.h:869
int paramid
Definition primnodes.h:397
FromExpr * jointree
Definition parsenodes.h:182
List * targetList
Definition parsenodes.h:198
static bool hash_ok_operator(OpExpr *expr)
Definition subselect.c:836

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(), fb(), forfour, generate_new_exec_param(), get_commutator(), PlannerInfo::glob, 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(), MemSet, NIL, OidIsValid, OpExpr::opno, Param::paramid, PlannerInfo::parse, 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 648 of file subselect.c.

651{
653
654 context.root = root;
655 context.subst_nodes = subst_nodes;
656 return convert_testexpr_mutator(testexpr, &context);
657}
static Node * convert_testexpr_mutator(Node *node, convert_testexpr_context *context)
Definition subselect.c:660

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

Referenced by build_subplan(), convert_ANY_sublink_to_join(), and convert_VALUES_to_ANY().

◆ convert_testexpr_mutator()

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

Definition at line 660 of file subselect.c.

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

References convert_testexpr_mutator(), copyObject, elog, ERROR, expression_tree_mutator, fb(), 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().

◆ convert_VALUES_to_ANY()

ScalarArrayOpExpr * convert_VALUES_to_ANY ( PlannerInfo root,
Node testexpr,
Query values 
)

Definition at line 1230 of file subselect.c.

1231{
1233 Node *leftop;
1234 Node *rightop;
1235 Oid opno;
1236 ListCell *lc;
1237 Oid inputcollid;
1238 List *exprs = NIL;
1239
1240 /*
1241 * Check we have a binary operator over a single-column subquery with no
1242 * joins and no LIMIT/OFFSET/ORDER BY clauses.
1243 */
1244 if (!IsA(testexpr, OpExpr) ||
1245 list_length(((OpExpr *) testexpr)->args) != 2 ||
1246 list_length(values->targetList) > 1 ||
1247 values->limitCount != NULL ||
1248 values->limitOffset != NULL ||
1249 values->sortClause != NIL ||
1250 list_length(values->rtable) != 1)
1251 return NULL;
1252
1254 leftop = linitial(((OpExpr *) testexpr)->args);
1255 rightop = lsecond(((OpExpr *) testexpr)->args);
1256 opno = ((OpExpr *) testexpr)->opno;
1257 inputcollid = ((OpExpr *) testexpr)->inputcollid;
1258
1259 /*
1260 * Also, check that only RTE corresponds to VALUES; the list of values has
1261 * at least two items and no volatile functions.
1262 */
1263 if (rte->rtekind != RTE_VALUES ||
1264 list_length(rte->values_lists) < 2 ||
1265 contain_volatile_functions((Node *) rte->values_lists))
1266 return NULL;
1267
1268 foreach(lc, rte->values_lists)
1269 {
1270 List *elem = lfirst(lc);
1271 Node *value = linitial(elem);
1272
1273 /*
1274 * Prepare an evaluation of the right side of the operator with
1275 * substitution of the given value.
1276 */
1278
1279 /*
1280 * Try to evaluate constant expressions. We could get Const as a
1281 * result.
1282 */
1284
1285 /*
1286 * As we only support constant output arrays, all the items must also
1287 * be constant.
1288 */
1289 if (!IsA(value, Const))
1290 return NULL;
1291
1292 exprs = lappend(exprs, value);
1293 }
1294
1295 /* Finally, build ScalarArrayOpExpr at the top of the 'exprs' list. */
1296 return make_SAOP_expr(opno, leftop, exprType(rightop),
1297 linitial_oid(rte->colcollations), inputcollid,
1298 exprs, false);
1299}
static Datum values[MAXATTR]
Definition bootstrap.c:188
ScalarArrayOpExpr * make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
Definition clauses.c:6236
static struct @174 value
@ RTE_VALUES
#define linitial_node(type, l)
Definition pg_list.h:181
#define list_make1(x1)
Definition pg_list.h:212
#define linitial_oid(l)
Definition pg_list.h:180

References contain_volatile_functions(), convert_testexpr(), eval_const_expressions(), exprType(), fb(), IsA, lappend(), lfirst, linitial, linitial_node, linitial_oid, list_length(), list_make1, lsecond, make_SAOP_expr(), NIL, root, RTE_VALUES, value, and values.

Referenced by pull_up_sublinks_qual_recurse().

◆ finalize_agg_primnode()

static bool finalize_agg_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 3268 of file subselect.c.

3269{
3270 if (node == NULL)
3271 return false;
3272 if (IsA(node, Aggref))
3273 {
3274 Aggref *agg = (Aggref *) node;
3275
3276 /* we should not consider the direct arguments, if any */
3277 finalize_primnode((Node *) agg->args, context);
3278 finalize_primnode((Node *) agg->aggfilter, context);
3279 return false; /* there can't be any Aggrefs below here */
3280 }
3281 return expression_tree_walker(node, finalize_agg_primnode, context);
3282}
static bool finalize_agg_primnode(Node *node, finalize_primnode_context *context)
Definition subselect.c:3268
static bool finalize_primnode(Node *node, finalize_primnode_context *context)
Definition subselect.c:3185

References expression_tree_walker, fb(), 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 2587 of file subselect.c.

2591{
2598 ListCell *l;
2599
2600 if (plan == NULL)
2601 return NULL;
2602
2603 context.root = root;
2604 context.paramids = NULL; /* initialize set to empty */
2605 locally_added_param = -1; /* there isn't one */
2606 nestloop_params = NULL; /* there aren't any */
2607
2608 /*
2609 * Examine any initPlans to determine the set of external params they
2610 * reference and the set of output params they supply. (We assume
2611 * SS_finalize_plan was run on them already.)
2612 */
2614 foreach(l, plan->initPlan)
2615 {
2618 ListCell *l2;
2619
2621 foreach(l2, initsubplan->setParam)
2622 {
2624 }
2625 }
2626
2627 /* Any setParams are validly referenceable in this node and children */
2628 if (initSetParam)
2630
2631 /*
2632 * When we call finalize_primnode, context.paramids sets are automatically
2633 * merged together. But when recursing to self, we have to do it the hard
2634 * way. We want the paramids set to include params in subplans as well as
2635 * at this level.
2636 */
2637
2638 /* Find params in targetlist and qual */
2639 finalize_primnode((Node *) plan->targetlist, &context);
2640 finalize_primnode((Node *) plan->qual, &context);
2641
2642 /*
2643 * If it's a parallel-aware scan node, mark it as dependent on the parent
2644 * Gather/GatherMerge's rescan Param.
2645 */
2646 if (plan->parallel_aware)
2647 {
2648 if (gather_param < 0)
2649 elog(ERROR, "parallel-aware plan node is not below a Gather");
2650 context.paramids =
2652 }
2653
2654 /* Check additional node-type-specific fields */
2655 switch (nodeTag(plan))
2656 {
2657 case T_Result:
2658 finalize_primnode(((Result *) plan)->resconstantqual,
2659 &context);
2660 break;
2661
2662 case T_SeqScan:
2663 context.paramids = bms_add_members(context.paramids, scan_params);
2664 break;
2665
2666 case T_SampleScan:
2667 finalize_primnode((Node *) ((SampleScan *) plan)->tablesample,
2668 &context);
2669 context.paramids = bms_add_members(context.paramids, scan_params);
2670 break;
2671
2672 case T_IndexScan:
2673 finalize_primnode((Node *) ((IndexScan *) plan)->indexqual,
2674 &context);
2675 finalize_primnode((Node *) ((IndexScan *) plan)->indexorderby,
2676 &context);
2677
2678 /*
2679 * we need not look at indexqualorig, since it will have the same
2680 * param references as indexqual. Likewise, we can ignore
2681 * indexorderbyorig.
2682 */
2683 context.paramids = bms_add_members(context.paramids, scan_params);
2684 break;
2685
2686 case T_IndexOnlyScan:
2687 finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexqual,
2688 &context);
2689 finalize_primnode((Node *) ((IndexOnlyScan *) plan)->recheckqual,
2690 &context);
2691 finalize_primnode((Node *) ((IndexOnlyScan *) plan)->indexorderby,
2692 &context);
2693
2694 /*
2695 * we need not look at indextlist, since it cannot contain Params.
2696 */
2697 context.paramids = bms_add_members(context.paramids, scan_params);
2698 break;
2699
2700 case T_BitmapIndexScan:
2701 finalize_primnode((Node *) ((BitmapIndexScan *) plan)->indexqual,
2702 &context);
2703
2704 /*
2705 * we need not look at indexqualorig, since it will have the same
2706 * param references as indexqual.
2707 */
2708 break;
2709
2710 case T_BitmapHeapScan:
2711 finalize_primnode((Node *) ((BitmapHeapScan *) plan)->bitmapqualorig,
2712 &context);
2713 context.paramids = bms_add_members(context.paramids, scan_params);
2714 break;
2715
2716 case T_TidScan:
2717 finalize_primnode((Node *) ((TidScan *) plan)->tidquals,
2718 &context);
2719 context.paramids = bms_add_members(context.paramids, scan_params);
2720 break;
2721
2722 case T_TidRangeScan:
2723 finalize_primnode((Node *) ((TidRangeScan *) plan)->tidrangequals,
2724 &context);
2725 context.paramids = bms_add_members(context.paramids, scan_params);
2726 break;
2727
2728 case T_SubqueryScan:
2729 {
2731 RelOptInfo *rel;
2733
2734 /* We must run finalize_plan on the subquery */
2735 rel = find_base_rel(root, sscan->scan.scanrelid);
2737 if (gather_param >= 0)
2739 gather_param);
2740 finalize_plan(rel->subroot, sscan->subplan, gather_param,
2742
2743 /* Now we can add its extParams to the parent's params */
2744 context.paramids = bms_add_members(context.paramids,
2745 sscan->subplan->extParam);
2746 /* We need scan_params too, though */
2747 context.paramids = bms_add_members(context.paramids,
2748 scan_params);
2749 }
2750 break;
2751
2752 case T_FunctionScan:
2753 {
2755 ListCell *lc;
2756
2757 /*
2758 * Call finalize_primnode independently on each function
2759 * expression, so that we can record which params are
2760 * referenced in each, in order to decide which need
2761 * re-evaluating during rescan.
2762 */
2763 foreach(lc, fscan->functions)
2764 {
2767
2768 funccontext = context;
2770
2772
2773 /* remember results for execution */
2774 rtfunc->funcparams = funccontext.paramids;
2775
2776 /* add the function's params to the overall set */
2777 context.paramids = bms_add_members(context.paramids,
2778 funccontext.paramids);
2779 }
2780
2781 context.paramids = bms_add_members(context.paramids,
2782 scan_params);
2783 }
2784 break;
2785
2786 case T_TableFuncScan:
2787 finalize_primnode((Node *) ((TableFuncScan *) plan)->tablefunc,
2788 &context);
2789 context.paramids = bms_add_members(context.paramids, scan_params);
2790 break;
2791
2792 case T_ValuesScan:
2793 finalize_primnode((Node *) ((ValuesScan *) plan)->values_lists,
2794 &context);
2795 context.paramids = bms_add_members(context.paramids, scan_params);
2796 break;
2797
2798 case T_CteScan:
2799 {
2800 /*
2801 * You might think we should add the node's cteParam to
2802 * paramids, but we shouldn't because that param is just a
2803 * linkage mechanism for multiple CteScan nodes for the same
2804 * CTE; it is never used for changed-param signaling. What we
2805 * have to do instead is to find the referenced CTE plan and
2806 * incorporate its external paramids, so that the correct
2807 * things will happen if the CTE references outer-level
2808 * variables. See test cases for bug #4902. (We assume
2809 * SS_finalize_plan was run on the CTE plan already.)
2810 */
2811 int plan_id = ((CteScan *) plan)->ctePlanId;
2812 Plan *cteplan;
2813
2814 /* so, do this ... */
2815 if (plan_id < 1 || plan_id > list_length(root->glob->subplans))
2816 elog(ERROR, "could not find plan for CteScan referencing plan ID %d",
2817 plan_id);
2818 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2819 context.paramids =
2820 bms_add_members(context.paramids, cteplan->extParam);
2821
2822#ifdef NOT_USED
2823 /* ... but not this */
2824 context.paramids =
2825 bms_add_member(context.paramids,
2826 ((CteScan *) plan)->cteParam);
2827#endif
2828
2829 context.paramids = bms_add_members(context.paramids,
2830 scan_params);
2831 }
2832 break;
2833
2834 case T_WorkTableScan:
2835 context.paramids =
2836 bms_add_member(context.paramids,
2837 ((WorkTableScan *) plan)->wtParam);
2838 context.paramids = bms_add_members(context.paramids, scan_params);
2839 break;
2840
2842 context.paramids = bms_add_members(context.paramids, scan_params);
2843 break;
2844
2845 case T_ForeignScan:
2846 {
2848
2849 finalize_primnode((Node *) fscan->fdw_exprs,
2850 &context);
2851 finalize_primnode((Node *) fscan->fdw_recheck_quals,
2852 &context);
2853
2854 /* We assume fdw_scan_tlist cannot contain Params */
2855 context.paramids = bms_add_members(context.paramids,
2856 scan_params);
2857 }
2858 break;
2859
2860 case T_CustomScan:
2861 {
2863 ListCell *lc;
2864
2865 finalize_primnode((Node *) cscan->custom_exprs,
2866 &context);
2867 /* We assume custom_scan_tlist cannot contain Params */
2868 context.paramids =
2870
2871 /* child nodes if any */
2872 foreach(lc, cscan->custom_plans)
2873 {
2874 context.paramids =
2875 bms_add_members(context.paramids,
2877 (Plan *) lfirst(lc),
2880 scan_params));
2881 }
2882 }
2883 break;
2884
2885 case T_ModifyTable:
2886 {
2888
2889 /* Force descendant scan nodes to reference epqParam */
2895 finalize_primnode((Node *) mtplan->returningLists,
2896 &context);
2897 finalize_primnode((Node *) mtplan->onConflictSet,
2898 &context);
2899 finalize_primnode((Node *) mtplan->onConflictWhere,
2900 &context);
2901 /* exclRelTlist contains only Vars, doesn't need examination */
2902 }
2903 break;
2904
2905 case T_Append:
2906 {
2907 foreach(l, ((Append *) plan)->appendplans)
2908 {
2909 context.paramids =
2910 bms_add_members(context.paramids,
2912 (Plan *) lfirst(l),
2915 scan_params));
2916 }
2917 }
2918 break;
2919
2920 case T_MergeAppend:
2921 {
2922 foreach(l, ((MergeAppend *) plan)->mergeplans)
2923 {
2924 context.paramids =
2925 bms_add_members(context.paramids,
2927 (Plan *) lfirst(l),
2930 scan_params));
2931 }
2932 }
2933 break;
2934
2935 case T_BitmapAnd:
2936 {
2937 foreach(l, ((BitmapAnd *) plan)->bitmapplans)
2938 {
2939 context.paramids =
2940 bms_add_members(context.paramids,
2942 (Plan *) lfirst(l),
2945 scan_params));
2946 }
2947 }
2948 break;
2949
2950 case T_BitmapOr:
2951 {
2952 foreach(l, ((BitmapOr *) plan)->bitmapplans)
2953 {
2954 context.paramids =
2955 bms_add_members(context.paramids,
2957 (Plan *) lfirst(l),
2960 scan_params));
2961 }
2962 }
2963 break;
2964
2965 case T_NestLoop:
2966 {
2967 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2968 &context);
2969 /* collect set of params that will be passed to right child */
2970 foreach(l, ((NestLoop *) plan)->nestParams)
2971 {
2973
2975 nlp->paramno);
2976 }
2977 }
2978 break;
2979
2980 case T_MergeJoin:
2981 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2982 &context);
2983 finalize_primnode((Node *) ((MergeJoin *) plan)->mergeclauses,
2984 &context);
2985 break;
2986
2987 case T_HashJoin:
2988 finalize_primnode((Node *) ((Join *) plan)->joinqual,
2989 &context);
2990 finalize_primnode((Node *) ((HashJoin *) plan)->hashclauses,
2991 &context);
2992 break;
2993
2994 case T_Hash:
2995 finalize_primnode((Node *) ((Hash *) plan)->hashkeys,
2996 &context);
2997 break;
2998
2999 case T_Limit:
3000 finalize_primnode(((Limit *) plan)->limitOffset,
3001 &context);
3002 finalize_primnode(((Limit *) plan)->limitCount,
3003 &context);
3004 break;
3005
3006 case T_RecursiveUnion:
3007 /* child nodes are allowed to reference wtParam */
3008 locally_added_param = ((RecursiveUnion *) plan)->wtParam;
3011 /* wtParam does *not* get added to scan_params */
3012 break;
3013
3014 case T_LockRows:
3015 /* Force descendant scan nodes to reference epqParam */
3016 locally_added_param = ((LockRows *) plan)->epqParam;
3021 break;
3022
3023 case T_Agg:
3024 {
3025 Agg *agg = (Agg *) plan;
3026
3027 /*
3028 * AGG_HASHED plans need to know which Params are referenced
3029 * in aggregate calls. Do a separate scan to identify them.
3030 */
3031 if (agg->aggstrategy == AGG_HASHED)
3032 {
3033 finalize_primnode_context aggcontext;
3034
3035 aggcontext.root = root;
3036 aggcontext.paramids = NULL;
3037 finalize_agg_primnode((Node *) agg->plan.targetlist,
3038 &aggcontext);
3039 finalize_agg_primnode((Node *) agg->plan.qual,
3040 &aggcontext);
3041 agg->aggParams = aggcontext.paramids;
3042 }
3043 }
3044 break;
3045
3046 case T_WindowAgg:
3047 finalize_primnode(((WindowAgg *) plan)->startOffset,
3048 &context);
3049 finalize_primnode(((WindowAgg *) plan)->endOffset,
3050 &context);
3051 break;
3052
3053 case T_Gather:
3054 /* child nodes are allowed to reference rescan_param, if any */
3055 locally_added_param = ((Gather *) plan)->rescan_param;
3056 if (locally_added_param >= 0)
3057 {
3060
3061 /*
3062 * We currently don't support nested Gathers. The issue so
3063 * far as this function is concerned would be how to identify
3064 * which child nodes depend on which Gather.
3065 */
3066 Assert(gather_param < 0);
3067 /* Pass down rescan_param to child parallel-aware nodes */
3069 }
3070 /* rescan_param does *not* get added to scan_params */
3071 break;
3072
3073 case T_GatherMerge:
3074 /* child nodes are allowed to reference rescan_param, if any */
3075 locally_added_param = ((GatherMerge *) plan)->rescan_param;
3076 if (locally_added_param >= 0)
3077 {
3080
3081 /*
3082 * We currently don't support nested Gathers. The issue so
3083 * far as this function is concerned would be how to identify
3084 * which child nodes depend on which Gather.
3085 */
3086 Assert(gather_param < 0);
3087 /* Pass down rescan_param to child parallel-aware nodes */
3089 }
3090 /* rescan_param does *not* get added to scan_params */
3091 break;
3092
3093 case T_Memoize:
3094 finalize_primnode((Node *) ((Memoize *) plan)->param_exprs,
3095 &context);
3096 break;
3097
3098 case T_ProjectSet:
3099 case T_Material:
3100 case T_Sort:
3101 case T_IncrementalSort:
3102 case T_Unique:
3103 case T_SetOp:
3104 case T_Group:
3105 /* no node-type-specific fields need fixing */
3106 break;
3107
3108 default:
3109 elog(ERROR, "unrecognized node type: %d",
3110 (int) nodeTag(plan));
3111 }
3112
3113 /* Process left and right child plans, if any */
3115 plan->lefttree,
3118 scan_params);
3119 context.paramids = bms_add_members(context.paramids, child_params);
3120
3121 if (nestloop_params)
3122 {
3123 /* right child can reference nestloop_params as well as valid_params */
3125 plan->righttree,
3128 scan_params);
3129 /* ... and they don't count as parameters used at my level */
3132 }
3133 else
3134 {
3135 /* easy case */
3137 plan->righttree,
3140 scan_params);
3141 }
3142 context.paramids = bms_add_members(context.paramids, child_params);
3143
3144 /*
3145 * Any locally generated parameter doesn't count towards its generating
3146 * plan node's external dependencies. (Note: if we changed valid_params
3147 * and/or scan_params, we leak those bitmapsets; not worth the notational
3148 * trouble to clean them up.)
3149 */
3150 if (locally_added_param >= 0)
3151 {
3152 context.paramids = bms_del_member(context.paramids,
3154 }
3155
3156 /* Now we have all the paramids referenced in this node and children */
3157
3158 if (!bms_is_subset(context.paramids, valid_params))
3159 elog(ERROR, "plan should not reference subplan's variable");
3160
3161 /*
3162 * The plan node's allParam and extParam fields should include all its
3163 * referenced paramids, plus contributions from any child initPlans.
3164 * However, any setParams of the initPlans should not be present in the
3165 * parent node's extParams, only in its allParams. (It's possible that
3166 * some initPlans have extParams that are setParams of other initPlans.)
3167 */
3168
3169 /* allParam must include initplans' extParams and setParams */
3170 plan->allParam = bms_union(context.paramids, initExtParam);
3171 plan->allParam = bms_add_members(plan->allParam, initSetParam);
3172 /* extParam must include any initplan extParams */
3173 plan->extParam = bms_union(context.paramids, initExtParam);
3174 /* but not any initplan setParams */
3175 plan->extParam = bms_del_members(plan->extParam, initSetParam);
3176
3177 return plan->allParam;
3178}
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:1145
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition bitmapset.c:852
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:901
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:366
#define planner_subplan_get_plan(root, subplan)
Definition pathnodes.h:277
#define lfirst_int(lc)
Definition pg_list.h:173
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:544
Bitmapset * outer_params
Definition pathnodes.h:331
PlannerInfo * subroot
Definition pathnodes.h:1088
static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
Definition subselect.c:2587

References AGG_HASHED, Assert, bms_add_member(), bms_add_members(), bms_copy(), bms_del_member(), bms_del_members(), bms_difference(), bms_free(), bms_is_subset(), bms_union(), elog, ModifyTable::epqParam, ERROR, fb(), finalize_agg_primnode(), finalize_plan(), finalize_primnode(), find_base_rel(), RangeTblFunction::funcexpr, lfirst, lfirst_int, list_length(), list_nth(), nodeTag, PlannerInfo::outer_params, finalize_primnode_context::paramids, plan, planner_subplan_get_plan, finalize_primnode_context::root, root, and RelOptInfo::subroot.

Referenced by finalize_plan(), and SS_finalize_plan().

◆ finalize_primnode()

static bool finalize_primnode ( Node node,
finalize_primnode_context context 
)
static

Definition at line 3185 of file subselect.c.

3186{
3187 if (node == NULL)
3188 return false;
3189 if (IsA(node, Param))
3190 {
3191 if (((Param *) node)->paramkind == PARAM_EXEC)
3192 {
3193 int paramid = ((Param *) node)->paramid;
3194
3195 context->paramids = bms_add_member(context->paramids, paramid);
3196 }
3197 return false; /* no more to do here */
3198 }
3199 else if (IsA(node, Aggref))
3200 {
3201 /*
3202 * Check to see if the aggregate will be replaced by a Param
3203 * referencing a subquery output during setrefs.c. If so, we must
3204 * account for that Param here. (For various reasons, it's not
3205 * convenient to perform that substitution earlier than setrefs.c, nor
3206 * to perform this processing after setrefs.c. Thus we need a wart
3207 * here.)
3208 */
3209 Aggref *aggref = (Aggref *) node;
3210 Param *aggparam;
3211
3213 if (aggparam != NULL)
3214 context->paramids = bms_add_member(context->paramids,
3215 aggparam->paramid);
3216 /* Fall through to examine the agg's arguments */
3217 }
3218 else if (IsA(node, SubPlan))
3219 {
3220 SubPlan *subplan = (SubPlan *) node;
3221 Plan *plan = planner_subplan_get_plan(context->root, subplan);
3222 ListCell *lc;
3224
3225 /* Recurse into the testexpr, but not into the Plan */
3226 finalize_primnode(subplan->testexpr, context);
3227
3228 /*
3229 * Remove any param IDs of output parameters of the subplan that were
3230 * referenced in the testexpr. These are not interesting for
3231 * parameter change signaling since we always re-evaluate the subplan.
3232 * Note that this wouldn't work too well if there might be uses of the
3233 * same param IDs elsewhere in the plan, but that can't happen because
3234 * generate_new_exec_param never tries to merge params.
3235 */
3236 foreach(lc, subplan->paramIds)
3237 {
3238 context->paramids = bms_del_member(context->paramids,
3239 lfirst_int(lc));
3240 }
3241
3242 /* Also examine args list */
3243 finalize_primnode((Node *) subplan->args, context);
3244
3245 /*
3246 * Add params needed by the subplan to paramids, but excluding those
3247 * we will pass down to it. (We assume SS_finalize_plan was run on
3248 * the subplan already.)
3249 */
3250 subparamids = bms_copy(plan->extParam);
3251 foreach(lc, subplan->parParam)
3252 {
3254 }
3255 context->paramids = bms_join(context->paramids, subparamids);
3256
3257 return false; /* no more to do here */
3258 }
3259 return expression_tree_walker(node, finalize_primnode, context);
3260}
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition bitmapset.c:1214
@ PARAM_EXEC
Definition primnodes.h:386
Param * find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
Definition setrefs.c:3593

References SubPlan::args, bms_add_member(), bms_copy(), bms_del_member(), bms_join(), expression_tree_walker, fb(), finalize_primnode(), find_minmax_agg_replacement_param(), IsA, lfirst_int, PARAM_EXEC, 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 586 of file subselect.c.

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

References exprCollation(), exprType(), exprTypmod(), fb(), 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 619 of file subselect.c.

620{
621 List *result;
622 ListCell *lc;
623
624 result = NIL;
625 foreach(lc, tlist)
626 {
628 Var *var;
629
630 if (tent->resjunk)
631 continue;
632
633 var = makeVarFromTargetEntry(varno, tent);
634 result = lappend(result, var);
635 }
636
637 return result;
638}
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition makefuncs.c:107

References fb(), 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 121 of file subselect.c.

123{
124 /* In cases such as EXISTS, tlist might be empty; arbitrarily use VOID */
125 if (plan->targetlist)
126 {
128
129 if (!tent->resjunk)
130 {
131 *coltype = exprType((Node *) tent->expr);
132 *coltypmod = exprTypmod((Node *) tent->expr);
133 *colcollation = exprCollation((Node *) tent->expr);
134 return;
135 }
136 }
137 *coltype = VOIDOID;
138 *coltypmod = -1;
140}

References exprCollation(), exprType(), exprTypmod(), fb(), 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 836 of file subselect.c.

837{
838 Oid opid = expr->opno;
839
840 /* quick out if not a binary operator */
841 if (list_length(expr->args) != 2)
842 return false;
843 if (opid == ARRAY_EQ_OP ||
845 {
846 /* these are strict, but must check input type to ensure hashable */
847 Node *leftarg = linitial(expr->args);
848
850 }
851 else
852 {
853 /* else must look up the operator properties */
856
858 if (!HeapTupleIsValid(tup))
859 elog(ERROR, "cache lookup failed for operator %u", opid);
861 if (!optup->oprcanhash || !func_strict(optup->oprcode))
862 {
864 return false;
865 }
867 return true;
868 }
869}
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
bool op_hashjoinable(Oid opno, Oid inputtype)
Definition lsyscache.c:1657
bool func_strict(Oid funcid)
Definition lsyscache.c:1981
END_CATALOG_STRUCT typedef FormData_pg_operator * Form_pg_operator
Definition pg_operator.h:87
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220

References OpExpr::args, elog, ERROR, exprType(), fb(), Form_pg_operator, 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 1140 of file subselect.c.

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

References castNode, inline_cte_walker_context::ctename, CommonTableExpr::ctename, inline_cte_walker_context::ctequery, CommonTableExpr::ctequery, fb(), 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 1153 of file subselect.c.

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

References copyObject, inline_cte_walker_context::ctename, inline_cte_walker_context::ctequery, expression_tree_walker, fb(), IncrementVarSublevelsUp(), inline_cte_walker(), IsA, inline_cte_walker_context::levelsup, NIL, QTW_EXAMINE_RTES_AFTER, query_tree_walker, RTE_CTE, and RTE_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 165 of file subselect.c.

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

References ALL_SUBLINK, ANY_SUBLINK, Assert, build_subplan(), castNode, choose_plan_name(), convert_EXISTS_to_ANY(), copyObject, create_plan(), EXISTS_SUBLINK, fb(), fetch_upper_rel(), get_cheapest_fractional_path(), IsA, list_make2, makeNode, NIL, plan, root, simplify_EXISTS_query(), sublinktype_to_string(), subpath_is_hashable(), subquery_planner(), and UPPERREL_FINAL.

Referenced by process_sublinks_mutator().

◆ process_sublinks_mutator()

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

Definition at line 2217 of file subselect.c.

2218{
2220
2221 locContext.root = context->root;
2222
2223 if (node == NULL)
2224 return NULL;
2225 if (IsA(node, SubLink))
2226 {
2227 SubLink *sublink = (SubLink *) node;
2228 Node *testexpr;
2229
2230 /*
2231 * First, recursively process the lefthand-side expressions, if any.
2232 * They're not top-level anymore.
2233 */
2234 locContext.isTopQual = false;
2235 testexpr = process_sublinks_mutator(sublink->testexpr, &locContext);
2236
2237 /*
2238 * Now build the SubPlan node and make the expr to return.
2239 */
2240 return make_subplan(context->root,
2241 (Query *) sublink->subselect,
2242 sublink->subLinkType,
2243 sublink->subLinkId,
2244 testexpr,
2245 context->isTopQual);
2246 }
2247
2248 /*
2249 * Don't recurse into the arguments of an outer PHV, Aggref, GroupingFunc,
2250 * or ReturningExpr here. Any SubLinks in the arguments have to be dealt
2251 * with at the outer query level; they'll be handled when build_subplan
2252 * collects the PHV, Aggref, GroupingFunc, or ReturningExpr into the
2253 * arguments to be passed down to the current subplan.
2254 */
2255 if (IsA(node, PlaceHolderVar))
2256 {
2257 if (((PlaceHolderVar *) node)->phlevelsup > 0)
2258 return node;
2259 }
2260 else if (IsA(node, Aggref))
2261 {
2262 if (((Aggref *) node)->agglevelsup > 0)
2263 return node;
2264 }
2265 else if (IsA(node, GroupingFunc))
2266 {
2267 if (((GroupingFunc *) node)->agglevelsup > 0)
2268 return node;
2269 }
2270 else if (IsA(node, ReturningExpr))
2271 {
2272 if (((ReturningExpr *) node)->retlevelsup > 0)
2273 return node;
2274 }
2275
2276 /*
2277 * We should never see a SubPlan expression in the input (since this is
2278 * the very routine that creates 'em to begin with). We shouldn't find
2279 * ourselves invoked directly on a Query, either.
2280 */
2281 Assert(!IsA(node, SubPlan));
2282 Assert(!IsA(node, AlternativeSubPlan));
2283 Assert(!IsA(node, Query));
2284
2285 /*
2286 * Because make_subplan() could return an AND or OR clause, we have to
2287 * take steps to preserve AND/OR flatness of a qual. We assume the input
2288 * has been AND/OR flattened and so we need no recursion here.
2289 *
2290 * (Due to the coding here, we will not get called on the List subnodes of
2291 * an AND; and the input is *not* yet in implicit-AND format. So no check
2292 * is needed for a bare List.)
2293 *
2294 * Anywhere within the top-level AND/OR clause structure, we can tell
2295 * make_subplan() that NULL and FALSE are interchangeable. So isTopQual
2296 * propagates down in both cases. (Note that this is unlike the meaning
2297 * of "top level qual" used in most other places in Postgres.)
2298 */
2299 if (is_andclause(node))
2300 {
2301 List *newargs = NIL;
2302 ListCell *l;
2303
2304 /* Still at qual top-level */
2305 locContext.isTopQual = context->isTopQual;
2306
2307 foreach(l, ((BoolExpr *) node)->args)
2308 {
2309 Node *newarg;
2310
2312 if (is_andclause(newarg))
2313 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2314 else
2316 }
2317 return (Node *) make_andclause(newargs);
2318 }
2319
2320 if (is_orclause(node))
2321 {
2322 List *newargs = NIL;
2323 ListCell *l;
2324
2325 /* Still at qual top-level */
2326 locContext.isTopQual = context->isTopQual;
2327
2328 foreach(l, ((BoolExpr *) node)->args)
2329 {
2330 Node *newarg;
2331
2333 if (is_orclause(newarg))
2334 newargs = list_concat(newargs, ((BoolExpr *) newarg)->args);
2335 else
2337 }
2338 return (Node *) make_orclause(newargs);
2339 }
2340
2341 /*
2342 * If we recurse down through anything other than an AND or OR node, we
2343 * are definitely not at top qual level anymore.
2344 */
2345 locContext.isTopQual = false;
2346
2347 return expression_tree_mutator(node,
2349 &locContext);
2350}
List * list_concat(List *list1, const List *list2)
Definition list.c:561
Expr * make_orclause(List *orclauses)
Definition makefuncs.c:743
Expr * make_andclause(List *andclauses)
Definition makefuncs.c:727
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:2217
static Node * make_subplan(PlannerInfo *root, Query *orig_subquery, SubLinkType subLinkType, int subLinkId, Node *testexpr, bool isTopQual)
Definition subselect.c:165

References Assert, expression_tree_mutator, fb(), is_andclause(), is_orclause(), IsA, process_sublinks_context::isTopQual, lappend(), lfirst, list_concat(), make_andclause(), make_orclause(), make_subplan(), NIL, process_sublinks_mutator(), and process_sublinks_context::root.

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

2160{
2161 if (node == NULL)
2162 return NULL;
2163 if (IsA(node, Var))
2164 {
2165 if (((Var *) node)->varlevelsup > 0)
2166 return (Node *) replace_outer_var(root, (Var *) node);
2167 }
2168 if (IsA(node, PlaceHolderVar))
2169 {
2170 if (((PlaceHolderVar *) node)->phlevelsup > 0)
2172 (PlaceHolderVar *) node);
2173 }
2174 if (IsA(node, Aggref))
2175 {
2176 if (((Aggref *) node)->agglevelsup > 0)
2177 return (Node *) replace_outer_agg(root, (Aggref *) node);
2178 }
2179 if (IsA(node, GroupingFunc))
2180 {
2181 if (((GroupingFunc *) node)->agglevelsup > 0)
2182 return (Node *) replace_outer_grouping(root, (GroupingFunc *) node);
2183 }
2184 if (IsA(node, MergeSupportFunc))
2185 {
2186 if (root->parse->commandType != CMD_MERGE)
2188 (MergeSupportFunc *) node);
2189 }
2190 if (IsA(node, ReturningExpr))
2191 {
2192 if (((ReturningExpr *) node)->retlevelsup > 0)
2194 (ReturningExpr *) node);
2195 }
2197}
@ CMD_MERGE
Definition nodes.h:279
Param * replace_outer_merge_support(PlannerInfo *root, MergeSupportFunc *msf)
Param * replace_outer_agg(PlannerInfo *root, Aggref *agg)
Param * replace_outer_returning(PlannerInfo *root, ReturningExpr *rexpr)
Param * replace_outer_grouping(PlannerInfo *root, GroupingFunc *grp)
Param * replace_outer_var(PlannerInfo *root, Var *var)
Param * replace_outer_placeholdervar(PlannerInfo *root, PlaceHolderVar *phv)
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition subselect.c:2159

References CMD_MERGE, expression_tree_mutator, fb(), 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 1796 of file subselect.c.

1797{
1798 /*
1799 * We don't try to simplify at all if the query uses set operations,
1800 * aggregates, grouping sets, SRFs, modifying CTEs, HAVING, OFFSET, or FOR
1801 * UPDATE/SHARE; none of these seem likely in normal usage and their
1802 * possible effects are complex. (Note: we could ignore an "OFFSET 0"
1803 * clause, but that traditionally is used as an optimization fence, so we
1804 * don't.)
1805 */
1806 if (query->commandType != CMD_SELECT ||
1807 query->setOperations ||
1808 query->hasAggs ||
1809 query->groupingSets ||
1810 query->hasWindowFuncs ||
1811 query->hasTargetSRFs ||
1812 query->hasModifyingCTE ||
1813 query->havingQual ||
1814 query->limitOffset ||
1815 query->rowMarks)
1816 return false;
1817
1818 /*
1819 * LIMIT with a constant positive (or NULL) value doesn't affect the
1820 * semantics of EXISTS, so let's ignore such clauses. This is worth doing
1821 * because people accustomed to certain other DBMSes may be in the habit
1822 * of writing EXISTS(SELECT ... LIMIT 1) as an optimization. If there's a
1823 * LIMIT with anything else as argument, though, we can't simplify.
1824 */
1825 if (query->limitCount)
1826 {
1827 /*
1828 * The LIMIT clause has not yet been through eval_const_expressions,
1829 * so we have to apply that here. It might seem like this is a waste
1830 * of cycles, since the only case plausibly worth worrying about is
1831 * "LIMIT 1" ... but what we'll actually see is "LIMIT int8(1::int4)",
1832 * so we have to fold constants or we're not going to recognize it.
1833 */
1834 Node *node = eval_const_expressions(root, query->limitCount);
1835 Const *limit;
1836
1837 /* Might as well update the query if we simplified the clause. */
1838 query->limitCount = node;
1839
1840 if (!IsA(node, Const))
1841 return false;
1842
1843 limit = (Const *) node;
1844 Assert(limit->consttype == INT8OID);
1845 if (!limit->constisnull && DatumGetInt64(limit->constvalue) <= 0)
1846 return false;
1847
1848 /* Whether or not the targetlist is safe, we can drop the LIMIT. */
1849 query->limitCount = NULL;
1850 }
1851
1852 /*
1853 * Otherwise, we can throw away the targetlist, as well as any GROUP,
1854 * WINDOW, DISTINCT, and ORDER BY clauses; none of those clauses will
1855 * change a nonzero-rows result to zero rows or vice versa. (Furthermore,
1856 * since our parsetree representation of these clauses depends on the
1857 * targetlist, we'd better throw them away if we drop the targetlist.)
1858 */
1859 query->targetList = NIL;
1860 query->groupClause = NIL;
1861 query->windowClause = NIL;
1862 query->distinctClause = NIL;
1863 query->sortClause = NIL;
1864 query->hasDistinctOn = false;
1865
1866 /*
1867 * Since we have thrown away the GROUP BY clauses, we'd better get rid of
1868 * the RTE_GROUP RTE and clear the hasGroupRTE flag. To safely get rid of
1869 * the RTE_GROUP RTE without shifting the index of any subsequent RTE in
1870 * the rtable, we convert the RTE to be RTE_RESULT type in-place, and zero
1871 * out RTE_GROUP-specific fields.
1872 */
1873 if (query->hasGroupRTE)
1874 {
1876 {
1877 if (rte->rtekind == RTE_GROUP)
1878 {
1879 rte->rtekind = RTE_RESULT;
1880 rte->groupexprs = NIL;
1881
1882 /* A query should only have one RTE_GROUP, so we can stop. */
1883 break;
1884 }
1885 }
1886
1887 query->hasGroupRTE = false;
1888 }
1889
1890 return true;
1891}
@ RTE_RESULT
@ RTE_GROUP
#define foreach_node(type, var, lst)
Definition pg_list.h:496
static int64 DatumGetInt64(Datum X)
Definition postgres.h:403
Oid consttype
Definition primnodes.h:330
Node * limitCount
Definition parsenodes.h:231
Node * setOperations
Definition parsenodes.h:236
List * groupClause
Definition parsenodes.h:216
Node * havingQual
Definition parsenodes.h:222
List * rtable
Definition parsenodes.h:175
Node * limitOffset
Definition parsenodes.h:230
List * windowClause
Definition parsenodes.h:224
List * groupingSets
Definition parsenodes.h:220
List * distinctClause
Definition parsenodes.h:226
List * sortClause
Definition parsenodes.h:228

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

2535{
2536 plan->initPlan = root->init_plans;
2537}

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

2430{
2432 bool unsafe_initplans;
2433 ListCell *lc;
2434
2435 /* Nothing to do if no initPlans */
2436 if (root->init_plans == NIL)
2437 return;
2438
2439 /*
2440 * Compute the cost increment just once, since it will be the same for all
2441 * Paths. Also check for parallel-unsafe initPlans.
2442 */
2443 SS_compute_initplan_cost(root->init_plans,
2445
2446 /*
2447 * Now adjust the costs and parallel_safe flags.
2448 */
2449 foreach(lc, final_rel->pathlist)
2450 {
2451 Path *path = (Path *) lfirst(lc);
2452
2453 path->startup_cost += initplan_cost;
2454 path->total_cost += initplan_cost;
2455 if (unsafe_initplans)
2456 path->parallel_safe = false;
2457 }
2458
2459 /*
2460 * Adjust partial paths' costs too, or forget them entirely if we must
2461 * consider the rel parallel-unsafe.
2462 */
2463 if (unsafe_initplans)
2464 {
2465 final_rel->partial_pathlist = NIL;
2466 final_rel->consider_parallel = false;
2467 }
2468 else
2469 {
2470 foreach(lc, final_rel->partial_pathlist)
2471 {
2472 Path *path = (Path *) lfirst(lc);
2473
2474 path->startup_cost += initplan_cost;
2475 path->total_cost += initplan_cost;
2476 }
2477 }
2478
2479 /* We needn't do set_cheapest() here, caller will do it */
2480}
double Cost
Definition nodes.h:261
Cost startup_cost
Definition pathnodes.h:1995
Cost total_cost
Definition pathnodes.h:1996
bool parallel_safe
Definition pathnodes.h:1988
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition subselect.c:2493

References fb(), lfirst, NIL, Path::parallel_safe, 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 2493 of file subselect.c.

2496{
2498 bool unsafe_initplans;
2499 ListCell *lc;
2500
2501 /*
2502 * We assume each initPlan gets run once during top plan startup. This is
2503 * a conservative overestimate, since in fact an initPlan might be
2504 * executed later than plan startup, or even not at all.
2505 */
2506 initplan_cost = 0;
2507 unsafe_initplans = false;
2508 foreach(lc, init_plans)
2509 {
2511
2512 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2513 if (!initsubplan->parallel_safe)
2514 unsafe_initplans = true;
2515 }
2518}
#define lfirst_node(type, lc)
Definition pg_list.h:176

References fb(), and lfirst_node.

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

2550{
2551 /* No setup needed, just recurse through plan tree. */
2552 (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2553}

References fb(), finalize_plan(), plan, and root.

Referenced by standard_planner().

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2365 of file subselect.c.

2366{
2367 Bitmapset *outer_params;
2369 ListCell *l;
2370
2371 /*
2372 * If no parameters have been assigned anywhere in the tree, we certainly
2373 * don't need to do anything here.
2374 */
2375 if (root->glob->paramExecTypes == NIL)
2376 return;
2377
2378 /*
2379 * Scan all query levels above this one to see which parameters are due to
2380 * be available from them, either because lower query levels have
2381 * requested them (via plan_params) or because they will be available from
2382 * initPlans of those levels.
2383 */
2384 outer_params = NULL;
2385 for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2386 {
2387 /*
2388 * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
2389 */
2390 foreach(l, proot->plan_params)
2391 {
2393
2394 outer_params = bms_add_member(outer_params, pitem->paramId);
2395 }
2396 /* Include any outputs of outer-level initPlans */
2397 foreach(l, proot->init_plans)
2398 {
2400 ListCell *l2;
2401
2402 foreach(l2, initsubplan->setParam)
2403 {
2404 outer_params = bms_add_member(outer_params, lfirst_int(l2));
2405 }
2406 }
2407 /* Include worktable ID, if a recursive query is being planned */
2408 if (proot->wt_param_id >= 0)
2409 outer_params = bms_add_member(outer_params, proot->wt_param_id);
2410 }
2411 root->outer_params = outer_params;
2412}

References bms_add_member(), fb(), lfirst, lfirst_int, NIL, and root.

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

3313{
3314 SubPlan *node;
3315
3316 /*
3317 * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3318 * the global lists. Ideally we'd save a real path, but right now our
3319 * sole caller doesn't build a path that exactly matches the plan. Since
3320 * we're not currently going to need the path for an initplan, it's not
3321 * worth requiring construction of such a path.
3322 */
3323 root->glob->subplans = lappend(root->glob->subplans, plan);
3324 root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3325 root->glob->subroots = lappend(root->glob->subroots, subroot);
3326
3327 /*
3328 * Create a SubPlan node and add it to the outer list of InitPlans. Note
3329 * it has to appear after any other InitPlans it might depend on (see
3330 * comments in ExecReScan).
3331 */
3332 node = makeNode(SubPlan);
3333 node->subLinkType = EXPR_SUBLINK;
3334 node->plan_id = list_length(root->glob->subplans);
3335 node->plan_name = subroot->plan_name;
3336 node->isInitPlan = true;
3338 &node->firstColCollation);
3339 node->parallel_safe = plan->parallel_safe;
3340 node->setParam = list_make1_int(prm->paramid);
3341
3342 root->init_plans = lappend(root->init_plans, node);
3343
3344 /*
3345 * The node can't have any inputs (since it's an initplan), so the
3346 * parParam and args lists remain empty.
3347 */
3348
3349 /* Set costs of SubPlan using info from the plan tree */
3350 cost_subplan(subroot, node, plan);
3351}

References cost_subplan(), EXPR_SUBLINK, fb(), SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), SubPlan::isInitPlan, lappend(), list_length(), list_make1_int, makeNode, SubPlan::parallel_safe, plan, SubPlan::plan_id, PlannerInfo::plan_name, SubPlan::plan_name, 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 3294 of file subselect.c.

3297{
3298 return generate_new_exec_param(root, resulttype,
3300}

References fb(), generate_new_exec_param(), and root.

Referenced by preprocess_minmax_aggregates().

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 884 of file subselect.c.

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

References SubPlan::args, Assert, assign_special_exec_param(), choose_plan_name(), 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, fb(), fetch_upper_rel(), SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), inline_cte(), lappend(), lappend_int(), lfirst, list_length(), list_make1_int, makeNode, NIL, SubPlan::parallel_safe, SubPlan::paramIds, SubPlan::parParam, plan, SubPlan::plan_id, PlannerInfo::plan_name, SubPlan::plan_name, root, SubPlan::setParam, SubPlan::subLinkType, subquery_planner(), SubPlan::testexpr, SubPlan::unknownEqFalse, UPPERREL_FINAL, and SubPlan::useHashTable.

Referenced by subquery_planner().

◆ SS_process_sublinks()

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

Definition at line 2207 of file subselect.c.

2208{
2210
2211 context.root = root;
2212 context.isTopQual = isQual;
2213 return process_sublinks_mutator(expr, &context);
2214}

References fb(), 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 2152 of file subselect.c.

2153{
2154 /* No setup needed for tree walk, so away we go */
2156}

References replace_correlation_vars_mutator(), and root.

Referenced by preprocess_expression().

◆ sublink_testexpr_is_not_nullable()

static bool sublink_testexpr_is_not_nullable ( PlannerInfo root,
SubLink sublink 
)
static

Definition at line 1483 of file subselect.c.

1484{
1485 Node *testexpr = sublink->testexpr;
1486 List *outer_exprs = NIL;
1487
1488 /* Punt if sublink is not in the expected format */
1489 if (sublink->subLinkType != ANY_SUBLINK || testexpr == NULL)
1490 return false;
1491
1492 if (IsA(testexpr, OpExpr))
1493 {
1494 /* single-column comparison */
1495 OpExpr *opexpr = (OpExpr *) testexpr;
1496
1497 /* standard ANY structure should be op(outer_var, param) */
1498 if (list_length(opexpr->args) != 2)
1499 return false;
1500
1501 /*
1502 * We rely on membership in a B-tree or Hash operator family as a
1503 * guarantee that the operator acts as a proper boolean comparison and
1504 * does not yield NULL for valid non-null inputs.
1505 */
1506 if (!op_is_safe_index_member(opexpr->opno))
1507 return false;
1508
1510 }
1511 else if (is_andclause(testexpr) || is_orclause(testexpr))
1512 {
1513 /* multi-column equality or inequality checks */
1514 BoolExpr *bexpr = (BoolExpr *) testexpr;
1515
1516 foreach_ptr(OpExpr, opexpr, bexpr->args)
1517 {
1518 if (!IsA(opexpr, OpExpr))
1519 return false;
1520
1521 /* standard ANY structure should be op(outer_var, param) */
1522 if (list_length(opexpr->args) != 2)
1523 return false;
1524
1525 /* verify operator safety; see comment above */
1526 if (!op_is_safe_index_member(opexpr->opno))
1527 return false;
1528
1530 }
1531 }
1532 else if (IsA(testexpr, RowCompareExpr))
1533 {
1534 /* multi-column ordering checks */
1535 RowCompareExpr *rcexpr = (RowCompareExpr *) testexpr;
1536
1537 foreach_oid(opno, rcexpr->opnos)
1538 {
1539 /* verify operator safety; see comment above */
1540 if (!op_is_safe_index_member(opno))
1541 return false;
1542 }
1543
1545 }
1546 else
1547 {
1548 /* Punt if other node types */
1549 return false;
1550 }
1551
1552 /*
1553 * Since the query hasn't yet been through expression preprocessing, we
1554 * must apply flatten_join_alias_vars to the outer expressions to avoid
1555 * being fooled by join aliases.
1556 *
1557 * We do not need to apply flatten_group_exprs though, since grouping Vars
1558 * cannot appear in jointree quals.
1559 */
1560 outer_exprs = (List *)
1562
1563 /* Check that every outer expression is non-nullable */
1565 {
1566 /*
1567 * We have already collected relation-level not-null constraints for
1568 * the outer query, so we can consult the global hash table for
1569 * nullability information.
1570 */
1572 return false;
1573
1574 /*
1575 * Note: It is possible to further prove non-nullability by examining
1576 * the qual clauses available at or below the jointree node where this
1577 * NOT IN clause is evaluated, but for the moment it doesn't seem
1578 * worth the extra complication.
1579 */
1580 }
1581
1582 return true;
1583}
bool expr_is_nonnullable(PlannerInfo *root, Expr *expr, NotNullSource source)
Definition clauses.c:4749
bool op_is_safe_index_member(Oid opno)
Definition lsyscache.c:873
@ NOTNULL_SOURCE_HASHTABLE
Definition optimizer.h:137
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
#define foreach_oid(var, lst)
Definition pg_list.h:471
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition var.c:781

References ANY_SUBLINK, OpExpr::args, expr_is_nonnullable(), fb(), flatten_join_alias_vars(), foreach_oid, foreach_ptr, is_andclause(), is_orclause(), IsA, lappend(), linitial, list_concat(), list_length(), NIL, NOTNULL_SOURCE_HASHTABLE, op_is_safe_index_member(), OpExpr::opno, and root.

Referenced by convert_ANY_sublink_to_join().

◆ sublinktype_to_string()

static const char * sublinktype_to_string ( SubLinkType  subLinkType)
static

Definition at line 3357 of file subselect.c.

3358{
3359 switch (subLinkType)
3360 {
3361 case EXISTS_SUBLINK:
3362 return "exists";
3363 case ALL_SUBLINK:
3364 return "all";
3365 case ANY_SUBLINK:
3366 return "any";
3367 case ROWCOMPARE_SUBLINK:
3368 return "rowcompare";
3369 case EXPR_SUBLINK:
3370 return "expr";
3371 case MULTIEXPR_SUBLINK:
3372 return "multiexpr";
3373 case ARRAY_SUBLINK:
3374 return "array";
3375 case CTE_SUBLINK:
3376 return "cte";
3377 }
3378 Assert(false);
3379 return "???";
3380}

References ALL_SUBLINK, ANY_SUBLINK, ARRAY_SUBLINK, Assert, CTE_SUBLINK, EXISTS_SUBLINK, EXPR_SUBLINK, MULTIEXPR_SUBLINK, and ROWCOMPARE_SUBLINK.

Referenced by make_subplan().

◆ subpath_is_hashable()

static bool subpath_is_hashable ( Path path,
bool  unknownEqFalse 
)
static

Definition at line 740 of file subselect.c.

741{
743
744 /*
745 * The estimated size of the hashtable holding the subquery result must
746 * fit in hash_mem. (Note: reject on equality, to ensure that an estimate
747 * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
748 */
750 path->pathtarget->width,
751 unknownEqFalse);
753 return false;
754
755 return true;
756}
size_t Size
Definition c.h:691
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680
Size EstimateSubplanHashTableSpace(double nentries, Size tupleWidth, bool unknownEqFalse)
Cardinality rows
Definition pathnodes.h:1993

References EstimateSubplanHashTableSpace(), fb(), get_hash_memory_limit(), and Path::rows.

Referenced by make_subplan().

◆ subplan_is_hashable()

static bool subplan_is_hashable ( Plan plan,
bool  unknownEqFalse 
)
static

Definition at line 716 of file subselect.c.

717{
719
720 /*
721 * The estimated size of the hashtable holding the subquery result must
722 * fit in hash_mem. (Note: reject on equality, to ensure that an estimate
723 * of SIZE_MAX disables hashing regardless of the hash_mem limit.)
724 */
726 plan->plan_width,
727 unknownEqFalse);
729 return false;
730
731 return true;
732}

References EstimateSubplanHashTableSpace(), fb(), get_hash_memory_limit(), and plan.

Referenced by build_subplan().

◆ test_opexpr_is_hashable()

static bool test_opexpr_is_hashable ( OpExpr testexpr,
List param_ids 
)
static

Definition at line 796 of file subselect.c.

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

References OpExpr::args, contain_exec_param(), contain_var_clause(), fb(), 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 765 of file subselect.c.

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

References fb(), is_andclause(), IsA, lfirst, and test_opexpr_is_hashable().

Referenced by build_subplan().