PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
allpaths.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/sysattr.h"
#include "access/tsmapi.h"
#include "catalog/pg_class.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "optimizer/appendinfo.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/geqo.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/tlist.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "partitioning/partbounds.h"
#include "port/pg_bitutils.h"
#include "rewrite/rewriteManip.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
Include dependency graph for allpaths.c:

Go to the source code of this file.

Data Structures

struct  pushdown_safety_info
 

Macros

#define UNSAFE_HAS_VOLATILE_FUNC   (1 << 0)
 
#define UNSAFE_HAS_SET_FUNC   (1 << 1)
 
#define UNSAFE_NOTIN_DISTINCTON_CLAUSE   (1 << 2)
 
#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE   (1 << 3)
 
#define UNSAFE_TYPE_MISMATCH   (1 << 4)
 

Typedefs

typedef struct pushdown_safety_info pushdown_safety_info
 
typedef enum pushdown_safe_type pushdown_safe_type
 

Enumerations

enum  pushdown_safe_type { PUSHDOWN_UNSAFE , PUSHDOWN_SAFE , PUSHDOWN_WINDOWCLAUSE_RUNCOND }
 

Functions

static void set_base_rel_consider_startup (PlannerInfo *root)
 
static void set_base_rel_sizes (PlannerInfo *root)
 
static void setup_simple_grouped_rels (PlannerInfo *root)
 
static void set_base_rel_pathlists (PlannerInfo *root)
 
static void set_rel_size (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_rel_pathlist (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_plain_rel_size (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void create_plain_partial_paths (PlannerInfo *root, RelOptInfo *rel)
 
static void set_rel_consider_parallel (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_plain_rel_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_tablesample_rel_size (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_tablesample_rel_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_foreign_size (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_foreign_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_append_rel_size (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_append_rel_pathlist (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_grouped_rel_pathlist (PlannerInfo *root, RelOptInfo *rel)
 
static void generate_orderedappend_paths (PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
 
static Pathget_cheapest_parameterized_child_path (PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
 
static void accumulate_append_subpath (Path *path, List **subpaths, List **special_subpaths)
 
static Pathget_singleton_append_subpath (Path *path)
 
static void set_dummy_rel_pathlist (RelOptInfo *rel)
 
static void set_subquery_pathlist (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_function_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_values_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_tablefunc_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_cte_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_namedtuplestore_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_result_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_worktable_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static RelOptInfomake_rel_from_joinlist (PlannerInfo *root, List *joinlist)
 
static bool subquery_is_pushdown_safe (Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
 
static bool recurse_pushdown_safe (Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
 
static void check_output_expressions (Query *subquery, pushdown_safety_info *safetyInfo)
 
static void compare_tlist_datatypes (List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
 
static bool targetIsInAllPartitionLists (TargetEntry *tle, Query *query)
 
static pushdown_safe_type qual_is_pushdown_safe (Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
 
static void subquery_push_qual (Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
 
static void recurse_push_qual (Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
 
static void remove_unused_subquery_outputs (Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
 
RelOptInfomake_one_rel (PlannerInfo *root, List *joinlist)
 
void add_paths_to_append_rel (PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
 
static bool find_window_run_conditions (Query *subquery, AttrNumber attno, WindowFunc *wfunc, OpExpr *opexpr, bool wfunc_left, bool *keep_original, Bitmapset **run_cond_attrs)
 
static bool check_and_push_window_quals (Query *subquery, Node *clause, Bitmapset **run_cond_attrs)
 
void generate_gather_paths (PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 
static Listget_useful_pathkeys_for_relation (PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
 
void generate_useful_gather_paths (PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 
void generate_grouped_paths (PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *rel)
 
RelOptInfostandard_join_search (PlannerInfo *root, int levels_needed, List *initial_rels)
 
void create_partial_bitmap_paths (PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual)
 
int compute_parallel_worker (RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
 
void generate_partitionwise_join_paths (PlannerInfo *root, RelOptInfo *rel)
 

Variables

bool enable_geqo = false
 
bool enable_eager_aggregate = true
 
int geqo_threshold
 
double min_eager_agg_group_size
 
int min_parallel_table_scan_size
 
int min_parallel_index_scan_size
 
set_rel_pathlist_hook_type set_rel_pathlist_hook = NULL
 
join_search_hook_type join_search_hook = NULL
 

Macro Definition Documentation

◆ UNSAFE_HAS_SET_FUNC

#define UNSAFE_HAS_SET_FUNC   (1 << 1)

Definition at line 56 of file allpaths.c.

◆ UNSAFE_HAS_VOLATILE_FUNC

#define UNSAFE_HAS_VOLATILE_FUNC   (1 << 0)

Definition at line 55 of file allpaths.c.

◆ UNSAFE_NOTIN_DISTINCTON_CLAUSE

#define UNSAFE_NOTIN_DISTINCTON_CLAUSE   (1 << 2)

Definition at line 57 of file allpaths.c.

◆ UNSAFE_NOTIN_PARTITIONBY_CLAUSE

#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE   (1 << 3)

Definition at line 58 of file allpaths.c.

◆ UNSAFE_TYPE_MISMATCH

#define UNSAFE_TYPE_MISMATCH   (1 << 4)

Definition at line 59 of file allpaths.c.

Typedef Documentation

◆ pushdown_safe_type

◆ pushdown_safety_info

Enumeration Type Documentation

◆ pushdown_safe_type

Enumerator
PUSHDOWN_UNSAFE 
PUSHDOWN_SAFE 
PUSHDOWN_WINDOWCLAUSE_RUNCOND 

Definition at line 72 of file allpaths.c.

73{
74 PUSHDOWN_UNSAFE, /* unsafe to push qual into subquery */
75 PUSHDOWN_SAFE, /* safe to push qual into subquery */
76 PUSHDOWN_WINDOWCLAUSE_RUNCOND, /* unsafe, but may work as WindowClause
77 * run condition */
pushdown_safe_type
Definition: allpaths.c:73
@ PUSHDOWN_WINDOWCLAUSE_RUNCOND
Definition: allpaths.c:76
@ PUSHDOWN_UNSAFE
Definition: allpaths.c:74
@ PUSHDOWN_SAFE
Definition: allpaths.c:75

Function Documentation

◆ accumulate_append_subpath()

static void accumulate_append_subpath ( Path path,
List **  subpaths,
List **  special_subpaths 
)
static

Definition at line 2213 of file allpaths.c.

2214{
2215 if (IsA(path, AppendPath))
2216 {
2217 AppendPath *apath = (AppendPath *) path;
2218
2219 if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2220 {
2221 *subpaths = list_concat(*subpaths, apath->subpaths);
2222 return;
2223 }
2224 else if (special_subpaths != NULL)
2225 {
2226 List *new_special_subpaths;
2227
2228 /* Split Parallel Append into partial and non-partial subpaths */
2229 *subpaths = list_concat(*subpaths,
2230 list_copy_tail(apath->subpaths,
2231 apath->first_partial_path));
2232 new_special_subpaths = list_copy_head(apath->subpaths,
2233 apath->first_partial_path);
2234 *special_subpaths = list_concat(*special_subpaths,
2235 new_special_subpaths);
2236 return;
2237 }
2238 }
2239 else if (IsA(path, MergeAppendPath))
2240 {
2241 MergeAppendPath *mpath = (MergeAppendPath *) path;
2242
2243 *subpaths = list_concat(*subpaths, mpath->subpaths);
2244 return;
2245 }
2246
2247 *subpaths = lappend(*subpaths, path);
2248}
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1613
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * list_copy_head(const List *oldlist, int len)
Definition: list.c:1593
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
int first_partial_path
Definition: pathnodes.h:2184
List * subpaths
Definition: pathnodes.h:2182
Definition: pg_list.h:54
bool parallel_aware
Definition: pathnodes.h:1902

References AppendPath::first_partial_path, IsA, lappend(), list_concat(), list_copy_head(), list_copy_tail(), Path::parallel_aware, AppendPath::path, AppendPath::subpaths, and MergeAppendPath::subpaths.

Referenced by add_paths_to_append_rel(), and generate_orderedappend_paths().

◆ add_paths_to_append_rel()

void add_paths_to_append_rel ( PlannerInfo root,
RelOptInfo rel,
List live_childrels 
)

Definition at line 1404 of file allpaths.c.

1406{
1407 List *subpaths = NIL;
1408 bool subpaths_valid = true;
1409 List *startup_subpaths = NIL;
1410 bool startup_subpaths_valid = true;
1411 List *partial_subpaths = NIL;
1412 List *pa_partial_subpaths = NIL;
1413 List *pa_nonpartial_subpaths = NIL;
1414 bool partial_subpaths_valid = true;
1415 bool pa_subpaths_valid;
1416 List *all_child_pathkeys = NIL;
1417 List *all_child_outers = NIL;
1418 ListCell *l;
1419 double partial_rows = -1;
1420
1421 /* If appropriate, consider parallel append */
1422 pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1423
1424 /*
1425 * For every non-dummy child, remember the cheapest path. Also, identify
1426 * all pathkeys (orderings) and parameterizations (required_outer sets)
1427 * available for the non-dummy member relations.
1428 */
1429 foreach(l, live_childrels)
1430 {
1431 RelOptInfo *childrel = lfirst(l);
1432 ListCell *lcp;
1433 Path *cheapest_partial_path = NULL;
1434
1435 /*
1436 * If child has an unparameterized cheapest-total path, add that to
1437 * the unparameterized Append path we are constructing for the parent.
1438 * If not, there's no workable unparameterized path.
1439 *
1440 * With partitionwise aggregates, the child rel's pathlist may be
1441 * empty, so don't assume that a path exists here.
1442 */
1443 if (childrel->pathlist != NIL &&
1444 childrel->cheapest_total_path->param_info == NULL)
1446 &subpaths, NULL);
1447 else
1448 subpaths_valid = false;
1449
1450 /*
1451 * When the planner is considering cheap startup plans, we'll also
1452 * collect all the cheapest_startup_paths (if set) and build an
1453 * AppendPath containing those as subpaths.
1454 */
1455 if (rel->consider_startup && childrel->cheapest_startup_path != NULL)
1456 {
1457 Path *cheapest_path;
1458
1459 /*
1460 * With an indication of how many tuples the query should provide,
1461 * the optimizer tries to choose the path optimal for that
1462 * specific number of tuples.
1463 */
1464 if (root->tuple_fraction > 0.0)
1465 cheapest_path =
1467 root->tuple_fraction);
1468 else
1469 cheapest_path = childrel->cheapest_startup_path;
1470
1471 /* cheapest_startup_path must not be a parameterized path. */
1472 Assert(cheapest_path->param_info == NULL);
1473 accumulate_append_subpath(cheapest_path,
1474 &startup_subpaths,
1475 NULL);
1476 }
1477 else
1478 startup_subpaths_valid = false;
1479
1480
1481 /* Same idea, but for a partial plan. */
1482 if (childrel->partial_pathlist != NIL)
1483 {
1484 cheapest_partial_path = linitial(childrel->partial_pathlist);
1485 accumulate_append_subpath(cheapest_partial_path,
1486 &partial_subpaths, NULL);
1487 }
1488 else
1489 partial_subpaths_valid = false;
1490
1491 /*
1492 * Same idea, but for a parallel append mixing partial and non-partial
1493 * paths.
1494 */
1495 if (pa_subpaths_valid)
1496 {
1497 Path *nppath = NULL;
1498
1499 nppath =
1501
1502 if (cheapest_partial_path == NULL && nppath == NULL)
1503 {
1504 /* Neither a partial nor a parallel-safe path? Forget it. */
1505 pa_subpaths_valid = false;
1506 }
1507 else if (nppath == NULL ||
1508 (cheapest_partial_path != NULL &&
1509 cheapest_partial_path->total_cost < nppath->total_cost))
1510 {
1511 /* Partial path is cheaper or the only option. */
1512 Assert(cheapest_partial_path != NULL);
1513 accumulate_append_subpath(cheapest_partial_path,
1514 &pa_partial_subpaths,
1515 &pa_nonpartial_subpaths);
1516 }
1517 else
1518 {
1519 /*
1520 * Either we've got only a non-partial path, or we think that
1521 * a single backend can execute the best non-partial path
1522 * faster than all the parallel backends working together can
1523 * execute the best partial path.
1524 *
1525 * It might make sense to be more aggressive here. Even if
1526 * the best non-partial path is more expensive than the best
1527 * partial path, it could still be better to choose the
1528 * non-partial path if there are several such paths that can
1529 * be given to different workers. For now, we don't try to
1530 * figure that out.
1531 */
1533 &pa_nonpartial_subpaths,
1534 NULL);
1535 }
1536 }
1537
1538 /*
1539 * Collect lists of all the available path orderings and
1540 * parameterizations for all the children. We use these as a
1541 * heuristic to indicate which sort orderings and parameterizations we
1542 * should build Append and MergeAppend paths for.
1543 */
1544 foreach(lcp, childrel->pathlist)
1545 {
1546 Path *childpath = (Path *) lfirst(lcp);
1547 List *childkeys = childpath->pathkeys;
1548 Relids childouter = PATH_REQ_OUTER(childpath);
1549
1550 /* Unsorted paths don't contribute to pathkey list */
1551 if (childkeys != NIL)
1552 {
1553 ListCell *lpk;
1554 bool found = false;
1555
1556 /* Have we already seen this ordering? */
1557 foreach(lpk, all_child_pathkeys)
1558 {
1559 List *existing_pathkeys = (List *) lfirst(lpk);
1560
1561 if (compare_pathkeys(existing_pathkeys,
1562 childkeys) == PATHKEYS_EQUAL)
1563 {
1564 found = true;
1565 break;
1566 }
1567 }
1568 if (!found)
1569 {
1570 /* No, so add it to all_child_pathkeys */
1571 all_child_pathkeys = lappend(all_child_pathkeys,
1572 childkeys);
1573 }
1574 }
1575
1576 /* Unparameterized paths don't contribute to param-set list */
1577 if (childouter)
1578 {
1579 ListCell *lco;
1580 bool found = false;
1581
1582 /* Have we already seen this param set? */
1583 foreach(lco, all_child_outers)
1584 {
1585 Relids existing_outers = (Relids) lfirst(lco);
1586
1587 if (bms_equal(existing_outers, childouter))
1588 {
1589 found = true;
1590 break;
1591 }
1592 }
1593 if (!found)
1594 {
1595 /* No, so add it to all_child_outers */
1596 all_child_outers = lappend(all_child_outers,
1597 childouter);
1598 }
1599 }
1600 }
1601 }
1602
1603 /*
1604 * If we found unparameterized paths for all children, build an unordered,
1605 * unparameterized Append path for the rel. (Note: this is correct even
1606 * if we have zero or one live subpath due to constraint exclusion.)
1607 */
1608 if (subpaths_valid)
1609 add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1610 NIL, NULL, 0, false,
1611 -1));
1612
1613 /* build an AppendPath for the cheap startup paths, if valid */
1614 if (startup_subpaths_valid)
1615 add_path(rel, (Path *) create_append_path(root, rel, startup_subpaths,
1616 NIL, NIL, NULL, 0, false, -1));
1617
1618 /*
1619 * Consider an append of unordered, unparameterized partial paths. Make
1620 * it parallel-aware if possible.
1621 */
1622 if (partial_subpaths_valid && partial_subpaths != NIL)
1623 {
1624 AppendPath *appendpath;
1625 ListCell *lc;
1626 int parallel_workers = 0;
1627
1628 /* Find the highest number of workers requested for any subpath. */
1629 foreach(lc, partial_subpaths)
1630 {
1631 Path *path = lfirst(lc);
1632
1633 parallel_workers = Max(parallel_workers, path->parallel_workers);
1634 }
1635 Assert(parallel_workers > 0);
1636
1637 /*
1638 * If the use of parallel append is permitted, always request at least
1639 * log2(# of children) workers. We assume it can be useful to have
1640 * extra workers in this case because they will be spread out across
1641 * the children. The precise formula is just a guess, but we don't
1642 * want to end up with a radically different answer for a table with N
1643 * partitions vs. an unpartitioned table with the same data, so the
1644 * use of some kind of log-scaling here seems to make some sense.
1645 */
1647 {
1648 parallel_workers = Max(parallel_workers,
1649 pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1650 parallel_workers = Min(parallel_workers,
1652 }
1653 Assert(parallel_workers > 0);
1654
1655 /* Generate a partial append path. */
1656 appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1657 NIL, NULL, parallel_workers,
1659 -1);
1660
1661 /*
1662 * Make sure any subsequent partial paths use the same row count
1663 * estimate.
1664 */
1665 partial_rows = appendpath->path.rows;
1666
1667 /* Add the path. */
1668 add_partial_path(rel, (Path *) appendpath);
1669 }
1670
1671 /*
1672 * Consider a parallel-aware append using a mix of partial and non-partial
1673 * paths. (This only makes sense if there's at least one child which has
1674 * a non-partial path that is substantially cheaper than any partial path;
1675 * otherwise, we should use the append path added in the previous step.)
1676 */
1677 if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1678 {
1679 AppendPath *appendpath;
1680 ListCell *lc;
1681 int parallel_workers = 0;
1682
1683 /*
1684 * Find the highest number of workers requested for any partial
1685 * subpath.
1686 */
1687 foreach(lc, pa_partial_subpaths)
1688 {
1689 Path *path = lfirst(lc);
1690
1691 parallel_workers = Max(parallel_workers, path->parallel_workers);
1692 }
1693
1694 /*
1695 * Same formula here as above. It's even more important in this
1696 * instance because the non-partial paths won't contribute anything to
1697 * the planned number of parallel workers.
1698 */
1699 parallel_workers = Max(parallel_workers,
1700 pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1701 parallel_workers = Min(parallel_workers,
1703 Assert(parallel_workers > 0);
1704
1705 appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1706 pa_partial_subpaths,
1707 NIL, NULL, parallel_workers, true,
1708 partial_rows);
1709 add_partial_path(rel, (Path *) appendpath);
1710 }
1711
1712 /*
1713 * Also build unparameterized ordered append paths based on the collected
1714 * list of child pathkeys.
1715 */
1716 if (subpaths_valid)
1717 generate_orderedappend_paths(root, rel, live_childrels,
1718 all_child_pathkeys);
1719
1720 /*
1721 * Build Append paths for each parameterization seen among the child rels.
1722 * (This may look pretty expensive, but in most cases of practical
1723 * interest, the child rels will expose mostly the same parameterizations,
1724 * so that not that many cases actually get considered here.)
1725 *
1726 * The Append node itself cannot enforce quals, so all qual checking must
1727 * be done in the child paths. This means that to have a parameterized
1728 * Append path, we must have the exact same parameterization for each
1729 * child path; otherwise some children might be failing to check the
1730 * moved-down quals. To make them match up, we can try to increase the
1731 * parameterization of lesser-parameterized paths.
1732 */
1733 foreach(l, all_child_outers)
1734 {
1735 Relids required_outer = (Relids) lfirst(l);
1736 ListCell *lcr;
1737
1738 /* Select the child paths for an Append with this parameterization */
1739 subpaths = NIL;
1740 subpaths_valid = true;
1741 foreach(lcr, live_childrels)
1742 {
1743 RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1744 Path *subpath;
1745
1746 if (childrel->pathlist == NIL)
1747 {
1748 /* failed to make a suitable path for this child */
1749 subpaths_valid = false;
1750 break;
1751 }
1752
1754 childrel,
1755 required_outer);
1756 if (subpath == NULL)
1757 {
1758 /* failed to make a suitable path for this child */
1759 subpaths_valid = false;
1760 break;
1761 }
1762 accumulate_append_subpath(subpath, &subpaths, NULL);
1763 }
1764
1765 if (subpaths_valid)
1766 add_path(rel, (Path *)
1767 create_append_path(root, rel, subpaths, NIL,
1768 NIL, required_outer, 0, false,
1769 -1));
1770 }
1771
1772 /*
1773 * When there is only a single child relation, the Append path can inherit
1774 * any ordering available for the child rel's path, so that it's useful to
1775 * consider ordered partial paths. Above we only considered the cheapest
1776 * partial path for each child, but let's also make paths using any
1777 * partial paths that have pathkeys.
1778 */
1779 if (list_length(live_childrels) == 1)
1780 {
1781 RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1782
1783 /* skip the cheapest partial path, since we already used that above */
1784 for_each_from(l, childrel->partial_pathlist, 1)
1785 {
1786 Path *path = (Path *) lfirst(l);
1787 AppendPath *appendpath;
1788
1789 /* skip paths with no pathkeys. */
1790 if (path->pathkeys == NIL)
1791 continue;
1792
1793 appendpath = create_append_path(root, rel, NIL, list_make1(path),
1794 NIL, NULL,
1795 path->parallel_workers, true,
1796 partial_rows);
1797 add_partial_path(rel, (Path *) appendpath);
1798 }
1799 }
1800}
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:2125
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition: allpaths.c:1830
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2213
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
#define Min(x, y)
Definition: c.h:1003
#define Max(x, y)
Definition: c.h:997
int max_parallel_workers_per_gather
Definition: costsize.c:143
bool enable_parallel_append
Definition: costsize.c:161
Assert(PointerIsAligned(start, uint64))
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:311
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:304
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition: pathkeys.c:699
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:794
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1299
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:460
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1919
Bitmapset * Relids
Definition: pathnodes.h:30
@ PATHKEYS_EQUAL
Definition: paths.h:212
static int pg_leftmost_one_pos32(uint32 word)
Definition: pg_bitutils.h:41
#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 list_make1(x1)
Definition: pg_list.h:212
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:6584
tree ctl root
Definition: radixtree.h:1857
List * pathkeys
Definition: pathnodes.h:1915
Cardinality rows
Definition: pathnodes.h:1909
int parallel_workers
Definition: pathnodes.h:1906
Cost total_cost
Definition: pathnodes.h:1912
bool consider_parallel
Definition: pathnodes.h:946
List * pathlist
Definition: pathnodes.h:957
struct Path * cheapest_startup_path
Definition: pathnodes.h:960
struct Path * cheapest_total_path
Definition: pathnodes.h:961
bool consider_startup
Definition: pathnodes.h:942
List * partial_pathlist
Definition: pathnodes.h:959

References accumulate_append_subpath(), add_partial_path(), add_path(), Assert(), bms_equal(), RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, compare_pathkeys(), RelOptInfo::consider_parallel, RelOptInfo::consider_startup, create_append_path(), enable_parallel_append, for_each_from, generate_orderedappend_paths(), get_cheapest_fractional_path(), get_cheapest_parallel_safe_total_inner(), get_cheapest_parameterized_child_path(), lappend(), lfirst, linitial, list_length(), list_make1, Max, max_parallel_workers_per_gather, Min, NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, AppendPath::path, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, RelOptInfo::pathlist, pg_leftmost_one_pos32(), root, Path::rows, subpath(), and Path::total_cost.

Referenced by apply_scanjoin_target_to_paths(), create_partitionwise_grouping_paths(), generate_partitionwise_join_paths(), and set_append_rel_pathlist().

◆ check_and_push_window_quals()

static bool check_and_push_window_quals ( Query subquery,
Node clause,
Bitmapset **  run_cond_attrs 
)
static

Definition at line 2530 of file allpaths.c.

2532{
2533 OpExpr *opexpr = (OpExpr *) clause;
2534 bool keep_original = true;
2535 Var *var1;
2536 Var *var2;
2537
2538 /* We're only able to use OpExprs with 2 operands */
2539 if (!IsA(opexpr, OpExpr))
2540 return true;
2541
2542 if (list_length(opexpr->args) != 2)
2543 return true;
2544
2545 /*
2546 * Currently, we restrict this optimization to strict OpExprs. The reason
2547 * for this is that during execution, once the runcondition becomes false,
2548 * we stop evaluating WindowFuncs. To avoid leaving around stale window
2549 * function result values, we set them to NULL. Having only strict
2550 * OpExprs here ensures that we properly filter out the tuples with NULLs
2551 * in the top-level WindowAgg.
2552 */
2553 set_opfuncid(opexpr);
2554 if (!func_strict(opexpr->opfuncid))
2555 return true;
2556
2557 /*
2558 * Check for plain Vars that reference window functions in the subquery.
2559 * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2560 * be used as part of the run condition.
2561 */
2562
2563 /* Check the left side of the OpExpr */
2564 var1 = linitial(opexpr->args);
2565 if (IsA(var1, Var) && var1->varattno > 0)
2566 {
2567 TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2568 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2569
2570 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2571 true, &keep_original, run_cond_attrs))
2572 return keep_original;
2573 }
2574
2575 /* and check the right side */
2576 var2 = lsecond(opexpr->args);
2577 if (IsA(var2, Var) && var2->varattno > 0)
2578 {
2579 TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2580 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2581
2582 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2583 false, &keep_original, run_cond_attrs))
2584 return keep_original;
2585 }
2586
2587 return true;
2588}
static bool find_window_run_conditions(Query *subquery, AttrNumber attno, WindowFunc *wfunc, OpExpr *opexpr, bool wfunc_left, bool *keep_original, Bitmapset **run_cond_attrs)
Definition: allpaths.c:2340
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
bool func_strict(Oid funcid)
Definition: lsyscache.c:1928
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1872
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define lsecond(l)
Definition: pg_list.h:183
List * args
Definition: primnodes.h:868
List * targetList
Definition: parsenodes.h:198
Expr * expr
Definition: primnodes.h:2239
AttrNumber resno
Definition: primnodes.h:2241
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274

References OpExpr::args, TargetEntry::expr, find_window_run_conditions(), func_strict(), if(), IsA, linitial, list_length(), list_nth(), lsecond, TargetEntry::resno, set_opfuncid(), Query::targetList, and Var::varattno.

Referenced by set_subquery_pathlist().

◆ check_output_expressions()

static void check_output_expressions ( Query subquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4192 of file allpaths.c.

4193{
4194 ListCell *lc;
4195
4196 foreach(lc, subquery->targetList)
4197 {
4198 TargetEntry *tle = (TargetEntry *) lfirst(lc);
4199
4200 if (tle->resjunk)
4201 continue; /* ignore resjunk columns */
4202
4203 /* Functions returning sets are unsafe (point 1) */
4204 if (subquery->hasTargetSRFs &&
4205 (safetyInfo->unsafeFlags[tle->resno] &
4206 UNSAFE_HAS_SET_FUNC) == 0 &&
4208 {
4209 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
4210 continue;
4211 }
4212
4213 /* Volatile functions are unsafe (point 2) */
4214 if ((safetyInfo->unsafeFlags[tle->resno] &
4217 {
4218 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
4219 continue;
4220 }
4221
4222 /* If subquery uses DISTINCT ON, check point 3 */
4223 if (subquery->hasDistinctOn &&
4224 (safetyInfo->unsafeFlags[tle->resno] &
4227 {
4228 /* non-DISTINCT column, so mark it unsafe */
4230 continue;
4231 }
4232
4233 /* If subquery uses window functions, check point 4 */
4234 if (subquery->hasWindowFuncs &&
4235 (safetyInfo->unsafeFlags[tle->resno] &
4237 !targetIsInAllPartitionLists(tle, subquery))
4238 {
4239 /* not present in all PARTITION BY clauses, so mark it unsafe */
4241 continue;
4242 }
4243 }
4244}
#define UNSAFE_HAS_VOLATILE_FUNC
Definition: allpaths.c:55
#define UNSAFE_NOTIN_DISTINCTON_CLAUSE
Definition: allpaths.c:57
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:4297
#define UNSAFE_HAS_SET_FUNC
Definition: allpaths.c:56
#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE
Definition: allpaths.c:58
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:542
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:763
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition: postgres_ext.h:37
Definition: nodes.h:135
List * distinctClause
Definition: parsenodes.h:226
unsigned char * unsafeFlags
Definition: allpaths.c:64

References contain_volatile_functions(), Query::distinctClause, TargetEntry::expr, expression_returns_set(), InvalidOid, lfirst, TargetEntry::resno, targetIsInAllPartitionLists(), targetIsInSortList(), Query::targetList, UNSAFE_HAS_SET_FUNC, UNSAFE_HAS_VOLATILE_FUNC, UNSAFE_NOTIN_DISTINCTON_CLAUSE, UNSAFE_NOTIN_PARTITIONBY_CLAUSE, and pushdown_safety_info::unsafeFlags.

Referenced by subquery_is_pushdown_safe().

◆ compare_tlist_datatypes()

static void compare_tlist_datatypes ( List tlist,
List colTypes,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4264 of file allpaths.c.

4266{
4267 ListCell *l;
4268 ListCell *colType = list_head(colTypes);
4269
4270 foreach(l, tlist)
4271 {
4272 TargetEntry *tle = (TargetEntry *) lfirst(l);
4273
4274 if (tle->resjunk)
4275 continue; /* ignore resjunk columns */
4276 if (colType == NULL)
4277 elog(ERROR, "wrong number of tlist entries");
4278 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
4279 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
4280 colType = lnext(colTypes, colType);
4281 }
4282 if (colType != NULL)
4283 elog(ERROR, "wrong number of tlist entries");
4284}
#define UNSAFE_TYPE_MISMATCH
Definition: allpaths.c:59
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define lfirst_oid(lc)
Definition: pg_list.h:174

References elog, ERROR, TargetEntry::expr, exprType(), lfirst, lfirst_oid, list_head(), lnext(), TargetEntry::resno, UNSAFE_TYPE_MISMATCH, and pushdown_safety_info::unsafeFlags.

Referenced by subquery_is_pushdown_safe().

◆ compute_parallel_worker()

int compute_parallel_worker ( RelOptInfo rel,
double  heap_pages,
double  index_pages,
int  max_workers 
)

Definition at line 4689 of file allpaths.c.

4691{
4692 int parallel_workers = 0;
4693
4694 /*
4695 * If the user has set the parallel_workers reloption, use that; otherwise
4696 * select a default number of workers.
4697 */
4698 if (rel->rel_parallel_workers != -1)
4699 parallel_workers = rel->rel_parallel_workers;
4700 else
4701 {
4702 /*
4703 * If the number of pages being scanned is insufficient to justify a
4704 * parallel scan, just return zero ... unless it's an inheritance
4705 * child. In that case, we want to generate a parallel path here
4706 * anyway. It might not be worthwhile just for this relation, but
4707 * when combined with all of its inheritance siblings it may well pay
4708 * off.
4709 */
4710 if (rel->reloptkind == RELOPT_BASEREL &&
4711 ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4712 (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4713 return 0;
4714
4715 if (heap_pages >= 0)
4716 {
4717 int heap_parallel_threshold;
4718 int heap_parallel_workers = 1;
4719
4720 /*
4721 * Select the number of workers based on the log of the size of
4722 * the relation. This probably needs to be a good deal more
4723 * sophisticated, but we need something here for now. Note that
4724 * the upper limit of the min_parallel_table_scan_size GUC is
4725 * chosen to prevent overflow here.
4726 */
4727 heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4728 while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4729 {
4730 heap_parallel_workers++;
4731 heap_parallel_threshold *= 3;
4732 if (heap_parallel_threshold > INT_MAX / 3)
4733 break; /* avoid overflow */
4734 }
4735
4736 parallel_workers = heap_parallel_workers;
4737 }
4738
4739 if (index_pages >= 0)
4740 {
4741 int index_parallel_workers = 1;
4742 int index_parallel_threshold;
4743
4744 /* same calculation as for heap_pages above */
4745 index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4746 while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4747 {
4748 index_parallel_workers++;
4749 index_parallel_threshold *= 3;
4750 if (index_parallel_threshold > INT_MAX / 3)
4751 break; /* avoid overflow */
4752 }
4753
4754 if (parallel_workers > 0)
4755 parallel_workers = Min(parallel_workers, index_parallel_workers);
4756 else
4757 parallel_workers = index_parallel_workers;
4758 }
4759 }
4760
4761 /* In no case use more than caller supplied maximum number of workers */
4762 parallel_workers = Min(parallel_workers, max_workers);
4763
4764 return parallel_workers;
4765}
int min_parallel_index_scan_size
Definition: allpaths.c:86
int min_parallel_table_scan_size
Definition: allpaths.c:85
uint32 BlockNumber
Definition: block.h:31
@ RELOPT_BASEREL
Definition: pathnodes.h:886
RelOptKind reloptkind
Definition: pathnodes.h:924
int rel_parallel_workers
Definition: pathnodes.h:1010

References Max, Min, min_parallel_index_scan_size, min_parallel_table_scan_size, RelOptInfo::rel_parallel_workers, RELOPT_BASEREL, and RelOptInfo::reloptkind.

Referenced by cost_index(), create_partial_bitmap_paths(), create_plain_partial_paths(), and plan_create_index_workers().

◆ create_partial_bitmap_paths()

void create_partial_bitmap_paths ( PlannerInfo root,
RelOptInfo rel,
Path bitmapqual 
)

Definition at line 4653 of file allpaths.c.

4655{
4656 int parallel_workers;
4657 double pages_fetched;
4658
4659 /* Compute heap pages for bitmap heap scan */
4660 pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4661 NULL, NULL);
4662
4663 parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4665
4666 if (parallel_workers <= 0)
4667 return;
4668
4670 bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4671}
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4689
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6549
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1097
Relids lateral_relids
Definition: pathnodes.h:971

References add_partial_path(), compute_bitmap_pages(), compute_parallel_worker(), create_bitmap_heap_path(), RelOptInfo::lateral_relids, max_parallel_workers_per_gather, and root.

Referenced by create_index_paths().

◆ create_plain_partial_paths()

static void create_plain_partial_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 860 of file allpaths.c.

861{
862 int parallel_workers;
863
864 parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
866
867 /* If any limit was set to zero, the user doesn't want a parallel scan. */
868 if (parallel_workers <= 0)
869 return;
870
871 /* Add an unordered partial path based on a parallel sequential scan. */
872 add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
873}
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:982
BlockNumber pages
Definition: pathnodes.h:1002

References add_partial_path(), compute_parallel_worker(), create_seqscan_path(), max_parallel_workers_per_gather, RelOptInfo::pages, and root.

Referenced by set_plain_rel_pathlist().

◆ find_window_run_conditions()

static bool find_window_run_conditions ( Query subquery,
AttrNumber  attno,
WindowFunc wfunc,
OpExpr opexpr,
bool  wfunc_left,
bool *  keep_original,
Bitmapset **  run_cond_attrs 
)
static

Definition at line 2340 of file allpaths.c.

2343{
2344 Oid prosupport;
2345 Expr *otherexpr;
2348 WindowClause *wclause;
2349 List *opinfos;
2350 OpExpr *runopexpr;
2351 Oid runoperator;
2352 ListCell *lc;
2353
2354 *keep_original = true;
2355
2356 while (IsA(wfunc, RelabelType))
2357 wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2358
2359 /* we can only work with window functions */
2360 if (!IsA(wfunc, WindowFunc))
2361 return false;
2362
2363 /* can't use it if there are subplans in the WindowFunc */
2364 if (contain_subplans((Node *) wfunc))
2365 return false;
2366
2367 prosupport = get_func_support(wfunc->winfnoid);
2368
2369 /* Check if there's a support function for 'wfunc' */
2370 if (!OidIsValid(prosupport))
2371 return false;
2372
2373 /* get the Expr from the other side of the OpExpr */
2374 if (wfunc_left)
2375 otherexpr = lsecond(opexpr->args);
2376 else
2377 otherexpr = linitial(opexpr->args);
2378
2379 /*
2380 * The value being compared must not change during the evaluation of the
2381 * window partition.
2382 */
2383 if (!is_pseudo_constant_clause((Node *) otherexpr))
2384 return false;
2385
2386 /* find the window clause belonging to the window function */
2387 wclause = (WindowClause *) list_nth(subquery->windowClause,
2388 wfunc->winref - 1);
2389
2390 req.type = T_SupportRequestWFuncMonotonic;
2391 req.window_func = wfunc;
2392 req.window_clause = wclause;
2393
2394 /* call the support function */
2397 PointerGetDatum(&req)));
2398
2399 /*
2400 * Nothing to do if the function is neither monotonically increasing nor
2401 * monotonically decreasing.
2402 */
2403 if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2404 return false;
2405
2406 runopexpr = NULL;
2407 runoperator = InvalidOid;
2408 opinfos = get_op_index_interpretation(opexpr->opno);
2409
2410 foreach(lc, opinfos)
2411 {
2413 CompareType cmptype = opinfo->cmptype;
2414
2415 /* handle < / <= */
2416 if (cmptype == COMPARE_LT || cmptype == COMPARE_LE)
2417 {
2418 /*
2419 * < / <= is supported for monotonically increasing functions in
2420 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2421 * for monotonically decreasing functions.
2422 */
2423 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2424 (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2425 {
2426 *keep_original = false;
2427 runopexpr = opexpr;
2428 runoperator = opexpr->opno;
2429 }
2430 break;
2431 }
2432 /* handle > / >= */
2433 else if (cmptype == COMPARE_GT || cmptype == COMPARE_GE)
2434 {
2435 /*
2436 * > / >= is supported for monotonically decreasing functions in
2437 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2438 * for monotonically increasing functions.
2439 */
2440 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2441 (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2442 {
2443 *keep_original = false;
2444 runopexpr = opexpr;
2445 runoperator = opexpr->opno;
2446 }
2447 break;
2448 }
2449 /* handle = */
2450 else if (cmptype == COMPARE_EQ)
2451 {
2452 CompareType newcmptype;
2453
2454 /*
2455 * When both monotonically increasing and decreasing then the
2456 * return value of the window function will be the same each time.
2457 * We can simply use 'opexpr' as the run condition without
2458 * modifying it.
2459 */
2461 {
2462 *keep_original = false;
2463 runopexpr = opexpr;
2464 runoperator = opexpr->opno;
2465 break;
2466 }
2467
2468 /*
2469 * When monotonically increasing we make a qual with <wfunc> <=
2470 * <value> or <value> >= <wfunc> in order to filter out values
2471 * which are above the value in the equality condition. For
2472 * monotonically decreasing functions we want to filter values
2473 * below the value in the equality condition.
2474 */
2476 newcmptype = wfunc_left ? COMPARE_LE : COMPARE_GE;
2477 else
2478 newcmptype = wfunc_left ? COMPARE_GE : COMPARE_LE;
2479
2480 /* We must keep the original equality qual */
2481 *keep_original = true;
2482 runopexpr = opexpr;
2483
2484 /* determine the operator to use for the WindowFuncRunCondition */
2485 runoperator = get_opfamily_member_for_cmptype(opinfo->opfamily_id,
2486 opinfo->oplefttype,
2487 opinfo->oprighttype,
2488 newcmptype);
2489 break;
2490 }
2491 }
2492
2493 if (runopexpr != NULL)
2494 {
2495 WindowFuncRunCondition *wfuncrc;
2496
2498 wfuncrc->opno = runoperator;
2499 wfuncrc->inputcollid = runopexpr->inputcollid;
2500 wfuncrc->wfunc_left = wfunc_left;
2501 wfuncrc->arg = copyObject(otherexpr);
2502
2503 wfunc->runCondition = lappend(wfunc->runCondition, wfuncrc);
2504
2505 /* record that this attno was used in a run condition */
2506 *run_cond_attrs = bms_add_member(*run_cond_attrs,
2508 return true;
2509 }
2510
2511 /* unsupported OpExpr */
2512 return false;
2513}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define OidIsValid(objectId)
Definition: c.h:774
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:2095
bool contain_subplans(Node *clause)
Definition: clauses.c:334
CompareType
Definition: cmptype.h:32
@ COMPARE_LE
Definition: cmptype.h:35
@ COMPARE_GT
Definition: cmptype.h:38
@ COMPARE_EQ
Definition: cmptype.h:36
@ COMPARE_GE
Definition: cmptype.h:37
@ COMPARE_LT
Definition: cmptype.h:34
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:720
Oid get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype, CompareType cmptype)
Definition: lsyscache.c:197
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:2025
List * get_op_index_interpretation(Oid opno)
Definition: lsyscache.c:673
#define copyObject(obj)
Definition: nodes.h:232
#define makeNode(_type_)
Definition: nodes.h:161
void * arg
@ MONOTONICFUNC_NONE
Definition: plannodes.h:1820
@ MONOTONICFUNC_DECREASING
Definition: plannodes.h:1822
@ MONOTONICFUNC_INCREASING
Definition: plannodes.h:1821
@ MONOTONICFUNC_BOTH
Definition: plannodes.h:1823
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322
unsigned int Oid
Definition: postgres_ext.h:32
Oid opno
Definition: primnodes.h:850
CompareType cmptype
Definition: lsyscache.h:28
List * windowClause
Definition: parsenodes.h:224
MonotonicFunction monotonic
Definition: supportnodes.h:299
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References arg, WindowFuncRunCondition::arg, OpExpr::args, bms_add_member(), OpIndexInterpretation::cmptype, COMPARE_EQ, COMPARE_GE, COMPARE_GT, COMPARE_LE, COMPARE_LT, contain_subplans(), copyObject, DatumGetPointer(), FirstLowInvalidHeapAttributeNumber, get_func_support(), get_op_index_interpretation(), get_opfamily_member_for_cmptype(), InvalidOid, is_pseudo_constant_clause(), IsA, lappend(), lfirst, linitial, list_nth(), lsecond, makeNode, SupportRequestWFuncMonotonic::monotonic, MONOTONICFUNC_BOTH, MONOTONICFUNC_DECREASING, MONOTONICFUNC_INCREASING, MONOTONICFUNC_NONE, OidFunctionCall1, OidIsValid, OpIndexInterpretation::opfamily_id, OpIndexInterpretation::oplefttype, WindowFuncRunCondition::opno, OpExpr::opno, OpIndexInterpretation::oprighttype, PointerGetDatum(), SupportRequestWFuncMonotonic::type, WindowFuncRunCondition::wfunc_left, SupportRequestWFuncMonotonic::window_clause, SupportRequestWFuncMonotonic::window_func, Query::windowClause, WindowFunc::winfnoid, and WindowFunc::winref.

Referenced by check_and_push_window_quals().

◆ generate_gather_paths()

void generate_gather_paths ( PlannerInfo root,
RelOptInfo rel,
bool  override_rows 
)

Definition at line 3175 of file allpaths.c.

3176{
3177 Path *cheapest_partial_path;
3178 Path *simple_gather_path;
3179 ListCell *lc;
3180 double rows;
3181 double *rowsp = NULL;
3182
3183 /* If there are no partial paths, there's nothing to do here. */
3184 if (rel->partial_pathlist == NIL)
3185 return;
3186
3187 /* Should we override the rel's rowcount estimate? */
3188 if (override_rows)
3189 rowsp = &rows;
3190
3191 /*
3192 * The output of Gather is always unsorted, so there's only one partial
3193 * path of interest: the cheapest one. That will be the one at the front
3194 * of partial_pathlist because of the way add_partial_path works.
3195 */
3196 cheapest_partial_path = linitial(rel->partial_pathlist);
3197 rows = compute_gather_rows(cheapest_partial_path);
3198 simple_gather_path = (Path *)
3199 create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
3200 NULL, rowsp);
3201 add_path(rel, simple_gather_path);
3202
3203 /*
3204 * For each useful ordering, we can consider an order-preserving Gather
3205 * Merge.
3206 */
3207 foreach(lc, rel->partial_pathlist)
3208 {
3209 Path *subpath = (Path *) lfirst(lc);
3210 GatherMergePath *path;
3211
3212 if (subpath->pathkeys == NIL)
3213 continue;
3214
3217 subpath->pathkeys, NULL, rowsp);
3218 add_path(rel, &path->path);
3219 }
3220}
double compute_gather_rows(Path *path)
Definition: costsize.c:6660
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1749
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1801
struct PathTarget * reltarget
Definition: pathnodes.h:952

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_gather_path(), lfirst, linitial, NIL, RelOptInfo::partial_pathlist, GatherMergePath::path, RelOptInfo::reltarget, root, and subpath().

Referenced by generate_useful_gather_paths().

◆ generate_grouped_paths()

void generate_grouped_paths ( PlannerInfo root,
RelOptInfo grouped_rel,
RelOptInfo rel 
)

Definition at line 3429 of file allpaths.c.

3431{
3432 RelAggInfo *agg_info = grouped_rel->agg_info;
3433 AggClauseCosts agg_costs;
3434 bool can_hash;
3435 bool can_sort;
3436 Path *cheapest_total_path = NULL;
3437 Path *cheapest_partial_path = NULL;
3438 double dNumGroups = 0;
3439 double dNumPartialGroups = 0;
3440 List *group_pathkeys = NIL;
3441
3442 if (IS_DUMMY_REL(rel))
3443 {
3444 mark_dummy_rel(grouped_rel);
3445 return;
3446 }
3447
3448 /*
3449 * We push partial aggregation only to the lowest possible level in the
3450 * join tree that is deemed useful.
3451 */
3452 if (!bms_equal(agg_info->apply_at, rel->relids) ||
3453 !agg_info->agg_useful)
3454 return;
3455
3456 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3458
3459 /*
3460 * Determine whether it's possible to perform sort-based implementations
3461 * of grouping, and generate the pathkeys that represent the grouping
3462 * requirements in that case.
3463 */
3464 can_sort = grouping_is_sortable(agg_info->group_clauses);
3465 if (can_sort)
3466 {
3467 RelOptInfo *top_grouped_rel;
3468 List *top_group_tlist;
3469
3470 top_grouped_rel = IS_OTHER_REL(rel) ?
3471 rel->top_parent->grouped_rel : grouped_rel;
3472 top_group_tlist =
3473 make_tlist_from_pathtarget(top_grouped_rel->agg_info->target);
3474
3475 group_pathkeys =
3477 top_group_tlist);
3478 }
3479
3480 /*
3481 * Determine whether we should consider hash-based implementations of
3482 * grouping.
3483 */
3484 Assert(root->numOrderedAggs == 0);
3485 can_hash = (agg_info->group_clauses != NIL &&
3487
3488 /*
3489 * Consider whether we should generate partially aggregated non-partial
3490 * paths. We can only do this if we have a non-partial path.
3491 */
3492 if (rel->pathlist != NIL)
3493 {
3494 cheapest_total_path = rel->cheapest_total_path;
3495 Assert(cheapest_total_path != NULL);
3496 }
3497
3498 /*
3499 * If parallelism is possible for grouped_rel, then we should consider
3500 * generating partially-grouped partial paths. However, if the ungrouped
3501 * rel has no partial paths, then we can't.
3502 */
3503 if (grouped_rel->consider_parallel && rel->partial_pathlist != NIL)
3504 {
3505 cheapest_partial_path = linitial(rel->partial_pathlist);
3506 Assert(cheapest_partial_path != NULL);
3507 }
3508
3509 /* Estimate number of partial groups. */
3510 if (cheapest_total_path != NULL)
3511 dNumGroups = estimate_num_groups(root,
3512 agg_info->group_exprs,
3513 cheapest_total_path->rows,
3514 NULL, NULL);
3515 if (cheapest_partial_path != NULL)
3516 dNumPartialGroups = estimate_num_groups(root,
3517 agg_info->group_exprs,
3518 cheapest_partial_path->rows,
3519 NULL, NULL);
3520
3521 if (can_sort && cheapest_total_path != NULL)
3522 {
3523 ListCell *lc;
3524
3525 /*
3526 * Use any available suitably-sorted path as input, and also consider
3527 * sorting the cheapest-total path and incremental sort on any paths
3528 * with presorted keys.
3529 *
3530 * To save planning time, we ignore parameterized input paths unless
3531 * they are the cheapest-total path.
3532 */
3533 foreach(lc, rel->pathlist)
3534 {
3535 Path *input_path = (Path *) lfirst(lc);
3536 Path *path;
3537 bool is_sorted;
3538 int presorted_keys;
3539
3540 /*
3541 * Ignore parameterized paths that are not the cheapest-total
3542 * path.
3543 */
3544 if (input_path->param_info &&
3545 input_path != cheapest_total_path)
3546 continue;
3547
3548 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3549 input_path->pathkeys,
3550 &presorted_keys);
3551
3552 /*
3553 * Ignore paths that are not suitably or partially sorted, unless
3554 * they are the cheapest total path (no need to deal with paths
3555 * which have presorted keys when incremental sort is disabled).
3556 */
3557 if (!is_sorted && input_path != cheapest_total_path &&
3558 (presorted_keys == 0 || !enable_incremental_sort))
3559 continue;
3560
3561 /*
3562 * Since the path originates from a non-grouped relation that is
3563 * not aware of eager aggregation, we must ensure that it provides
3564 * the correct input for partial aggregation.
3565 */
3566 path = (Path *) create_projection_path(root,
3567 grouped_rel,
3568 input_path,
3569 agg_info->agg_input);
3570
3571 if (!is_sorted)
3572 {
3573 /*
3574 * We've no need to consider both a sort and incremental sort.
3575 * We'll just do a sort if there are no presorted keys and an
3576 * incremental sort when there are presorted keys.
3577 */
3578 if (presorted_keys == 0 || !enable_incremental_sort)
3579 path = (Path *) create_sort_path(root,
3580 grouped_rel,
3581 path,
3582 group_pathkeys,
3583 -1.0);
3584 else
3586 grouped_rel,
3587 path,
3588 group_pathkeys,
3589 presorted_keys,
3590 -1.0);
3591 }
3592
3593 /*
3594 * qual is NIL because the HAVING clause cannot be evaluated until
3595 * the final value of the aggregate is known.
3596 */
3597 path = (Path *) create_agg_path(root,
3598 grouped_rel,
3599 path,
3600 agg_info->target,
3601 AGG_SORTED,
3603 agg_info->group_clauses,
3604 NIL,
3605 &agg_costs,
3606 dNumGroups);
3607
3608 add_path(grouped_rel, path);
3609 }
3610 }
3611
3612 if (can_sort && cheapest_partial_path != NULL)
3613 {
3614 ListCell *lc;
3615
3616 /* Similar to above logic, but for partial paths. */
3617 foreach(lc, rel->partial_pathlist)
3618 {
3619 Path *input_path = (Path *) lfirst(lc);
3620 Path *path;
3621 bool is_sorted;
3622 int presorted_keys;
3623
3624 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3625 input_path->pathkeys,
3626 &presorted_keys);
3627
3628 /*
3629 * Ignore paths that are not suitably or partially sorted, unless
3630 * they are the cheapest partial path (no need to deal with paths
3631 * which have presorted keys when incremental sort is disabled).
3632 */
3633 if (!is_sorted && input_path != cheapest_partial_path &&
3634 (presorted_keys == 0 || !enable_incremental_sort))
3635 continue;
3636
3637 /*
3638 * Since the path originates from a non-grouped relation that is
3639 * not aware of eager aggregation, we must ensure that it provides
3640 * the correct input for partial aggregation.
3641 */
3642 path = (Path *) create_projection_path(root,
3643 grouped_rel,
3644 input_path,
3645 agg_info->agg_input);
3646
3647 if (!is_sorted)
3648 {
3649 /*
3650 * We've no need to consider both a sort and incremental sort.
3651 * We'll just do a sort if there are no presorted keys and an
3652 * incremental sort when there are presorted keys.
3653 */
3654 if (presorted_keys == 0 || !enable_incremental_sort)
3655 path = (Path *) create_sort_path(root,
3656 grouped_rel,
3657 path,
3658 group_pathkeys,
3659 -1.0);
3660 else
3662 grouped_rel,
3663 path,
3664 group_pathkeys,
3665 presorted_keys,
3666 -1.0);
3667 }
3668
3669 /*
3670 * qual is NIL because the HAVING clause cannot be evaluated until
3671 * the final value of the aggregate is known.
3672 */
3673 path = (Path *) create_agg_path(root,
3674 grouped_rel,
3675 path,
3676 agg_info->target,
3677 AGG_SORTED,
3679 agg_info->group_clauses,
3680 NIL,
3681 &agg_costs,
3682 dNumPartialGroups);
3683
3684 add_partial_path(grouped_rel, path);
3685 }
3686 }
3687
3688 /*
3689 * Add a partially-grouped HashAgg Path where possible
3690 */
3691 if (can_hash && cheapest_total_path != NULL)
3692 {
3693 Path *path;
3694
3695 /*
3696 * Since the path originates from a non-grouped relation that is not
3697 * aware of eager aggregation, we must ensure that it provides the
3698 * correct input for partial aggregation.
3699 */
3700 path = (Path *) create_projection_path(root,
3701 grouped_rel,
3702 cheapest_total_path,
3703 agg_info->agg_input);
3704
3705 /*
3706 * qual is NIL because the HAVING clause cannot be evaluated until the
3707 * final value of the aggregate is known.
3708 */
3709 path = (Path *) create_agg_path(root,
3710 grouped_rel,
3711 path,
3712 agg_info->target,
3713 AGG_HASHED,
3715 agg_info->group_clauses,
3716 NIL,
3717 &agg_costs,
3718 dNumGroups);
3719
3720 add_path(grouped_rel, path);
3721 }
3722
3723 /*
3724 * Now add a partially-grouped HashAgg partial Path where possible
3725 */
3726 if (can_hash && cheapest_partial_path != NULL)
3727 {
3728 Path *path;
3729
3730 /*
3731 * Since the path originates from a non-grouped relation that is not
3732 * aware of eager aggregation, we must ensure that it provides the
3733 * correct input for partial aggregation.
3734 */
3735 path = (Path *) create_projection_path(root,
3736 grouped_rel,
3737 cheapest_partial_path,
3738 agg_info->agg_input);
3739
3740 /*
3741 * qual is NIL because the HAVING clause cannot be evaluated until the
3742 * final value of the aggregate is known.
3743 */
3744 path = (Path *) create_agg_path(root,
3745 grouped_rel,
3746 path,
3747 agg_info->target,
3748 AGG_HASHED,
3750 agg_info->group_clauses,
3751 NIL,
3752 &agg_costs,
3753 dNumPartialGroups);
3754
3755 add_partial_path(grouped_rel, path);
3756 }
3757}
#define MemSet(start, val, len)
Definition: c.h:1019
bool enable_incremental_sort
Definition: costsize.c:151
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1513
@ AGG_SORTED
Definition: nodes.h:365
@ AGG_HASHED
Definition: nodes.h:366
@ AGGSPLIT_INITIAL_SERIAL
Definition: nodes.h:389
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:558
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:1336
ProjectionPath * create_projection_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target)
Definition: pathnode.c:2523
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2791
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2840
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2993
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:2196
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:913
void get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
Definition: prepagg.c:559
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3456
List * group_exprs
Definition: pathnodes.h:1206
bool agg_useful
Definition: pathnodes.h:1215
List * group_clauses
Definition: pathnodes.h:1204
struct PathTarget * agg_input
Definition: pathnodes.h:1201
Relids apply_at
Definition: pathnodes.h:1209
struct PathTarget * target
Definition: pathnodes.h:1198
Relids relids
Definition: pathnodes.h:930
struct RelAggInfo * agg_info
Definition: pathnodes.h:1069
struct RelOptInfo * grouped_rel
Definition: pathnodes.h:1071
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:540
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:624
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:560

References add_partial_path(), add_path(), AGG_HASHED, RelOptInfo::agg_info, RelAggInfo::agg_input, AGG_SORTED, RelAggInfo::agg_useful, AGGSPLIT_INITIAL_SERIAL, RelAggInfo::apply_at, Assert(), bms_equal(), RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_agg_path(), create_incremental_sort_path(), create_projection_path(), create_sort_path(), enable_incremental_sort, estimate_num_groups(), get_agg_clause_costs(), RelAggInfo::group_clauses, RelAggInfo::group_exprs, RelOptInfo::grouped_rel, grouping_is_hashable(), grouping_is_sortable(), IS_DUMMY_REL, IS_OTHER_REL, lfirst, linitial, make_pathkeys_for_sortclauses(), make_tlist_from_pathtarget(), mark_dummy_rel(), MemSet, NIL, RelOptInfo::partial_pathlist, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::pathlist, RelOptInfo::relids, root, Path::rows, and RelAggInfo::target.

Referenced by generate_partitionwise_join_paths(), merge_clump(), set_grouped_rel_pathlist(), and standard_join_search().

◆ generate_orderedappend_paths()

static void generate_orderedappend_paths ( PlannerInfo root,
RelOptInfo rel,
List live_childrels,
List all_child_pathkeys 
)
static

Definition at line 1830 of file allpaths.c.

1833{
1834 ListCell *lcp;
1835 List *partition_pathkeys = NIL;
1836 List *partition_pathkeys_desc = NIL;
1837 bool partition_pathkeys_partial = true;
1838 bool partition_pathkeys_desc_partial = true;
1839
1840 /*
1841 * Some partitioned table setups may allow us to use an Append node
1842 * instead of a MergeAppend. This is possible in cases such as RANGE
1843 * partitioned tables where it's guaranteed that an earlier partition must
1844 * contain rows which come earlier in the sort order. To detect whether
1845 * this is relevant, build pathkey descriptions of the partition ordering,
1846 * for both forward and reverse scans.
1847 */
1848 if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1849 partitions_are_ordered(rel->boundinfo, rel->live_parts))
1850 {
1851 partition_pathkeys = build_partition_pathkeys(root, rel,
1853 &partition_pathkeys_partial);
1854
1855 partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1857 &partition_pathkeys_desc_partial);
1858
1859 /*
1860 * You might think we should truncate_useless_pathkeys here, but
1861 * allowing partition keys which are a subset of the query's pathkeys
1862 * can often be useful. For example, consider a table partitioned by
1863 * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1864 * paths that can produce the a, b, c ordering (perhaps via indexes on
1865 * (a, b, c)) then it works to consider the appendrel output as
1866 * ordered by a, b, c.
1867 */
1868 }
1869
1870 /* Now consider each interesting sort ordering */
1871 foreach(lcp, all_child_pathkeys)
1872 {
1873 List *pathkeys = (List *) lfirst(lcp);
1874 List *startup_subpaths = NIL;
1875 List *total_subpaths = NIL;
1876 List *fractional_subpaths = NIL;
1877 bool startup_neq_total = false;
1878 bool match_partition_order;
1879 bool match_partition_order_desc;
1880 int end_index;
1881 int first_index;
1882 int direction;
1883
1884 /*
1885 * Determine if this sort ordering matches any partition pathkeys we
1886 * have, for both ascending and descending partition order. If the
1887 * partition pathkeys happen to be contained in pathkeys then it still
1888 * works, as described above, providing that the partition pathkeys
1889 * are complete and not just a prefix of the partition keys. (In such
1890 * cases we'll be relying on the child paths to have sorted the
1891 * lower-order columns of the required pathkeys.)
1892 */
1893 match_partition_order =
1894 pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1895 (!partition_pathkeys_partial &&
1896 pathkeys_contained_in(partition_pathkeys, pathkeys));
1897
1898 match_partition_order_desc = !match_partition_order &&
1899 (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1900 (!partition_pathkeys_desc_partial &&
1901 pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1902
1903 /*
1904 * When the required pathkeys match the reverse of the partition
1905 * order, we must build the list of paths in reverse starting with the
1906 * last matching partition first. We can get away without making any
1907 * special cases for this in the loop below by just looping backward
1908 * over the child relations in this case.
1909 */
1910 if (match_partition_order_desc)
1911 {
1912 /* loop backward */
1913 first_index = list_length(live_childrels) - 1;
1914 end_index = -1;
1915 direction = -1;
1916
1917 /*
1918 * Set this to true to save us having to check for
1919 * match_partition_order_desc in the loop below.
1920 */
1921 match_partition_order = true;
1922 }
1923 else
1924 {
1925 /* for all other case, loop forward */
1926 first_index = 0;
1927 end_index = list_length(live_childrels);
1928 direction = 1;
1929 }
1930
1931 /* Select the child paths for this ordering... */
1932 for (int i = first_index; i != end_index; i += direction)
1933 {
1934 RelOptInfo *childrel = list_nth_node(RelOptInfo, live_childrels, i);
1935 Path *cheapest_startup,
1936 *cheapest_total,
1937 *cheapest_fractional = NULL;
1938
1939 /* Locate the right paths, if they are available. */
1940 cheapest_startup =
1942 pathkeys,
1943 NULL,
1945 false);
1946 cheapest_total =
1948 pathkeys,
1949 NULL,
1950 TOTAL_COST,
1951 false);
1952
1953 /*
1954 * If we can't find any paths with the right order just use the
1955 * cheapest-total path; we'll have to sort it later.
1956 */
1957 if (cheapest_startup == NULL || cheapest_total == NULL)
1958 {
1959 cheapest_startup = cheapest_total =
1960 childrel->cheapest_total_path;
1961 /* Assert we do have an unparameterized path for this child */
1962 Assert(cheapest_total->param_info == NULL);
1963 }
1964
1965 /*
1966 * When building a fractional path, determine a cheapest
1967 * fractional path for each child relation too. Looking at startup
1968 * and total costs is not enough, because the cheapest fractional
1969 * path may be dominated by two separate paths (one for startup,
1970 * one for total).
1971 *
1972 * When needed (building fractional path), determine the cheapest
1973 * fractional path too.
1974 */
1975 if (root->tuple_fraction > 0)
1976 {
1977 double path_fraction = root->tuple_fraction;
1978
1979 /*
1980 * Merge Append considers only live children relations. Dummy
1981 * relations must be filtered out before.
1982 */
1983 Assert(childrel->rows > 0);
1984
1985 /* Convert absolute limit to a path fraction */
1986 if (path_fraction >= 1.0)
1987 path_fraction /= childrel->rows;
1988
1989 cheapest_fractional =
1991 pathkeys,
1992 NULL,
1993 path_fraction);
1994
1995 /*
1996 * If we found no path with matching pathkeys, use the
1997 * cheapest total path instead.
1998 *
1999 * XXX We might consider partially sorted paths too (with an
2000 * incremental sort on top). But we'd have to build all the
2001 * incremental paths, do the costing etc.
2002 */
2003 if (!cheapest_fractional)
2004 cheapest_fractional = cheapest_total;
2005 }
2006
2007 /*
2008 * Notice whether we actually have different paths for the
2009 * "cheapest" and "total" cases; frequently there will be no point
2010 * in two create_merge_append_path() calls.
2011 */
2012 if (cheapest_startup != cheapest_total)
2013 startup_neq_total = true;
2014
2015 /*
2016 * Collect the appropriate child paths. The required logic varies
2017 * for the Append and MergeAppend cases.
2018 */
2019 if (match_partition_order)
2020 {
2021 /*
2022 * We're going to make a plain Append path. We don't need
2023 * most of what accumulate_append_subpath would do, but we do
2024 * want to cut out child Appends or MergeAppends if they have
2025 * just a single subpath (and hence aren't doing anything
2026 * useful).
2027 */
2028 cheapest_startup = get_singleton_append_subpath(cheapest_startup);
2029 cheapest_total = get_singleton_append_subpath(cheapest_total);
2030
2031 startup_subpaths = lappend(startup_subpaths, cheapest_startup);
2032 total_subpaths = lappend(total_subpaths, cheapest_total);
2033
2034 if (cheapest_fractional)
2035 {
2036 cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
2037 fractional_subpaths = lappend(fractional_subpaths, cheapest_fractional);
2038 }
2039 }
2040 else
2041 {
2042 /*
2043 * Otherwise, rely on accumulate_append_subpath to collect the
2044 * child paths for the MergeAppend.
2045 */
2046 accumulate_append_subpath(cheapest_startup,
2047 &startup_subpaths, NULL);
2048 accumulate_append_subpath(cheapest_total,
2049 &total_subpaths, NULL);
2050
2051 if (cheapest_fractional)
2052 accumulate_append_subpath(cheapest_fractional,
2053 &fractional_subpaths, NULL);
2054 }
2055 }
2056
2057 /* ... and build the Append or MergeAppend paths */
2058 if (match_partition_order)
2059 {
2060 /* We only need Append */
2062 rel,
2063 startup_subpaths,
2064 NIL,
2065 pathkeys,
2066 NULL,
2067 0,
2068 false,
2069 -1));
2070 if (startup_neq_total)
2072 rel,
2073 total_subpaths,
2074 NIL,
2075 pathkeys,
2076 NULL,
2077 0,
2078 false,
2079 -1));
2080
2081 if (fractional_subpaths)
2083 rel,
2084 fractional_subpaths,
2085 NIL,
2086 pathkeys,
2087 NULL,
2088 0,
2089 false,
2090 -1));
2091 }
2092 else
2093 {
2094 /* We need MergeAppend */
2096 rel,
2097 startup_subpaths,
2098 pathkeys,
2099 NULL));
2100 if (startup_neq_total)
2102 rel,
2103 total_subpaths,
2104 pathkeys,
2105 NULL));
2106
2107 if (fractional_subpaths)
2109 rel,
2110 fractional_subpaths,
2111 pathkeys,
2112 NULL));
2113 }
2114 }
2115}
static Path * get_singleton_append_subpath(Path *path)
Definition: allpaths.c:2258
int i
Definition: isn.c:77
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2853
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:666
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:620
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:919
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:343
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1470
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:898
@ TOTAL_COST
Definition: pathnodes.h:38
@ STARTUP_COST
Definition: pathnodes.h:38
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
@ BackwardScanDirection
Definition: sdir.h:26
@ ForwardScanDirection
Definition: sdir.h:28
Bitmapset * live_parts
Definition: pathnodes.h:1111
Cardinality rows
Definition: pathnodes.h:936

References accumulate_append_subpath(), add_path(), Assert(), BackwardScanDirection, build_partition_pathkeys(), RelOptInfo::cheapest_total_path, create_append_path(), create_merge_append_path(), ForwardScanDirection, get_cheapest_fractional_path_for_pathkeys(), get_cheapest_path_for_pathkeys(), get_singleton_append_subpath(), i, IS_SIMPLE_REL, lappend(), lfirst, list_length(), list_nth_node, RelOptInfo::live_parts, NIL, partitions_are_ordered(), pathkeys_contained_in(), RelOptInfo::pathlist, root, RelOptInfo::rows, STARTUP_COST, and TOTAL_COST.

Referenced by add_paths_to_append_rel().

◆ generate_partitionwise_join_paths()

void generate_partitionwise_join_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4777 of file allpaths.c.

4778{
4779 List *live_children = NIL;
4780 int cnt_parts;
4781 int num_parts;
4782 RelOptInfo **part_rels;
4783
4784 /* Handle only join relations here. */
4785 if (!IS_JOIN_REL(rel))
4786 return;
4787
4788 /* We've nothing to do if the relation is not partitioned. */
4789 if (!IS_PARTITIONED_REL(rel))
4790 return;
4791
4792 /* The relation should have consider_partitionwise_join set. */
4794
4795 /* Guard against stack overflow due to overly deep partition hierarchy. */
4797
4798 num_parts = rel->nparts;
4799 part_rels = rel->part_rels;
4800
4801 /* Collect non-dummy child-joins. */
4802 for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4803 {
4804 RelOptInfo *child_rel = part_rels[cnt_parts];
4805
4806 /* If it's been pruned entirely, it's certainly dummy. */
4807 if (child_rel == NULL)
4808 continue;
4809
4810 /* Make partitionwise join paths for this partitioned child-join. */
4812
4813 /* If we failed to make any path for this child, we must give up. */
4814 if (child_rel->pathlist == NIL)
4815 {
4816 /*
4817 * Mark the parent joinrel as unpartitioned so that later
4818 * functions treat it correctly.
4819 */
4820 rel->nparts = 0;
4821 return;
4822 }
4823
4824 /* Else, identify the cheapest path for it. */
4825 set_cheapest(child_rel);
4826
4827 /* Dummy children need not be scanned, so ignore those. */
4828 if (IS_DUMMY_REL(child_rel))
4829 continue;
4830
4831 /*
4832 * Except for the topmost scan/join rel, consider generating partial
4833 * aggregation paths for the grouped relation on top of the paths of
4834 * this partitioned child-join. After that, we're done creating paths
4835 * for the grouped relation, so run set_cheapest().
4836 */
4837 if (child_rel->grouped_rel != NULL &&
4838 !bms_equal(IS_OTHER_REL(rel) ?
4839 rel->top_parent_relids : rel->relids,
4840 root->all_query_rels))
4841 {
4842 RelOptInfo *grouped_rel = child_rel->grouped_rel;
4843
4844 Assert(IS_GROUPED_REL(grouped_rel));
4845
4846 generate_grouped_paths(root, grouped_rel, child_rel);
4847 set_cheapest(grouped_rel);
4848 }
4849
4850#ifdef OPTIMIZER_DEBUG
4851 pprint(child_rel);
4852#endif
4853
4854 live_children = lappend(live_children, child_rel);
4855 }
4856
4857 /* If all child-joins are dummy, parent join is also dummy. */
4858 if (!live_children)
4859 {
4860 mark_dummy_rel(rel);
4861 return;
4862 }
4863
4864 /* Build additional paths for this rel from child-join paths. */
4865 add_paths_to_append_rel(root, rel, live_children);
4866 list_free(live_children);
4867}
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:4777
void generate_grouped_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *rel)
Definition: allpaths.c:3429
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1404
void pprint(const void *obj)
Definition: print.c:54
void list_free(List *list)
Definition: list.c:1546
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:269
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:903
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1138
#define IS_GROUPED_REL(rel)
Definition: pathnodes.h:1164
void check_stack_depth(void)
Definition: stack_depth.c:95
Relids top_parent_relids
Definition: pathnodes.h:1081
bool consider_partitionwise_join
Definition: pathnodes.h:1063

References add_paths_to_append_rel(), Assert(), bms_equal(), check_stack_depth(), RelOptInfo::consider_partitionwise_join, generate_grouped_paths(), generate_partitionwise_join_paths(), RelOptInfo::grouped_rel, IS_DUMMY_REL, IS_GROUPED_REL, IS_JOIN_REL, IS_OTHER_REL, IS_PARTITIONED_REL, lappend(), list_free(), mark_dummy_rel(), NIL, RelOptInfo::nparts, RelOptInfo::pathlist, pprint(), RelOptInfo::relids, root, set_cheapest(), and RelOptInfo::top_parent_relids.

Referenced by generate_partitionwise_join_paths(), merge_clump(), and standard_join_search().

◆ generate_useful_gather_paths()

void generate_useful_gather_paths ( PlannerInfo root,
RelOptInfo rel,
bool  override_rows 
)

Definition at line 3312 of file allpaths.c.

3313{
3314 ListCell *lc;
3315 double rows;
3316 double *rowsp = NULL;
3317 List *useful_pathkeys_list = NIL;
3318 Path *cheapest_partial_path = NULL;
3319
3320 /* If there are no partial paths, there's nothing to do here. */
3321 if (rel->partial_pathlist == NIL)
3322 return;
3323
3324 /* Should we override the rel's rowcount estimate? */
3325 if (override_rows)
3326 rowsp = &rows;
3327
3328 /* generate the regular gather (merge) paths */
3329 generate_gather_paths(root, rel, override_rows);
3330
3331 /* consider incremental sort for interesting orderings */
3332 useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3333
3334 /* used for explicit (full) sort paths */
3335 cheapest_partial_path = linitial(rel->partial_pathlist);
3336
3337 /*
3338 * Consider sorted paths for each interesting ordering. We generate both
3339 * incremental and full sort.
3340 */
3341 foreach(lc, useful_pathkeys_list)
3342 {
3343 List *useful_pathkeys = lfirst(lc);
3344 ListCell *lc2;
3345 bool is_sorted;
3346 int presorted_keys;
3347
3348 foreach(lc2, rel->partial_pathlist)
3349 {
3350 Path *subpath = (Path *) lfirst(lc2);
3351 GatherMergePath *path;
3352
3353 is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3354 subpath->pathkeys,
3355 &presorted_keys);
3356
3357 /*
3358 * We don't need to consider the case where a subpath is already
3359 * fully sorted because generate_gather_paths already creates a
3360 * gather merge path for every subpath that has pathkeys present.
3361 *
3362 * But since the subpath is already sorted, we know we don't need
3363 * to consider adding a sort (full or incremental) on top of it,
3364 * so we can continue here.
3365 */
3366 if (is_sorted)
3367 continue;
3368
3369 /*
3370 * Try at least sorting the cheapest path and also try
3371 * incrementally sorting any path which is partially sorted
3372 * already (no need to deal with paths which have presorted keys
3373 * when incremental sort is disabled unless it's the cheapest
3374 * input path).
3375 */
3376 if (subpath != cheapest_partial_path &&
3377 (presorted_keys == 0 || !enable_incremental_sort))
3378 continue;
3379
3380 /*
3381 * Consider regular sort for any path that's not presorted or if
3382 * incremental sort is disabled. We've no need to consider both
3383 * sort and incremental sort on the same path. We assume that
3384 * incremental sort is always faster when there are presorted
3385 * keys.
3386 *
3387 * This is not redundant with the gather paths created in
3388 * generate_gather_paths, because that doesn't generate ordered
3389 * output. Here we add an explicit sort to match the useful
3390 * ordering.
3391 */
3392 if (presorted_keys == 0 || !enable_incremental_sort)
3393 {
3395 rel,
3396 subpath,
3397 useful_pathkeys,
3398 -1.0);
3399 }
3400 else
3402 rel,
3403 subpath,
3404 useful_pathkeys,
3405 presorted_keys,
3406 -1);
3408 path = create_gather_merge_path(root, rel,
3409 subpath,
3410 rel->reltarget,
3411 subpath->pathkeys,
3412 NULL,
3413 rowsp);
3414
3415 add_path(rel, &path->path);
3416 }
3417 }
3418}
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:3244
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3175

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, generate_gather_paths(), get_useful_pathkeys_for_relation(), lfirst, linitial, NIL, RelOptInfo::partial_pathlist, GatherMergePath::path, pathkeys_count_contained_in(), RelOptInfo::reltarget, root, and subpath().

Referenced by apply_scanjoin_target_to_paths(), create_partial_distinct_paths(), create_partial_unique_paths(), gather_grouping_paths(), merge_clump(), set_rel_pathlist(), and standard_join_search().

◆ get_cheapest_parameterized_child_path()

static Path * get_cheapest_parameterized_child_path ( PlannerInfo root,
RelOptInfo rel,
Relids  required_outer 
)
static

Definition at line 2125 of file allpaths.c.

2127{
2128 Path *cheapest;
2129 ListCell *lc;
2130
2131 /*
2132 * Look up the cheapest existing path with no more than the needed
2133 * parameterization. If it has exactly the needed parameterization, we're
2134 * done.
2135 */
2137 NIL,
2138 required_outer,
2139 TOTAL_COST,
2140 false);
2141 Assert(cheapest != NULL);
2142 if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
2143 return cheapest;
2144
2145 /*
2146 * Otherwise, we can "reparameterize" an existing path to match the given
2147 * parameterization, which effectively means pushing down additional
2148 * joinquals to be checked within the path's scan. However, some existing
2149 * paths might check the available joinquals already while others don't;
2150 * therefore, it's not clear which existing path will be cheapest after
2151 * reparameterization. We have to go through them all and find out.
2152 */
2153 cheapest = NULL;
2154 foreach(lc, rel->pathlist)
2155 {
2156 Path *path = (Path *) lfirst(lc);
2157
2158 /* Can't use it if it needs more than requested parameterization */
2159 if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
2160 continue;
2161
2162 /*
2163 * Reparameterization can only increase the path's cost, so if it's
2164 * already more expensive than the current cheapest, forget it.
2165 */
2166 if (cheapest != NULL &&
2167 compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2168 continue;
2169
2170 /* Reparameterize if needed, then recheck cost */
2171 if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
2172 {
2173 path = reparameterize_path(root, path, required_outer, 1.0);
2174 if (path == NULL)
2175 continue; /* failed to reparameterize this one */
2176 Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
2177
2178 if (cheapest != NULL &&
2179 compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2180 continue;
2181 }
2182
2183 /* We have a new best path */
2184 cheapest = path;
2185 }
2186
2187 /* Return the best path, or NULL if we found no suitable candidate */
2188 return cheapest;
2189}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:69
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3855

References Assert(), bms_equal(), bms_is_subset(), compare_path_costs(), get_cheapest_path_for_pathkeys(), lfirst, NIL, PATH_REQ_OUTER, RelOptInfo::pathlist, reparameterize_path(), root, and TOTAL_COST.

Referenced by add_paths_to_append_rel().

◆ get_singleton_append_subpath()

static Path * get_singleton_append_subpath ( Path path)
static

Definition at line 2258 of file allpaths.c.

2259{
2260 Assert(!path->parallel_aware);
2261
2262 if (IsA(path, AppendPath))
2263 {
2264 AppendPath *apath = (AppendPath *) path;
2265
2266 if (list_length(apath->subpaths) == 1)
2267 return (Path *) linitial(apath->subpaths);
2268 }
2269 else if (IsA(path, MergeAppendPath))
2270 {
2271 MergeAppendPath *mpath = (MergeAppendPath *) path;
2272
2273 if (list_length(mpath->subpaths) == 1)
2274 return (Path *) linitial(mpath->subpaths);
2275 }
2276
2277 return path;
2278}

References Assert(), IsA, linitial, list_length(), Path::parallel_aware, AppendPath::subpaths, and MergeAppendPath::subpaths.

Referenced by generate_orderedappend_paths().

◆ get_useful_pathkeys_for_relation()

static List * get_useful_pathkeys_for_relation ( PlannerInfo root,
RelOptInfo rel,
bool  require_parallel_safe 
)
static

Definition at line 3244 of file allpaths.c.

3246{
3247 List *useful_pathkeys_list = NIL;
3248
3249 /*
3250 * Considering query_pathkeys is always worth it, because it might allow
3251 * us to avoid a total sort when we have a partially presorted path
3252 * available or to push the total sort into the parallel portion of the
3253 * query.
3254 */
3255 if (root->query_pathkeys)
3256 {
3257 ListCell *lc;
3258 int npathkeys = 0; /* useful pathkeys */
3259
3260 foreach(lc, root->query_pathkeys)
3261 {
3262 PathKey *pathkey = (PathKey *) lfirst(lc);
3263 EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3264
3265 /*
3266 * We can only build a sort for pathkeys that contain a
3267 * safe-to-compute-early EC member computable from the current
3268 * relation's reltarget, so ignore the remainder of the list as
3269 * soon as we find a pathkey without such a member.
3270 *
3271 * It's still worthwhile to return any prefix of the pathkeys list
3272 * that meets this requirement, as we may be able to do an
3273 * incremental sort.
3274 *
3275 * If requested, ensure the sort expression is parallel-safe too.
3276 */
3277 if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
3278 require_parallel_safe))
3279 break;
3280
3281 npathkeys++;
3282 }
3283
3284 /*
3285 * The whole query_pathkeys list matches, so append it directly, to
3286 * allow comparing pathkeys easily by comparing list pointer. If we
3287 * have to truncate the pathkeys, we gotta do a copy though.
3288 */
3289 if (npathkeys == list_length(root->query_pathkeys))
3290 useful_pathkeys_list = lappend(useful_pathkeys_list,
3291 root->query_pathkeys);
3292 else if (npathkeys > 0)
3293 useful_pathkeys_list = lappend(useful_pathkeys_list,
3294 list_copy_head(root->query_pathkeys,
3295 npathkeys));
3296 }
3297
3298 return useful_pathkeys_list;
3299}
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
Definition: equivclass.c:1077

References lappend(), lfirst, list_copy_head(), list_length(), NIL, relation_can_be_sorted_early(), and root.

Referenced by generate_useful_gather_paths().

◆ make_one_rel()

RelOptInfo * make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 177 of file allpaths.c.

178{
179 RelOptInfo *rel;
180 Index rti;
181 double total_pages;
182
183 /* Mark base rels as to whether we care about fast-start plans */
185
186 /*
187 * Compute size estimates and consider_parallel flags for each base rel.
188 */
190
191 /*
192 * Build grouped relations for simple rels (i.e., base or "other" member
193 * relations) where possible.
194 */
196
197 /*
198 * We should now have size estimates for every actual table involved in
199 * the query, and we also know which if any have been deleted from the
200 * query by join removal, pruned by partition pruning, or eliminated by
201 * constraint exclusion. So we can now compute total_table_pages.
202 *
203 * Note that appendrels are not double-counted here, even though we don't
204 * bother to distinguish RelOptInfos for appendrel parents, because the
205 * parents will have pages = 0.
206 *
207 * XXX if a table is self-joined, we will count it once per appearance,
208 * which perhaps is the wrong thing ... but that's not completely clear,
209 * and detecting self-joins here is difficult, so ignore it for now.
210 */
211 total_pages = 0;
212 for (rti = 1; rti < root->simple_rel_array_size; rti++)
213 {
214 RelOptInfo *brel = root->simple_rel_array[rti];
215
216 /* there may be empty slots corresponding to non-baserel RTEs */
217 if (brel == NULL)
218 continue;
219
220 Assert(brel->relid == rti); /* sanity check on array */
221
222 if (IS_DUMMY_REL(brel))
223 continue;
224
225 if (IS_SIMPLE_REL(brel))
226 total_pages += (double) brel->pages;
227 }
228 root->total_table_pages = total_pages;
229
230 /*
231 * Generate access paths for each base rel.
232 */
234
235 /*
236 * Generate access paths for the entire join tree.
237 */
238 rel = make_rel_from_joinlist(root, joinlist);
239
240 /*
241 * The result should join all and only the query's base + outer-join rels.
242 */
243 Assert(bms_equal(rel->relids, root->all_query_rels));
244
245 return rel;
246}
static void set_base_rel_sizes(PlannerInfo *root)
Definition: allpaths.c:302
static void set_base_rel_consider_startup(PlannerInfo *root)
Definition: allpaths.c:259
static void set_base_rel_pathlists(PlannerInfo *root)
Definition: allpaths.c:378
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:3767
static void setup_simple_grouped_rels(PlannerInfo *root)
Definition: allpaths.c:344
unsigned int Index
Definition: c.h:619
Index relid
Definition: pathnodes.h:976

References Assert(), bms_equal(), IS_DUMMY_REL, IS_SIMPLE_REL, make_rel_from_joinlist(), RelOptInfo::pages, RelOptInfo::relid, RelOptInfo::relids, root, set_base_rel_consider_startup(), set_base_rel_pathlists(), set_base_rel_sizes(), and setup_simple_grouped_rels().

Referenced by query_planner().

◆ make_rel_from_joinlist()

static RelOptInfo * make_rel_from_joinlist ( PlannerInfo root,
List joinlist 
)
static

Definition at line 3767 of file allpaths.c.

3768{
3769 int levels_needed;
3770 List *initial_rels;
3771 ListCell *jl;
3772
3773 /*
3774 * Count the number of child joinlist nodes. This is the depth of the
3775 * dynamic-programming algorithm we must employ to consider all ways of
3776 * joining the child nodes.
3777 */
3778 levels_needed = list_length(joinlist);
3779
3780 if (levels_needed <= 0)
3781 return NULL; /* nothing to do? */
3782
3783 /*
3784 * Construct a list of rels corresponding to the child joinlist nodes.
3785 * This may contain both base rels and rels constructed according to
3786 * sub-joinlists.
3787 */
3788 initial_rels = NIL;
3789 foreach(jl, joinlist)
3790 {
3791 Node *jlnode = (Node *) lfirst(jl);
3792 RelOptInfo *thisrel;
3793
3794 if (IsA(jlnode, RangeTblRef))
3795 {
3796 int varno = ((RangeTblRef *) jlnode)->rtindex;
3797
3798 thisrel = find_base_rel(root, varno);
3799 }
3800 else if (IsA(jlnode, List))
3801 {
3802 /* Recurse to handle subproblem */
3803 thisrel = make_rel_from_joinlist(root, (List *) jlnode);
3804 }
3805 else
3806 {
3807 elog(ERROR, "unrecognized joinlist node type: %d",
3808 (int) nodeTag(jlnode));
3809 thisrel = NULL; /* keep compiler quiet */
3810 }
3811
3812 initial_rels = lappend(initial_rels, thisrel);
3813 }
3814
3815 if (levels_needed == 1)
3816 {
3817 /*
3818 * Single joinlist node, so we're done.
3819 */
3820 return (RelOptInfo *) linitial(initial_rels);
3821 }
3822 else
3823 {
3824 /*
3825 * Consider the different orders in which we could join the rels,
3826 * using a plugin, GEQO, or the regular join search code.
3827 *
3828 * We put the initial_rels list into a PlannerInfo field because
3829 * has_legal_joinclause() needs to look at it (ugly :-().
3830 */
3831 root->initial_rels = initial_rels;
3832
3833 if (join_search_hook)
3834 return (*join_search_hook) (root, levels_needed, initial_rels);
3835 else if (enable_geqo && levels_needed >= geqo_threshold)
3836 return geqo(root, levels_needed, initial_rels);
3837 else
3838 return standard_join_search(root, levels_needed, initial_rels);
3839 }
3840}
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3872
int geqo_threshold
Definition: allpaths.c:83
join_search_hook_type join_search_hook
Definition: allpaths.c:92
bool enable_geqo
Definition: allpaths.c:81
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:74
#define nodeTag(nodeptr)
Definition: nodes.h:139
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:529

References elog, enable_geqo, ERROR, find_base_rel(), geqo(), geqo_threshold, IsA, join_search_hook, lappend(), lfirst, linitial, list_length(), make_rel_from_joinlist(), NIL, nodeTag, root, and standard_join_search().

Referenced by make_one_rel(), and make_rel_from_joinlist().

◆ qual_is_pushdown_safe()

static pushdown_safe_type qual_is_pushdown_safe ( Query subquery,
Index  rti,
RestrictInfo rinfo,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4340 of file allpaths.c.

4342{
4344 Node *qual = (Node *) rinfo->clause;
4345 List *vars;
4346 ListCell *vl;
4347
4348 /* Refuse subselects (point 1) */
4349 if (contain_subplans(qual))
4350 return PUSHDOWN_UNSAFE;
4351
4352 /* Refuse volatile quals if we found they'd be unsafe (point 2) */
4353 if (safetyInfo->unsafeVolatile &&
4355 return PUSHDOWN_UNSAFE;
4356
4357 /* Refuse leaky quals if told to (point 3) */
4358 if (safetyInfo->unsafeLeaky &&
4359 contain_leaked_vars(qual))
4360 return PUSHDOWN_UNSAFE;
4361
4362 /*
4363 * Examine all Vars used in clause. Since it's a restriction clause, all
4364 * such Vars must refer to subselect output columns ... unless this is
4365 * part of a LATERAL subquery, in which case there could be lateral
4366 * references.
4367 *
4368 * By omitting the relevant flags, this also gives us a cheap sanity check
4369 * that no aggregates or window functions appear in the qual. Those would
4370 * be unsafe to push down, but at least for the moment we could never see
4371 * any in a qual anyhow.
4372 */
4374 foreach(vl, vars)
4375 {
4376 Var *var = (Var *) lfirst(vl);
4377
4378 /*
4379 * XXX Punt if we find any PlaceHolderVars in the restriction clause.
4380 * It's not clear whether a PHV could safely be pushed down, and even
4381 * less clear whether such a situation could arise in any cases of
4382 * practical interest anyway. So for the moment, just refuse to push
4383 * down.
4384 */
4385 if (!IsA(var, Var))
4386 {
4387 safe = PUSHDOWN_UNSAFE;
4388 break;
4389 }
4390
4391 /*
4392 * Punt if we find any lateral references. It would be safe to push
4393 * these down, but we'd have to convert them into outer references,
4394 * which subquery_push_qual lacks the infrastructure to do. The case
4395 * arises so seldom that it doesn't seem worth working hard on.
4396 */
4397 if (var->varno != rti)
4398 {
4399 safe = PUSHDOWN_UNSAFE;
4400 break;
4401 }
4402
4403 /* Subqueries have no system columns */
4404 Assert(var->varattno >= 0);
4405
4406 /* Check point 4 */
4407 if (var->varattno == 0)
4408 {
4409 safe = PUSHDOWN_UNSAFE;
4410 break;
4411 }
4412
4413 /* Check point 5 */
4414 if (safetyInfo->unsafeFlags[var->varattno] != 0)
4415 {
4416 if (safetyInfo->unsafeFlags[var->varattno] &
4419 {
4420 safe = PUSHDOWN_UNSAFE;
4421 break;
4422 }
4423 else
4424 {
4425 /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
4427 /* don't break, we might find another Var that's unsafe */
4428 }
4429 }
4430 }
4431
4432 list_free(vars);
4433
4434 return safe;
4435}
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1269
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
Expr * clause
Definition: pathnodes.h:2795
int varno
Definition: primnodes.h:269
Definition: regcomp.c:282
List * pull_var_clause(Node *node, int flags)
Definition: var.c:653

References Assert(), RestrictInfo::clause, contain_leaked_vars(), contain_subplans(), contain_volatile_functions(), if(), IsA, lfirst, list_free(), pull_var_clause(), PUSHDOWN_SAFE, PUSHDOWN_UNSAFE, PUSHDOWN_WINDOWCLAUSE_RUNCOND, PVC_INCLUDE_PLACEHOLDERS, UNSAFE_HAS_SET_FUNC, UNSAFE_HAS_VOLATILE_FUNC, UNSAFE_NOTIN_DISTINCTON_CLAUSE, UNSAFE_TYPE_MISMATCH, pushdown_safety_info::unsafeFlags, pushdown_safety_info::unsafeLeaky, pushdown_safety_info::unsafeVolatile, Var::varattno, and Var::varno.

Referenced by set_subquery_pathlist().

◆ recurse_push_qual()

static void recurse_push_qual ( Node setOp,
Query topquery,
RangeTblEntry rte,
Index  rti,
Node qual 
)
static

Definition at line 4489 of file allpaths.c.

4491{
4492 if (IsA(setOp, RangeTblRef))
4493 {
4494 RangeTblRef *rtr = (RangeTblRef *) setOp;
4495 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4496 Query *subquery = subrte->subquery;
4497
4498 Assert(subquery != NULL);
4499 subquery_push_qual(subquery, rte, rti, qual);
4500 }
4501 else if (IsA(setOp, SetOperationStmt))
4502 {
4503 SetOperationStmt *op = (SetOperationStmt *) setOp;
4504
4505 recurse_push_qual(op->larg, topquery, rte, rti, qual);
4506 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4507 }
4508 else
4509 {
4510 elog(ERROR, "unrecognized node type: %d",
4511 (int) nodeTag(setOp));
4512 }
4513}
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:4441
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:4489
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * rtable
Definition: parsenodes.h:175
Query * subquery
Definition: parsenodes.h:1135

References Assert(), elog, ERROR, IsA, SetOperationStmt::larg, nodeTag, SetOperationStmt::rarg, recurse_push_qual(), rt_fetch, Query::rtable, RangeTblRef::rtindex, RangeTblEntry::subquery, and subquery_push_qual().

Referenced by recurse_push_qual(), and subquery_push_qual().

◆ recurse_pushdown_safe()

static bool recurse_pushdown_safe ( Node setOp,
Query topquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4123 of file allpaths.c.

4125{
4126 if (IsA(setOp, RangeTblRef))
4127 {
4128 RangeTblRef *rtr = (RangeTblRef *) setOp;
4129 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
4130 Query *subquery = rte->subquery;
4131
4132 Assert(subquery != NULL);
4133 return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
4134 }
4135 else if (IsA(setOp, SetOperationStmt))
4136 {
4137 SetOperationStmt *op = (SetOperationStmt *) setOp;
4138
4139 /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
4140 if (op->op == SETOP_EXCEPT)
4141 return false;
4142 /* Else recurse */
4143 if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
4144 return false;
4145 if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
4146 return false;
4147 }
4148 else
4149 {
4150 elog(ERROR, "unrecognized node type: %d",
4151 (int) nodeTag(setOp));
4152 }
4153 return true;
4154}
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:4067
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:4123
@ SETOP_EXCEPT
Definition: parsenodes.h:2179
SetOperation op
Definition: parsenodes.h:2255

References Assert(), elog, ERROR, IsA, SetOperationStmt::larg, nodeTag, SetOperationStmt::op, SetOperationStmt::rarg, recurse_pushdown_safe(), rt_fetch, Query::rtable, RangeTblRef::rtindex, SETOP_EXCEPT, RangeTblEntry::subquery, and subquery_is_pushdown_safe().

Referenced by recurse_pushdown_safe(), and subquery_is_pushdown_safe().

◆ remove_unused_subquery_outputs()

static void remove_unused_subquery_outputs ( Query subquery,
RelOptInfo rel,
Bitmapset extra_used_attrs 
)
static

Definition at line 4541 of file allpaths.c.

4543{
4544 Bitmapset *attrs_used;
4545 ListCell *lc;
4546
4547 /*
4548 * Just point directly to extra_used_attrs. No need to bms_copy as none of
4549 * the current callers use the Bitmapset after calling this function.
4550 */
4551 attrs_used = extra_used_attrs;
4552
4553 /*
4554 * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4555 * could update all the child SELECTs' tlists, but it seems not worth the
4556 * trouble presently.
4557 */
4558 if (subquery->setOperations)
4559 return;
4560
4561 /*
4562 * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4563 * time: all its output columns must be used in the distinctClause.
4564 */
4565 if (subquery->distinctClause && !subquery->hasDistinctOn)
4566 return;
4567
4568 /*
4569 * Collect a bitmap of all the output column numbers used by the upper
4570 * query.
4571 *
4572 * Add all the attributes needed for joins or final output. Note: we must
4573 * look at rel's targetlist, not the attr_needed data, because attr_needed
4574 * isn't computed for inheritance child rels, cf set_append_rel_size().
4575 * (XXX might be worth changing that sometime.)
4576 */
4577 pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4578
4579 /* Add all the attributes used by un-pushed-down restriction clauses. */
4580 foreach(lc, rel->baserestrictinfo)
4581 {
4582 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4583
4584 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4585 }
4586
4587 /*
4588 * If there's a whole-row reference to the subquery, we can't remove
4589 * anything.
4590 */
4592 return;
4593
4594 /*
4595 * Run through the tlist and zap entries we don't need. It's okay to
4596 * modify the tlist items in-place because set_subquery_pathlist made a
4597 * copy of the subquery.
4598 */
4599 foreach(lc, subquery->targetList)
4600 {
4601 TargetEntry *tle = (TargetEntry *) lfirst(lc);
4602 Node *texpr = (Node *) tle->expr;
4603
4604 /*
4605 * If it has a sortgroupref number, it's used in some sort/group
4606 * clause so we'd better not remove it. Also, don't remove any
4607 * resjunk columns, since their reason for being has nothing to do
4608 * with anybody reading the subquery's output. (It's likely that
4609 * resjunk columns in a sub-SELECT would always have ressortgroupref
4610 * set, but even if they don't, it seems imprudent to remove them.)
4611 */
4612 if (tle->ressortgroupref || tle->resjunk)
4613 continue;
4614
4615 /*
4616 * If it's used by the upper query, we can't remove it.
4617 */
4619 attrs_used))
4620 continue;
4621
4622 /*
4623 * If it contains a set-returning function, we can't remove it since
4624 * that could change the number of rows returned by the subquery.
4625 */
4626 if (subquery->hasTargetSRFs &&
4628 continue;
4629
4630 /*
4631 * If it contains volatile functions, we daren't remove it for fear
4632 * that the user is expecting their side-effects to happen.
4633 */
4634 if (contain_volatile_functions(texpr))
4635 continue;
4636
4637 /*
4638 * OK, we don't need it. Replace the expression with a NULL constant.
4639 * Preserve the exposed type of the expression, in case something
4640 * looks at the rowtype of the subquery's result.
4641 */
4642 tle->expr = (Expr *) makeNullConst(exprType(texpr),
4643 exprTypmod(texpr),
4644 exprCollation(texpr));
4645 }
4646}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:388
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
List * exprs
Definition: pathnodes.h:1782
Node * setOperations
Definition: parsenodes.h:236
List * baserestrictinfo
Definition: pathnodes.h:1049
Index ressortgroupref
Definition: primnodes.h:2245
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:296

References RelOptInfo::baserestrictinfo, bms_is_member(), RestrictInfo::clause, contain_volatile_functions(), Query::distinctClause, TargetEntry::expr, exprCollation(), expression_returns_set(), PathTarget::exprs, exprType(), exprTypmod(), FirstLowInvalidHeapAttributeNumber, if(), lfirst, makeNullConst(), pull_varattnos(), RelOptInfo::relid, RelOptInfo::reltarget, TargetEntry::resno, TargetEntry::ressortgroupref, Query::setOperations, and Query::targetList.

Referenced by set_subquery_pathlist().

◆ set_append_rel_pathlist()

static void set_append_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 1305 of file allpaths.c.

1307{
1308 int parentRTindex = rti;
1309 List *live_childrels = NIL;
1310 ListCell *l;
1311
1312 /*
1313 * Generate access paths for each member relation, and remember the
1314 * non-dummy children.
1315 */
1316 foreach(l, root->append_rel_list)
1317 {
1318 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1319 int childRTindex;
1320 RangeTblEntry *childRTE;
1321 RelOptInfo *childrel;
1322
1323 /* append_rel_list contains all append rels; ignore others */
1324 if (appinfo->parent_relid != parentRTindex)
1325 continue;
1326
1327 /* Re-locate the child RTE and RelOptInfo */
1328 childRTindex = appinfo->child_relid;
1329 childRTE = root->simple_rte_array[childRTindex];
1330 childrel = root->simple_rel_array[childRTindex];
1331
1332 /*
1333 * If set_append_rel_size() decided the parent appendrel was
1334 * parallel-unsafe at some point after visiting this child rel, we
1335 * need to propagate the unsafety marking down to the child, so that
1336 * we don't generate useless partial paths for it.
1337 */
1338 if (!rel->consider_parallel)
1339 childrel->consider_parallel = false;
1340
1341 /*
1342 * Compute the child's access paths.
1343 */
1344 set_rel_pathlist(root, childrel, childRTindex, childRTE);
1345
1346 /*
1347 * If child is dummy, ignore it.
1348 */
1349 if (IS_DUMMY_REL(childrel))
1350 continue;
1351
1352 /*
1353 * Child is live, so add it to the live_childrels list for use below.
1354 */
1355 live_childrels = lappend(live_childrels, childrel);
1356 }
1357
1358 /* Add paths to the append relation. */
1359 add_paths_to_append_rel(root, rel, live_childrels);
1360}
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:514
Index child_relid
Definition: pathnodes.h:3196
Index parent_relid
Definition: pathnodes.h:3195

References add_paths_to_append_rel(), AppendRelInfo::child_relid, RelOptInfo::consider_parallel, IS_DUMMY_REL, lappend(), lfirst, NIL, AppendRelInfo::parent_relid, root, and set_rel_pathlist().

Referenced by set_rel_pathlist().

◆ set_append_rel_size()

static void set_append_rel_size ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 1010 of file allpaths.c.

1012{
1013 int parentRTindex = rti;
1014 bool has_live_children;
1015 double parent_tuples;
1016 double parent_rows;
1017 double parent_size;
1018 double *parent_attrsizes;
1019 int nattrs;
1020 ListCell *l;
1021
1022 /* Guard against stack overflow due to overly deep inheritance tree. */
1024
1025 Assert(IS_SIMPLE_REL(rel));
1026
1027 /*
1028 * If this is a partitioned baserel, set the consider_partitionwise_join
1029 * flag; currently, we only consider partitionwise joins with the baserel
1030 * if its targetlist doesn't contain a whole-row Var.
1031 */
1033 rel->reloptkind == RELOPT_BASEREL &&
1034 rte->relkind == RELKIND_PARTITIONED_TABLE &&
1035 bms_is_empty(rel->attr_needed[InvalidAttrNumber - rel->min_attr]))
1036 rel->consider_partitionwise_join = true;
1037
1038 /*
1039 * Initialize to compute size estimates for whole append relation.
1040 *
1041 * We handle tuples estimates by setting "tuples" to the total number of
1042 * tuples accumulated from each live child, rather than using "rows".
1043 * Although an appendrel itself doesn't directly enforce any quals, its
1044 * child relations may. Therefore, setting "tuples" equal to "rows" for
1045 * an appendrel isn't always appropriate, and can lead to inaccurate cost
1046 * estimates. For example, when estimating the number of distinct values
1047 * from an appendrel, we would be unable to adjust the estimate based on
1048 * the restriction selectivity (see estimate_num_groups).
1049 *
1050 * We handle width estimates by weighting the widths of different child
1051 * rels proportionally to their number of rows. This is sensible because
1052 * the use of width estimates is mainly to compute the total relation
1053 * "footprint" if we have to sort or hash it. To do this, we sum the
1054 * total equivalent size (in "double" arithmetic) and then divide by the
1055 * total rowcount estimate. This is done separately for the total rel
1056 * width and each attribute.
1057 *
1058 * Note: if you consider changing this logic, beware that child rels could
1059 * have zero rows and/or width, if they were excluded by constraints.
1060 */
1061 has_live_children = false;
1062 parent_tuples = 0;
1063 parent_rows = 0;
1064 parent_size = 0;
1065 nattrs = rel->max_attr - rel->min_attr + 1;
1066 parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
1067
1068 foreach(l, root->append_rel_list)
1069 {
1070 AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1071 int childRTindex;
1072 RangeTblEntry *childRTE;
1073 RelOptInfo *childrel;
1074 List *childrinfos;
1075 ListCell *parentvars;
1076 ListCell *childvars;
1077 ListCell *lc;
1078
1079 /* append_rel_list contains all append rels; ignore others */
1080 if (appinfo->parent_relid != parentRTindex)
1081 continue;
1082
1083 childRTindex = appinfo->child_relid;
1084 childRTE = root->simple_rte_array[childRTindex];
1085
1086 /*
1087 * The child rel's RelOptInfo was already created during
1088 * add_other_rels_to_query.
1089 */
1090 childrel = find_base_rel(root, childRTindex);
1092
1093 /* We may have already proven the child to be dummy. */
1094 if (IS_DUMMY_REL(childrel))
1095 continue;
1096
1097 /*
1098 * We have to copy the parent's targetlist and quals to the child,
1099 * with appropriate substitution of variables. However, the
1100 * baserestrictinfo quals were already copied/substituted when the
1101 * child RelOptInfo was built. So we don't need any additional setup
1102 * before applying constraint exclusion.
1103 */
1104 if (relation_excluded_by_constraints(root, childrel, childRTE))
1105 {
1106 /*
1107 * This child need not be scanned, so we can omit it from the
1108 * appendrel.
1109 */
1110 set_dummy_rel_pathlist(childrel);
1111 continue;
1112 }
1113
1114 /*
1115 * Constraint exclusion failed, so copy the parent's join quals and
1116 * targetlist to the child, with appropriate variable substitutions.
1117 *
1118 * We skip join quals that came from above outer joins that can null
1119 * this rel, since they would be of no value while generating paths
1120 * for the child. This saves some effort while processing the child
1121 * rel, and it also avoids an implementation restriction in
1122 * adjust_appendrel_attrs (it can't apply nullingrels to a non-Var).
1123 */
1124 childrinfos = NIL;
1125 foreach(lc, rel->joininfo)
1126 {
1127 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1128
1129 if (!bms_overlap(rinfo->clause_relids, rel->nulling_relids))
1130 childrinfos = lappend(childrinfos,
1132 (Node *) rinfo,
1133 1, &appinfo));
1134 }
1135 childrel->joininfo = childrinfos;
1136
1137 /*
1138 * Now for the child's targetlist.
1139 *
1140 * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1141 * expressions, which otherwise would not occur in a rel's targetlist.
1142 * Code that might be looking at an appendrel child must cope with
1143 * such. (Normally, a rel's targetlist would only include Vars and
1144 * PlaceHolderVars.) XXX we do not bother to update the cost or width
1145 * fields of childrel->reltarget; not clear if that would be useful.
1146 */
1147 childrel->reltarget->exprs = (List *)
1149 (Node *) rel->reltarget->exprs,
1150 1, &appinfo);
1151
1152 /*
1153 * We have to make child entries in the EquivalenceClass data
1154 * structures as well. This is needed either if the parent
1155 * participates in some eclass joins (because we will want to consider
1156 * inner-indexscan joins on the individual children) or if the parent
1157 * has useful pathkeys (because we should try to build MergeAppend
1158 * paths that produce those sort orderings).
1159 */
1160 if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1161 add_child_rel_equivalences(root, appinfo, rel, childrel);
1162 childrel->has_eclass_joins = rel->has_eclass_joins;
1163
1164 /*
1165 * Note: we could compute appropriate attr_needed data for the child's
1166 * variables, by transforming the parent's attr_needed through the
1167 * translated_vars mapping. However, currently there's no need
1168 * because attr_needed is only examined for base relations not
1169 * otherrels. So we just leave the child's attr_needed empty.
1170 */
1171
1172 /*
1173 * If we consider partitionwise joins with the parent rel, do the same
1174 * for partitioned child rels.
1175 *
1176 * Note: here we abuse the consider_partitionwise_join flag by setting
1177 * it for child rels that are not themselves partitioned. We do so to
1178 * tell try_partitionwise_join() that the child rel is sufficiently
1179 * valid to be used as a per-partition input, even if it later gets
1180 * proven to be dummy. (It's not usable until we've set up the
1181 * reltarget and EC entries, which we just did.)
1182 */
1184 childrel->consider_partitionwise_join = true;
1185
1186 /*
1187 * If parallelism is allowable for this query in general, see whether
1188 * it's allowable for this childrel in particular. But if we've
1189 * already decided the appendrel is not parallel-safe as a whole,
1190 * there's no point in considering parallelism for this child. For
1191 * consistency, do this before calling set_rel_size() for the child.
1192 */
1193 if (root->glob->parallelModeOK && rel->consider_parallel)
1194 set_rel_consider_parallel(root, childrel, childRTE);
1195
1196 /*
1197 * Compute the child's size.
1198 */
1199 set_rel_size(root, childrel, childRTindex, childRTE);
1200
1201 /*
1202 * It is possible that constraint exclusion detected a contradiction
1203 * within a child subquery, even though we didn't prove one above. If
1204 * so, we can skip this child.
1205 */
1206 if (IS_DUMMY_REL(childrel))
1207 continue;
1208
1209 /* We have at least one live child. */
1210 has_live_children = true;
1211
1212 /*
1213 * If any live child is not parallel-safe, treat the whole appendrel
1214 * as not parallel-safe. In future we might be able to generate plans
1215 * in which some children are farmed out to workers while others are
1216 * not; but we don't have that today, so it's a waste to consider
1217 * partial paths anywhere in the appendrel unless it's all safe.
1218 * (Child rels visited before this one will be unmarked in
1219 * set_append_rel_pathlist().)
1220 */
1221 if (!childrel->consider_parallel)
1222 rel->consider_parallel = false;
1223
1224 /*
1225 * Accumulate size information from each live child.
1226 */
1227 Assert(childrel->rows > 0);
1228
1229 parent_tuples += childrel->tuples;
1230 parent_rows += childrel->rows;
1231 parent_size += childrel->reltarget->width * childrel->rows;
1232
1233 /*
1234 * Accumulate per-column estimates too. We need not do anything for
1235 * PlaceHolderVars in the parent list. If child expression isn't a
1236 * Var, or we didn't record a width estimate for it, we have to fall
1237 * back on a datatype-based estimate.
1238 *
1239 * By construction, child's targetlist is 1-to-1 with parent's.
1240 */
1241 forboth(parentvars, rel->reltarget->exprs,
1242 childvars, childrel->reltarget->exprs)
1243 {
1244 Var *parentvar = (Var *) lfirst(parentvars);
1245 Node *childvar = (Node *) lfirst(childvars);
1246
1247 if (IsA(parentvar, Var) && parentvar->varno == parentRTindex)
1248 {
1249 int pndx = parentvar->varattno - rel->min_attr;
1250 int32 child_width = 0;
1251
1252 if (IsA(childvar, Var) &&
1253 ((Var *) childvar)->varno == childrel->relid)
1254 {
1255 int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1256
1257 child_width = childrel->attr_widths[cndx];
1258 }
1259 if (child_width <= 0)
1260 child_width = get_typavgwidth(exprType(childvar),
1261 exprTypmod(childvar));
1262 Assert(child_width > 0);
1263 parent_attrsizes[pndx] += child_width * childrel->rows;
1264 }
1265 }
1266 }
1267
1268 if (has_live_children)
1269 {
1270 /*
1271 * Save the finished size estimates.
1272 */
1273 int i;
1274
1275 Assert(parent_rows > 0);
1276 rel->tuples = parent_tuples;
1277 rel->rows = parent_rows;
1278 rel->reltarget->width = rint(parent_size / parent_rows);
1279 for (i = 0; i < nattrs; i++)
1280 rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1281
1282 /*
1283 * Note that we leave rel->pages as zero; this is important to avoid
1284 * double-counting the appendrel tree in total_table_pages.
1285 */
1286 }
1287 else
1288 {
1289 /*
1290 * All children were excluded by constraints, so mark the whole
1291 * appendrel dummy. We must do this in this phase so that the rel's
1292 * dummy-ness is visible when we generate paths for other rels.
1293 */
1295 }
1296
1297 pfree(parent_attrsizes);
1298}
static void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:2292
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:643
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:405
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:200
#define InvalidAttrNumber
Definition: attnum.h:23
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
#define bms_is_empty(a)
Definition: bitmapset.h:118
int32_t int32
Definition: c.h:534
bool enable_partitionwise_join
Definition: costsize.c:159
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
Definition: equivclass.c:2833
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2745
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:2319
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:888
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1700
List * joininfo
Definition: pathnodes.h:1055
Cardinality tuples
Definition: pathnodes.h:1003
bool has_eclass_joins
Definition: pathnodes.h:1057
AttrNumber max_attr
Definition: pathnodes.h:984
Relids nulling_relids
Definition: pathnodes.h:992
AttrNumber min_attr
Definition: pathnodes.h:982

References add_child_rel_equivalences(), adjust_appendrel_attrs(), Assert(), bms_is_empty, bms_overlap(), check_stack_depth(), AppendRelInfo::child_relid, RelOptInfo::consider_parallel, RelOptInfo::consider_partitionwise_join, enable_partitionwise_join, PathTarget::exprs, exprType(), exprTypmod(), find_base_rel(), forboth, get_typavgwidth(), RelOptInfo::has_eclass_joins, has_useful_pathkeys(), i, InvalidAttrNumber, IS_DUMMY_REL, IS_SIMPLE_REL, IsA, RelOptInfo::joininfo, lappend(), lfirst, RelOptInfo::max_attr, RelOptInfo::min_attr, NIL, RelOptInfo::nulling_relids, palloc0(), AppendRelInfo::parent_relid, pfree(), relation_excluded_by_constraints(), RelOptInfo::relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, root, RelOptInfo::rows, set_dummy_rel_pathlist(), set_rel_consider_parallel(), set_rel_size(), RelOptInfo::tuples, Var::varattno, Var::varno, and PathTarget::width.

Referenced by set_rel_size().

◆ set_base_rel_consider_startup()

static void set_base_rel_consider_startup ( PlannerInfo root)
static

Definition at line 259 of file allpaths.c.

260{
261 /*
262 * Since parameterized paths can only be used on the inside of a nestloop
263 * join plan, there is usually little value in considering fast-start
264 * plans for them. However, for relations that are on the RHS of a SEMI
265 * or ANTI join, a fast-start plan can be useful because we're only going
266 * to care about fetching one tuple anyway.
267 *
268 * To minimize growth of planning time, we currently restrict this to
269 * cases where the RHS is a single base relation, not a join; there is no
270 * provision for consider_param_startup to get set at all on joinrels.
271 * Also we don't worry about appendrels. costsize.c's costing rules for
272 * nestloop semi/antijoins don't consider such cases either.
273 */
274 ListCell *lc;
275
276 foreach(lc, root->join_info_list)
277 {
278 SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
279 int varno;
280
281 if ((sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) &&
283 {
284 RelOptInfo *rel = find_base_rel(root, varno);
285
286 rel->consider_param_startup = true;
287 }
288 }
289}
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:715
@ JOIN_SEMI
Definition: nodes.h:317
@ JOIN_ANTI
Definition: nodes.h:318
bool consider_param_startup
Definition: pathnodes.h:944
JoinType jointype
Definition: pathnodes.h:3124
Relids syn_righthand
Definition: pathnodes.h:3123

References bms_get_singleton_member(), RelOptInfo::consider_param_startup, find_base_rel(), JOIN_ANTI, JOIN_SEMI, SpecialJoinInfo::jointype, lfirst, root, and SpecialJoinInfo::syn_righthand.

Referenced by make_one_rel().

◆ set_base_rel_pathlists()

static void set_base_rel_pathlists ( PlannerInfo root)
static

Definition at line 378 of file allpaths.c.

379{
380 Index rti;
381
382 for (rti = 1; rti < root->simple_rel_array_size; rti++)
383 {
384 RelOptInfo *rel = root->simple_rel_array[rti];
385
386 /* there may be empty slots corresponding to non-baserel RTEs */
387 if (rel == NULL)
388 continue;
389
390 Assert(rel->relid == rti); /* sanity check on array */
391
392 /* ignore RTEs that are "other rels" */
393 if (rel->reloptkind != RELOPT_BASEREL)
394 continue;
395
396 set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
397 }
398}

References Assert(), RelOptInfo::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, root, and set_rel_pathlist().

Referenced by make_one_rel().

◆ set_base_rel_sizes()

static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 302 of file allpaths.c.

303{
304 Index rti;
305
306 for (rti = 1; rti < root->simple_rel_array_size; rti++)
307 {
308 RelOptInfo *rel = root->simple_rel_array[rti];
309 RangeTblEntry *rte;
310
311 /* there may be empty slots corresponding to non-baserel RTEs */
312 if (rel == NULL)
313 continue;
314
315 Assert(rel->relid == rti); /* sanity check on array */
316
317 /* ignore RTEs that are "other rels" */
318 if (rel->reloptkind != RELOPT_BASEREL)
319 continue;
320
321 rte = root->simple_rte_array[rti];
322
323 /*
324 * If parallelism is allowable for this query in general, see whether
325 * it's allowable for this rel in particular. We have to do this
326 * before set_rel_size(), because (a) if this rel is an inheritance
327 * parent, set_append_rel_size() will use and perhaps change the rel's
328 * consider_parallel flag, and (b) for some RTE types, set_rel_size()
329 * goes ahead and makes paths immediately.
330 */
331 if (root->glob->parallelModeOK)
333
334 set_rel_size(root, rel, rti, rte);
335 }
336}

References Assert(), RelOptInfo::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, root, set_rel_consider_parallel(), and set_rel_size().

Referenced by make_one_rel().

◆ set_cte_pathlist()

static void set_cte_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 2983 of file allpaths.c.

2984{
2985 Path *ctepath;
2986 Plan *cteplan;
2987 PlannerInfo *cteroot;
2988 Index levelsup;
2989 List *pathkeys;
2990 int ndx;
2991 ListCell *lc;
2992 int plan_id;
2993 Relids required_outer;
2994
2995 /*
2996 * Find the referenced CTE, and locate the path and plan previously made
2997 * for it.
2998 */
2999 levelsup = rte->ctelevelsup;
3000 cteroot = root;
3001 while (levelsup-- > 0)
3002 {
3003 cteroot = cteroot->parent_root;
3004 if (!cteroot) /* shouldn't happen */
3005 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3006 }
3007
3008 /*
3009 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3010 * on planning the CTEs (ie, this is a side-reference from another CTE).
3011 * So we mustn't use forboth here.
3012 */
3013 ndx = 0;
3014 foreach(lc, cteroot->parse->cteList)
3015 {
3016 CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3017
3018 if (strcmp(cte->ctename, rte->ctename) == 0)
3019 break;
3020 ndx++;
3021 }
3022 if (lc == NULL) /* shouldn't happen */
3023 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3024 if (ndx >= list_length(cteroot->cte_plan_ids))
3025 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3026 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3027 if (plan_id <= 0)
3028 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
3029
3030 Assert(list_length(root->glob->subpaths) == list_length(root->glob->subplans));
3031 ctepath = (Path *) list_nth(root->glob->subpaths, plan_id - 1);
3032 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
3033
3034 /* Mark rel with estimated output rows, width, etc */
3035 set_cte_size_estimates(root, rel, cteplan->plan_rows);
3036
3037 /* Convert the ctepath's pathkeys to outer query's representation */
3039 rel,
3040 ctepath->pathkeys,
3041 cteplan->targetlist);
3042
3043 /*
3044 * We don't support pushing join clauses into the quals of a CTE scan, but
3045 * it could still have required parameterization due to LATERAL refs in
3046 * its tlist.
3047 */
3048 required_outer = rel->lateral_relids;
3049
3050 /* Generate appropriate path */
3051 add_path(rel, create_ctescan_path(root, rel, pathkeys, required_outer));
3052}
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:6110
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:1054
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1953
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:310
Cardinality plan_rows
Definition: plannodes.h:205
List * targetlist
Definition: plannodes.h:229
List * cte_plan_ids
Definition: pathnodes.h:333
Query * parse
Definition: pathnodes.h:227
List * cteList
Definition: parsenodes.h:173
char * ctename
Definition: parsenodes.h:1227
Index ctelevelsup
Definition: parsenodes.h:1229

References add_path(), Assert(), convert_subquery_pathkeys(), create_ctescan_path(), PlannerInfo::cte_plan_ids, RangeTblEntry::ctelevelsup, Query::cteList, RangeTblEntry::ctename, CommonTableExpr::ctename, elog, ERROR, RelOptInfo::lateral_relids, lfirst, list_length(), list_nth(), list_nth_int(), PlannerInfo::parse, Path::pathkeys, Plan::plan_rows, root, set_cte_size_estimates(), and Plan::targetlist.

Referenced by set_rel_size().

◆ set_dummy_rel_pathlist()

static void set_dummy_rel_pathlist ( RelOptInfo rel)
static

Definition at line 2292 of file allpaths.c.

2293{
2294 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2295 rel->rows = 0;
2296 rel->reltarget->width = 0;
2297
2298 /* Discard any pre-existing paths; no further need for them */
2299 rel->pathlist = NIL;
2300 rel->partial_pathlist = NIL;
2301
2302 /* Set up the dummy path */
2303 add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2304 NIL, rel->lateral_relids,
2305 0, false, -1));
2306
2307 /*
2308 * We set the cheapest-path fields immediately, just in case they were
2309 * pointing at some discarded path. This is redundant in current usage
2310 * because set_rel_pathlist will do it later, but it's cheap so we keep it
2311 * for safety and consistency with mark_dummy_rel.
2312 */
2313 set_cheapest(rel);
2314}

References add_path(), create_append_path(), RelOptInfo::lateral_relids, NIL, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, RelOptInfo::reltarget, RelOptInfo::rows, set_cheapest(), and PathTarget::width.

Referenced by set_append_rel_size(), set_rel_size(), and set_subquery_pathlist().

◆ set_foreign_pathlist()

static void set_foreign_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 992 of file allpaths.c.

993{
994 /* Call the FDW's GetForeignPaths function to generate path(s) */
995 rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
996}

References root.

Referenced by set_rel_pathlist().

◆ set_foreign_size()

static void set_foreign_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 968 of file allpaths.c.

969{
970 /* Mark rel with estimated output rows, width, etc */
972
973 /* Let FDW adjust the size estimates, if it can */
974 rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
975
976 /* ... but do not let it set the rows estimate to zero */
977 rel->rows = clamp_row_est(rel->rows);
978
979 /*
980 * Also, make sure rel->tuples is not insane relative to rel->rows.
981 * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
982 * FDW doesn't do anything to replace that.
983 */
984 rel->tuples = Max(rel->tuples, rel->rows);
985}
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6210
double clamp_row_est(double nrows)
Definition: costsize.c:213

References clamp_row_est(), Max, root, RelOptInfo::rows, set_foreign_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

◆ set_function_pathlist()

static void set_function_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 2872 of file allpaths.c.

2873{
2874 Relids required_outer;
2875 List *pathkeys = NIL;
2876
2877 /*
2878 * We don't support pushing join clauses into the quals of a function
2879 * scan, but it could still have required parameterization due to LATERAL
2880 * refs in the function expression.
2881 */
2882 required_outer = rel->lateral_relids;
2883
2884 /*
2885 * The result is considered unordered unless ORDINALITY was used, in which
2886 * case it is ordered by the ordinal column (the last one). See if we
2887 * care, by checking for uses of that Var in equivalence classes.
2888 */
2889 if (rte->funcordinality)
2890 {
2891 AttrNumber ordattno = rel->max_attr;
2892 Var *var = NULL;
2893 ListCell *lc;
2894
2895 /*
2896 * Is there a Var for it in rel's targetlist? If not, the query did
2897 * not reference the ordinality column, or at least not in any way
2898 * that would be interesting for sorting.
2899 */
2900 foreach(lc, rel->reltarget->exprs)
2901 {
2902 Var *node = (Var *) lfirst(lc);
2903
2904 /* checking varno/varlevelsup is just paranoia */
2905 if (IsA(node, Var) &&
2906 node->varattno == ordattno &&
2907 node->varno == rel->relid &&
2908 node->varlevelsup == 0)
2909 {
2910 var = node;
2911 break;
2912 }
2913 }
2914
2915 /*
2916 * Try to build pathkeys for this Var with int8 sorting. We tell
2917 * build_expression_pathkey not to build any new equivalence class; if
2918 * the Var isn't already mentioned in some EC, it means that nothing
2919 * cares about the ordering.
2920 */
2921 if (var)
2922 pathkeys = build_expression_pathkey(root,
2923 (Expr *) var,
2924 Int8LessOperator,
2925 rel->relids,
2926 false);
2927 }
2928
2929 /* Generate appropriate path */
2931 pathkeys, required_outer));
2932}
int16 AttrNumber
Definition: attnum.h:21
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:1000
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1875
bool funcordinality
Definition: parsenodes.h:1210
Index varlevelsup
Definition: primnodes.h:294

References add_path(), build_expression_pathkey(), create_functionscan_path(), PathTarget::exprs, RangeTblEntry::funcordinality, IsA, RelOptInfo::lateral_relids, lfirst, RelOptInfo::max_attr, NIL, RelOptInfo::relid, RelOptInfo::relids, RelOptInfo::reltarget, root, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by set_rel_pathlist().

◆ set_grouped_rel_pathlist()

static void set_grouped_rel_pathlist ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 1368 of file allpaths.c.

1369{
1370 RelOptInfo *grouped_rel;
1371
1372 /*
1373 * If there are no aggregate expressions or grouping expressions, eager
1374 * aggregation is not possible.
1375 */
1376 if (root->agg_clause_list == NIL ||
1377 root->group_expr_list == NIL)
1378 return;
1379
1380 /* Add paths to the grouped base relation if one exists. */
1381 grouped_rel = rel->grouped_rel;
1382 if (grouped_rel)
1383 {
1384 Assert(IS_GROUPED_REL(grouped_rel));
1385
1386 generate_grouped_paths(root, grouped_rel, rel);
1387 set_cheapest(grouped_rel);
1388 }
1389}

References Assert(), generate_grouped_paths(), RelOptInfo::grouped_rel, IS_GROUPED_REL, NIL, root, and set_cheapest().

Referenced by set_rel_pathlist().

◆ set_namedtuplestore_pathlist()

static void set_namedtuplestore_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 3062 of file allpaths.c.

3064{
3065 Relids required_outer;
3066
3067 /* Mark rel with estimated output rows, width, etc */
3069
3070 /*
3071 * We don't support pushing join clauses into the quals of a tuplestore
3072 * scan, but it could still have required parameterization due to LATERAL
3073 * refs in its tlist.
3074 */
3075 required_outer = rel->lateral_relids;
3076
3077 /* Generate appropriate path */
3078 add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
3079}
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6148
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1979

References add_path(), create_namedtuplestorescan_path(), RelOptInfo::lateral_relids, root, and set_namedtuplestore_size_estimates().

Referenced by set_rel_size().

◆ set_plain_rel_pathlist()

static void set_plain_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 822 of file allpaths.c.

823{
824 Relids required_outer;
825
826 /*
827 * We don't support pushing join clauses into the quals of a seqscan, but
828 * it could still have required parameterization due to LATERAL refs in
829 * its tlist.
830 */
831 required_outer = rel->lateral_relids;
832
833 /*
834 * Consider TID scans.
835 *
836 * If create_tidscan_paths returns true, then a TID scan path is forced.
837 * This happens when rel->baserestrictinfo contains CurrentOfExpr, because
838 * the executor can't handle any other type of path for such queries.
839 * Hence, we return without adding any other paths.
840 */
841 if (create_tidscan_paths(root, rel))
842 return;
843
844 /* Consider sequential scan */
845 add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
846
847 /* If appropriate, consider parallel sequential scan */
848 if (rel->consider_parallel && required_outer == NULL)
850
851 /* Consider index scans */
853}
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:860
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:240
bool create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: tidpath.c:498

References add_path(), RelOptInfo::consider_parallel, create_index_paths(), create_plain_partial_paths(), create_seqscan_path(), create_tidscan_paths(), RelOptInfo::lateral_relids, and root.

Referenced by set_rel_pathlist().

◆ set_plain_rel_size()

static void set_plain_rel_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 626 of file allpaths.c.

627{
628 /*
629 * Test any partial indexes of rel for applicability. We must do this
630 * first since partial unique indexes can affect size estimates.
631 */
633
634 /* Mark rel with estimated output rows, width, etc */
636}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5384
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:3967

References check_index_predicates(), root, and set_baserel_size_estimates().

Referenced by set_rel_size().

◆ set_rel_consider_parallel()

static void set_rel_consider_parallel ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 643 of file allpaths.c.

645{
646 /*
647 * The flag has previously been initialized to false, so we can just
648 * return if it becomes clear that we can't safely set it.
649 */
651
652 /* Don't call this if parallelism is disallowed for the entire query. */
653 Assert(root->glob->parallelModeOK);
654
655 /* This should only be called for baserels and appendrel children. */
656 Assert(IS_SIMPLE_REL(rel));
657
658 /* Assorted checks based on rtekind. */
659 switch (rte->rtekind)
660 {
661 case RTE_RELATION:
662
663 /*
664 * Currently, parallel workers can't access the leader's temporary
665 * tables. We could possibly relax this if we wrote all of its
666 * local buffers at the start of the query and made no changes
667 * thereafter (maybe we could allow hint bit changes), and if we
668 * taught the workers to read them. Writing a large number of
669 * temporary buffers could be expensive, though, and we don't have
670 * the rest of the necessary infrastructure right now anyway. So
671 * for now, bail out if we see a temporary table.
672 */
673 if (get_rel_persistence(rte->relid) == RELPERSISTENCE_TEMP)
674 return;
675
676 /*
677 * Table sampling can be pushed down to workers if the sample
678 * function and its arguments are safe.
679 */
680 if (rte->tablesample != NULL)
681 {
682 char proparallel = func_parallel(rte->tablesample->tsmhandler);
683
684 if (proparallel != PROPARALLEL_SAFE)
685 return;
686 if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
687 return;
688 }
689
690 /*
691 * Ask FDWs whether they can support performing a ForeignScan
692 * within a worker. Most often, the answer will be no. For
693 * example, if the nature of the FDW is such that it opens a TCP
694 * connection with a remote server, each parallel worker would end
695 * up with a separate connection, and these connections might not
696 * be appropriately coordinated between workers and the leader.
697 */
698 if (rte->relkind == RELKIND_FOREIGN_TABLE)
699 {
700 Assert(rel->fdwroutine);
701 if (!rel->fdwroutine->IsForeignScanParallelSafe)
702 return;
703 if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
704 return;
705 }
706
707 /*
708 * There are additional considerations for appendrels, which we'll
709 * deal with in set_append_rel_size and set_append_rel_pathlist.
710 * For now, just set consider_parallel based on the rel's own
711 * quals and targetlist.
712 */
713 break;
714
715 case RTE_SUBQUERY:
716
717 /*
718 * There's no intrinsic problem with scanning a subquery-in-FROM
719 * (as distinct from a SubPlan or InitPlan) in a parallel worker.
720 * If the subquery doesn't happen to have any parallel-safe paths,
721 * then flagging it as consider_parallel won't change anything,
722 * but that's true for plain tables, too. We must set
723 * consider_parallel based on the rel's own quals and targetlist,
724 * so that if a subquery path is parallel-safe but the quals and
725 * projection we're sticking onto it are not, we correctly mark
726 * the SubqueryScanPath as not parallel-safe. (Note that
727 * set_subquery_pathlist() might push some of these quals down
728 * into the subquery itself, but that doesn't change anything.)
729 *
730 * We can't push sub-select containing LIMIT/OFFSET to workers as
731 * there is no guarantee that the row order will be fully
732 * deterministic, and applying LIMIT/OFFSET will lead to
733 * inconsistent results at the top-level. (In some cases, where
734 * the result is ordered, we could relax this restriction. But it
735 * doesn't currently seem worth expending extra effort to do so.)
736 */
737 {
738 Query *subquery = castNode(Query, rte->subquery);
739
740 if (limit_needed(subquery))
741 return;
742 }
743 break;
744
745 case RTE_JOIN:
746 /* Shouldn't happen; we're only considering baserels here. */
747 Assert(false);
748 return;
749
750 case RTE_FUNCTION:
751 /* Check for parallel-restricted functions. */
752 if (!is_parallel_safe(root, (Node *) rte->functions))
753 return;
754 break;
755
756 case RTE_TABLEFUNC:
757 /* not parallel safe */
758 return;
759
760 case RTE_VALUES:
761 /* Check for parallel-restricted functions. */
762 if (!is_parallel_safe(root, (Node *) rte->values_lists))
763 return;
764 break;
765
766 case RTE_CTE:
767
768 /*
769 * CTE tuplestores aren't shared among parallel workers, so we
770 * force all CTE scans to happen in the leader. Also, populating
771 * the CTE would require executing a subplan that's not available
772 * in the worker, might be parallel-restricted, and must get
773 * executed only once.
774 */
775 return;
776
778
779 /*
780 * tuplestore cannot be shared, at least without more
781 * infrastructure to support that.
782 */
783 return;
784
785 case RTE_RESULT:
786 /* RESULT RTEs, in themselves, are no problem. */
787 break;
788 case RTE_GROUP:
789 /* Shouldn't happen; we're only considering baserels here. */
790 Assert(false);
791 return;
792 }
793
794 /*
795 * If there's anything in baserestrictinfo that's parallel-restricted, we
796 * give up on parallelizing access to this relation. We could consider
797 * instead postponing application of the restricted quals until we're
798 * above all the parallelism in the plan tree, but it's not clear that
799 * that would be a win in very many cases, and it might be tricky to make
800 * outer join clauses work correctly. It would likely break equivalence
801 * classes, too.
802 */
804 return;
805
806 /*
807 * Likewise, if the relation's outputs are not parallel-safe, give up.
808 * (Usually, they're just Vars, but sometimes they're not.)
809 */
810 if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
811 return;
812
813 /* We have a winner. */
814 rel->consider_parallel = true;
815}
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:757
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2245
char func_parallel(Oid funcid)
Definition: lsyscache.c:1966
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ RTE_JOIN
Definition: parsenodes.h:1045
@ RTE_CTE
Definition: parsenodes.h:1049
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1050
@ RTE_VALUES
Definition: parsenodes.h:1048
@ RTE_SUBQUERY
Definition: parsenodes.h:1044
@ RTE_RESULT
Definition: parsenodes.h:1051
@ RTE_FUNCTION
Definition: parsenodes.h:1046
@ RTE_TABLEFUNC
Definition: parsenodes.h:1047
@ RTE_GROUP
Definition: parsenodes.h:1054
@ RTE_RELATION
Definition: parsenodes.h:1043
bool limit_needed(Query *parse)
Definition: planner.c:2773
struct TableSampleClause * tablesample
Definition: parsenodes.h:1129
List * values_lists
Definition: parsenodes.h:1221
List * functions
Definition: parsenodes.h:1208
RTEKind rtekind
Definition: parsenodes.h:1078

References TableSampleClause::args, Assert(), RelOptInfo::baserestrictinfo, castNode, RelOptInfo::consider_parallel, PathTarget::exprs, func_parallel(), RangeTblEntry::functions, get_rel_persistence(), is_parallel_safe(), IS_SIMPLE_REL, limit_needed(), RelOptInfo::reltarget, root, RTE_CTE, RTE_FUNCTION, RTE_GROUP, RTE_JOIN, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::subquery, RangeTblEntry::tablesample, TableSampleClause::tsmhandler, and RangeTblEntry::values_lists.

Referenced by set_append_rel_size(), and set_base_rel_sizes().

◆ set_rel_pathlist()

static void set_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 514 of file allpaths.c.

516{
517 if (IS_DUMMY_REL(rel))
518 {
519 /* We already proved the relation empty, so nothing more to do */
520 }
521 else if (rte->inh)
522 {
523 /* It's an "append relation", process accordingly */
524 set_append_rel_pathlist(root, rel, rti, rte);
525 }
526 else
527 {
528 switch (rel->rtekind)
529 {
530 case RTE_RELATION:
531 if (rte->relkind == RELKIND_FOREIGN_TABLE)
532 {
533 /* Foreign table */
534 set_foreign_pathlist(root, rel, rte);
535 }
536 else if (rte->tablesample != NULL)
537 {
538 /* Sampled relation */
540 }
541 else
542 {
543 /* Plain relation */
544 set_plain_rel_pathlist(root, rel, rte);
545 }
546 break;
547 case RTE_SUBQUERY:
548 /* Subquery --- fully handled during set_rel_size */
549 break;
550 case RTE_FUNCTION:
551 /* RangeFunction */
552 set_function_pathlist(root, rel, rte);
553 break;
554 case RTE_TABLEFUNC:
555 /* Table Function */
556 set_tablefunc_pathlist(root, rel, rte);
557 break;
558 case RTE_VALUES:
559 /* Values list */
560 set_values_pathlist(root, rel, rte);
561 break;
562 case RTE_CTE:
563 /* CTE reference --- fully handled during set_rel_size */
564 break;
566 /* tuplestore reference --- fully handled during set_rel_size */
567 break;
568 case RTE_RESULT:
569 /* simple Result --- fully handled during set_rel_size */
570 break;
571 default:
572 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
573 break;
574 }
575 }
576
577 /*
578 * Allow a plugin to editorialize on the set of Paths for this base
579 * relation. It could add new paths (such as CustomPaths) by calling
580 * add_path(), or add_partial_path() if parallel aware. It could also
581 * delete or modify paths added by the core code.
582 */
584 (*set_rel_pathlist_hook) (root, rel, rti, rte);
585
586 /*
587 * If this is a baserel, we should normally consider gathering any partial
588 * paths we may have created for it. We have to do this after calling the
589 * set_rel_pathlist_hook, else it cannot add partial paths to be included
590 * here.
591 *
592 * However, if this is an inheritance child, skip it. Otherwise, we could
593 * end up with a very large number of gather nodes, each trying to grab
594 * its own pool of workers. Instead, we'll consider gathering partial
595 * paths for the parent appendrel.
596 *
597 * Also, if this is the topmost scan/join rel, we postpone gathering until
598 * the final scan/join targetlist is available (see grouping_planner).
599 */
600 if (rel->reloptkind == RELOPT_BASEREL &&
601 !bms_equal(rel->relids, root->all_query_rels))
603
604 /* Now find the cheapest of the paths for this rel */
605 set_cheapest(rel);
606
607 /*
608 * If a grouped relation for this rel exists, build partial aggregation
609 * paths for it.
610 *
611 * Note that this can only happen after we've called set_cheapest() for
612 * this base rel, because we need its cheapest paths.
613 */
615
616#ifdef OPTIMIZER_DEBUG
617 pprint(rel);
618#endif
619}
static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:920
static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:992
static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1305
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3312
static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2872
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:822
static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2959
set_rel_pathlist_hook_type set_rel_pathlist_hook
Definition: allpaths.c:89
static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2939
static void set_grouped_rel_pathlist(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:1368
RTEKind rtekind
Definition: pathnodes.h:980

References bms_equal(), elog, ERROR, generate_useful_gather_paths(), RangeTblEntry::inh, IS_DUMMY_REL, pprint(), RelOptInfo::relids, RELOPT_BASEREL, RelOptInfo::reloptkind, root, RTE_CTE, RTE_FUNCTION, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RelOptInfo::rtekind, set_append_rel_pathlist(), set_cheapest(), set_foreign_pathlist(), set_function_pathlist(), set_grouped_rel_pathlist(), set_plain_rel_pathlist(), set_rel_pathlist_hook, set_tablefunc_pathlist(), set_tablesample_rel_pathlist(), set_values_pathlist(), and RangeTblEntry::tablesample.

Referenced by set_append_rel_pathlist(), and set_base_rel_pathlists().

◆ set_rel_size()

static void set_rel_size ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 405 of file allpaths.c.

407{
408 if (rel->reloptkind == RELOPT_BASEREL &&
410 {
411 /*
412 * We proved we don't need to scan the rel via constraint exclusion,
413 * so set up a single dummy path for it. Here we only check this for
414 * regular baserels; if it's an otherrel, CE was already checked in
415 * set_append_rel_size().
416 *
417 * In this case, we go ahead and set up the relation's path right away
418 * instead of leaving it for set_rel_pathlist to do. This is because
419 * we don't have a convention for marking a rel as dummy except by
420 * assigning a dummy path to it.
421 */
423 }
424 else if (rte->inh)
425 {
426 /* It's an "append relation", process accordingly */
427 set_append_rel_size(root, rel, rti, rte);
428 }
429 else
430 {
431 switch (rel->rtekind)
432 {
433 case RTE_RELATION:
434 if (rte->relkind == RELKIND_FOREIGN_TABLE)
435 {
436 /* Foreign table */
437 set_foreign_size(root, rel, rte);
438 }
439 else if (rte->relkind == RELKIND_PARTITIONED_TABLE)
440 {
441 /*
442 * We could get here if asked to scan a partitioned table
443 * with ONLY. In that case we shouldn't scan any of the
444 * partitions, so mark it as a dummy rel.
445 */
447 }
448 else if (rte->tablesample != NULL)
449 {
450 /* Sampled relation */
452 }
453 else
454 {
455 /* Plain relation */
456 set_plain_rel_size(root, rel, rte);
457 }
458 break;
459 case RTE_SUBQUERY:
460
461 /*
462 * Subqueries don't support making a choice between
463 * parameterized and unparameterized paths, so just go ahead
464 * and build their paths immediately.
465 */
466 set_subquery_pathlist(root, rel, rti, rte);
467 break;
468 case RTE_FUNCTION:
470 break;
471 case RTE_TABLEFUNC:
473 break;
474 case RTE_VALUES:
476 break;
477 case RTE_CTE:
478
479 /*
480 * CTEs don't support making a choice between parameterized
481 * and unparameterized paths, so just go ahead and build their
482 * paths immediately.
483 */
484 if (rte->self_reference)
485 set_worktable_pathlist(root, rel, rte);
486 else
487 set_cte_pathlist(root, rel, rte);
488 break;
490 /* Might as well just build the path immediately */
492 break;
493 case RTE_RESULT:
494 /* Might as well just build the path immediately */
495 set_result_pathlist(root, rel, rte);
496 break;
497 default:
498 elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
499 break;
500 }
501 }
502
503 /*
504 * We insist that all non-dummy rels have a nonzero rowcount estimate.
505 */
506 Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
507}
static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:2603
static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:3062
static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:880
static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:3089
static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:3116
static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:968
static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2983
static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1010
static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:626
void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6018
void set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6056
void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6078

References Assert(), elog, ERROR, RangeTblEntry::inh, IS_DUMMY_REL, relation_excluded_by_constraints(), RELOPT_BASEREL, RelOptInfo::reloptkind, root, RelOptInfo::rows, RTE_CTE, RTE_FUNCTION, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RelOptInfo::rtekind, set_append_rel_size(), set_cte_pathlist(), set_dummy_rel_pathlist(), set_foreign_size(), set_function_size_estimates(), set_namedtuplestore_pathlist(), set_plain_rel_size(), set_result_pathlist(), set_subquery_pathlist(), set_tablefunc_size_estimates(), set_tablesample_rel_size(), set_values_size_estimates(), set_worktable_pathlist(), and RangeTblEntry::tablesample.

Referenced by set_append_rel_size(), and set_base_rel_sizes().

◆ set_result_pathlist()

static void set_result_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 3089 of file allpaths.c.

3091{
3092 Relids required_outer;
3093
3094 /* Mark rel with estimated output rows, width, etc */
3096
3097 /*
3098 * We don't support pushing join clauses into the quals of a Result scan,
3099 * but it could still have required parameterization due to LATERAL refs
3100 * in its tlist.
3101 */
3102 required_outer = rel->lateral_relids;
3103
3104 /* Generate appropriate path */
3105 add_path(rel, create_resultscan_path(root, rel, required_outer));
3106}
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6181
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2005

References add_path(), create_resultscan_path(), RelOptInfo::lateral_relids, root, and set_result_size_estimates().

Referenced by set_rel_size().

◆ set_subquery_pathlist()

static void set_subquery_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 2603 of file allpaths.c.

2605{
2606 Query *parse = root->parse;
2607 Query *subquery = rte->subquery;
2608 bool trivial_pathtarget;
2609 Relids required_outer;
2610 pushdown_safety_info safetyInfo;
2611 double tuple_fraction;
2612 RelOptInfo *sub_final_rel;
2613 Bitmapset *run_cond_attrs = NULL;
2614 ListCell *lc;
2615 char *plan_name;
2616
2617 /*
2618 * Must copy the Query so that planning doesn't mess up the RTE contents
2619 * (really really need to fix the planner to not scribble on its input,
2620 * someday ... but see remove_unused_subquery_outputs to start with).
2621 */
2622 subquery = copyObject(subquery);
2623
2624 /*
2625 * If it's a LATERAL subquery, it might contain some Vars of the current
2626 * query level, requiring it to be treated as parameterized, even though
2627 * we don't support pushing down join quals into subqueries.
2628 */
2629 required_outer = rel->lateral_relids;
2630
2631 /*
2632 * Zero out result area for subquery_is_pushdown_safe, so that it can set
2633 * flags as needed while recursing. In particular, we need a workspace
2634 * for keeping track of the reasons why columns are unsafe to reference.
2635 * These reasons are stored in the bits inside unsafeFlags[i] when we
2636 * discover reasons that column i of the subquery is unsafe to be used in
2637 * a pushed-down qual.
2638 */
2639 memset(&safetyInfo, 0, sizeof(safetyInfo));
2640 safetyInfo.unsafeFlags = (unsigned char *)
2641 palloc0((list_length(subquery->targetList) + 1) * sizeof(unsigned char));
2642
2643 /*
2644 * If the subquery has the "security_barrier" flag, it means the subquery
2645 * originated from a view that must enforce row-level security. Then we
2646 * must not push down quals that contain leaky functions. (Ideally this
2647 * would be checked inside subquery_is_pushdown_safe, but since we don't
2648 * currently pass the RTE to that function, we must do it here.)
2649 */
2650 safetyInfo.unsafeLeaky = rte->security_barrier;
2651
2652 /*
2653 * If there are any restriction clauses that have been attached to the
2654 * subquery relation, consider pushing them down to become WHERE or HAVING
2655 * quals of the subquery itself. This transformation is useful because it
2656 * may allow us to generate a better plan for the subquery than evaluating
2657 * all the subquery output rows and then filtering them.
2658 *
2659 * There are several cases where we cannot push down clauses. Restrictions
2660 * involving the subquery are checked by subquery_is_pushdown_safe().
2661 * Restrictions on individual clauses are checked by
2662 * qual_is_pushdown_safe(). Also, we don't want to push down
2663 * pseudoconstant clauses; better to have the gating node above the
2664 * subquery.
2665 *
2666 * Non-pushed-down clauses will get evaluated as qpquals of the
2667 * SubqueryScan node.
2668 *
2669 * XXX Are there any cases where we want to make a policy decision not to
2670 * push down a pushable qual, because it'd result in a worse plan?
2671 */
2672 if (rel->baserestrictinfo != NIL &&
2673 subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2674 {
2675 /* OK to consider pushing down individual quals */
2676 List *upperrestrictlist = NIL;
2677 ListCell *l;
2678
2679 foreach(l, rel->baserestrictinfo)
2680 {
2681 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2682 Node *clause = (Node *) rinfo->clause;
2683
2684 if (rinfo->pseudoconstant)
2685 {
2686 upperrestrictlist = lappend(upperrestrictlist, rinfo);
2687 continue;
2688 }
2689
2690 switch (qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2691 {
2692 case PUSHDOWN_SAFE:
2693 /* Push it down */
2694 subquery_push_qual(subquery, rte, rti, clause);
2695 break;
2696
2698
2699 /*
2700 * Since we can't push the qual down into the subquery,
2701 * check if it happens to reference a window function. If
2702 * so then it might be useful to use for the WindowAgg's
2703 * runCondition.
2704 */
2705 if (!subquery->hasWindowFuncs ||
2706 check_and_push_window_quals(subquery, clause,
2707 &run_cond_attrs))
2708 {
2709 /*
2710 * subquery has no window funcs or the clause is not a
2711 * suitable window run condition qual or it is, but
2712 * the original must also be kept in the upper query.
2713 */
2714 upperrestrictlist = lappend(upperrestrictlist, rinfo);
2715 }
2716 break;
2717
2718 case PUSHDOWN_UNSAFE:
2719 upperrestrictlist = lappend(upperrestrictlist, rinfo);
2720 break;
2721 }
2722 }
2723 rel->baserestrictinfo = upperrestrictlist;
2724 /* We don't bother recomputing baserestrict_min_security */
2725 }
2726
2727 pfree(safetyInfo.unsafeFlags);
2728
2729 /*
2730 * The upper query might not use all the subquery's output columns; if
2731 * not, we can simplify. Pass the attributes that were pushed down into
2732 * WindowAgg run conditions to ensure we don't accidentally think those
2733 * are unused.
2734 */
2735 remove_unused_subquery_outputs(subquery, rel, run_cond_attrs);
2736
2737 /*
2738 * We can safely pass the outer tuple_fraction down to the subquery if the
2739 * outer level has no joining, aggregation, or sorting to do. Otherwise
2740 * we'd better tell the subquery to plan for full retrieval. (XXX This
2741 * could probably be made more intelligent ...)
2742 */
2743 if (parse->hasAggs ||
2744 parse->groupClause ||
2745 parse->groupingSets ||
2746 root->hasHavingQual ||
2747 parse->distinctClause ||
2748 parse->sortClause ||
2749 bms_membership(root->all_baserels) == BMS_MULTIPLE)
2750 tuple_fraction = 0.0; /* default case */
2751 else
2752 tuple_fraction = root->tuple_fraction;
2753
2754 /* plan_params should not be in use in current query level */
2755 Assert(root->plan_params == NIL);
2756
2757 /* Generate a subroot and Paths for the subquery */
2758 plan_name = choose_plan_name(root->glob, rte->eref->aliasname, false);
2759 rel->subroot = subquery_planner(root->glob, subquery, plan_name,
2760 root, false, tuple_fraction, NULL);
2761
2762 /* Isolate the params needed by this specific subplan */
2763 rel->subplan_params = root->plan_params;
2764 root->plan_params = NIL;
2765
2766 /*
2767 * It's possible that constraint exclusion proved the subquery empty. If
2768 * so, it's desirable to produce an unadorned dummy path so that we will
2769 * recognize appropriate optimizations at this query level.
2770 */
2771 sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2772
2773 if (IS_DUMMY_REL(sub_final_rel))
2774 {
2776 return;
2777 }
2778
2779 /*
2780 * Mark rel with estimated output rows, width, etc. Note that we have to
2781 * do this before generating outer-query paths, else cost_subqueryscan is
2782 * not happy.
2783 */
2785
2786 /*
2787 * Also detect whether the reltarget is trivial, so that we can pass that
2788 * info to cost_subqueryscan (rather than re-deriving it multiple times).
2789 * It's trivial if it fetches all the subplan output columns in order.
2790 */
2791 if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2792 trivial_pathtarget = false;
2793 else
2794 {
2795 trivial_pathtarget = true;
2796 foreach(lc, rel->reltarget->exprs)
2797 {
2798 Node *node = (Node *) lfirst(lc);
2799 Var *var;
2800
2801 if (!IsA(node, Var))
2802 {
2803 trivial_pathtarget = false;
2804 break;
2805 }
2806 var = (Var *) node;
2807 if (var->varno != rti ||
2808 var->varattno != foreach_current_index(lc) + 1)
2809 {
2810 trivial_pathtarget = false;
2811 break;
2812 }
2813 }
2814 }
2815
2816 /*
2817 * For each Path that subquery_planner produced, make a SubqueryScanPath
2818 * in the outer query.
2819 */
2820 foreach(lc, sub_final_rel->pathlist)
2821 {
2822 Path *subpath = (Path *) lfirst(lc);
2823 List *pathkeys;
2824
2825 /* Convert subpath's pathkeys to outer representation */
2827 rel,
2828 subpath->pathkeys,
2829 make_tlist_from_pathtarget(subpath->pathtarget));
2830
2831 /* Generate outer path using this subpath */
2832 add_path(rel, (Path *)
2834 trivial_pathtarget,
2835 pathkeys, required_outer));
2836 }
2837
2838 /* If outer rel allows parallelism, do same for partial paths. */
2839 if (rel->consider_parallel && bms_is_empty(required_outer))
2840 {
2841 /* If consider_parallel is false, there should be no partial paths. */
2842 Assert(sub_final_rel->consider_parallel ||
2843 sub_final_rel->partial_pathlist == NIL);
2844
2845 /* Same for partial paths. */
2846 foreach(lc, sub_final_rel->partial_pathlist)
2847 {
2848 Path *subpath = (Path *) lfirst(lc);
2849 List *pathkeys;
2850
2851 /* Convert subpath's pathkeys to outer representation */
2853 rel,
2854 subpath->pathkeys,
2855 make_tlist_from_pathtarget(subpath->pathtarget));
2856
2857 /* Generate outer path using this subpath */
2858 add_partial_path(rel, (Path *)
2860 trivial_pathtarget,
2861 pathkeys,
2862 required_outer));
2863 }
2864 }
2865}
static pushdown_safe_type qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:4340
static bool check_and_push_window_quals(Query *subquery, Node *clause, Bitmapset **run_cond_attrs)
Definition: allpaths.c:2530
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
Definition: allpaths.c:4541
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
@ BMS_MULTIPLE
Definition: bitmapset.h:73
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5938
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, bool trivial_pathtarget, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1845
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
char * choose_plan_name(PlannerGlobal *glob, const char *name, bool always_number)
Definition: planner.c:8944
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition: planner.c:693
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1581
List * subplan_params
Definition: pathnodes.h:1008
PlannerInfo * subroot
Definition: pathnodes.h:1007

References add_partial_path(), add_path(), Assert(), RelOptInfo::baserestrictinfo, bms_is_empty, bms_membership(), BMS_MULTIPLE, check_and_push_window_quals(), choose_plan_name(), RestrictInfo::clause, RelOptInfo::consider_parallel, convert_subquery_pathkeys(), copyObject, create_subqueryscan_path(), PathTarget::exprs, fetch_upper_rel(), foreach_current_index, if(), IS_DUMMY_REL, IsA, lappend(), RelOptInfo::lateral_relids, lfirst, list_length(), make_tlist_from_pathtarget(), NIL, palloc0(), parse(), RelOptInfo::partial_pathlist, RelOptInfo::pathlist, pfree(), PUSHDOWN_SAFE, PUSHDOWN_UNSAFE, PUSHDOWN_WINDOWCLAUSE_RUNCOND, qual_is_pushdown_safe(), RelOptInfo::reltarget, remove_unused_subquery_outputs(), root, set_dummy_rel_pathlist(), set_subquery_size_estimates(), subpath(), RelOptInfo::subplan_params, RangeTblEntry::subquery, subquery_is_pushdown_safe(), subquery_planner(), subquery_push_qual(), RelOptInfo::subroot, Query::targetList, pushdown_safety_info::unsafeFlags, pushdown_safety_info::unsafeLeaky, UPPERREL_FINAL, Var::varattno, and Var::varno.

Referenced by set_rel_size().

◆ set_tablefunc_pathlist()

static void set_tablefunc_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 2959 of file allpaths.c.

2960{
2961 Relids required_outer;
2962
2963 /*
2964 * We don't support pushing join clauses into the quals of a tablefunc
2965 * scan, but it could still have required parameterization due to LATERAL
2966 * refs in the function expression.
2967 */
2968 required_outer = rel->lateral_relids;
2969
2970 /* Generate appropriate path */
2972 required_outer));
2973}
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1901

References add_path(), create_tablefuncscan_path(), RelOptInfo::lateral_relids, and root.

Referenced by set_rel_pathlist().

◆ set_tablesample_rel_pathlist()

static void set_tablesample_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 920 of file allpaths.c.

921{
922 Relids required_outer;
923 Path *path;
924
925 /*
926 * We don't support pushing join clauses into the quals of a samplescan,
927 * but it could still have required parameterization due to LATERAL refs
928 * in its tlist or TABLESAMPLE arguments.
929 */
930 required_outer = rel->lateral_relids;
931
932 /* Consider sampled scan */
933 path = create_samplescan_path(root, rel, required_outer);
934
935 /*
936 * If the sampling method does not support repeatable scans, we must avoid
937 * plans that would scan the rel multiple times. Ideally, we'd simply
938 * avoid putting the rel on the inside of a nestloop join; but adding such
939 * a consideration to the planner seems like a great deal of complication
940 * to support an uncommon usage of second-rate sampling methods. Instead,
941 * if there is a risk that the query might perform an unsafe join, just
942 * wrap the SampleScan in a Materialize node. We can check for joins by
943 * counting the membership of all_query_rels (note that this correctly
944 * counts inheritance trees as single rels). If we're inside a subquery,
945 * we can't easily check whether a join might occur in the outer query, so
946 * just assume one is possible.
947 *
948 * GetTsmRoutine is relatively expensive compared to the other tests here,
949 * so check repeatable_across_scans last, even though that's a bit odd.
950 */
951 if ((root->query_level > 1 ||
952 bms_membership(root->all_query_rels) != BMS_SINGLETON) &&
954 {
955 path = (Path *) create_material_path(rel, path);
956 }
957
958 add_path(rel, path);
959
960 /* For the moment, at least, there are no other paths to consider */
961}
@ BMS_SINGLETON
Definition: bitmapset.h:72
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1007
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1656
bool repeatable_across_scans
Definition: tsmapi.h:65
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

References add_path(), bms_membership(), BMS_SINGLETON, create_material_path(), create_samplescan_path(), GetTsmRoutine(), RelOptInfo::lateral_relids, TsmRoutine::repeatable_across_scans, root, RangeTblEntry::tablesample, and TableSampleClause::tsmhandler.

Referenced by set_rel_pathlist().

◆ set_tablesample_rel_size()

static void set_tablesample_rel_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 880 of file allpaths.c.

881{
882 TableSampleClause *tsc = rte->tablesample;
883 TsmRoutine *tsm;
884 BlockNumber pages;
885 double tuples;
886
887 /*
888 * Test any partial indexes of rel for applicability. We must do this
889 * first since partial unique indexes can affect size estimates.
890 */
892
893 /*
894 * Call the sampling method's estimation function to estimate the number
895 * of pages it will read and the number of tuples it will return. (Note:
896 * we assume the function returns sane values.)
897 */
898 tsm = GetTsmRoutine(tsc->tsmhandler);
899 tsm->SampleScanGetSampleSize(root, rel, tsc->args,
900 &pages, &tuples);
901
902 /*
903 * For the moment, because we will only consider a SampleScan path for the
904 * rel, it's okay to just overwrite the pages and tuples estimates for the
905 * whole relation. If we ever consider multiple path types for sampled
906 * rels, we'll need more complication.
907 */
908 rel->pages = pages;
909 rel->tuples = tuples;
910
911 /* Mark rel with estimated output rows, width, etc */
913}
SampleScanGetSampleSize_function SampleScanGetSampleSize
Definition: tsmapi.h:68

References TableSampleClause::args, check_index_predicates(), GetTsmRoutine(), RelOptInfo::pages, root, TsmRoutine::SampleScanGetSampleSize, set_baserel_size_estimates(), RangeTblEntry::tablesample, TableSampleClause::tsmhandler, and RelOptInfo::tuples.

Referenced by set_rel_size().

◆ set_values_pathlist()

static void set_values_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 2939 of file allpaths.c.

2940{
2941 Relids required_outer;
2942
2943 /*
2944 * We don't support pushing join clauses into the quals of a values scan,
2945 * but it could still have required parameterization due to LATERAL refs
2946 * in the values expressions.
2947 */
2948 required_outer = rel->lateral_relids;
2949
2950 /* Generate appropriate path */
2951 add_path(rel, create_valuesscan_path(root, rel, required_outer));
2952}
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1927

References add_path(), create_valuesscan_path(), RelOptInfo::lateral_relids, and root.

Referenced by set_rel_pathlist().

◆ set_worktable_pathlist()

static void set_worktable_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 3116 of file allpaths.c.

3117{
3118 Path *ctepath;
3119 PlannerInfo *cteroot;
3120 Index levelsup;
3121 Relids required_outer;
3122
3123 /*
3124 * We need to find the non-recursive term's path, which is in the plan
3125 * level that's processing the recursive UNION, which is one level *below*
3126 * where the CTE comes from.
3127 */
3128 levelsup = rte->ctelevelsup;
3129 if (levelsup == 0) /* shouldn't happen */
3130 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3131 levelsup--;
3132 cteroot = root;
3133 while (levelsup-- > 0)
3134 {
3135 cteroot = cteroot->parent_root;
3136 if (!cteroot) /* shouldn't happen */
3137 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3138 }
3139 ctepath = cteroot->non_recursive_path;
3140 if (!ctepath) /* shouldn't happen */
3141 elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
3142
3143 /* Mark rel with estimated output rows, width, etc */
3144 set_cte_size_estimates(root, rel, ctepath->rows);
3145
3146 /*
3147 * We don't support pushing join clauses into the quals of a worktable
3148 * scan, but it could still have required parameterization due to LATERAL
3149 * refs in its tlist. (I'm not sure this is actually possible given the
3150 * restrictions on recursive references, but it's easy enough to support.)
3151 */
3152 required_outer = rel->lateral_relids;
3153
3154 /* Generate appropriate path */
3155 add_path(rel, create_worktablescan_path(root, rel, required_outer));
3156}
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2031
struct Path * non_recursive_path
Definition: pathnodes.h:577

References add_path(), create_worktablescan_path(), RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, elog, ERROR, RelOptInfo::lateral_relids, PlannerInfo::non_recursive_path, root, Path::rows, and set_cte_size_estimates().

Referenced by set_rel_size().

◆ setup_simple_grouped_rels()

static void setup_simple_grouped_rels ( PlannerInfo root)
static

Definition at line 344 of file allpaths.c.

345{
346 Index rti;
347
348 /*
349 * If there are no aggregate expressions or grouping expressions, eager
350 * aggregation is not possible.
351 */
352 if (root->agg_clause_list == NIL ||
353 root->group_expr_list == NIL)
354 return;
355
356 for (rti = 1; rti < root->simple_rel_array_size; rti++)
357 {
358 RelOptInfo *rel = root->simple_rel_array[rti];
359
360 /* there may be empty slots corresponding to non-baserel RTEs */
361 if (rel == NULL)
362 continue;
363
364 Assert(rel->relid == rti); /* sanity check on array */
365 Assert(IS_SIMPLE_REL(rel)); /* sanity check on rel */
366
367 (void) build_simple_grouped_rel(root, rel);
368 }
369}
RelOptInfo * build_simple_grouped_rel(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:433

References Assert(), build_simple_grouped_rel(), IS_SIMPLE_REL, NIL, RelOptInfo::relid, and root.

Referenced by make_one_rel().

◆ standard_join_search()

RelOptInfo * standard_join_search ( PlannerInfo root,
int  levels_needed,
List initial_rels 
)

Definition at line 3872 of file allpaths.c.

3873{
3874 int lev;
3875 RelOptInfo *rel;
3876
3877 /*
3878 * This function cannot be invoked recursively within any one planning
3879 * problem, so join_rel_level[] can't be in use already.
3880 */
3881 Assert(root->join_rel_level == NULL);
3882
3883 /*
3884 * We employ a simple "dynamic programming" algorithm: we first find all
3885 * ways to build joins of two jointree items, then all ways to build joins
3886 * of three items (from two-item joins and single items), then four-item
3887 * joins, and so on until we have considered all ways to join all the
3888 * items into one rel.
3889 *
3890 * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3891 * set root->join_rel_level[1] to represent all the single-jointree-item
3892 * relations.
3893 */
3894 root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3895
3896 root->join_rel_level[1] = initial_rels;
3897
3898 for (lev = 2; lev <= levels_needed; lev++)
3899 {
3900 ListCell *lc;
3901
3902 /*
3903 * Determine all possible pairs of relations to be joined at this
3904 * level, and build paths for making each one from every available
3905 * pair of lower-level relations.
3906 */
3908
3909 /*
3910 * Run generate_partitionwise_join_paths() and
3911 * generate_useful_gather_paths() for each just-processed joinrel. We
3912 * could not do this earlier because both regular and partial paths
3913 * can get added to a particular joinrel at multiple times within
3914 * join_search_one_level.
3915 *
3916 * After that, we're done creating paths for the joinrel, so run
3917 * set_cheapest().
3918 *
3919 * In addition, we also run generate_grouped_paths() for the grouped
3920 * relation of each just-processed joinrel, and run set_cheapest() for
3921 * the grouped relation afterwards.
3922 */
3923 foreach(lc, root->join_rel_level[lev])
3924 {
3925 bool is_top_rel;
3926
3927 rel = (RelOptInfo *) lfirst(lc);
3928
3929 is_top_rel = bms_equal(rel->relids, root->all_query_rels);
3930
3931 /* Create paths for partitionwise joins. */
3933
3934 /*
3935 * Except for the topmost scan/join rel, consider gathering
3936 * partial paths. We'll do the same for the topmost scan/join rel
3937 * once we know the final targetlist (see grouping_planner's and
3938 * its call to apply_scanjoin_target_to_paths).
3939 */
3940 if (!is_top_rel)
3942
3943 /* Find and save the cheapest paths for this rel */
3944 set_cheapest(rel);
3945
3946 /*
3947 * Except for the topmost scan/join rel, consider generating
3948 * partial aggregation paths for the grouped relation on top of
3949 * the paths of this rel. After that, we're done creating paths
3950 * for the grouped relation, so run set_cheapest().
3951 */
3952 if (rel->grouped_rel != NULL && !is_top_rel)
3953 {
3954 RelOptInfo *grouped_rel = rel->grouped_rel;
3955
3956 Assert(IS_GROUPED_REL(grouped_rel));
3957
3958 generate_grouped_paths(root, grouped_rel, rel);
3959 set_cheapest(grouped_rel);
3960 }
3961
3962#ifdef OPTIMIZER_DEBUG
3963 pprint(rel);
3964#endif
3965 }
3966 }
3967
3968 /*
3969 * We should have a single rel at the final level.
3970 */
3971 if (root->join_rel_level[levels_needed] == NIL)
3972 elog(ERROR, "failed to build any %d-way joins", levels_needed);
3973 Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3974
3975 rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3976
3977 root->join_rel_level = NULL;
3978
3979 return rel;
3980}
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:78

References Assert(), bms_equal(), elog, ERROR, generate_grouped_paths(), generate_partitionwise_join_paths(), generate_useful_gather_paths(), RelOptInfo::grouped_rel, IS_GROUPED_REL, join_search_one_level(), lfirst, linitial, list_length(), NIL, palloc0(), pprint(), RelOptInfo::relids, root, and set_cheapest().

Referenced by make_rel_from_joinlist().

◆ subquery_is_pushdown_safe()

static bool subquery_is_pushdown_safe ( Query subquery,
Query topquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4067 of file allpaths.c.

4069{
4070 SetOperationStmt *topop;
4071
4072 /* Check point 1 */
4073 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
4074 return false;
4075
4076 /* Check point 6 */
4077 if (subquery->groupClause && subquery->groupingSets)
4078 return false;
4079
4080 /* Check points 3, 4, and 5 */
4081 if (subquery->distinctClause ||
4082 subquery->hasWindowFuncs ||
4083 subquery->hasTargetSRFs)
4084 safetyInfo->unsafeVolatile = true;
4085
4086 /*
4087 * If we're at a leaf query, check for unsafe expressions in its target
4088 * list, and mark any reasons why they're unsafe in unsafeFlags[].
4089 * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
4090 * so no need to check them.)
4091 */
4092 if (subquery->setOperations == NULL)
4093 check_output_expressions(subquery, safetyInfo);
4094
4095 /* Are we at top level, or looking at a setop component? */
4096 if (subquery == topquery)
4097 {
4098 /* Top level, so check any component queries */
4099 if (subquery->setOperations != NULL)
4100 if (!recurse_pushdown_safe(subquery->setOperations, topquery,
4101 safetyInfo))
4102 return false;
4103 }
4104 else
4105 {
4106 /* Setop component must not have more components (too weird) */
4107 if (subquery->setOperations != NULL)
4108 return false;
4109 /* Check whether setop component output types match top level */
4110 topop = castNode(SetOperationStmt, topquery->setOperations);
4111 Assert(topop);
4113 topop->colTypes,
4114 safetyInfo);
4115 }
4116 return true;
4117}
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:4264
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:4192
Node * limitCount
Definition: parsenodes.h:231
List * groupClause
Definition: parsenodes.h:216
Node * limitOffset
Definition: parsenodes.h:230
List * groupingSets
Definition: parsenodes.h:220

References Assert(), castNode, check_output_expressions(), compare_tlist_datatypes(), Query::distinctClause, Query::groupClause, Query::groupingSets, Query::limitCount, Query::limitOffset, recurse_pushdown_safe(), Query::setOperations, Query::targetList, and pushdown_safety_info::unsafeVolatile.

Referenced by recurse_pushdown_safe(), and set_subquery_pathlist().

◆ subquery_push_qual()

static void subquery_push_qual ( Query subquery,
RangeTblEntry rte,
Index  rti,
Node qual 
)
static

Definition at line 4441 of file allpaths.c.

4442{
4443 if (subquery->setOperations != NULL)
4444 {
4445 /* Recurse to push it separately to each component query */
4446 recurse_push_qual(subquery->setOperations, subquery,
4447 rte, rti, qual);
4448 }
4449 else
4450 {
4451 /*
4452 * We need to replace Vars in the qual (which must refer to outputs of
4453 * the subquery) with copies of the subquery's targetlist expressions.
4454 * Note that at this point, any uplevel Vars in the qual should have
4455 * been replaced with Params, so they need no work.
4456 *
4457 * This step also ensures that when we are pushing into a setop tree,
4458 * each component query gets its own copy of the qual.
4459 */
4460 qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
4461 subquery->targetList,
4462 subquery->resultRelation,
4464 &subquery->hasSubLinks);
4465
4466 /*
4467 * Now attach the qual to the proper place: normally WHERE, but if the
4468 * subquery uses grouping or aggregation, put it in HAVING (since the
4469 * qual really refers to the group-result rows).
4470 */
4471 if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
4472 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
4473 else
4474 subquery->jointree->quals =
4475 make_and_qual(subquery->jointree->quals, qual);
4476
4477 /*
4478 * We need not change the subquery's hasAggs or hasSubLinks flags,
4479 * since we can't be pushing down any aggregates that weren't there
4480 * before, and we don't push down subselects at all.
4481 */
4482 }
4483}
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:780
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, int result_relation, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
@ REPLACEVARS_REPORT_ERROR
Definition: rewriteManip.h:39
Node * quals
Definition: primnodes.h:2358
FromExpr * jointree
Definition: parsenodes.h:182
Node * havingQual
Definition: parsenodes.h:222

References Query::groupClause, Query::groupingSets, Query::havingQual, Query::jointree, make_and_qual(), FromExpr::quals, recurse_push_qual(), REPLACEVARS_REPORT_ERROR, ReplaceVarsFromTargetList(), Query::setOperations, and Query::targetList.

Referenced by recurse_push_qual(), and set_subquery_pathlist().

◆ targetIsInAllPartitionLists()

static bool targetIsInAllPartitionLists ( TargetEntry tle,
Query query 
)
static

Definition at line 4297 of file allpaths.c.

4298{
4299 ListCell *lc;
4300
4301 foreach(lc, query->windowClause)
4302 {
4303 WindowClause *wc = (WindowClause *) lfirst(lc);
4304
4306 return false;
4307 }
4308 return true;
4309}
List * partitionClause
Definition: parsenodes.h:1574

References InvalidOid, lfirst, WindowClause::partitionClause, targetIsInSortList(), and Query::windowClause.

Referenced by check_output_expressions().

Variable Documentation

◆ enable_eager_aggregate

bool enable_eager_aggregate = true

Definition at line 82 of file allpaths.c.

Referenced by setup_eager_aggregation().

◆ enable_geqo

bool enable_geqo = false

Definition at line 81 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ geqo_threshold

int geqo_threshold

Definition at line 83 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

join_search_hook_type join_search_hook = NULL

Definition at line 92 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_eager_agg_group_size

double min_eager_agg_group_size

Definition at line 84 of file allpaths.c.

Referenced by create_rel_agg_info().

◆ min_parallel_index_scan_size

int min_parallel_index_scan_size

Definition at line 86 of file allpaths.c.

Referenced by compute_parallel_worker(), and parallel_vacuum_compute_workers().

◆ min_parallel_table_scan_size

int min_parallel_table_scan_size

Definition at line 85 of file allpaths.c.

Referenced by compute_parallel_worker().

◆ set_rel_pathlist_hook

set_rel_pathlist_hook_type set_rel_pathlist_hook = NULL

Definition at line 89 of file allpaths.c.

Referenced by set_rel_pathlist().