PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
subselect.h File Reference
#include "nodes/pathnodes.h"
#include "nodes/plannodes.h"
Include dependency graph for subselect.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void SS_process_ctes (PlannerInfo *root)
 
ScalarArrayOpExprconvert_VALUES_to_ANY (PlannerInfo *root, Node *testexpr, Query *values)
 
JoinExprconvert_ANY_sublink_to_join (PlannerInfo *root, SubLink *sublink, Relids available_rels)
 
JoinExprconvert_EXISTS_sublink_to_join (PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
 
NodeSS_replace_correlation_vars (PlannerInfo *root, Node *expr)
 
NodeSS_process_sublinks (PlannerInfo *root, Node *expr, bool isQual)
 
void SS_identify_outer_params (PlannerInfo *root)
 
void SS_charge_for_initplans (PlannerInfo *root, RelOptInfo *final_rel)
 
void SS_compute_initplan_cost (List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
 
void SS_attach_initplans (PlannerInfo *root, Plan *plan)
 
void SS_finalize_plan (PlannerInfo *root, Plan *plan)
 
ParamSS_make_initplan_output_param (PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
 
void SS_make_initplan_from_plan (PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
 

Function Documentation

◆ convert_ANY_sublink_to_join()

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

Definition at line 1333 of file subselect.c.

1335{
1336 JoinExpr *result;
1337 Query *parse = root->parse;
1338 Query *subselect = (Query *) sublink->subselect;
1339 Relids upper_varnos;
1340 int rtindex;
1341 ParseNamespaceItem *nsitem;
1342 RangeTblEntry *rte;
1343 RangeTblRef *rtr;
1344 List *subquery_vars;
1345 Node *quals;
1346 ParseState *pstate;
1347 Relids sub_ref_outer_relids;
1348 bool use_lateral;
1349
1350 Assert(sublink->subLinkType == ANY_SUBLINK);
1351
1352 /*
1353 * If the sub-select contains any Vars of the parent query, we treat it as
1354 * LATERAL. (Vars from higher levels don't matter here.)
1355 */
1356 sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
1357 use_lateral = !bms_is_empty(sub_ref_outer_relids);
1358
1359 /*
1360 * Can't convert if the sub-select contains parent-level Vars of relations
1361 * not in available_rels.
1362 */
1363 if (!bms_is_subset(sub_ref_outer_relids, available_rels))
1364 return NULL;
1365
1366 /*
1367 * The test expression must contain some Vars of the parent query, else
1368 * it's not gonna be a join. (Note that it won't have Vars referring to
1369 * the subquery, rather Params.)
1370 */
1371 upper_varnos = pull_varnos(root, sublink->testexpr);
1372 if (bms_is_empty(upper_varnos))
1373 return NULL;
1374
1375 /*
1376 * However, it can't refer to anything outside available_rels.
1377 */
1378 if (!bms_is_subset(upper_varnos, available_rels))
1379 return NULL;
1380
1381 /*
1382 * The combining operators and left-hand expressions mustn't be volatile.
1383 */
1385 return NULL;
1386
1387 /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1388 pstate = make_parsestate(NULL);
1389
1390 /*
1391 * Okay, pull up the sub-select into upper range table.
1392 *
1393 * We rely here on the assumption that the outer query has no references
1394 * to the inner (necessarily true, other than the Vars that we build
1395 * below). Therefore this is a lot easier than what pull_up_subqueries has
1396 * to go through.
1397 */
1398 nsitem = addRangeTableEntryForSubquery(pstate,
1399 subselect,
1400 makeAlias("ANY_subquery", NIL),
1401 use_lateral,
1402 false);
1403 rte = nsitem->p_rte;
1404 parse->rtable = lappend(parse->rtable, rte);
1405 rtindex = list_length(parse->rtable);
1406
1407 /*
1408 * Form a RangeTblRef for the pulled-up sub-select.
1409 */
1410 rtr = makeNode(RangeTblRef);
1411 rtr->rtindex = rtindex;
1412
1413 /*
1414 * Build a list of Vars representing the subselect outputs.
1415 */
1416 subquery_vars = generate_subquery_vars(root,
1417 subselect->targetList,
1418 rtindex);
1419
1420 /*
1421 * Build the new join's qual expression, replacing Params with these Vars.
1422 */
1423 quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1424
1425 /*
1426 * And finally, build the JoinExpr node.
1427 */
1428 result = makeNode(JoinExpr);
1429 result->jointype = JOIN_SEMI;
1430 result->isNatural = false;
1431 result->larg = NULL; /* caller must fill this in */
1432 result->rarg = (Node *) rtr;
1433 result->usingClause = NIL;
1434 result->join_using_alias = NULL;
1435 result->quals = quals;
1436 result->alias = NULL;
1437 result->rtindex = 0; /* we don't need an RTE for it */
1438
1439 return result;
1440}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
#define bms_is_empty(a)
Definition: bitmapset.h:118
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:539
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
Definition: list.c:339
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:438
#define makeNode(_type_)
Definition: nodes.h:161
@ JOIN_SEMI
Definition: nodes.h:313
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
@ ANY_SUBLINK
Definition: primnodes.h:1016
tree ctl root
Definition: radixtree.h:1857
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
Node * quals
Definition: primnodes.h:2318
JoinType jointype
Definition: primnodes.h:2309
int rtindex
Definition: primnodes.h:2322
Node * larg
Definition: primnodes.h:2311
bool isNatural
Definition: primnodes.h:2310
Node * rarg
Definition: primnodes.h:2312
Definition: pg_list.h:54
Definition: nodes.h:135
List * targetList
Definition: parsenodes.h:193
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:615
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:644
Relids pull_varnos_of_level(PlannerInfo *root, Node *node, int levelsup)
Definition: var.c:140
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114

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

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_EXISTS_sublink_to_join()

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

Definition at line 1450 of file subselect.c.

1452{
1453 JoinExpr *result;
1454 Query *parse = root->parse;
1455 Query *subselect = (Query *) sublink->subselect;
1456 Node *whereClause;
1457 int rtoffset;
1458 int varno;
1459 Relids clause_varnos;
1460 Relids upper_varnos;
1461
1462 Assert(sublink->subLinkType == EXISTS_SUBLINK);
1463
1464 /*
1465 * Can't flatten if it contains WITH. (We could arrange to pull up the
1466 * WITH into the parent query's cteList, but that risks changing the
1467 * semantics, since a WITH ought to be executed once per associated query
1468 * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1469 * this case, since it just produces a subquery RTE that doesn't have to
1470 * get flattened into the parent query.
1471 */
1472 if (subselect->cteList)
1473 return NULL;
1474
1475 /*
1476 * Copy the subquery so we can modify it safely (see comments in
1477 * make_subplan).
1478 */
1479 subselect = copyObject(subselect);
1480
1481 /*
1482 * See if the subquery can be simplified based on the knowledge that it's
1483 * being used in EXISTS(). If we aren't able to get rid of its
1484 * targetlist, we have to fail, because the pullup operation leaves us
1485 * with noplace to evaluate the targetlist.
1486 */
1487 if (!simplify_EXISTS_query(root, subselect))
1488 return NULL;
1489
1490 /*
1491 * Separate out the WHERE clause. (We could theoretically also remove
1492 * top-level plain JOIN/ON clauses, but it's probably not worth the
1493 * trouble.)
1494 */
1495 whereClause = subselect->jointree->quals;
1496 subselect->jointree->quals = NULL;
1497
1498 /*
1499 * The rest of the sub-select must not refer to any Vars of the parent
1500 * query. (Vars of higher levels should be okay, though.)
1501 */
1502 if (contain_vars_of_level((Node *) subselect, 1))
1503 return NULL;
1504
1505 /*
1506 * On the other hand, the WHERE clause must contain some Vars of the
1507 * parent query, else it's not gonna be a join.
1508 */
1509 if (!contain_vars_of_level(whereClause, 1))
1510 return NULL;
1511
1512 /*
1513 * We don't risk optimizing if the WHERE clause is volatile, either.
1514 */
1515 if (contain_volatile_functions(whereClause))
1516 return NULL;
1517
1518 /*
1519 * The subquery must have a nonempty jointree, but we can make it so.
1520 */
1521 replace_empty_jointree(subselect);
1522
1523 /*
1524 * Prepare to pull up the sub-select into top range table.
1525 *
1526 * We rely here on the assumption that the outer query has no references
1527 * to the inner (necessarily true). Therefore this is a lot easier than
1528 * what pull_up_subqueries has to go through.
1529 *
1530 * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1531 * do. The machinations of simplify_EXISTS_query ensured that there is
1532 * nothing interesting in the subquery except an rtable and jointree, and
1533 * even the jointree FromExpr no longer has quals. So we can just append
1534 * the rtable to our own and use the FromExpr in our jointree. But first,
1535 * adjust all level-zero varnos in the subquery to account for the rtable
1536 * merger.
1537 */
1538 rtoffset = list_length(parse->rtable);
1539 OffsetVarNodes((Node *) subselect, rtoffset, 0);
1540 OffsetVarNodes(whereClause, rtoffset, 0);
1541
1542 /*
1543 * Upper-level vars in subquery will now be one level closer to their
1544 * parent than before; in particular, anything that had been level 1
1545 * becomes level zero.
1546 */
1547 IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1548 IncrementVarSublevelsUp(whereClause, -1, 1);
1549
1550 /*
1551 * Now that the WHERE clause is adjusted to match the parent query
1552 * environment, we can easily identify all the level-zero rels it uses.
1553 * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1554 * not.
1555 */
1556 clause_varnos = pull_varnos(root, whereClause);
1557 upper_varnos = NULL;
1558 varno = -1;
1559 while ((varno = bms_next_member(clause_varnos, varno)) >= 0)
1560 {
1561 if (varno <= rtoffset)
1562 upper_varnos = bms_add_member(upper_varnos, varno);
1563 }
1564 bms_free(clause_varnos);
1565 Assert(!bms_is_empty(upper_varnos));
1566
1567 /*
1568 * Now that we've got the set of upper-level varnos, we can make the last
1569 * check: only available_rels can be referenced.
1570 */
1571 if (!bms_is_subset(upper_varnos, available_rels))
1572 return NULL;
1573
1574 /*
1575 * Now we can attach the modified subquery rtable to the parent. This also
1576 * adds subquery's RTEPermissionInfos into the upper query.
1577 */
1578 CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1579 subselect->rtable, subselect->rteperminfos);
1580
1581 /*
1582 * And finally, build the JoinExpr node.
1583 */
1584 result = makeNode(JoinExpr);
1585 result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1586 result->isNatural = false;
1587 result->larg = NULL; /* caller must fill this in */
1588 /* flatten out the FromExpr node if it's useless */
1589 if (list_length(subselect->jointree->fromlist) == 1)
1590 result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1591 else
1592 result->rarg = (Node *) subselect->jointree;
1593 result->usingClause = NIL;
1594 result->join_using_alias = NULL;
1595 result->quals = whereClause;
1596 result->alias = NULL;
1597 result->rtindex = 0; /* we don't need an RTE for it */
1598
1599 return result;
1600}
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define copyObject(obj)
Definition: nodes.h:230
@ JOIN_ANTI
Definition: nodes.h:314
#define linitial(l)
Definition: pg_list.h:178
void replace_empty_jointree(Query *parse)
Definition: prepjointree.c:410
@ EXISTS_SUBLINK
Definition: primnodes.h:1014
void OffsetVarNodes(Node *node, int offset, int sublevels_up)
Definition: rewriteManip.c:476
void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos)
Definition: rewriteManip.c:347
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
Definition: rewriteManip.c:928
Node * quals
Definition: primnodes.h:2338
FromExpr * jointree
Definition: parsenodes.h:177
List * cteList
Definition: parsenodes.h:168
static bool simplify_EXISTS_query(PlannerInfo *root, Query *query)
Definition: subselect.c:1619
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:444

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

Referenced by pull_up_sublinks_qual_recurse().

◆ convert_VALUES_to_ANY()

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

Definition at line 1227 of file subselect.c.

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

References generate_unaccent_rules::args, contain_volatile_functions(), convert_testexpr(), eval_const_expressions(), exprType(), IsA, lappend(), lfirst, linitial, linitial_node, linitial_oid, list_length(), list_make1, lsecond, make_SAOP_expr(), NIL, root, RTE_VALUES, RangeTblEntry::rtekind, value, values, and RangeTblEntry::values_lists.

Referenced by pull_up_sublinks_qual_recurse().

◆ SS_attach_initplans()

void SS_attach_initplans ( PlannerInfo root,
Plan plan 
)

Definition at line 2353 of file subselect.c.

2354{
2355 plan->initPlan = root->init_plans;
2356}
#define plan(x)
Definition: pg_regress.c:161

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

2249{
2250 Cost initplan_cost;
2251 bool unsafe_initplans;
2252 ListCell *lc;
2253
2254 /* Nothing to do if no initPlans */
2255 if (root->init_plans == NIL)
2256 return;
2257
2258 /*
2259 * Compute the cost increment just once, since it will be the same for all
2260 * Paths. Also check for parallel-unsafe initPlans.
2261 */
2262 SS_compute_initplan_cost(root->init_plans,
2263 &initplan_cost, &unsafe_initplans);
2264
2265 /*
2266 * Now adjust the costs and parallel_safe flags.
2267 */
2268 foreach(lc, final_rel->pathlist)
2269 {
2270 Path *path = (Path *) lfirst(lc);
2271
2272 path->startup_cost += initplan_cost;
2273 path->total_cost += initplan_cost;
2274 if (unsafe_initplans)
2275 path->parallel_safe = false;
2276 }
2277
2278 /*
2279 * Adjust partial paths' costs too, or forget them entirely if we must
2280 * consider the rel parallel-unsafe.
2281 */
2282 if (unsafe_initplans)
2283 {
2284 final_rel->partial_pathlist = NIL;
2285 final_rel->consider_parallel = false;
2286 }
2287 else
2288 {
2289 foreach(lc, final_rel->partial_pathlist)
2290 {
2291 Path *path = (Path *) lfirst(lc);
2292
2293 path->startup_cost += initplan_cost;
2294 path->total_cost += initplan_cost;
2295 }
2296 }
2297
2298 /* We needn't do set_cheapest() here, caller will do it */
2299}
double Cost
Definition: nodes.h:257
Cost startup_cost
Definition: pathnodes.h:1798
Cost total_cost
Definition: pathnodes.h:1799
bool parallel_safe
Definition: pathnodes.h:1791
bool consider_parallel
Definition: pathnodes.h:914
List * pathlist
Definition: pathnodes.h:925
List * partial_pathlist
Definition: pathnodes.h:927
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2312

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

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_compute_initplan_cost()

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

Definition at line 2312 of file subselect.c.

2315{
2316 Cost initplan_cost;
2317 bool unsafe_initplans;
2318 ListCell *lc;
2319
2320 /*
2321 * We assume each initPlan gets run once during top plan startup. This is
2322 * a conservative overestimate, since in fact an initPlan might be
2323 * executed later than plan startup, or even not at all.
2324 */
2325 initplan_cost = 0;
2326 unsafe_initplans = false;
2327 foreach(lc, init_plans)
2328 {
2329 SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2330
2331 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2332 if (!initsubplan->parallel_safe)
2333 unsafe_initplans = true;
2334 }
2335 *initplan_cost_p = initplan_cost;
2336 *unsafe_initplans_p = unsafe_initplans;
2337}
#define lfirst_node(type, lc)
Definition: pg_list.h:176
bool parallel_safe
Definition: primnodes.h:1101
Cost startup_cost
Definition: primnodes.h:1110
Cost per_call_cost
Definition: primnodes.h:1111

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

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

◆ SS_finalize_plan()

void SS_finalize_plan ( PlannerInfo root,
Plan plan 
)

Definition at line 2368 of file subselect.c.

2369{
2370 /* No setup needed, just recurse through plan tree. */
2371 (void) finalize_plan(root, plan, -1, root->outer_params, NULL);
2372}
static Bitmapset * finalize_plan(PlannerInfo *root, Plan *plan, int gather_param, Bitmapset *valid_params, Bitmapset *scan_params)
Definition: subselect.c:2406

References finalize_plan(), plan, and root.

Referenced by standard_planner().

◆ SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInfo root)

Definition at line 2184 of file subselect.c.

2185{
2186 Bitmapset *outer_params;
2187 PlannerInfo *proot;
2188 ListCell *l;
2189
2190 /*
2191 * If no parameters have been assigned anywhere in the tree, we certainly
2192 * don't need to do anything here.
2193 */
2194 if (root->glob->paramExecTypes == NIL)
2195 return;
2196
2197 /*
2198 * Scan all query levels above this one to see which parameters are due to
2199 * be available from them, either because lower query levels have
2200 * requested them (via plan_params) or because they will be available from
2201 * initPlans of those levels.
2202 */
2203 outer_params = NULL;
2204 for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2205 {
2206 /*
2207 * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
2208 */
2209 foreach(l, proot->plan_params)
2210 {
2212
2213 outer_params = bms_add_member(outer_params, pitem->paramId);
2214 }
2215 /* Include any outputs of outer-level initPlans */
2216 foreach(l, proot->init_plans)
2217 {
2218 SubPlan *initsubplan = (SubPlan *) lfirst(l);
2219 ListCell *l2;
2220
2221 foreach(l2, initsubplan->setParam)
2222 {
2223 outer_params = bms_add_member(outer_params, lfirst_int(l2));
2224 }
2225 }
2226 /* Include worktable ID, if a recursive query is being planned */
2227 if (proot->wt_param_id >= 0)
2228 outer_params = bms_add_member(outer_params, proot->wt_param_id);
2229 }
2230 root->outer_params = outer_params;
2231}
#define lfirst_int(lc)
Definition: pg_list.h:173
List * init_plans
Definition: pathnodes.h:323
int wt_param_id
Definition: pathnodes.h:560
List * plan_params
Definition: pathnodes.h:244
List * setParam
Definition: primnodes.h:1105

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

Referenced by build_minmax_path(), and subquery_planner().

◆ SS_make_initplan_from_plan()

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

Definition at line 3129 of file subselect.c.

3132{
3133 SubPlan *node;
3134
3135 /*
3136 * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3137 * the global lists. Ideally we'd save a real path, but right now our
3138 * sole caller doesn't build a path that exactly matches the plan. Since
3139 * we're not currently going to need the path for an initplan, it's not
3140 * worth requiring construction of such a path.
3141 */
3142 root->glob->subplans = lappend(root->glob->subplans, plan);
3143 root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3144 root->glob->subroots = lappend(root->glob->subroots, subroot);
3145
3146 /*
3147 * Create a SubPlan node and add it to the outer list of InitPlans. Note
3148 * it has to appear after any other InitPlans it might depend on (see
3149 * comments in ExecReScan).
3150 */
3151 node = makeNode(SubPlan);
3152 node->subLinkType = EXPR_SUBLINK;
3153 node->plan_id = list_length(root->glob->subplans);
3154 node->plan_name = psprintf("InitPlan %d", node->plan_id);
3156 &node->firstColCollation);
3157 node->parallel_safe = plan->parallel_safe;
3158 node->setParam = list_make1_int(prm->paramid);
3159
3160 root->init_plans = lappend(root->init_plans, node);
3161
3162 /*
3163 * The node can't have any inputs (since it's an initplan), so the
3164 * parParam and args lists remain empty.
3165 */
3166
3167 /* Set costs of SubPlan using info from the plan tree */
3168 cost_subplan(subroot, node, plan);
3169}
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4533
#define list_make1_int(x1)
Definition: pg_list.h:227
@ EXPR_SUBLINK
Definition: primnodes.h:1018
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
int paramid
Definition: primnodes.h:394
int plan_id
Definition: primnodes.h:1087
char * plan_name
Definition: primnodes.h:1089
int32 firstColTypmod
Definition: primnodes.h:1092
Oid firstColCollation
Definition: primnodes.h:1093
SubLinkType subLinkType
Definition: primnodes.h:1082
Oid firstColType
Definition: primnodes.h:1091
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:118

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

Referenced by create_minmaxagg_plan().

◆ SS_make_initplan_output_param()

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

Definition at line 3113 of file subselect.c.

3116{
3117 return generate_new_exec_param(root, resulttype,
3118 resulttypmod, resultcollation);
3119}
Param * generate_new_exec_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation)
Definition: paramassign.c:684

References generate_new_exec_param(), and root.

Referenced by preprocess_minmax_aggregates().

◆ SS_process_ctes()

void SS_process_ctes ( PlannerInfo root)

Definition at line 880 of file subselect.c.

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

References SubPlan::args, Assert(), assign_special_exec_param(), RelOptInfo::cheapest_total_path, CMD_SELECT, contain_dml(), contain_outer_selfref(), contain_volatile_functions(), copyObject, cost_subplan(), create_plan(), CTE_SUBLINK, CommonTableExpr::ctematerialized, CTEMaterializeDefault, CTEMaterializeNever, CommonTableExpr::ctename, CommonTableExpr::ctequery, elog, ERROR, 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, SubPlan::plan_name, psprintf(), 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 2026 of file subselect.c.

2027{
2029
2030 context.root = root;
2031 context.isTopQual = isQual;
2032 return process_sublinks_mutator(expr, &context);
2033}
static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context)
Definition: subselect.c:2036

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

Referenced by build_subplan(), and preprocess_expression().

◆ SS_replace_correlation_vars()

Node * SS_replace_correlation_vars ( PlannerInfo root,
Node expr 
)

Definition at line 1971 of file subselect.c.

1972{
1973 /* No setup needed for tree walk, so away we go */
1975}
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:1978

References replace_correlation_vars_mutator(), and root.

Referenced by preprocess_expression().