PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, List **child_append_relid_sets)
 
static Pathget_singleton_append_subpath (Path *path, List **child_append_relid_sets)
 
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,
List **  child_append_relid_sets 
)
static

Definition at line 2242 of file allpaths.c.

2244{
2245 if (IsA(path, AppendPath))
2246 {
2247 AppendPath *apath = (AppendPath *) path;
2248
2249 if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2250 {
2251 *subpaths = list_concat(*subpaths, apath->subpaths);
2252 *child_append_relid_sets =
2253 lappend(*child_append_relid_sets, path->parent->relids);
2254 *child_append_relid_sets =
2255 list_concat(*child_append_relid_sets,
2256 apath->child_append_relid_sets);
2257 return;
2258 }
2259 else if (special_subpaths != NULL)
2260 {
2262
2263 /* Split Parallel Append into partial and non-partial subpaths */
2264 *subpaths = list_concat(*subpaths,
2265 list_copy_tail(apath->subpaths,
2266 apath->first_partial_path));
2268 apath->first_partial_path);
2271 *child_append_relid_sets =
2272 lappend(*child_append_relid_sets, path->parent->relids);
2273 *child_append_relid_sets =
2274 list_concat(*child_append_relid_sets,
2275 apath->child_append_relid_sets);
2276 return;
2277 }
2278 }
2279 else if (IsA(path, MergeAppendPath))
2280 {
2282
2283 *subpaths = list_concat(*subpaths, mpath->subpaths);
2284 *child_append_relid_sets =
2285 lappend(*child_append_relid_sets, path->parent->relids);
2286 *child_append_relid_sets =
2287 list_concat(*child_append_relid_sets,
2288 mpath->child_append_relid_sets);
2289 return;
2290 }
2291
2292 *subpaths = lappend(*subpaths, path);
2293}
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
static int fb(int x)
Definition pg_list.h:54

References fb(), IsA, lappend(), list_concat(), list_copy_head(), and list_copy_tail().

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 1406 of file allpaths.c.

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

References accumulate_append_subpath(), add_partial_path(), add_path(), Assert, bms_equal(), AppendPathInput::child_append_relid_sets, compare_pathkeys(), RelOptInfo::consider_parallel, RelOptInfo::consider_startup, create_append_path(), enable_parallel_append, fb(), 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, AppendPathInput::partial_subpaths, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, pg_leftmost_one_pos32(), root, subpath(), and AppendPathInput::subpaths.

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 2596 of file allpaths.c.

2598{
2599 OpExpr *opexpr = (OpExpr *) clause;
2600 bool keep_original = true;
2601 Var *var1;
2602 Var *var2;
2603
2604 /* We're only able to use OpExprs with 2 operands */
2605 if (!IsA(opexpr, OpExpr))
2606 return true;
2607
2608 if (list_length(opexpr->args) != 2)
2609 return true;
2610
2611 /*
2612 * Currently, we restrict this optimization to strict OpExprs. The reason
2613 * for this is that during execution, once the runcondition becomes false,
2614 * we stop evaluating WindowFuncs. To avoid leaving around stale window
2615 * function result values, we set them to NULL. Having only strict
2616 * OpExprs here ensures that we properly filter out the tuples with NULLs
2617 * in the top-level WindowAgg.
2618 */
2619 set_opfuncid(opexpr);
2620 if (!func_strict(opexpr->opfuncid))
2621 return true;
2622
2623 /*
2624 * Check for plain Vars that reference window functions in the subquery.
2625 * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2626 * be used as part of the run condition.
2627 */
2628
2629 /* Check the left side of the OpExpr */
2630 var1 = linitial(opexpr->args);
2631 if (IsA(var1, Var) && var1->varattno > 0)
2632 {
2633 TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2634 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2635
2636 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2638 return keep_original;
2639 }
2640
2641 /* and check the right side */
2642 var2 = lsecond(opexpr->args);
2643 if (IsA(var2, Var) && var2->varattno > 0)
2644 {
2645 TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2646 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2647
2648 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2649 false, &keep_original, run_cond_attrs))
2650 return keep_original;
2651 }
2652
2653 return true;
2654}
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:2406
bool func_strict(Oid funcid)
Definition lsyscache.c:1911
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1871
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:869
List * targetList
Definition parsenodes.h:198

References OpExpr::args, fb(), find_window_run_conditions(), func_strict(), IsA, linitial, list_length(), list_nth(), lsecond, set_opfuncid(), and Query::targetList.

Referenced by set_subquery_pathlist().

◆ check_output_expressions()

static void check_output_expressions ( Query subquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 4258 of file allpaths.c.

4259{
4261 ListCell *lc;
4262
4263 /*
4264 * We must be careful with grouping Vars and join alias Vars in the
4265 * subquery's outputs, as they hide the underlying expressions.
4266 *
4267 * We need to expand grouping Vars to their underlying expressions (the
4268 * grouping clauses) because the grouping expressions themselves might be
4269 * volatile or set-returning. However, we do not need to expand join
4270 * alias Vars, as their underlying structure does not introduce volatile
4271 * or set-returning functions at the current level.
4272 *
4273 * In neither case do we need to recursively examine the Vars contained in
4274 * these underlying expressions. Even if they reference outputs from
4275 * lower-level subqueries (at any depth), those references are guaranteed
4276 * not to expand to volatile or set-returning functions, because
4277 * subqueries containing such functions in their targetlists are never
4278 * pulled up.
4279 */
4280 if (subquery->hasGroupRTE)
4281 {
4283 flatten_group_exprs(NULL, subquery, (Node *) subquery->targetList);
4284 }
4285
4286 foreach(lc, flattened_targetList)
4287 {
4289
4290 if (tle->resjunk)
4291 continue; /* ignore resjunk columns */
4292
4293 /* Functions returning sets are unsafe (point 1) */
4294 if (subquery->hasTargetSRFs &&
4295 (safetyInfo->unsafeFlags[tle->resno] &
4296 UNSAFE_HAS_SET_FUNC) == 0 &&
4297 expression_returns_set((Node *) tle->expr))
4298 {
4299 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
4300 continue;
4301 }
4302
4303 /* Volatile functions are unsafe (point 2) */
4304 if ((safetyInfo->unsafeFlags[tle->resno] &
4307 {
4308 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
4309 continue;
4310 }
4311
4312 /* If subquery uses DISTINCT ON, check point 3 */
4313 if (subquery->hasDistinctOn &&
4314 (safetyInfo->unsafeFlags[tle->resno] &
4317 {
4318 /* non-DISTINCT column, so mark it unsafe */
4319 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_DISTINCTON_CLAUSE;
4320 continue;
4321 }
4322
4323 /* If subquery uses window functions, check point 4 */
4324 if (subquery->hasWindowFuncs &&
4325 (safetyInfo->unsafeFlags[tle->resno] &
4327 !targetIsInAllPartitionLists(tle, subquery))
4328 {
4329 /* not present in all PARTITION BY clauses, so mark it unsafe */
4330 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_PARTITIONBY_CLAUSE;
4331 continue;
4332 }
4333 }
4334}
#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:4387
#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:547
bool expression_returns_set(Node *clause)
Definition nodeFuncs.c:763
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition nodes.h:135
List * distinctClause
Definition parsenodes.h:226
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition var.c:972

References contain_volatile_functions(), Query::distinctClause, expression_returns_set(), fb(), flatten_group_exprs(), InvalidOid, lfirst, targetIsInAllPartitionLists(), targetIsInSortList(), Query::targetList, UNSAFE_HAS_SET_FUNC, UNSAFE_HAS_VOLATILE_FUNC, UNSAFE_NOTIN_DISTINCTON_CLAUSE, and UNSAFE_NOTIN_PARTITIONBY_CLAUSE.

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 4354 of file allpaths.c.

4356{
4357 ListCell *l;
4359
4360 foreach(l, tlist)
4361 {
4363
4364 if (tle->resjunk)
4365 continue; /* ignore resjunk columns */
4366 if (colType == NULL)
4367 elog(ERROR, "wrong number of tlist entries");
4368 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
4369 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
4371 }
4372 if (colType != NULL)
4373 elog(ERROR, "wrong number of tlist entries");
4374}
#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, exprType(), fb(), lfirst, lfirst_oid, list_head(), lnext(), and UNSAFE_TYPE_MISMATCH.

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 4779 of file allpaths.c.

4781{
4782 int parallel_workers = 0;
4783
4784 /*
4785 * If the user has set the parallel_workers reloption, use that; otherwise
4786 * select a default number of workers.
4787 */
4788 if (rel->rel_parallel_workers != -1)
4789 parallel_workers = rel->rel_parallel_workers;
4790 else
4791 {
4792 /*
4793 * If the number of pages being scanned is insufficient to justify a
4794 * parallel scan, just return zero ... unless it's an inheritance
4795 * child. In that case, we want to generate a parallel path here
4796 * anyway. It might not be worthwhile just for this relation, but
4797 * when combined with all of its inheritance siblings it may well pay
4798 * off.
4799 */
4800 if (rel->reloptkind == RELOPT_BASEREL &&
4803 return 0;
4804
4805 if (heap_pages >= 0)
4806 {
4808 int heap_parallel_workers = 1;
4809
4810 /*
4811 * Select the number of workers based on the log of the size of
4812 * the relation. This probably needs to be a good deal more
4813 * sophisticated, but we need something here for now. Note that
4814 * the upper limit of the min_parallel_table_scan_size GUC is
4815 * chosen to prevent overflow here.
4816 */
4819 {
4823 break; /* avoid overflow */
4824 }
4825
4826 parallel_workers = heap_parallel_workers;
4827 }
4828
4829 if (index_pages >= 0)
4830 {
4831 int index_parallel_workers = 1;
4833
4834 /* same calculation as for heap_pages above */
4837 {
4841 break; /* avoid overflow */
4842 }
4843
4844 if (parallel_workers > 0)
4845 parallel_workers = Min(parallel_workers, index_parallel_workers);
4846 else
4847 parallel_workers = index_parallel_workers;
4848 }
4849 }
4850
4851 /* In no case use more than caller supplied maximum number of workers */
4852 parallel_workers = Min(parallel_workers, max_workers);
4853
4854 return parallel_workers;
4855}
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:965
RelOptKind reloptkind
Definition pathnodes.h:1003
int rel_parallel_workers
Definition pathnodes.h:1091

References fb(), 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(), create_tidscan_paths(), and plan_create_index_workers().

◆ create_partial_bitmap_paths()

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

Definition at line 4743 of file allpaths.c.

4745{
4746 int parallel_workers;
4747 double pages_fetched;
4748
4749 /* Compute heap pages for bitmap heap scan */
4750 pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4751 NULL, NULL);
4752
4753 parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4755
4756 if (parallel_workers <= 0)
4757 return;
4758
4760 bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4761}
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition allpaths.c:4779
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition costsize.c:6656
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition pathnode.c:1102
Relids lateral_relids
Definition pathnodes.h:1052

References add_partial_path(), compute_bitmap_pages(), compute_parallel_worker(), create_bitmap_heap_path(), fb(), 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 862 of file allpaths.c.

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

References add_partial_path(), compute_parallel_worker(), create_seqscan_path(), fb(), 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 2406 of file allpaths.c.

2409{
2411 Expr *otherexpr;
2415 List *opinfos;
2418 ListCell *lc;
2419
2420 *keep_original = true;
2421
2422 while (IsA(wfunc, RelabelType))
2423 wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2424
2425 /* we can only work with window functions */
2426 if (!IsA(wfunc, WindowFunc))
2427 return false;
2428
2429 /* can't use it if there are subplans in the WindowFunc */
2430 if (contain_subplans((Node *) wfunc))
2431 return false;
2432
2433 prosupport = get_func_support(wfunc->winfnoid);
2434
2435 /* Check if there's a support function for 'wfunc' */
2436 if (!OidIsValid(prosupport))
2437 return false;
2438
2439 /* get the Expr from the other side of the OpExpr */
2440 if (wfunc_left)
2441 otherexpr = lsecond(opexpr->args);
2442 else
2443 otherexpr = linitial(opexpr->args);
2444
2445 /*
2446 * The value being compared must not change during the evaluation of the
2447 * window partition.
2448 */
2450 return false;
2451
2452 /* find the window clause belonging to the window function */
2453 wclause = (WindowClause *) list_nth(subquery->windowClause,
2454 wfunc->winref - 1);
2455
2457 req.window_func = wfunc;
2458 req.window_clause = wclause;
2459
2460 /* call the support function */
2463 PointerGetDatum(&req)));
2464
2465 /*
2466 * Nothing to do if the function is neither monotonically increasing nor
2467 * monotonically decreasing.
2468 */
2469 if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2470 return false;
2471
2472 runopexpr = NULL;
2475
2476 foreach(lc, opinfos)
2477 {
2479 CompareType cmptype = opinfo->cmptype;
2480
2481 /* handle < / <= */
2482 if (cmptype == COMPARE_LT || cmptype == COMPARE_LE)
2483 {
2484 /*
2485 * < / <= is supported for monotonically increasing functions in
2486 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2487 * for monotonically decreasing functions.
2488 */
2489 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2490 (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2491 {
2492 *keep_original = false;
2493 runopexpr = opexpr;
2494 runoperator = opexpr->opno;
2495 }
2496 break;
2497 }
2498 /* handle > / >= */
2499 else if (cmptype == COMPARE_GT || cmptype == COMPARE_GE)
2500 {
2501 /*
2502 * > / >= is supported for monotonically decreasing functions in
2503 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2504 * for monotonically increasing functions.
2505 */
2506 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2507 (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2508 {
2509 *keep_original = false;
2510 runopexpr = opexpr;
2511 runoperator = opexpr->opno;
2512 }
2513 break;
2514 }
2515 /* handle = */
2516 else if (cmptype == COMPARE_EQ)
2517 {
2519
2520 /*
2521 * When both monotonically increasing and decreasing then the
2522 * return value of the window function will be the same each time.
2523 * We can simply use 'opexpr' as the run condition without
2524 * modifying it.
2525 */
2527 {
2528 *keep_original = false;
2529 runopexpr = opexpr;
2530 runoperator = opexpr->opno;
2531 break;
2532 }
2533
2534 /*
2535 * When monotonically increasing we make a qual with <wfunc> <=
2536 * <value> or <value> >= <wfunc> in order to filter out values
2537 * which are above the value in the equality condition. For
2538 * monotonically decreasing functions we want to filter values
2539 * below the value in the equality condition.
2540 */
2542 newcmptype = wfunc_left ? COMPARE_LE : COMPARE_GE;
2543 else
2544 newcmptype = wfunc_left ? COMPARE_GE : COMPARE_LE;
2545
2546 /* We must keep the original equality qual */
2547 *keep_original = true;
2548 runopexpr = opexpr;
2549
2550 /* determine the operator to use for the WindowFuncRunCondition */
2552 opinfo->oplefttype,
2553 opinfo->oprighttype,
2554 newcmptype);
2555 break;
2556 }
2557 }
2558
2559 if (runopexpr != NULL)
2560 {
2562
2564 wfuncrc->opno = runoperator;
2565 wfuncrc->inputcollid = runopexpr->inputcollid;
2566 wfuncrc->wfunc_left = wfunc_left;
2568
2569 wfunc->runCondition = lappend(wfunc->runCondition, wfuncrc);
2570
2571 /* record that this attno was used in a run condition */
2574 return true;
2575 }
2576
2577 /* unsupported OpExpr */
2578 return false;
2579}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define OidIsValid(objectId)
Definition c.h:821
bool is_pseudo_constant_clause(Node *clause)
Definition clauses.c:2100
bool contain_subplans(Node *clause)
Definition clauses.c:339
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
Datum arg
Definition elog.c:1322
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
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:2008
List * get_op_index_interpretation(Oid opno)
Definition lsyscache.c:666
#define copyObject(obj)
Definition nodes.h:232
#define makeNode(_type_)
Definition nodes.h:161
@ MONOTONICFUNC_NONE
Definition plannodes.h:1837
@ MONOTONICFUNC_DECREASING
Definition plannodes.h:1839
@ MONOTONICFUNC_INCREASING
Definition plannodes.h:1838
@ MONOTONICFUNC_BOTH
Definition plannodes.h:1840
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
unsigned int Oid
Oid opno
Definition primnodes.h:851
CompareType cmptype
Definition lsyscache.h:28
List * windowClause
Definition parsenodes.h:224
MonotonicFunction monotonic
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References arg, OpExpr::args, bms_add_member(), OpIndexInterpretation::cmptype, COMPARE_EQ, COMPARE_GE, COMPARE_GT, COMPARE_LE, COMPARE_LT, contain_subplans(), copyObject, DatumGetPointer(), fb(), 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, OpExpr::opno, PointerGetDatum(), 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 3241 of file allpaths.c.

3242{
3245 ListCell *lc;
3246 double rows;
3247 double *rowsp = NULL;
3248
3249 /* If there are no partial paths, there's nothing to do here. */
3250 if (rel->partial_pathlist == NIL)
3251 return;
3252
3253 /* Should we override the rel's rowcount estimate? */
3254 if (override_rows)
3255 rowsp = &rows;
3256
3257 /*
3258 * The output of Gather is always unsorted, so there's only one partial
3259 * path of interest: the cheapest one. That will be the one at the front
3260 * of partial_pathlist because of the way add_partial_path works.
3261 */
3266 NULL, rowsp);
3268
3269 /*
3270 * For each useful ordering, we can consider an order-preserving Gather
3271 * Merge.
3272 */
3273 foreach(lc, rel->partial_pathlist)
3274 {
3275 Path *subpath = (Path *) lfirst(lc);
3276 GatherMergePath *path;
3277
3278 if (subpath->pathkeys == NIL)
3279 continue;
3280
3283 subpath->pathkeys, NULL, rowsp);
3284 add_path(rel, &path->path);
3285 }
3286}
double compute_gather_rows(Path *path)
Definition costsize.c:6767
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition pathnode.c:1766
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition pathnode.c:1818
struct PathTarget * reltarget
Definition pathnodes.h:1033
List * partial_pathlist
Definition pathnodes.h:1040

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_gather_path(), fb(), 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 3495 of file allpaths.c.

3497{
3498 RelAggInfo *agg_info = grouped_rel->agg_info;
3500 bool can_hash;
3501 bool can_sort;
3502 Path *cheapest_total_path = NULL;
3504 double dNumGroups = 0;
3505 double dNumPartialGroups = 0;
3506 List *group_pathkeys = NIL;
3507
3508 if (IS_DUMMY_REL(rel))
3509 {
3510 mark_dummy_rel(grouped_rel);
3511 return;
3512 }
3513
3514 /*
3515 * We push partial aggregation only to the lowest possible level in the
3516 * join tree that is deemed useful.
3517 */
3518 if (!bms_equal(agg_info->apply_agg_at, rel->relids) ||
3519 !agg_info->agg_useful)
3520 return;
3521
3522 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3524
3525 /*
3526 * Determine whether it's possible to perform sort-based implementations
3527 * of grouping, and generate the pathkeys that represent the grouping
3528 * requirements in that case.
3529 */
3531 if (can_sort)
3532 {
3535
3537 rel->top_parent->grouped_rel : grouped_rel;
3540
3541 group_pathkeys =
3544 }
3545
3546 /*
3547 * Determine whether we should consider hash-based implementations of
3548 * grouping.
3549 */
3550 Assert(root->numOrderedAggs == 0);
3551 can_hash = (agg_info->group_clauses != NIL &&
3553
3554 /*
3555 * Consider whether we should generate partially aggregated non-partial
3556 * paths. We can only do this if we have a non-partial path.
3557 */
3558 if (rel->pathlist != NIL)
3559 {
3560 cheapest_total_path = rel->cheapest_total_path;
3561 Assert(cheapest_total_path != NULL);
3562 }
3563
3564 /*
3565 * If parallelism is possible for grouped_rel, then we should consider
3566 * generating partially-grouped partial paths. However, if the ungrouped
3567 * rel has no partial paths, then we can't.
3568 */
3569 if (grouped_rel->consider_parallel && rel->partial_pathlist != NIL)
3570 {
3573 }
3574
3575 /* Estimate number of partial groups. */
3576 if (cheapest_total_path != NULL)
3578 agg_info->group_exprs,
3579 cheapest_total_path->rows,
3580 NULL, NULL);
3583 agg_info->group_exprs,
3585 NULL, NULL);
3586
3587 if (can_sort && cheapest_total_path != NULL)
3588 {
3589 ListCell *lc;
3590
3591 /*
3592 * Use any available suitably-sorted path as input, and also consider
3593 * sorting the cheapest-total path and incremental sort on any paths
3594 * with presorted keys.
3595 *
3596 * To save planning time, we ignore parameterized input paths unless
3597 * they are the cheapest-total path.
3598 */
3599 foreach(lc, rel->pathlist)
3600 {
3601 Path *input_path = (Path *) lfirst(lc);
3602 Path *path;
3603 bool is_sorted;
3604 int presorted_keys;
3605
3606 /*
3607 * Ignore parameterized paths that are not the cheapest-total
3608 * path.
3609 */
3610 if (input_path->param_info &&
3611 input_path != cheapest_total_path)
3612 continue;
3613
3614 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3615 input_path->pathkeys,
3616 &presorted_keys);
3617
3618 /*
3619 * Ignore paths that are not suitably or partially sorted, unless
3620 * they are the cheapest total path (no need to deal with paths
3621 * which have presorted keys when incremental sort is disabled).
3622 */
3623 if (!is_sorted && input_path != cheapest_total_path &&
3624 (presorted_keys == 0 || !enable_incremental_sort))
3625 continue;
3626
3627 /*
3628 * Since the path originates from a non-grouped relation that is
3629 * not aware of eager aggregation, we must ensure that it provides
3630 * the correct input for partial aggregation.
3631 */
3632 path = (Path *) create_projection_path(root,
3633 grouped_rel,
3634 input_path,
3635 agg_info->agg_input);
3636
3637 if (!is_sorted)
3638 {
3639 /*
3640 * We've no need to consider both a sort and incremental sort.
3641 * We'll just do a sort if there are no presorted keys and an
3642 * incremental sort when there are presorted keys.
3643 */
3644 if (presorted_keys == 0 || !enable_incremental_sort)
3645 path = (Path *) create_sort_path(root,
3646 grouped_rel,
3647 path,
3648 group_pathkeys,
3649 -1.0);
3650 else
3652 grouped_rel,
3653 path,
3654 group_pathkeys,
3655 presorted_keys,
3656 -1.0);
3657 }
3658
3659 /*
3660 * qual is NIL because the HAVING clause cannot be evaluated until
3661 * the final value of the aggregate is known.
3662 */
3663 path = (Path *) create_agg_path(root,
3664 grouped_rel,
3665 path,
3666 agg_info->target,
3667 AGG_SORTED,
3669 agg_info->group_clauses,
3670 NIL,
3671 &agg_costs,
3672 dNumGroups);
3673
3674 add_path(grouped_rel, path);
3675 }
3676 }
3677
3679 {
3680 ListCell *lc;
3681
3682 /* Similar to above logic, but for partial paths. */
3683 foreach(lc, rel->partial_pathlist)
3684 {
3685 Path *input_path = (Path *) lfirst(lc);
3686 Path *path;
3687 bool is_sorted;
3688 int presorted_keys;
3689
3690 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3691 input_path->pathkeys,
3692 &presorted_keys);
3693
3694 /*
3695 * Ignore paths that are not suitably or partially sorted, unless
3696 * they are the cheapest partial path (no need to deal with paths
3697 * which have presorted keys when incremental sort is disabled).
3698 */
3700 (presorted_keys == 0 || !enable_incremental_sort))
3701 continue;
3702
3703 /*
3704 * Since the path originates from a non-grouped relation that is
3705 * not aware of eager aggregation, we must ensure that it provides
3706 * the correct input for partial aggregation.
3707 */
3708 path = (Path *) create_projection_path(root,
3709 grouped_rel,
3710 input_path,
3711 agg_info->agg_input);
3712
3713 if (!is_sorted)
3714 {
3715 /*
3716 * We've no need to consider both a sort and incremental sort.
3717 * We'll just do a sort if there are no presorted keys and an
3718 * incremental sort when there are presorted keys.
3719 */
3720 if (presorted_keys == 0 || !enable_incremental_sort)
3721 path = (Path *) create_sort_path(root,
3722 grouped_rel,
3723 path,
3724 group_pathkeys,
3725 -1.0);
3726 else
3728 grouped_rel,
3729 path,
3730 group_pathkeys,
3731 presorted_keys,
3732 -1.0);
3733 }
3734
3735 /*
3736 * qual is NIL because the HAVING clause cannot be evaluated until
3737 * the final value of the aggregate is known.
3738 */
3739 path = (Path *) create_agg_path(root,
3740 grouped_rel,
3741 path,
3742 agg_info->target,
3743 AGG_SORTED,
3745 agg_info->group_clauses,
3746 NIL,
3747 &agg_costs,
3749
3750 add_partial_path(grouped_rel, path);
3751 }
3752 }
3753
3754 /*
3755 * Add a partially-grouped HashAgg Path where possible
3756 */
3757 if (can_hash && cheapest_total_path != NULL)
3758 {
3759 Path *path;
3760
3761 /*
3762 * Since the path originates from a non-grouped relation that is not
3763 * aware of eager aggregation, we must ensure that it provides the
3764 * correct input for partial aggregation.
3765 */
3766 path = (Path *) create_projection_path(root,
3767 grouped_rel,
3768 cheapest_total_path,
3769 agg_info->agg_input);
3770
3771 /*
3772 * qual is NIL because the HAVING clause cannot be evaluated until the
3773 * final value of the aggregate is known.
3774 */
3775 path = (Path *) create_agg_path(root,
3776 grouped_rel,
3777 path,
3778 agg_info->target,
3779 AGG_HASHED,
3781 agg_info->group_clauses,
3782 NIL,
3783 &agg_costs,
3784 dNumGroups);
3785
3786 add_path(grouped_rel, path);
3787 }
3788
3789 /*
3790 * Now add a partially-grouped HashAgg partial Path where possible
3791 */
3793 {
3794 Path *path;
3795
3796 /*
3797 * Since the path originates from a non-grouped relation that is not
3798 * aware of eager aggregation, we must ensure that it provides the
3799 * correct input for partial aggregation.
3800 */
3801 path = (Path *) create_projection_path(root,
3802 grouped_rel,
3804 agg_info->agg_input);
3805
3806 /*
3807 * qual is NIL because the HAVING clause cannot be evaluated until the
3808 * final value of the aggregate is known.
3809 */
3810 path = (Path *) create_agg_path(root,
3811 grouped_rel,
3812 path,
3813 agg_info->target,
3814 AGG_HASHED,
3816 agg_info->group_clauses,
3817 NIL,
3818 &agg_costs,
3820
3821 add_partial_path(grouped_rel, path);
3822 }
3823}
#define MemSet(start, val, len)
Definition c.h:1056
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:2540
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition pathnode.c:2808
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition pathnode.c:2857
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:3010
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2285
#define IS_OTHER_REL(rel)
Definition pathnodes.h:992
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:3771
Cardinality rows
Definition pathnodes.h:1991
Relids apply_agg_at
Definition pathnodes.h:1290
List * group_exprs
Definition pathnodes.h:1287
bool agg_useful
Definition pathnodes.h:1296
List * group_clauses
Definition pathnodes.h:1285
struct PathTarget * agg_input
Definition pathnodes.h:1282
struct PathTarget * target
Definition pathnodes.h:1279
Relids relids
Definition pathnodes.h:1009
struct RelAggInfo * agg_info
Definition pathnodes.h:1150
List * pathlist
Definition pathnodes.h:1038
struct Path * cheapest_total_path
Definition pathnodes.h:1042
struct RelOptInfo * grouped_rel
Definition pathnodes.h:1152
bool grouping_is_sortable(List *groupClause)
Definition tlist.c:549
List * make_tlist_from_pathtarget(PathTarget *target)
Definition tlist.c:633
bool grouping_is_hashable(List *groupClause)
Definition tlist.c:569

References add_partial_path(), add_path(), AGG_HASHED, RelOptInfo::agg_info, RelAggInfo::agg_input, AGG_SORTED, RelAggInfo::agg_useful, AGGSPLIT_INITIAL_SERIAL, RelAggInfo::apply_agg_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(), fb(), 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, 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 1838 of file allpaths.c.

1841{
1842 ListCell *lcp;
1845 bool partition_pathkeys_partial = true;
1847
1848 /*
1849 * Some partitioned table setups may allow us to use an Append node
1850 * instead of a MergeAppend. This is possible in cases such as RANGE
1851 * partitioned tables where it's guaranteed that an earlier partition must
1852 * contain rows which come earlier in the sort order. To detect whether
1853 * this is relevant, build pathkey descriptions of the partition ordering,
1854 * for both forward and reverse scans.
1855 */
1856 if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1857 partitions_are_ordered(rel->boundinfo, rel->live_parts))
1858 {
1862
1866
1867 /*
1868 * You might think we should truncate_useless_pathkeys here, but
1869 * allowing partition keys which are a subset of the query's pathkeys
1870 * can often be useful. For example, consider a table partitioned by
1871 * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1872 * paths that can produce the a, b, c ordering (perhaps via indexes on
1873 * (a, b, c)) then it works to consider the appendrel output as
1874 * ordered by a, b, c.
1875 */
1876 }
1877
1878 /* Now consider each interesting sort ordering */
1879 foreach(lcp, all_child_pathkeys)
1880 {
1881 List *pathkeys = (List *) lfirst(lcp);
1882 AppendPathInput startup = {0};
1883 AppendPathInput total = {0};
1885 bool startup_neq_total = false;
1886 bool fraction_neq_total = false;
1889 int end_index;
1890 int first_index;
1891 int direction;
1892
1893 /*
1894 * Determine if this sort ordering matches any partition pathkeys we
1895 * have, for both ascending and descending partition order. If the
1896 * partition pathkeys happen to be contained in pathkeys then it still
1897 * works, as described above, providing that the partition pathkeys
1898 * are complete and not just a prefix of the partition keys. (In such
1899 * cases we'll be relying on the child paths to have sorted the
1900 * lower-order columns of the required pathkeys.)
1901 */
1906
1911
1912 /*
1913 * When the required pathkeys match the reverse of the partition
1914 * order, we must build the list of paths in reverse starting with the
1915 * last matching partition first. We can get away without making any
1916 * special cases for this in the loop below by just looping backward
1917 * over the child relations in this case.
1918 */
1920 {
1921 /* loop backward */
1923 end_index = -1;
1924 direction = -1;
1925
1926 /*
1927 * Set this to true to save us having to check for
1928 * match_partition_order_desc in the loop below.
1929 */
1930 match_partition_order = true;
1931 }
1932 else
1933 {
1934 /* for all other case, loop forward */
1935 first_index = 0;
1937 direction = 1;
1938 }
1939
1940 /* Select the child paths for this ordering... */
1941 for (int i = first_index; i != end_index; i += direction)
1942 {
1947
1948 /* Locate the right paths, if they are available. */
1951 pathkeys,
1952 NULL,
1954 false);
1957 pathkeys,
1958 NULL,
1959 TOTAL_COST,
1960 false);
1961
1962 /*
1963 * If we can't find any paths with the right order just use the
1964 * cheapest-total path; we'll have to sort it later.
1965 */
1967 {
1969 childrel->cheapest_total_path;
1970 /* Assert we do have an unparameterized path for this child */
1971 Assert(cheapest_total->param_info == NULL);
1972 }
1973
1974 /*
1975 * When building a fractional path, determine a cheapest
1976 * fractional path for each child relation too. Looking at startup
1977 * and total costs is not enough, because the cheapest fractional
1978 * path may be dominated by two separate paths (one for startup,
1979 * one for total).
1980 *
1981 * When needed (building fractional path), determine the cheapest
1982 * fractional path too.
1983 */
1984 if (root->tuple_fraction > 0)
1985 {
1986 double path_fraction = root->tuple_fraction;
1987
1988 /*
1989 * We should not have a dummy child relation here. However,
1990 * we cannot use childrel->rows to compute the tuple fraction,
1991 * as childrel can be an upper relation with an unset row
1992 * estimate. Instead, we use the row estimate from the
1993 * cheapest_total path, which should already have been forced
1994 * to a sane value.
1995 */
1996 Assert(cheapest_total->rows > 0);
1997
1998 /* Convert absolute limit to a path fraction */
1999 if (path_fraction >= 1.0)
2001
2004 pathkeys,
2005 NULL,
2007
2008 /*
2009 * If we found no path with matching pathkeys, use the
2010 * cheapest total path instead.
2011 *
2012 * XXX We might consider partially sorted paths too (with an
2013 * incremental sort on top). But we'd have to build all the
2014 * incremental paths, do the costing etc.
2015 *
2016 * Also, notice whether we actually have different paths for
2017 * the "fractional" and "total" cases. This helps avoid
2018 * generating two identical ordered append paths.
2019 */
2023 fraction_neq_total = true;
2024 }
2025
2026 /*
2027 * Notice whether we actually have different paths for the
2028 * "cheapest" and "total" cases. This helps avoid generating two
2029 * identical ordered append paths.
2030 */
2032 startup_neq_total = true;
2033
2034 /*
2035 * Collect the appropriate child paths. The required logic varies
2036 * for the Append and MergeAppend cases.
2037 */
2039 {
2040 /*
2041 * We're going to make a plain Append path. We don't need
2042 * most of what accumulate_append_subpath would do, but we do
2043 * want to cut out child Appends or MergeAppends if they have
2044 * just a single subpath (and hence aren't doing anything
2045 * useful).
2046 */
2049 &startup.child_append_relid_sets);
2052 &total.child_append_relid_sets);
2053
2054 startup.subpaths = lappend(startup.subpaths, cheapest_startup);
2055 total.subpaths = lappend(total.subpaths, cheapest_total);
2056
2058 {
2061 &fractional.child_append_relid_sets);
2062 fractional.subpaths =
2064 }
2065 }
2066 else
2067 {
2068 /*
2069 * Otherwise, rely on accumulate_append_subpath to collect the
2070 * child paths for the MergeAppend.
2071 */
2073 &startup.subpaths, NULL,
2074 &startup.child_append_relid_sets);
2076 &total.subpaths, NULL,
2077 &total.child_append_relid_sets);
2078
2081 &fractional.subpaths, NULL,
2082 &fractional.child_append_relid_sets);
2083 }
2084 }
2085
2086 /* ... and build the Append or MergeAppend paths */
2088 {
2089 /* We only need Append */
2091 rel,
2092 startup,
2093 pathkeys,
2094 NULL,
2095 0,
2096 false,
2097 -1));
2100 rel,
2101 total,
2102 pathkeys,
2103 NULL,
2104 0,
2105 false,
2106 -1));
2107
2108 if (fractional.subpaths && fraction_neq_total)
2110 rel,
2111 fractional,
2112 pathkeys,
2113 NULL,
2114 0,
2115 false,
2116 -1));
2117 }
2118 else
2119 {
2120 /* We need MergeAppend */
2122 rel,
2123 startup.subpaths,
2124 startup.child_append_relid_sets,
2125 pathkeys,
2126 NULL));
2129 rel,
2130 total.subpaths,
2131 total.child_append_relid_sets,
2132 pathkeys,
2133 NULL));
2134
2135 if (fractional.subpaths && fraction_neq_total)
2137 rel,
2138 fractional.subpaths,
2139 fractional.child_append_relid_sets,
2140 pathkeys,
2141 NULL));
2142 }
2143 }
2144}
static Path * get_singleton_append_subpath(Path *path, List **child_append_relid_sets)
Definition allpaths.c:2308
int i
Definition isn.c:77
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
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 *child_append_relid_sets, List *pathkeys, Relids required_outer)
Definition pathnode.c:1477
#define IS_SIMPLE_REL(rel)
Definition pathnodes.h:977
@ TOTAL_COST
Definition pathnodes.h:111
@ STARTUP_COST
Definition pathnodes.h:111
#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:1192

References accumulate_append_subpath(), add_path(), Assert, BackwardScanDirection, build_partition_pathkeys(), AppendPathInput::child_append_relid_sets, create_append_path(), create_merge_append_path(), fb(), 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(), root, STARTUP_COST, AppendPathInput::subpaths, 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 4867 of file allpaths.c.

4868{
4870 int cnt_parts;
4871 int num_parts;
4873
4874 /* Handle only join relations here. */
4875 if (!IS_JOIN_REL(rel))
4876 return;
4877
4878 /* We've nothing to do if the relation is not partitioned. */
4879 if (!IS_PARTITIONED_REL(rel))
4880 return;
4881
4882 /* The relation should have consider_partitionwise_join set. */
4884
4885 /* Guard against stack overflow due to overly deep partition hierarchy. */
4887
4888 num_parts = rel->nparts;
4889 part_rels = rel->part_rels;
4890
4891 /* Collect non-dummy child-joins. */
4892 for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4893 {
4895
4896 /* If it's been pruned entirely, it's certainly dummy. */
4897 if (child_rel == NULL)
4898 continue;
4899
4900 /* Make partitionwise join paths for this partitioned child-join. */
4902
4903 /* If we failed to make any path for this child, we must give up. */
4904 if (child_rel->pathlist == NIL)
4905 {
4906 /*
4907 * Mark the parent joinrel as unpartitioned so that later
4908 * functions treat it correctly.
4909 */
4910 rel->nparts = 0;
4911 return;
4912 }
4913
4914 /* Else, identify the cheapest path for it. */
4916
4917 /* Dummy children need not be scanned, so ignore those. */
4919 continue;
4920
4921 /*
4922 * Except for the topmost scan/join rel, consider generating partial
4923 * aggregation paths for the grouped relation on top of the paths of
4924 * this partitioned child-join. After that, we're done creating paths
4925 * for the grouped relation, so run set_cheapest().
4926 */
4927 if (child_rel->grouped_rel != NULL &&
4928 !bms_equal(IS_OTHER_REL(rel) ?
4929 rel->top_parent_relids : rel->relids,
4930 root->all_query_rels))
4931 {
4932 RelOptInfo *grouped_rel = child_rel->grouped_rel;
4933
4934 Assert(IS_GROUPED_REL(grouped_rel));
4935
4936 generate_grouped_paths(root, grouped_rel, child_rel);
4937 set_cheapest(grouped_rel);
4938 }
4939
4940#ifdef OPTIMIZER_DEBUG
4942#endif
4943
4945 }
4946
4947 /* If all child-joins are dummy, parent join is also dummy. */
4948 if (!live_children)
4949 {
4950 mark_dummy_rel(rel);
4951 return;
4952 }
4953
4954 /* Build additional paths for this rel from child-join paths. */
4957}
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:4867
void generate_grouped_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *rel)
Definition allpaths.c:3495
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition allpaths.c:1406
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:268
#define IS_JOIN_REL(rel)
Definition pathnodes.h:982
#define IS_PARTITIONED_REL(rel)
Definition pathnodes.h:1219
#define IS_GROUPED_REL(rel)
Definition pathnodes.h:1245
void check_stack_depth(void)
Definition stack_depth.c:95
Relids top_parent_relids
Definition pathnodes.h:1162
bool consider_partitionwise_join
Definition pathnodes.h:1144

References add_paths_to_append_rel(), Assert, bms_equal(), check_stack_depth(), RelOptInfo::consider_partitionwise_join, fb(), 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, 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 3378 of file allpaths.c.

3379{
3380 ListCell *lc;
3381 double rows;
3382 double *rowsp = NULL;
3385
3386 /* If there are no partial paths, there's nothing to do here. */
3387 if (rel->partial_pathlist == NIL)
3388 return;
3389
3390 /* Should we override the rel's rowcount estimate? */
3391 if (override_rows)
3392 rowsp = &rows;
3393
3394 /* generate the regular gather (merge) paths */
3396
3397 /* consider incremental sort for interesting orderings */
3399
3400 /* used for explicit (full) sort paths */
3402
3403 /*
3404 * Consider sorted paths for each interesting ordering. We generate both
3405 * incremental and full sort.
3406 */
3407 foreach(lc, useful_pathkeys_list)
3408 {
3410 ListCell *lc2;
3411 bool is_sorted;
3412 int presorted_keys;
3413
3414 foreach(lc2, rel->partial_pathlist)
3415 {
3416 Path *subpath = (Path *) lfirst(lc2);
3417 GatherMergePath *path;
3418
3420 subpath->pathkeys,
3421 &presorted_keys);
3422
3423 /*
3424 * We don't need to consider the case where a subpath is already
3425 * fully sorted because generate_gather_paths already creates a
3426 * gather merge path for every subpath that has pathkeys present.
3427 *
3428 * But since the subpath is already sorted, we know we don't need
3429 * to consider adding a sort (full or incremental) on top of it,
3430 * so we can continue here.
3431 */
3432 if (is_sorted)
3433 continue;
3434
3435 /*
3436 * Try at least sorting the cheapest path and also try
3437 * incrementally sorting any path which is partially sorted
3438 * already (no need to deal with paths which have presorted keys
3439 * when incremental sort is disabled unless it's the cheapest
3440 * input path).
3441 */
3443 (presorted_keys == 0 || !enable_incremental_sort))
3444 continue;
3445
3446 /*
3447 * Consider regular sort for any path that's not presorted or if
3448 * incremental sort is disabled. We've no need to consider both
3449 * sort and incremental sort on the same path. We assume that
3450 * incremental sort is always faster when there are presorted
3451 * keys.
3452 *
3453 * This is not redundant with the gather paths created in
3454 * generate_gather_paths, because that doesn't generate ordered
3455 * output. Here we add an explicit sort to match the useful
3456 * ordering.
3457 */
3458 if (presorted_keys == 0 || !enable_incremental_sort)
3459 {
3461 rel,
3462 subpath,
3464 -1.0);
3465 }
3466 else
3468 rel,
3469 subpath,
3471 presorted_keys,
3472 -1);
3474 path = create_gather_merge_path(root, rel,
3475 subpath,
3476 rel->reltarget,
3477 subpath->pathkeys,
3478 NULL,
3479 rowsp);
3480
3481 add_path(rel, &path->path);
3482 }
3483 }
3484}
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition allpaths.c:3310
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition allpaths.c:3241

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, fb(), 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 2154 of file allpaths.c.

2156{
2157 Path *cheapest;
2158 ListCell *lc;
2159
2160 /*
2161 * Look up the cheapest existing path with no more than the needed
2162 * parameterization. If it has exactly the needed parameterization, we're
2163 * done.
2164 */
2166 NIL,
2168 TOTAL_COST,
2169 false);
2170 Assert(cheapest != NULL);
2172 return cheapest;
2173
2174 /*
2175 * Otherwise, we can "reparameterize" an existing path to match the given
2176 * parameterization, which effectively means pushing down additional
2177 * joinquals to be checked within the path's scan. However, some existing
2178 * paths might check the available joinquals already while others don't;
2179 * therefore, it's not clear which existing path will be cheapest after
2180 * reparameterization. We have to go through them all and find out.
2181 */
2182 cheapest = NULL;
2183 foreach(lc, rel->pathlist)
2184 {
2185 Path *path = (Path *) lfirst(lc);
2186
2187 /* Can't use it if it needs more than requested parameterization */
2189 continue;
2190
2191 /*
2192 * Reparameterization can only increase the path's cost, so if it's
2193 * already more expensive than the current cheapest, forget it.
2194 */
2195 if (cheapest != NULL &&
2197 continue;
2198
2199 /* Reparameterize if needed, then recheck cost */
2201 {
2202 path = reparameterize_path(root, path, required_outer, 1.0);
2203 if (path == NULL)
2204 continue; /* failed to reparameterize this one */
2206
2207 if (cheapest != NULL &&
2209 continue;
2210 }
2211
2212 /* We have a new best path */
2213 cheapest = path;
2214 }
2215
2216 /* Return the best path, or NULL if we found no suitable candidate */
2217 return cheapest;
2218}
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:68
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition pathnode.c:3869

References Assert, bms_equal(), bms_is_subset(), compare_path_costs(), fb(), 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,
List **  child_append_relid_sets 
)
static

Definition at line 2308 of file allpaths.c.

2309{
2310 Assert(!path->parallel_aware);
2311
2312 if (IsA(path, AppendPath))
2313 {
2314 AppendPath *apath = (AppendPath *) path;
2315
2316 if (list_length(apath->subpaths) == 1)
2317 {
2318 *child_append_relid_sets =
2319 lappend(*child_append_relid_sets, path->parent->relids);
2320 *child_append_relid_sets =
2321 list_concat(*child_append_relid_sets,
2322 apath->child_append_relid_sets);
2323 return (Path *) linitial(apath->subpaths);
2324 }
2325 }
2326 else if (IsA(path, MergeAppendPath))
2327 {
2329
2330 if (list_length(mpath->subpaths) == 1)
2331 {
2332 *child_append_relid_sets =
2333 lappend(*child_append_relid_sets, path->parent->relids);
2334 *child_append_relid_sets =
2335 list_concat(*child_append_relid_sets,
2336 mpath->child_append_relid_sets);
2337 return (Path *) linitial(mpath->subpaths);
2338 }
2339 }
2340
2341 return path;
2342}
bool parallel_aware
Definition pathnodes.h:1984

References Assert, fb(), IsA, lappend(), linitial, list_concat(), list_length(), and Path::parallel_aware.

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

3312{
3314
3315 /*
3316 * Considering query_pathkeys is always worth it, because it might allow
3317 * us to avoid a total sort when we have a partially presorted path
3318 * available or to push the total sort into the parallel portion of the
3319 * query.
3320 */
3321 if (root->query_pathkeys)
3322 {
3323 ListCell *lc;
3324 int npathkeys = 0; /* useful pathkeys */
3325
3326 foreach(lc, root->query_pathkeys)
3327 {
3329 EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3330
3331 /*
3332 * We can only build a sort for pathkeys that contain a
3333 * safe-to-compute-early EC member computable from the current
3334 * relation's reltarget, so ignore the remainder of the list as
3335 * soon as we find a pathkey without such a member.
3336 *
3337 * It's still worthwhile to return any prefix of the pathkeys list
3338 * that meets this requirement, as we may be able to do an
3339 * incremental sort.
3340 *
3341 * If requested, ensure the sort expression is parallel-safe too.
3342 */
3345 break;
3346
3347 npathkeys++;
3348 }
3349
3350 /*
3351 * The whole query_pathkeys list matches, so append it directly, to
3352 * allow comparing pathkeys easily by comparing list pointer. If we
3353 * have to truncate the pathkeys, we gotta do a copy though.
3354 */
3355 if (npathkeys == list_length(root->query_pathkeys))
3357 root->query_pathkeys);
3358 else if (npathkeys > 0)
3360 list_copy_head(root->query_pathkeys,
3361 npathkeys));
3362 }
3363
3364 return useful_pathkeys_list;
3365}
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)

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

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

References Assert, bms_equal(), fb(), IS_DUMMY_REL, IS_SIMPLE_REL, make_rel_from_joinlist(), 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 3833 of file allpaths.c.

3834{
3835 int levels_needed;
3836 List *initial_rels;
3837 ListCell *jl;
3838
3839 /*
3840 * Count the number of child joinlist nodes. This is the depth of the
3841 * dynamic-programming algorithm we must employ to consider all ways of
3842 * joining the child nodes.
3843 */
3845
3846 if (levels_needed <= 0)
3847 return NULL; /* nothing to do? */
3848
3849 /*
3850 * Construct a list of rels corresponding to the child joinlist nodes.
3851 * This may contain both base rels and rels constructed according to
3852 * sub-joinlists.
3853 */
3854 initial_rels = NIL;
3855 foreach(jl, joinlist)
3856 {
3857 Node *jlnode = (Node *) lfirst(jl);
3859
3860 if (IsA(jlnode, RangeTblRef))
3861 {
3862 int varno = ((RangeTblRef *) jlnode)->rtindex;
3863
3864 thisrel = find_base_rel(root, varno);
3865 }
3866 else if (IsA(jlnode, List))
3867 {
3868 /* Recurse to handle subproblem */
3870 }
3871 else
3872 {
3873 elog(ERROR, "unrecognized joinlist node type: %d",
3874 (int) nodeTag(jlnode));
3875 thisrel = NULL; /* keep compiler quiet */
3876 }
3877
3878 initial_rels = lappend(initial_rels, thisrel);
3879 }
3880
3881 if (levels_needed == 1)
3882 {
3883 /*
3884 * Single joinlist node, so we're done.
3885 */
3886 return (RelOptInfo *) linitial(initial_rels);
3887 }
3888 else
3889 {
3890 /*
3891 * Consider the different orders in which we could join the rels,
3892 * using a plugin, GEQO, or the regular join search code.
3893 *
3894 * We put the initial_rels list into a PlannerInfo field because
3895 * has_legal_joinclause() needs to look at it (ugly :-().
3896 */
3897 root->initial_rels = initial_rels;
3898
3899 if (join_search_hook)
3900 return (*join_search_hook) (root, levels_needed, initial_rels);
3902 return geqo(root, levels_needed, initial_rels);
3903 else
3904 return standard_join_search(root, levels_needed, initial_rels);
3905 }
3906}
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition allpaths.c:3938
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:533

References elog, enable_geqo, ERROR, fb(), 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 4430 of file allpaths.c.

4432{
4434 Node *qual = (Node *) rinfo->clause;
4435 List *vars;
4436 ListCell *vl;
4437
4438 /* Refuse subselects (point 1) */
4439 if (contain_subplans(qual))
4440 return PUSHDOWN_UNSAFE;
4441
4442 /* Refuse volatile quals if we found they'd be unsafe (point 2) */
4443 if (safetyInfo->unsafeVolatile &&
4445 return PUSHDOWN_UNSAFE;
4446
4447 /* Refuse leaky quals if told to (point 3) */
4448 if (safetyInfo->unsafeLeaky &&
4449 contain_leaked_vars(qual))
4450 return PUSHDOWN_UNSAFE;
4451
4452 /*
4453 * Examine all Vars used in clause. Since it's a restriction clause, all
4454 * such Vars must refer to subselect output columns ... unless this is
4455 * part of a LATERAL subquery, in which case there could be lateral
4456 * references.
4457 *
4458 * By omitting the relevant flags, this also gives us a cheap sanity check
4459 * that no aggregates or window functions appear in the qual. Those would
4460 * be unsafe to push down, but at least for the moment we could never see
4461 * any in a qual anyhow.
4462 */
4464 foreach(vl, vars)
4465 {
4466 Var *var = (Var *) lfirst(vl);
4467
4468 /*
4469 * XXX Punt if we find any PlaceHolderVars in the restriction clause.
4470 * It's not clear whether a PHV could safely be pushed down, and even
4471 * less clear whether such a situation could arise in any cases of
4472 * practical interest anyway. So for the moment, just refuse to push
4473 * down.
4474 */
4475 if (!IsA(var, Var))
4476 {
4478 break;
4479 }
4480
4481 /*
4482 * Punt if we find any lateral references. It would be safe to push
4483 * these down, but we'd have to convert them into outer references,
4484 * which subquery_push_qual lacks the infrastructure to do. The case
4485 * arises so seldom that it doesn't seem worth working hard on.
4486 */
4487 if (var->varno != rti)
4488 {
4490 break;
4491 }
4492
4493 /* Subqueries have no system columns */
4494 Assert(var->varattno >= 0);
4495
4496 /* Check point 4 */
4497 if (var->varattno == 0)
4498 {
4500 break;
4501 }
4502
4503 /* Check point 5 */
4504 if (safetyInfo->unsafeFlags[var->varattno] != 0)
4505 {
4506 if (safetyInfo->unsafeFlags[var->varattno] &
4509 {
4511 break;
4512 }
4513 else
4514 {
4515 /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
4517 /* don't break, we might find another Var that's unsafe */
4518 }
4519 }
4520 }
4521
4522 list_free(vars);
4523
4524 return safe;
4525}
bool contain_leaked_vars(Node *clause)
Definition clauses.c:1274
#define PVC_INCLUDE_PLACEHOLDERS
Definition optimizer.h:192
Expr * clause
Definition pathnodes.h:2886
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
List * pull_var_clause(Node *node, int flags)
Definition var.c:653

References Assert, RestrictInfo::clause, contain_leaked_vars(), contain_subplans(), contain_volatile_functions(), fb(), 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, 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 4579 of file allpaths.c.

4581{
4582 if (IsA(setOp, RangeTblRef))
4583 {
4585 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4586 Query *subquery = subrte->subquery;
4587
4588 Assert(subquery != NULL);
4589 subquery_push_qual(subquery, rte, rti, qual);
4590 }
4591 else if (IsA(setOp, SetOperationStmt))
4592 {
4594
4595 recurse_push_qual(op->larg, topquery, rte, rti, qual);
4596 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4597 }
4598 else
4599 {
4600 elog(ERROR, "unrecognized node type: %d",
4601 (int) nodeTag(setOp));
4602 }
4603}
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4531
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4579
#define rt_fetch(rangetable_index, rangetable)
Definition parsetree.h:31

References Assert, elog, ERROR, fb(), IsA, SetOperationStmt::larg, nodeTag, SetOperationStmt::rarg, recurse_push_qual(), rt_fetch, 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 4189 of file allpaths.c.

4191{
4192 if (IsA(setOp, RangeTblRef))
4193 {
4195 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
4196 Query *subquery = rte->subquery;
4197
4198 Assert(subquery != NULL);
4200 }
4201 else if (IsA(setOp, SetOperationStmt))
4202 {
4204
4205 /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
4206 if (op->op == SETOP_EXCEPT)
4207 return false;
4208 /* Else recurse */
4210 return false;
4212 return false;
4213 }
4214 else
4215 {
4216 elog(ERROR, "unrecognized node type: %d",
4217 (int) nodeTag(setOp));
4218 }
4219 return true;
4220}
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4133
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4189
@ SETOP_EXCEPT
SetOperation op

References Assert, elog, ERROR, fb(), IsA, SetOperationStmt::larg, nodeTag, SetOperationStmt::op, SetOperationStmt::rarg, recurse_pushdown_safe(), rt_fetch, SETOP_EXCEPT, 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 4631 of file allpaths.c.

4633{
4634 Bitmapset *attrs_used;
4635 ListCell *lc;
4636
4637 /*
4638 * Just point directly to extra_used_attrs. No need to bms_copy as none of
4639 * the current callers use the Bitmapset after calling this function.
4640 */
4641 attrs_used = extra_used_attrs;
4642
4643 /*
4644 * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4645 * could update all the child SELECTs' tlists, but it seems not worth the
4646 * trouble presently.
4647 */
4648 if (subquery->setOperations)
4649 return;
4650
4651 /*
4652 * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4653 * time: all its output columns must be used in the distinctClause.
4654 */
4655 if (subquery->distinctClause && !subquery->hasDistinctOn)
4656 return;
4657
4658 /*
4659 * Collect a bitmap of all the output column numbers used by the upper
4660 * query.
4661 *
4662 * Add all the attributes needed for joins or final output. Note: we must
4663 * look at rel's targetlist, not the attr_needed data, because attr_needed
4664 * isn't computed for inheritance child rels, cf set_append_rel_size().
4665 * (XXX might be worth changing that sometime.)
4666 */
4667 pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4668
4669 /* Add all the attributes used by un-pushed-down restriction clauses. */
4670 foreach(lc, rel->baserestrictinfo)
4671 {
4672 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4673
4674 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4675 }
4676
4677 /*
4678 * If there's a whole-row reference to the subquery, we can't remove
4679 * anything.
4680 */
4682 return;
4683
4684 /*
4685 * Run through the tlist and zap entries we don't need. It's okay to
4686 * modify the tlist items in-place because set_subquery_pathlist made a
4687 * copy of the subquery.
4688 */
4689 foreach(lc, subquery->targetList)
4690 {
4692 Node *texpr = (Node *) tle->expr;
4693
4694 /*
4695 * If it has a sortgroupref number, it's used in some sort/group
4696 * clause so we'd better not remove it. Also, don't remove any
4697 * resjunk columns, since their reason for being has nothing to do
4698 * with anybody reading the subquery's output. (It's likely that
4699 * resjunk columns in a sub-SELECT would always have ressortgroupref
4700 * set, but even if they don't, it seems imprudent to remove them.)
4701 */
4702 if (tle->ressortgroupref || tle->resjunk)
4703 continue;
4704
4705 /*
4706 * If it's used by the upper query, we can't remove it.
4707 */
4709 attrs_used))
4710 continue;
4711
4712 /*
4713 * If it contains a set-returning function, we can't remove it since
4714 * that could change the number of rows returned by the subquery.
4715 */
4716 if (subquery->hasTargetSRFs &&
4718 continue;
4719
4720 /*
4721 * If it contains volatile functions, we daren't remove it for fear
4722 * that the user is expecting their side-effects to happen.
4723 */
4725 continue;
4726
4727 /*
4728 * OK, we don't need it. Replace the expression with a NULL constant.
4729 * Preserve the exposed type of the expression, in case something
4730 * looks at the rowtype of the subquery's result.
4731 */
4732 tle->expr = (Expr *) makeNullConst(exprType(texpr),
4735 }
4736}
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:1864
Node * setOperations
Definition parsenodes.h:236
List * baserestrictinfo
Definition pathnodes.h:1130
Index relid
Definition pathnodes.h:1057
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, exprCollation(), expression_returns_set(), PathTarget::exprs, exprType(), exprTypmod(), fb(), FirstLowInvalidHeapAttributeNumber, lfirst, makeNullConst(), pull_varattnos(), RelOptInfo::relid, RelOptInfo::reltarget, 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 1307 of file allpaths.c.

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

References add_paths_to_append_rel(), RelOptInfo::consider_parallel, fb(), IS_DUMMY_REL, lappend(), lfirst, NIL, 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 1012 of file allpaths.c.

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

References add_child_rel_equivalences(), adjust_appendrel_attrs(), Assert, bms_is_empty, bms_overlap(), check_stack_depth(), RelOptInfo::consider_parallel, RelOptInfo::consider_partitionwise_join, enable_partitionwise_join, PathTarget::exprs, exprType(), exprTypmod(), fb(), 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(), pfree(), relation_excluded_by_constraints(), 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, 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 261 of file allpaths.c.

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

References bms_get_singleton_member(), RelOptInfo::consider_param_startup, fb(), 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 380 of file allpaths.c.

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

References Assert, fb(), 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 304 of file allpaths.c.

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

References Assert, fb(), 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 3049 of file allpaths.c.

3050{
3051 Path *ctepath;
3052 Plan *cteplan;
3054 Index levelsup;
3055 List *pathkeys;
3056 int ndx;
3057 ListCell *lc;
3058 int plan_id;
3060
3061 /*
3062 * Find the referenced CTE, and locate the path and plan previously made
3063 * for it.
3064 */
3065 levelsup = rte->ctelevelsup;
3066 cteroot = root;
3067 while (levelsup-- > 0)
3068 {
3069 cteroot = cteroot->parent_root;
3070 if (!cteroot) /* shouldn't happen */
3071 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3072 }
3073
3074 /*
3075 * Note: cte_plan_ids can be shorter than cteList, if we are still working
3076 * on planning the CTEs (ie, this is a side-reference from another CTE).
3077 * So we mustn't use forboth here.
3078 */
3079 ndx = 0;
3080 foreach(lc, cteroot->parse->cteList)
3081 {
3083
3084 if (strcmp(cte->ctename, rte->ctename) == 0)
3085 break;
3086 ndx++;
3087 }
3088 if (lc == NULL) /* shouldn't happen */
3089 elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3090 if (ndx >= list_length(cteroot->cte_plan_ids))
3091 elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3092 plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3093 if (plan_id <= 0)
3094 elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
3095
3096 Assert(list_length(root->glob->subpaths) == list_length(root->glob->subplans));
3097 ctepath = (Path *) list_nth(root->glob->subpaths, plan_id - 1);
3098 cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
3099
3100 /* Mark rel with estimated output rows, width, etc */
3101 set_cte_size_estimates(root, rel, cteplan->plan_rows);
3102
3103 /* Convert the ctepath's pathkeys to outer query's representation */
3105 rel,
3106 ctepath->pathkeys,
3107 cteplan->targetlist);
3108
3109 /*
3110 * We don't support pushing join clauses into the quals of a CTE scan, but
3111 * it could still have required parameterization due to LATERAL refs in
3112 * its tlist.
3113 */
3115
3116 /* Generate appropriate path */
3117 add_path(rel, create_ctescan_path(root, rel, pathkeys, required_outer));
3118}
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition costsize.c:6217
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:1970
static int list_nth_int(const List *list, int n)
Definition pg_list.h:310

References add_path(), Assert, convert_subquery_pathkeys(), create_ctescan_path(), CommonTableExpr::ctename, elog, ERROR, fb(), RelOptInfo::lateral_relids, lfirst, list_length(), list_nth(), list_nth_int(), root, and set_cte_size_estimates().

Referenced by set_rel_size().

◆ set_dummy_rel_pathlist()

static void set_dummy_rel_pathlist ( RelOptInfo rel)
static

Definition at line 2356 of file allpaths.c.

2357{
2358 AppendPathInput in = {0};
2359
2360 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2361 rel->rows = 0;
2362 rel->reltarget->width = 0;
2363
2364 /* Discard any pre-existing paths; no further need for them */
2365 rel->pathlist = NIL;
2366 rel->partial_pathlist = NIL;
2367
2368 /* Set up the dummy path */
2369 add_path(rel, (Path *) create_append_path(NULL, rel, in,
2370 NIL, rel->lateral_relids,
2371 0, false, -1));
2372
2373 /*
2374 * We set the cheapest-path fields immediately, just in case they were
2375 * pointing at some discarded path. This is redundant in current usage
2376 * because set_rel_pathlist will do it later, but it's cheap so we keep it
2377 * for safety and consistency with mark_dummy_rel.
2378 */
2379 set_cheapest(rel);
2380}

References add_path(), create_append_path(), fb(), 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 994 of file allpaths.c.

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

References fb(), RelOptInfo::relid, and root.

Referenced by set_rel_pathlist().

◆ set_foreign_size()

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

Definition at line 970 of file allpaths.c.

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

References clamp_row_est(), fb(), Max, RelOptInfo::relid, 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 2938 of file allpaths.c.

2939{
2941 List *pathkeys = NIL;
2942
2943 /*
2944 * We don't support pushing join clauses into the quals of a function
2945 * scan, but it could still have required parameterization due to LATERAL
2946 * refs in the function expression.
2947 */
2949
2950 /*
2951 * The result is considered unordered unless ORDINALITY was used, in which
2952 * case it is ordered by the ordinal column (the last one). See if we
2953 * care, by checking for uses of that Var in equivalence classes.
2954 */
2955 if (rte->funcordinality)
2956 {
2958 Var *var = NULL;
2959 ListCell *lc;
2960
2961 /*
2962 * Is there a Var for it in rel's targetlist? If not, the query did
2963 * not reference the ordinality column, or at least not in any way
2964 * that would be interesting for sorting.
2965 */
2966 foreach(lc, rel->reltarget->exprs)
2967 {
2968 Var *node = (Var *) lfirst(lc);
2969
2970 /* checking varno/varlevelsup is just paranoia */
2971 if (IsA(node, Var) &&
2972 node->varattno == ordattno &&
2973 node->varno == rel->relid &&
2974 node->varlevelsup == 0)
2975 {
2976 var = node;
2977 break;
2978 }
2979 }
2980
2981 /*
2982 * Try to build pathkeys for this Var with int8 sorting. We tell
2983 * build_expression_pathkey not to build any new equivalence class; if
2984 * the Var isn't already mentioned in some EC, it means that nothing
2985 * cares about the ordering.
2986 */
2987 if (var)
2988 pathkeys = build_expression_pathkey(root,
2989 (Expr *) var,
2991 rel->relids,
2992 false);
2993 }
2994
2995 /* Generate appropriate path */
2997 pathkeys, required_outer));
2998}
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:1892
Index varlevelsup
Definition primnodes.h:295

References add_path(), build_expression_pathkey(), create_functionscan_path(), PathTarget::exprs, fb(), 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 1370 of file allpaths.c.

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

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 3128 of file allpaths.c.

3130{
3132
3133 /* Mark rel with estimated output rows, width, etc */
3135
3136 /*
3137 * We don't support pushing join clauses into the quals of a tuplestore
3138 * scan, but it could still have required parameterization due to LATERAL
3139 * refs in its tlist.
3140 */
3142
3143 /* Generate appropriate path */
3145}
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6255
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1996

References add_path(), create_namedtuplestorescan_path(), fb(), 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 824 of file allpaths.c.

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

References add_path(), RelOptInfo::consider_parallel, create_index_paths(), create_plain_partial_paths(), create_seqscan_path(), create_tidscan_paths(), fb(), 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 628 of file allpaths.c.

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

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 645 of file allpaths.c.

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

References Assert, RelOptInfo::baserestrictinfo, castNode, RelOptInfo::consider_parallel, PathTarget::exprs, fb(), func_parallel(), 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, and RTE_VALUES.

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 516 of file allpaths.c.

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

References bms_equal(), elog, ERROR, fb(), generate_useful_gather_paths(), 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(), and set_values_pathlist().

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 407 of file allpaths.c.

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

References Assert, elog, ERROR, fb(), 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(), and set_worktable_pathlist().

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 3155 of file allpaths.c.

3157{
3159
3160 /* Mark rel with estimated output rows, width, etc */
3162
3163 /*
3164 * We don't support pushing join clauses into the quals of a Result scan,
3165 * but it could still have required parameterization due to LATERAL refs
3166 * in its tlist.
3167 */
3169
3170 /* Generate appropriate path */
3172}
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6288
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2022

References add_path(), create_resultscan_path(), fb(), 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 2669 of file allpaths.c.

2671{
2672 Query *parse = root->parse;
2673 Query *subquery = rte->subquery;
2674 bool trivial_pathtarget;
2677 double tuple_fraction;
2680 ListCell *lc;
2681 char *plan_name;
2682
2683 /*
2684 * Must copy the Query so that planning doesn't mess up the RTE contents
2685 * (really really need to fix the planner to not scribble on its input,
2686 * someday ... but see remove_unused_subquery_outputs to start with).
2687 */
2688 subquery = copyObject(subquery);
2689
2690 /*
2691 * If it's a LATERAL subquery, it might contain some Vars of the current
2692 * query level, requiring it to be treated as parameterized, even though
2693 * we don't support pushing down join quals into subqueries.
2694 */
2696
2697 /*
2698 * Zero out result area for subquery_is_pushdown_safe, so that it can set
2699 * flags as needed while recursing. In particular, we need a workspace
2700 * for keeping track of the reasons why columns are unsafe to reference.
2701 * These reasons are stored in the bits inside unsafeFlags[i] when we
2702 * discover reasons that column i of the subquery is unsafe to be used in
2703 * a pushed-down qual.
2704 */
2705 memset(&safetyInfo, 0, sizeof(safetyInfo));
2706 safetyInfo.unsafeFlags = (unsigned char *)
2707 palloc0((list_length(subquery->targetList) + 1) * sizeof(unsigned char));
2708
2709 /*
2710 * If the subquery has the "security_barrier" flag, it means the subquery
2711 * originated from a view that must enforce row-level security. Then we
2712 * must not push down quals that contain leaky functions. (Ideally this
2713 * would be checked inside subquery_is_pushdown_safe, but since we don't
2714 * currently pass the RTE to that function, we must do it here.)
2715 */
2716 safetyInfo.unsafeLeaky = rte->security_barrier;
2717
2718 /*
2719 * If there are any restriction clauses that have been attached to the
2720 * subquery relation, consider pushing them down to become WHERE or HAVING
2721 * quals of the subquery itself. This transformation is useful because it
2722 * may allow us to generate a better plan for the subquery than evaluating
2723 * all the subquery output rows and then filtering them.
2724 *
2725 * There are several cases where we cannot push down clauses. Restrictions
2726 * involving the subquery are checked by subquery_is_pushdown_safe().
2727 * Restrictions on individual clauses are checked by
2728 * qual_is_pushdown_safe(). Also, we don't want to push down
2729 * pseudoconstant clauses; better to have the gating node above the
2730 * subquery.
2731 *
2732 * Non-pushed-down clauses will get evaluated as qpquals of the
2733 * SubqueryScan node.
2734 *
2735 * XXX Are there any cases where we want to make a policy decision not to
2736 * push down a pushable qual, because it'd result in a worse plan?
2737 */
2738 if (rel->baserestrictinfo != NIL &&
2739 subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2740 {
2741 /* OK to consider pushing down individual quals */
2743 ListCell *l;
2744
2745 foreach(l, rel->baserestrictinfo)
2746 {
2747 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2748 Node *clause = (Node *) rinfo->clause;
2749
2750 if (rinfo->pseudoconstant)
2751 {
2753 continue;
2754 }
2755
2756 switch (qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2757 {
2758 case PUSHDOWN_SAFE:
2759 /* Push it down */
2760 subquery_push_qual(subquery, rte, rti, clause);
2761 break;
2762
2764
2765 /*
2766 * Since we can't push the qual down into the subquery,
2767 * check if it happens to reference a window function. If
2768 * so then it might be useful to use for the WindowAgg's
2769 * runCondition.
2770 */
2771 if (!subquery->hasWindowFuncs ||
2772 check_and_push_window_quals(subquery, clause,
2774 {
2775 /*
2776 * subquery has no window funcs or the clause is not a
2777 * suitable window run condition qual or it is, but
2778 * the original must also be kept in the upper query.
2779 */
2781 }
2782 break;
2783
2784 case PUSHDOWN_UNSAFE:
2786 break;
2787 }
2788 }
2790 /* We don't bother recomputing baserestrict_min_security */
2791 }
2792
2793 pfree(safetyInfo.unsafeFlags);
2794
2795 /*
2796 * The upper query might not use all the subquery's output columns; if
2797 * not, we can simplify. Pass the attributes that were pushed down into
2798 * WindowAgg run conditions to ensure we don't accidentally think those
2799 * are unused.
2800 */
2802
2803 /*
2804 * We can safely pass the outer tuple_fraction down to the subquery if the
2805 * outer level has no joining, aggregation, or sorting to do. Otherwise
2806 * we'd better tell the subquery to plan for full retrieval. (XXX This
2807 * could probably be made more intelligent ...)
2808 */
2809 if (parse->hasAggs ||
2810 parse->groupClause ||
2811 parse->groupingSets ||
2812 root->hasHavingQual ||
2813 parse->distinctClause ||
2814 parse->sortClause ||
2815 bms_membership(root->all_baserels) == BMS_MULTIPLE)
2816 tuple_fraction = 0.0; /* default case */
2817 else
2818 tuple_fraction = root->tuple_fraction;
2819
2820 /* plan_params should not be in use in current query level */
2821 Assert(root->plan_params == NIL);
2822
2823 /* Generate a subroot and Paths for the subquery */
2824 plan_name = choose_plan_name(root->glob, rte->eref->aliasname, false);
2825 rel->subroot = subquery_planner(root->glob, subquery, plan_name,
2826 root, false, tuple_fraction, NULL);
2827
2828 /* Isolate the params needed by this specific subplan */
2829 rel->subplan_params = root->plan_params;
2830 root->plan_params = NIL;
2831
2832 /*
2833 * It's possible that constraint exclusion proved the subquery empty. If
2834 * so, it's desirable to produce an unadorned dummy path so that we will
2835 * recognize appropriate optimizations at this query level.
2836 */
2838
2840 {
2842 return;
2843 }
2844
2845 /*
2846 * Mark rel with estimated output rows, width, etc. Note that we have to
2847 * do this before generating outer-query paths, else cost_subqueryscan is
2848 * not happy.
2849 */
2851
2852 /*
2853 * Also detect whether the reltarget is trivial, so that we can pass that
2854 * info to cost_subqueryscan (rather than re-deriving it multiple times).
2855 * It's trivial if it fetches all the subplan output columns in order.
2856 */
2857 if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2858 trivial_pathtarget = false;
2859 else
2860 {
2861 trivial_pathtarget = true;
2862 foreach(lc, rel->reltarget->exprs)
2863 {
2864 Node *node = (Node *) lfirst(lc);
2865 Var *var;
2866
2867 if (!IsA(node, Var))
2868 {
2869 trivial_pathtarget = false;
2870 break;
2871 }
2872 var = (Var *) node;
2873 if (var->varno != rti ||
2874 var->varattno != foreach_current_index(lc) + 1)
2875 {
2876 trivial_pathtarget = false;
2877 break;
2878 }
2879 }
2880 }
2881
2882 /*
2883 * For each Path that subquery_planner produced, make a SubqueryScanPath
2884 * in the outer query.
2885 */
2886 foreach(lc, sub_final_rel->pathlist)
2887 {
2888 Path *subpath = (Path *) lfirst(lc);
2889 List *pathkeys;
2890
2891 /* Convert subpath's pathkeys to outer representation */
2893 rel,
2894 subpath->pathkeys,
2895 make_tlist_from_pathtarget(subpath->pathtarget));
2896
2897 /* Generate outer path using this subpath */
2898 add_path(rel, (Path *)
2901 pathkeys, required_outer));
2902 }
2903
2904 /* If outer rel allows parallelism, do same for partial paths. */
2906 {
2907 /* If consider_parallel is false, there should be no partial paths. */
2908 Assert(sub_final_rel->consider_parallel ||
2909 sub_final_rel->partial_pathlist == NIL);
2910
2911 /* Same for partial paths. */
2912 foreach(lc, sub_final_rel->partial_pathlist)
2913 {
2914 Path *subpath = (Path *) lfirst(lc);
2915 List *pathkeys;
2916
2917 /* Convert subpath's pathkeys to outer representation */
2919 rel,
2920 subpath->pathkeys,
2921 make_tlist_from_pathtarget(subpath->pathtarget));
2922
2923 /* Generate outer path using this subpath */
2924 add_partial_path(rel, (Path *)
2927 pathkeys,
2929 }
2930 }
2931}
static pushdown_safe_type qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4430
static bool check_and_push_window_quals(Query *subquery, Node *clause, Bitmapset **run_cond_attrs)
Definition allpaths.c:2596
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
Definition allpaths.c:4631
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:765
@ BMS_MULTIPLE
Definition bitmapset.h:73
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6045
void parse(int)
Definition parse.c:49
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, bool trivial_pathtarget, List *pathkeys, Relids required_outer)
Definition pathnode.c:1862
@ UPPERREL_FINAL
Definition pathnodes.h:152
#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:9024
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition planner.c:743
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition relnode.c:1606
List * subplan_params
Definition pathnodes.h:1089
PlannerInfo * subroot
Definition pathnodes.h:1088

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, fb(), fetch_upper_rel(), foreach_current_index, IS_DUMMY_REL, IsA, lappend(), RelOptInfo::lateral_relids, lfirst, list_length(), make_tlist_from_pathtarget(), NIL, palloc0(), parse(), 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, subquery_is_pushdown_safe(), subquery_planner(), subquery_push_qual(), RelOptInfo::subroot, Query::targetList, 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 3025 of file allpaths.c.

3026{
3028
3029 /*
3030 * We don't support pushing join clauses into the quals of a tablefunc
3031 * scan, but it could still have required parameterization due to LATERAL
3032 * refs in the function expression.
3033 */
3035
3036 /* Generate appropriate path */
3039}
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1918

References add_path(), create_tablefuncscan_path(), fb(), 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 922 of file allpaths.c.

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

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 882 of file allpaths.c.

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

References check_index_predicates(), fb(), GetTsmRoutine(), RelOptInfo::pages, root, set_baserel_size_estimates(), 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 3005 of file allpaths.c.

3006{
3008
3009 /*
3010 * We don't support pushing join clauses into the quals of a values scan,
3011 * but it could still have required parameterization due to LATERAL refs
3012 * in the values expressions.
3013 */
3015
3016 /* Generate appropriate path */
3018}
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1944

References add_path(), create_valuesscan_path(), fb(), 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 3182 of file allpaths.c.

3183{
3184 Path *ctepath;
3186 Index levelsup;
3188
3189 /*
3190 * We need to find the non-recursive term's path, which is in the plan
3191 * level that's processing the recursive UNION, which is one level *below*
3192 * where the CTE comes from.
3193 */
3194 levelsup = rte->ctelevelsup;
3195 if (levelsup == 0) /* shouldn't happen */
3196 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3197 levelsup--;
3198 cteroot = root;
3199 while (levelsup-- > 0)
3200 {
3201 cteroot = cteroot->parent_root;
3202 if (!cteroot) /* shouldn't happen */
3203 elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3204 }
3205 ctepath = cteroot->non_recursive_path;
3206 if (!ctepath) /* shouldn't happen */
3207 elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
3208
3209 /* Mark rel with estimated output rows, width, etc */
3210 set_cte_size_estimates(root, rel, ctepath->rows);
3211
3212 /*
3213 * We don't support pushing join clauses into the quals of a worktable
3214 * scan, but it could still have required parameterization due to LATERAL
3215 * refs in its tlist. (I'm not sure this is actually possible given the
3216 * restrictions on recursive references, but it's easy enough to support.)
3217 */
3219
3220 /* Generate appropriate path */
3222}
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2048

References add_path(), create_worktablescan_path(), elog, ERROR, fb(), RelOptInfo::lateral_relids, root, RelOptInfo::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 346 of file allpaths.c.

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

References Assert, build_simple_grouped_rel(), fb(), 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 3938 of file allpaths.c.

3939{
3940 int lev;
3941 RelOptInfo *rel;
3942
3943 /*
3944 * This function cannot be invoked recursively within any one planning
3945 * problem, so join_rel_level[] can't be in use already.
3946 */
3947 Assert(root->join_rel_level == NULL);
3948
3949 /*
3950 * We employ a simple "dynamic programming" algorithm: we first find all
3951 * ways to build joins of two jointree items, then all ways to build joins
3952 * of three items (from two-item joins and single items), then four-item
3953 * joins, and so on until we have considered all ways to join all the
3954 * items into one rel.
3955 *
3956 * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3957 * set root->join_rel_level[1] to represent all the single-jointree-item
3958 * relations.
3959 */
3960 root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3961
3962 root->join_rel_level[1] = initial_rels;
3963
3964 for (lev = 2; lev <= levels_needed; lev++)
3965 {
3966 ListCell *lc;
3967
3968 /*
3969 * Determine all possible pairs of relations to be joined at this
3970 * level, and build paths for making each one from every available
3971 * pair of lower-level relations.
3972 */
3974
3975 /*
3976 * Run generate_partitionwise_join_paths() and
3977 * generate_useful_gather_paths() for each just-processed joinrel. We
3978 * could not do this earlier because both regular and partial paths
3979 * can get added to a particular joinrel at multiple times within
3980 * join_search_one_level.
3981 *
3982 * After that, we're done creating paths for the joinrel, so run
3983 * set_cheapest().
3984 *
3985 * In addition, we also run generate_grouped_paths() for the grouped
3986 * relation of each just-processed joinrel, and run set_cheapest() for
3987 * the grouped relation afterwards.
3988 */
3989 foreach(lc, root->join_rel_level[lev])
3990 {
3991 bool is_top_rel;
3992
3993 rel = (RelOptInfo *) lfirst(lc);
3994
3995 is_top_rel = bms_equal(rel->relids, root->all_query_rels);
3996
3997 /* Create paths for partitionwise joins. */
3999
4000 /*
4001 * Except for the topmost scan/join rel, consider gathering
4002 * partial paths. We'll do the same for the topmost scan/join rel
4003 * once we know the final targetlist (see grouping_planner's and
4004 * its call to apply_scanjoin_target_to_paths).
4005 */
4006 if (!is_top_rel)
4008
4009 /* Find and save the cheapest paths for this rel */
4010 set_cheapest(rel);
4011
4012 /*
4013 * Except for the topmost scan/join rel, consider generating
4014 * partial aggregation paths for the grouped relation on top of
4015 * the paths of this rel. After that, we're done creating paths
4016 * for the grouped relation, so run set_cheapest().
4017 */
4018 if (rel->grouped_rel != NULL && !is_top_rel)
4019 {
4020 RelOptInfo *grouped_rel = rel->grouped_rel;
4021
4022 Assert(IS_GROUPED_REL(grouped_rel));
4023
4024 generate_grouped_paths(root, grouped_rel, rel);
4025 set_cheapest(grouped_rel);
4026 }
4027
4028#ifdef OPTIMIZER_DEBUG
4029 pprint(rel);
4030#endif
4031 }
4032 }
4033
4034 /*
4035 * We should have a single rel at the final level.
4036 */
4037 if (root->join_rel_level[levels_needed] == NIL)
4038 elog(ERROR, "failed to build any %d-way joins", levels_needed);
4039 Assert(list_length(root->join_rel_level[levels_needed]) == 1);
4040
4041 rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
4042
4043 root->join_rel_level = NULL;
4044
4045 return rel;
4046}
void join_search_one_level(PlannerInfo *root, int level)
Definition joinrels.c:78

References Assert, bms_equal(), elog, ERROR, fb(), 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 4133 of file allpaths.c.

4135{
4137
4138 /* Check point 1 */
4139 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
4140 return false;
4141
4142 /* Check point 6 */
4143 if (subquery->groupClause && subquery->groupingSets)
4144 return false;
4145
4146 /* Check points 3, 4, and 5 */
4147 if (subquery->distinctClause ||
4148 subquery->hasWindowFuncs ||
4149 subquery->hasTargetSRFs)
4150 safetyInfo->unsafeVolatile = true;
4151
4152 /*
4153 * If we're at a leaf query, check for unsafe expressions in its target
4154 * list, and mark any reasons why they're unsafe in unsafeFlags[].
4155 * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
4156 * so no need to check them.)
4157 */
4158 if (subquery->setOperations == NULL)
4160
4161 /* Are we at top level, or looking at a setop component? */
4162 if (subquery == topquery)
4163 {
4164 /* Top level, so check any component queries */
4165 if (subquery->setOperations != NULL)
4167 safetyInfo))
4168 return false;
4169 }
4170 else
4171 {
4172 /* Setop component must not have more components (too weird) */
4173 if (subquery->setOperations != NULL)
4174 return false;
4175 /* Check whether setop component output types match top level */
4176 topop = castNode(SetOperationStmt, topquery->setOperations);
4177 Assert(topop);
4179 topop->colTypes,
4180 safetyInfo);
4181 }
4182 return true;
4183}
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4354
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4258
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, fb(), Query::groupClause, Query::groupingSets, Query::limitCount, Query::limitOffset, recurse_pushdown_safe(), Query::setOperations, and Query::targetList.

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 4531 of file allpaths.c.

4532{
4533 if (subquery->setOperations != NULL)
4534 {
4535 /* Recurse to push it separately to each component query */
4536 recurse_push_qual(subquery->setOperations, subquery,
4537 rte, rti, qual);
4538 }
4539 else
4540 {
4541 /*
4542 * We need to replace Vars in the qual (which must refer to outputs of
4543 * the subquery) with copies of the subquery's targetlist expressions.
4544 * Note that at this point, any uplevel Vars in the qual should have
4545 * been replaced with Params, so they need no work.
4546 *
4547 * This step also ensures that when we are pushing into a setop tree,
4548 * each component query gets its own copy of the qual.
4549 */
4550 qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
4551 subquery->targetList,
4552 subquery->resultRelation,
4554 &subquery->hasSubLinks);
4555
4556 /*
4557 * Now attach the qual to the proper place: normally WHERE, but if the
4558 * subquery uses grouping or aggregation, put it in HAVING (since the
4559 * qual really refers to the group-result rows).
4560 */
4561 if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
4562 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
4563 else
4564 subquery->jointree->quals =
4565 make_and_qual(subquery->jointree->quals, qual);
4566
4567 /*
4568 * We need not change the subquery's hasAggs or hasSubLinks flags,
4569 * since we can't be pushing down any aggregates that weren't there
4570 * before, and we don't push down subselects at all.
4571 */
4572 }
4573}
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
Node * quals
Definition primnodes.h:2359
FromExpr * jointree
Definition parsenodes.h:182
Node * havingQual
Definition parsenodes.h:222

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

4388{
4389 ListCell *lc;
4390
4391 foreach(lc, query->windowClause)
4392 {
4394
4396 return false;
4397 }
4398 return true;
4399}
List * partitionClause

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