PostgreSQL Source Code git master
Functions
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

 
 
 
JoinExprconvert_EXISTS_sublink_to_join (PlannerInfo *root, SubLink *sublink, bool under_not, Relids available_rels)
 
 
NodeSS_process_sublinks (PlannerInfo *root, Node *expr, bool isQual)
 
 
 
void  SS_compute_initplan_cost (List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
 
 
 
ParamSS_make_initplan_output_param (PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
 
 

Function Documentation

convert_ANY_sublink_to_join()

JoinExpr * convert_ANY_sublink_to_join ( PlannerInforoot,
SubLinksublink,
Relids  available_rels 
)

Definition at line 1334 of file subselect.c.

1336{
1337 JoinExpr *result;
1338 Query *parse = root->parse;
1339 Query *subselect = (Query *) sublink->subselect;
1340 Relids upper_varnos;
1341 int rtindex;
1342 ParseNamespaceItem *nsitem;
1343 RangeTblEntry *rte;
1344 RangeTblRef *rtr;
1345 List *subquery_vars;
1346 Node *quals;
1347 ParseState *pstate;
1348 Relids sub_ref_outer_relids;
1349 bool use_lateral;
1350
1351 Assert(sublink->subLinkType == ANY_SUBLINK);
1352
1353 /*
1354 * If the sub-select contains any Vars of the parent query, we treat it as
1355 * LATERAL. (Vars from higher levels don't matter here.)
1356 */
1357 sub_ref_outer_relids = pull_varnos_of_level(NULL, (Node *) subselect, 1);
1358 use_lateral = !bms_is_empty(sub_ref_outer_relids);
1359
1360 /*
1361 * Can't convert if the sub-select contains parent-level Vars of relations
1362 * not in available_rels.
1363 */
1364 if (!bms_is_subset(sub_ref_outer_relids, available_rels))
1365 return NULL;
1366
1367 /*
1368 * The test expression must contain some Vars of the parent query, else
1369 * it's not gonna be a join. (Note that it won't have Vars referring to
1370 * the subquery, rather Params.)
1371 */
1372 upper_varnos = pull_varnos(root, sublink->testexpr);
1373 if (bms_is_empty(upper_varnos))
1374 return NULL;
1375
1376 /*
1377 * However, it can't refer to anything outside available_rels.
1378 */
1379 if (!bms_is_subset(upper_varnos, available_rels))
1380 return NULL;
1381
1382 /*
1383 * The combining operators and left-hand expressions mustn't be volatile.
1384 */
1386 return NULL;
1387
1388 /* Create a dummy ParseState for addRangeTableEntryForSubquery */
1389 pstate = make_parsestate(NULL);
1390
1391 /*
1392 * Okay, pull up the sub-select into upper range table.
1393 *
1394 * We rely here on the assumption that the outer query has no references
1395 * to the inner (necessarily true, other than the Vars that we build
1396 * below). Therefore this is a lot easier than what pull_up_subqueries has
1397 * to go through.
1398 */
1399 nsitem = addRangeTableEntryForSubquery(pstate,
1400 subselect,
1401 NULL,
1402 use_lateral,
1403 false);
1404 rte = nsitem->p_rte;
1405 parse->rtable = lappend(parse->rtable, rte);
1406 rtindex = list_length(parse->rtable);
1407
1408 /*
1409 * Form a RangeTblRef for the pulled-up sub-select.
1410 */
1411 rtr = makeNode(RangeTblRef);
1412 rtr->rtindex = rtindex;
1413
1414 /*
1415 * Build a list of Vars representing the subselect outputs.
1416 */
1417 subquery_vars = generate_subquery_vars(root,
1418 subselect->targetList,
1419 rtindex);
1420
1421 /*
1422 * Build the new join's qual expression, replacing Params with these Vars.
1423 */
1424 quals = convert_testexpr(root, sublink->testexpr, subquery_vars);
1425
1426 /*
1427 * And finally, build the JoinExpr node.
1428 */
1429 result = makeNode(JoinExpr);
1430 result->jointype = JOIN_SEMI;
1431 result->isNatural = false;
1432 result->larg = NULL; /* caller must fill this in */
1433 result->rarg = (Node *) rtr;
1434 result->usingClause = NIL;
1435 result->join_using_alias = NULL;
1436 result->quals = quals;
1437 result->alias = NULL;
1438 result->rtindex = 0; /* we don't need an RTE for it */
1439
1440 return result;
1441}
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:542
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
Definition: list.c:339
#define makeNode(_type_)
Definition: nodes.h:161
@ JOIN_SEMI
Definition: nodes.h:317
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:1031
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:2338
JoinType jointype
Definition: primnodes.h:2329
int rtindex
Definition: primnodes.h:2342
Node * larg
Definition: primnodes.h:2331
bool isNatural
Definition: primnodes.h:2330
Node * rarg
Definition: primnodes.h:2332
Definition: pg_list.h:54
Definition: nodes.h:135
Definition: parsenodes.h:118
List * targetList
Definition: parsenodes.h:198
static List * generate_subquery_vars(PlannerInfo *root, List *tlist, Index varno)
Definition: subselect.c:617
static Node * convert_testexpr(PlannerInfo *root, Node *testexpr, List *subst_nodes)
Definition: subselect.c:646
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(), 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 ( PlannerInforoot,
SubLinksublink,
bool  under_not,
Relids  available_rels 
)

Definition at line 1451 of file subselect.c.

1453{
1454 JoinExpr *result;
1455 Query *parse = root->parse;
1456 Query *subselect = (Query *) sublink->subselect;
1457 Node *whereClause;
1458 PlannerInfo subroot;
1459 int rtoffset;
1460 int varno;
1461 Relids clause_varnos;
1462 Relids upper_varnos;
1463
1464 Assert(sublink->subLinkType == EXISTS_SUBLINK);
1465
1466 /*
1467 * Can't flatten if it contains WITH. (We could arrange to pull up the
1468 * WITH into the parent query's cteList, but that risks changing the
1469 * semantics, since a WITH ought to be executed once per associated query
1470 * call.) Note that convert_ANY_sublink_to_join doesn't have to reject
1471 * this case, since it just produces a subquery RTE that doesn't have to
1472 * get flattened into the parent query.
1473 */
1474 if (subselect->cteList)
1475 return NULL;
1476
1477 /*
1478 * Copy the subquery so we can modify it safely (see comments in
1479 * make_subplan).
1480 */
1481 subselect = copyObject(subselect);
1482
1483 /*
1484 * See if the subquery can be simplified based on the knowledge that it's
1485 * being used in EXISTS(). If we aren't able to get rid of its
1486 * targetlist, we have to fail, because the pullup operation leaves us
1487 * with noplace to evaluate the targetlist.
1488 */
1489 if (!simplify_EXISTS_query(root, subselect))
1490 return NULL;
1491
1492 /*
1493 * Separate out the WHERE clause. (We could theoretically also remove
1494 * top-level plain JOIN/ON clauses, but it's probably not worth the
1495 * trouble.)
1496 */
1497 whereClause = subselect->jointree->quals;
1498 subselect->jointree->quals = NULL;
1499
1500 /*
1501 * The rest of the sub-select must not refer to any Vars of the parent
1502 * query. (Vars of higher levels should be okay, though.)
1503 */
1504 if (contain_vars_of_level((Node *) subselect, 1))
1505 return NULL;
1506
1507 /*
1508 * On the other hand, the WHERE clause must contain some Vars of the
1509 * parent query, else it's not gonna be a join.
1510 */
1511 if (!contain_vars_of_level(whereClause, 1))
1512 return NULL;
1513
1514 /*
1515 * We don't risk optimizing if the WHERE clause is volatile, either.
1516 */
1517 if (contain_volatile_functions(whereClause))
1518 return NULL;
1519
1520 /*
1521 * Scan the rangetable for relation RTEs and retrieve the necessary
1522 * catalog information for each relation. Using this information, clear
1523 * the inh flag for any relation that has no children, collect not-null
1524 * attribute numbers for any relation that has column not-null
1525 * constraints, and expand virtual generated columns for any relation that
1526 * contains them.
1527 *
1528 * Note: we construct up an entirely dummy PlannerInfo for use here. This
1529 * is fine because only the "glob" and "parse" links will be used in this
1530 * case.
1531 *
1532 * Note: we temporarily assign back the WHERE clause so that any virtual
1533 * generated column references within it can be expanded. It should be
1534 * separated out again afterward.
1535 */
1536 MemSet(&subroot, 0, sizeof(subroot));
1537 subroot.type = T_PlannerInfo;
1538 subroot.glob = root->glob;
1539 subroot.parse = subselect;
1540 subselect->jointree->quals = whereClause;
1541 subselect = preprocess_relation_rtes(&subroot);
1542
1543 /*
1544 * Now separate out the WHERE clause again.
1545 */
1546 whereClause = subselect->jointree->quals;
1547 subselect->jointree->quals = NULL;
1548
1549 /*
1550 * The subquery must have a nonempty jointree, but we can make it so.
1551 */
1552 replace_empty_jointree(subselect);
1553
1554 /*
1555 * Prepare to pull up the sub-select into top range table.
1556 *
1557 * We rely here on the assumption that the outer query has no references
1558 * to the inner (necessarily true). Therefore this is a lot easier than
1559 * what pull_up_subqueries has to go through.
1560 *
1561 * In fact, it's even easier than what convert_ANY_sublink_to_join has to
1562 * do. The machinations of simplify_EXISTS_query ensured that there is
1563 * nothing interesting in the subquery except an rtable and jointree, and
1564 * even the jointree FromExpr no longer has quals. So we can just append
1565 * the rtable to our own and use the FromExpr in our jointree. But first,
1566 * adjust all level-zero varnos in the subquery to account for the rtable
1567 * merger.
1568 */
1569 rtoffset = list_length(parse->rtable);
1570 OffsetVarNodes((Node *) subselect, rtoffset, 0);
1571 OffsetVarNodes(whereClause, rtoffset, 0);
1572
1573 /*
1574 * Upper-level vars in subquery will now be one level closer to their
1575 * parent than before; in particular, anything that had been level 1
1576 * becomes level zero.
1577 */
1578 IncrementVarSublevelsUp((Node *) subselect, -1, 1);
1579 IncrementVarSublevelsUp(whereClause, -1, 1);
1580
1581 /*
1582 * Now that the WHERE clause is adjusted to match the parent query
1583 * environment, we can easily identify all the level-zero rels it uses.
1584 * The ones <= rtoffset belong to the upper query; the ones > rtoffset do
1585 * not.
1586 */
1587 clause_varnos = pull_varnos(root, whereClause);
1588 upper_varnos = NULL;
1589 varno = -1;
1590 while ((varno = bms_next_member(clause_varnos, varno)) >= 0)
1591 {
1592 if (varno <= rtoffset)
1593 upper_varnos = bms_add_member(upper_varnos, varno);
1594 }
1595 bms_free(clause_varnos);
1596 Assert(!bms_is_empty(upper_varnos));
1597
1598 /*
1599 * Now that we've got the set of upper-level varnos, we can make the last
1600 * check: only available_rels can be referenced.
1601 */
1602 if (!bms_is_subset(upper_varnos, available_rels))
1603 return NULL;
1604
1605 /*
1606 * Now we can attach the modified subquery rtable to the parent. This also
1607 * adds subquery's RTEPermissionInfos into the upper query.
1608 */
1609 CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1610 subselect->rtable, subselect->rteperminfos);
1611
1612 /*
1613 * And finally, build the JoinExpr node.
1614 */
1615 result = makeNode(JoinExpr);
1616 result->jointype = under_not ? JOIN_ANTI : JOIN_SEMI;
1617 result->isNatural = false;
1618 result->larg = NULL; /* caller must fill this in */
1619 /* flatten out the FromExpr node if it's useless */
1620 if (list_length(subselect->jointree->fromlist) == 1)
1621 result->rarg = (Node *) linitial(subselect->jointree->fromlist);
1622 else
1623 result->rarg = (Node *) subselect->jointree;
1624 result->usingClause = NIL;
1625 result->join_using_alias = NULL;
1626 result->quals = whereClause;
1627 result->alias = NULL;
1628 result->rtindex = 0; /* we don't need an RTE for it */
1629
1630 return result;
1631}
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 MemSet(start, val, len)
Definition: c.h:1019
#define copyObject(obj)
Definition: nodes.h:232
@ JOIN_ANTI
Definition: nodes.h:318
#define linitial(l)
Definition: pg_list.h:178
void replace_empty_jointree(Query *parse)
Definition: prepjointree.c:589
Query * preprocess_relation_rtes(PlannerInfo *root)
Definition: prepjointree.c:417
@ EXISTS_SUBLINK
Definition: primnodes.h:1029
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:884
Node * quals
Definition: primnodes.h:2358
FromExpr * jointree
Definition: parsenodes.h:182
List * cteList
Definition: parsenodes.h:173
static bool simplify_EXISTS_query(PlannerInfo *root, Query *query)
Definition: subselect.c:1650
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, MemSet, NIL, OffsetVarNodes(), parse(), preprocess_relation_rtes(), 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 ( PlannerInforoot,
Nodetestexpr,
Queryvalues 
)

Definition at line 1228 of file subselect.c.

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

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 ( PlannerInforoot,
Planplan 
)

Definition at line 2388 of file subselect.c.

2389{
2390 plan->initPlan = root->init_plans;
2391}
#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 ( PlannerInforoot,
RelOptInfofinal_rel 
)

Definition at line 2283 of file subselect.c.

2284{
2285 Cost initplan_cost;
2286 bool unsafe_initplans;
2287 ListCell *lc;
2288
2289 /* Nothing to do if no initPlans */
2290 if (root->init_plans == NIL)
2291 return;
2292
2293 /*
2294 * Compute the cost increment just once, since it will be the same for all
2295 * Paths. Also check for parallel-unsafe initPlans.
2296 */
2297 SS_compute_initplan_cost(root->init_plans,
2298 &initplan_cost, &unsafe_initplans);
2299
2300 /*
2301 * Now adjust the costs and parallel_safe flags.
2302 */
2303 foreach(lc, final_rel->pathlist)
2304 {
2305 Path *path = (Path *) lfirst(lc);
2306
2307 path->startup_cost += initplan_cost;
2308 path->total_cost += initplan_cost;
2309 if (unsafe_initplans)
2310 path->parallel_safe = false;
2311 }
2312
2313 /*
2314 * Adjust partial paths' costs too, or forget them entirely if we must
2315 * consider the rel parallel-unsafe.
2316 */
2317 if (unsafe_initplans)
2318 {
2319 final_rel->partial_pathlist = NIL;
2320 final_rel->consider_parallel = false;
2321 }
2322 else
2323 {
2324 foreach(lc, final_rel->partial_pathlist)
2325 {
2326 Path *path = (Path *) lfirst(lc);
2327
2328 path->startup_cost += initplan_cost;
2329 path->total_cost += initplan_cost;
2330 }
2331 }
2332
2333 /* We needn't do set_cheapest() here, caller will do it */
2334}
double Cost
Definition: nodes.h:261
Definition: pathnodes.h:1795
Cost startup_cost
Definition: pathnodes.h:1837
Cost total_cost
Definition: pathnodes.h:1838
bool parallel_safe
Definition: pathnodes.h:1830
bool consider_parallel
Definition: pathnodes.h:937
List * pathlist
Definition: pathnodes.h:948
List * partial_pathlist
Definition: pathnodes.h:950
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2347

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 ( Listinit_plans,
Costinitplan_cost_p,
bool *  unsafe_initplans_p 
)

Definition at line 2347 of file subselect.c.

2350{
2351 Cost initplan_cost;
2352 bool unsafe_initplans;
2353 ListCell *lc;
2354
2355 /*
2356 * We assume each initPlan gets run once during top plan startup. This is
2357 * a conservative overestimate, since in fact an initPlan might be
2358 * executed later than plan startup, or even not at all.
2359 */
2360 initplan_cost = 0;
2361 unsafe_initplans = false;
2362 foreach(lc, init_plans)
2363 {
2364 SubPlan *initsubplan = lfirst_node(SubPlan, lc);
2365
2366 initplan_cost += initsubplan->startup_cost + initsubplan->per_call_cost;
2367 if (!initsubplan->parallel_safe)
2368 unsafe_initplans = true;
2369 }
2370 *initplan_cost_p = initplan_cost;
2371 *unsafe_initplans_p = unsafe_initplans;
2372}
#define lfirst_node(type, lc)
Definition: pg_list.h:176
bool parallel_safe
Definition: primnodes.h:1117
Cost startup_cost
Definition: primnodes.h:1126
Cost per_call_cost
Definition: primnodes.h:1127

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 ( PlannerInforoot,
Planplan 
)

Definition at line 2403 of file subselect.c.

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

References finalize_plan(), plan, and root.

Referenced by standard_planner().

SS_identify_outer_params()

void SS_identify_outer_params ( PlannerInforoot )

Definition at line 2219 of file subselect.c.

2220{
2221 Bitmapset *outer_params;
2222 PlannerInfo *proot;
2223 ListCell *l;
2224
2225 /*
2226 * If no parameters have been assigned anywhere in the tree, we certainly
2227 * don't need to do anything here.
2228 */
2229 if (root->glob->paramExecTypes == NIL)
2230 return;
2231
2232 /*
2233 * Scan all query levels above this one to see which parameters are due to
2234 * be available from them, either because lower query levels have
2235 * requested them (via plan_params) or because they will be available from
2236 * initPlans of those levels.
2237 */
2238 outer_params = NULL;
2239 for (proot = root->parent_root; proot != NULL; proot = proot->parent_root)
2240 {
2241 /*
2242 * Include ordinary Var/PHV/Aggref/GroupingFunc/ReturningExpr params.
2243 */
2244 foreach(l, proot->plan_params)
2245 {
2247
2248 outer_params = bms_add_member(outer_params, pitem->paramId);
2249 }
2250 /* Include any outputs of outer-level initPlans */
2251 foreach(l, proot->init_plans)
2252 {
2253 SubPlan *initsubplan = (SubPlan *) lfirst(l);
2254 ListCell *l2;
2255
2256 foreach(l2, initsubplan->setParam)
2257 {
2258 outer_params = bms_add_member(outer_params, lfirst_int(l2));
2259 }
2260 }
2261 /* Include worktable ID, if a recursive query is being planned */
2262 if (proot->wt_param_id >= 0)
2263 outer_params = bms_add_member(outer_params, proot->wt_param_id);
2264 }
2265 root->outer_params = outer_params;
2266}
#define lfirst_int(lc)
Definition: pg_list.h:173
List * init_plans
Definition: pathnodes.h:327
int wt_param_id
Definition: pathnodes.h:566
List * plan_params
Definition: pathnodes.h:248
List * setParam
Definition: primnodes.h:1121

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 ( PlannerInforoot,
PlannerInfosubroot,
Planplan,
Paramprm 
)

Definition at line 3164 of file subselect.c.

3167{
3168 SubPlan *node;
3169
3170 /*
3171 * Add the subplan and its PlannerInfo, as well as a dummy path entry, to
3172 * the global lists. Ideally we'd save a real path, but right now our
3173 * sole caller doesn't build a path that exactly matches the plan. Since
3174 * we're not currently going to need the path for an initplan, it's not
3175 * worth requiring construction of such a path.
3176 */
3177 root->glob->subplans = lappend(root->glob->subplans, plan);
3178 root->glob->subpaths = lappend(root->glob->subpaths, NULL);
3179 root->glob->subroots = lappend(root->glob->subroots, subroot);
3180
3181 /*
3182 * Create a SubPlan node and add it to the outer list of InitPlans. Note
3183 * it has to appear after any other InitPlans it might depend on (see
3184 * comments in ExecReScan).
3185 */
3186 node = makeNode(SubPlan);
3187 node->subLinkType = EXPR_SUBLINK;
3188 node->plan_id = list_length(root->glob->subplans);
3189 node->plan_name = subroot->plan_name;
3190 node->isInitPlan = true;
3192 &node->firstColCollation);
3193 node->parallel_safe = plan->parallel_safe;
3194 node->setParam = list_make1_int(prm->paramid);
3195
3196 root->init_plans = lappend(root->init_plans, node);
3197
3198 /*
3199 * The node can't have any inputs (since it's an initplan), so the
3200 * parParam and args lists remain empty.
3201 */
3202
3203 /* Set costs of SubPlan using info from the plan tree */
3204 cost_subplan(subroot, node, plan);
3205}
void cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
Definition: costsize.c:4569
#define list_make1_int(x1)
Definition: pg_list.h:227
@ EXPR_SUBLINK
Definition: primnodes.h:1033
int paramid
Definition: primnodes.h:396
char * plan_name
Definition: pathnodes.h:239
int plan_id
Definition: primnodes.h:1102
char * plan_name
Definition: primnodes.h:1104
bool isInitPlan
Definition: primnodes.h:1111
int32 firstColTypmod
Definition: primnodes.h:1107
Oid firstColCollation
Definition: primnodes.h:1108
SubLinkType subLinkType
Definition: primnodes.h:1097
Oid firstColType
Definition: primnodes.h:1106
static void get_first_col_type(Plan *plan, Oid *coltype, int32 *coltypmod, Oid *colcollation)
Definition: subselect.c:119

References cost_subplan(), EXPR_SUBLINK, SubPlan::firstColCollation, SubPlan::firstColType, SubPlan::firstColTypmod, get_first_col_type(), SubPlan::isInitPlan, lappend(), list_length(), list_make1_int, makeNode, SubPlan::parallel_safe, Param::paramid, 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 ( PlannerInforoot,
Oid  resulttype,
int32  resulttypmod,
Oid  resultcollation 
)

Definition at line 3148 of file subselect.c.

3151{
3152 return generate_new_exec_param(root, resulttype,
3153 resulttypmod, resultcollation);
3154}
Param * generate_new_exec_param(PlannerInfo *root, Oid paramtype, int32 paramtypmod, Oid paramcollation)
Definition: paramassign.c:727

References generate_new_exec_param(), and root.

Referenced by preprocess_minmax_aggregates().

SS_process_ctes()

void SS_process_ctes ( PlannerInforoot )

Definition at line 882 of file subselect.c.

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

References SubPlan::args, Assert(), assign_special_exec_param(), RelOptInfo::cheapest_total_path, 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, 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 ( PlannerInforoot,
Nodeexpr,
bool  isQual 
)

Definition at line 2061 of file subselect.c.

2062{
2064
2065 context.root = root;
2066 context.isTopQual = isQual;
2067 return process_sublinks_mutator(expr, &context);
2068}
static Node * process_sublinks_mutator(Node *node, process_sublinks_context *context)
Definition: subselect.c:2071

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 ( PlannerInforoot,
Nodeexpr 
)

Definition at line 2006 of file subselect.c.

2007{
2008 /* No setup needed for tree walk, so away we go */
2010}
static Node * replace_correlation_vars_mutator(Node *node, PlannerInfo *root)
Definition: subselect.c:2013

References replace_correlation_vars_mutator(), and root.

Referenced by preprocess_expression().

AltStyle によって変換されたページ (->オリジナル) /