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 Oid pushdown_var_grouping_eqop (Var *var, void *context)
 
static Oid subquery_column_grouping_eqop (Query *subquery, AttrNumber attno)
 
static Oid setop_column_grouping_eqop (Node *setop, AttrNumber attno)
 
static bool setop_has_grouping (Node *setop)
 
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 2256 of file allpaths.c.

2258{
2259 if (IsA(path, AppendPath))
2260 {
2261 AppendPath *apath = (AppendPath *) path;
2262
2263 if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2264 {
2265 *subpaths = list_concat(*subpaths, apath->subpaths);
2266 *child_append_relid_sets =
2267 lappend(*child_append_relid_sets, path->parent->relids);
2268 *child_append_relid_sets =
2269 list_concat(*child_append_relid_sets,
2270 apath->child_append_relid_sets);
2271 return;
2272 }
2273 else if (special_subpaths != NULL)
2274 {
2276
2277 /* Split Parallel Append into partial and non-partial subpaths */
2278 *subpaths = list_concat(*subpaths,
2279 list_copy_tail(apath->subpaths,
2280 apath->first_partial_path));
2282 apath->first_partial_path);
2285 *child_append_relid_sets =
2286 lappend(*child_append_relid_sets, path->parent->relids);
2287 *child_append_relid_sets =
2288 list_concat(*child_append_relid_sets,
2289 apath->child_append_relid_sets);
2290 return;
2291 }
2292 }
2293 else if (IsA(path, MergeAppendPath))
2294 {
2296
2297 *subpaths = list_concat(*subpaths, mpath->subpaths);
2298 *child_append_relid_sets =
2299 lappend(*child_append_relid_sets, path->parent->relids);
2300 *child_append_relid_sets =
2301 list_concat(*child_append_relid_sets,
2302 mpath->child_append_relid_sets);
2303 return;
2304 }
2305
2306 *subpaths = lappend(*subpaths, path);
2307}
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:162
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 1420 of file allpaths.c.

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

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

2612{
2613 OpExpr *opexpr = (OpExpr *) clause;
2614 bool keep_original = true;
2615 Var *var1;
2616 Var *var2;
2617
2618 /* We're only able to use OpExprs with 2 operands */
2619 if (!IsA(opexpr, OpExpr))
2620 return true;
2621
2622 if (list_length(opexpr->args) != 2)
2623 return true;
2624
2625 /*
2626 * Currently, we restrict this optimization to strict OpExprs. The reason
2627 * for this is that during execution, once the runcondition becomes false,
2628 * we stop evaluating WindowFuncs. To avoid leaving around stale window
2629 * function result values, we set them to NULL. Having only strict
2630 * OpExprs here ensures that we properly filter out the tuples with NULLs
2631 * in the top-level WindowAgg.
2632 */
2633 set_opfuncid(opexpr);
2634 if (!func_strict(opexpr->opfuncid))
2635 return true;
2636
2637 /*
2638 * Check for plain Vars that reference window functions in the subquery.
2639 * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2640 * be used as part of the run condition.
2641 */
2642
2643 /* Check the left side of the OpExpr */
2644 var1 = linitial(opexpr->args);
2645 if (IsA(var1, Var) && var1->varattno > 0)
2646 {
2647 TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2648 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2649
2650 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2652 return keep_original;
2653 }
2654
2655 /* and check the right side */
2656 var2 = lsecond(opexpr->args);
2657 if (IsA(var2, Var) && var2->varattno > 0)
2658 {
2659 TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2660 WindowFunc *wfunc = (WindowFunc *) tle->expr;
2661
2662 if (find_window_run_conditions(subquery, tle->resno, wfunc, opexpr,
2663 false, &keep_original, run_cond_attrs))
2664 return keep_original;
2665 }
2666
2667 return true;
2668}
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:2420
bool func_strict(Oid funcid)
Definition lsyscache.c:2075
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1890
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define lsecond(l)
Definition pg_list.h:183
List * args
Definition primnodes.h:853
List * targetList
Definition parsenodes.h:203

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

4273{
4275 ListCell *lc;
4276
4277 /*
4278 * We must be careful with grouping Vars and join alias Vars in the
4279 * subquery's outputs, as they hide the underlying expressions.
4280 *
4281 * We need to expand grouping Vars to their underlying expressions (the
4282 * grouping clauses) because the grouping expressions themselves might be
4283 * volatile or set-returning. However, we do not need to expand join
4284 * alias Vars, as their underlying structure does not introduce volatile
4285 * or set-returning functions at the current level.
4286 *
4287 * In neither case do we need to recursively examine the Vars contained in
4288 * these underlying expressions. Even if they reference outputs from
4289 * lower-level subqueries (at any depth), those references are guaranteed
4290 * not to expand to volatile or set-returning functions, because
4291 * subqueries containing such functions in their targetlists are never
4292 * pulled up.
4293 */
4294 if (subquery->hasGroupRTE)
4295 {
4296 /*
4297 * We can safely pass NULL for the root here. This function uses the
4298 * expanded expressions solely to check for volatile or set-returning
4299 * functions, which is independent of the Vars' nullingrels.
4300 */
4302 flatten_group_exprs(NULL, subquery, (Node *) subquery->targetList);
4303 }
4304
4305 foreach(lc, flattened_targetList)
4306 {
4308
4309 if (tle->resjunk)
4310 continue; /* ignore resjunk columns */
4311
4312 /* Functions returning sets are unsafe (point 1) */
4313 if (subquery->hasTargetSRFs &&
4314 (safetyInfo->unsafeFlags[tle->resno] &
4315 UNSAFE_HAS_SET_FUNC) == 0 &&
4316 expression_returns_set((Node *) tle->expr))
4317 {
4318 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
4319 continue;
4320 }
4321
4322 /* Volatile functions are unsafe (point 2) */
4323 if ((safetyInfo->unsafeFlags[tle->resno] &
4326 {
4327 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
4328 continue;
4329 }
4330
4331 /* If subquery uses DISTINCT ON, check point 3 */
4332 if (subquery->hasDistinctOn &&
4333 (safetyInfo->unsafeFlags[tle->resno] &
4336 {
4337 /* non-DISTINCT column, so mark it unsafe */
4338 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_DISTINCTON_CLAUSE;
4339 continue;
4340 }
4341
4342 /* If subquery uses window functions, check point 4 */
4343 if (subquery->hasWindowFuncs &&
4344 (safetyInfo->unsafeFlags[tle->resno] &
4346 !targetIsInAllPartitionLists(tle, subquery))
4347 {
4348 /* not present in all PARTITION BY clauses, so mark it unsafe */
4349 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_PARTITIONBY_CLAUSE;
4350 continue;
4351 }
4352 }
4353}
#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:4406
#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:567
bool expression_returns_set(Node *clause)
Definition nodeFuncs.c:768
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition nodes.h:133
List * distinctClause
Definition parsenodes.h:231
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition var.c:999

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

4375{
4376 ListCell *l;
4378
4379 foreach(l, tlist)
4380 {
4382
4383 if (tle->resjunk)
4384 continue; /* ignore resjunk columns */
4385 if (colType == NULL)
4386 elog(ERROR, "wrong number of tlist entries");
4387 if (exprType((Node *) tle->expr) != lfirst_oid(colType))
4388 safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
4390 }
4391 if (colType != NULL)
4392 elog(ERROR, "wrong number of tlist entries");
4393}
#define UNSAFE_TYPE_MISMATCH
Definition allpaths.c:59
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
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:375
#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 4973 of file allpaths.c.

4975{
4976 int parallel_workers = 0;
4977
4978 /*
4979 * If the user has set the parallel_workers reloption, use that; otherwise
4980 * select a default number of workers.
4981 */
4982 if (rel->rel_parallel_workers != -1)
4983 parallel_workers = rel->rel_parallel_workers;
4984 else
4985 {
4986 /*
4987 * If the number of pages being scanned is insufficient to justify a
4988 * parallel scan, just return zero ... unless it's an inheritance
4989 * child. In that case, we want to generate a parallel path here
4990 * anyway. It might not be worthwhile just for this relation, but
4991 * when combined with all of its inheritance siblings it may well pay
4992 * off.
4993 */
4994 if (rel->reloptkind == RELOPT_BASEREL &&
4997 return 0;
4998
4999 if (heap_pages >= 0)
5000 {
5002 int heap_parallel_workers = 1;
5003
5004 /*
5005 * Select the number of workers based on the log of the size of
5006 * the relation. This probably needs to be a good deal more
5007 * sophisticated, but we need something here for now. Note that
5008 * the upper limit of the min_parallel_table_scan_size GUC is
5009 * chosen to prevent overflow here.
5010 */
5013 {
5017 break; /* avoid overflow */
5018 }
5019
5020 parallel_workers = heap_parallel_workers;
5021 }
5022
5023 if (index_pages >= 0)
5024 {
5025 int index_parallel_workers = 1;
5027
5028 /* same calculation as for heap_pages above */
5031 {
5035 break; /* avoid overflow */
5036 }
5037
5038 if (parallel_workers > 0)
5039 parallel_workers = Min(parallel_workers, index_parallel_workers);
5040 else
5041 parallel_workers = index_parallel_workers;
5042 }
5043 }
5044
5045 /* In no case use more than caller supplied maximum number of workers */
5046 parallel_workers = Min(parallel_workers, max_workers);
5047
5048 return parallel_workers;
5049}
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:977
RelOptKind reloptkind
Definition pathnodes.h:1015
int rel_parallel_workers
Definition pathnodes.h:1103

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

4939{
4940 int parallel_workers;
4941 double pages_fetched;
4942
4943 /* Compute heap pages for bitmap heap scan */
4944 pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4945 NULL, NULL);
4946
4947 parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4949
4950 if (parallel_workers <= 0)
4951 return;
4952
4954 bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4955}
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition allpaths.c:4973
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition costsize.c:6658
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition pathnode.c:1149
Relids lateral_relids
Definition pathnodes.h:1064

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

877{
878 int parallel_workers;
879
880 parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
882
883 /* If any limit was set to zero, the user doesn't want a parallel scan. */
884 if (parallel_workers <= 0)
885 return;
886
887 /* Add an unordered partial path based on a parallel sequential scan. */
888 add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
889}
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition pathnode.c:1026
BlockNumber pages
Definition pathnodes.h:1095

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

2423{
2425 Expr *otherexpr;
2429 List *opinfos;
2432 ListCell *lc;
2433
2434 *keep_original = true;
2435
2436 while (IsA(wfunc, RelabelType))
2437 wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2438
2439 /* we can only work with window functions */
2440 if (!IsA(wfunc, WindowFunc))
2441 return false;
2442
2443 /* can't use it if there are subplans in the WindowFunc */
2444 if (contain_subplans((Node *) wfunc))
2445 return false;
2446
2447 prosupport = get_func_support(wfunc->winfnoid);
2448
2449 /* Check if there's a support function for 'wfunc' */
2450 if (!OidIsValid(prosupport))
2451 return false;
2452
2453 /* get the Expr from the other side of the OpExpr */
2454 if (wfunc_left)
2455 otherexpr = lsecond(opexpr->args);
2456 else
2457 otherexpr = linitial(opexpr->args);
2458
2459 /*
2460 * The value being compared must not change during the evaluation of the
2461 * window partition.
2462 */
2464 return false;
2465
2466 /* find the window clause belonging to the window function */
2467 wclause = (WindowClause *) list_nth(subquery->windowClause,
2468 wfunc->winref - 1);
2469
2471 req.window_func = wfunc;
2472 req.window_clause = wclause;
2473
2474 /* call the support function */
2477 PointerGetDatum(&req)));
2478
2479 /*
2480 * Nothing to do if the function is neither monotonically increasing nor
2481 * monotonically decreasing.
2482 */
2483 if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2484 return false;
2485
2486 runopexpr = NULL;
2489
2490 foreach(lc, opinfos)
2491 {
2493 CompareType cmptype = opinfo->cmptype;
2494
2495 /* handle < / <= */
2496 if (cmptype == COMPARE_LT || cmptype == COMPARE_LE)
2497 {
2498 /*
2499 * < / <= is supported for monotonically increasing functions in
2500 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2501 * for monotonically decreasing functions.
2502 */
2503 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2504 (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2505 {
2506 *keep_original = false;
2507 runopexpr = opexpr;
2508 runoperator = opexpr->opno;
2509 }
2510 break;
2511 }
2512 /* handle > / >= */
2513 else if (cmptype == COMPARE_GT || cmptype == COMPARE_GE)
2514 {
2515 /*
2516 * > / >= is supported for monotonically decreasing functions in
2517 * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2518 * for monotonically increasing functions.
2519 */
2520 if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2521 (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2522 {
2523 *keep_original = false;
2524 runopexpr = opexpr;
2525 runoperator = opexpr->opno;
2526 }
2527 break;
2528 }
2529 /* handle = */
2530 else if (cmptype == COMPARE_EQ)
2531 {
2533
2534 /*
2535 * When both monotonically increasing and decreasing then the
2536 * return value of the window function will be the same each time.
2537 * We can simply use 'opexpr' as the run condition without
2538 * modifying it.
2539 */
2541 {
2542 *keep_original = false;
2543 runopexpr = opexpr;
2544 runoperator = opexpr->opno;
2545 break;
2546 }
2547
2548 /*
2549 * When monotonically increasing we make a qual with <wfunc> <=
2550 * <value> or <value> >= <wfunc> in order to filter out values
2551 * which are above the value in the equality condition. For
2552 * monotonically decreasing functions we want to filter values
2553 * below the value in the equality condition.
2554 */
2556 newcmptype = wfunc_left ? COMPARE_LE : COMPARE_GE;
2557 else
2558 newcmptype = wfunc_left ? COMPARE_GE : COMPARE_LE;
2559
2560 /* We must keep the original equality qual */
2561 *keep_original = true;
2562 runopexpr = opexpr;
2563
2564 /* determine the operator to use for the WindowFuncRunCondition */
2566 opinfo->oplefttype,
2567 opinfo->oprighttype,
2568 newcmptype);
2569 break;
2570 }
2571 }
2572
2573 if (runopexpr != NULL)
2574 {
2576
2578 wfuncrc->opno = runoperator;
2579 wfuncrc->inputcollid = runopexpr->inputcollid;
2580 wfuncrc->wfunc_left = wfunc_left;
2582
2583 wfunc->runCondition = lappend(wfunc->runCondition, wfuncrc);
2584
2585 /* record that this attno was used in a run condition */
2588 return true;
2589 }
2590
2591 /* unsupported OpExpr */
2592 return false;
2593}
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define OidIsValid(objectId)
Definition c.h:917
bool is_pseudo_constant_clause(Node *clause)
Definition clauses.c:2349
bool contain_subplans(Node *clause)
Definition clauses.c:359
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:1323
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:726
Oid get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype, CompareType cmptype)
Definition lsyscache.c:199
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2172
List * get_op_index_interpretation(Oid opno)
Definition lsyscache.c:729
#define copyObject(obj)
Definition nodes.h:230
#define makeNode(_type_)
Definition nodes.h:159
@ MONOTONICFUNC_NONE
Definition plannodes.h:1839
@ MONOTONICFUNC_DECREASING
Definition plannodes.h:1841
@ MONOTONICFUNC_INCREASING
Definition plannodes.h:1840
@ MONOTONICFUNC_BOTH
Definition plannodes.h:1842
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
#define PointerGetDatum(X)
Definition postgres.h:354
unsigned int Oid
Oid opno
Definition primnodes.h:835
CompareType cmptype
Definition lsyscache.h:28
List * windowClause
Definition parsenodes.h:229
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 3255 of file allpaths.c.

3256{
3259 ListCell *lc;
3260 double rows;
3261 double *rowsp = NULL;
3262
3263 /* If there are no partial paths, there's nothing to do here. */
3264 if (rel->partial_pathlist == NIL)
3265 return;
3266
3267 /* Should we override the rel's rowcount estimate? */
3268 if (override_rows)
3269 rowsp = &rows;
3270
3271 /*
3272 * The output of Gather is always unsorted, so there's only one partial
3273 * path of interest: the cheapest one. That will be the one at the front
3274 * of partial_pathlist because of the way add_partial_path works.
3275 */
3280 NULL, rowsp);
3282
3283 /*
3284 * For each useful ordering, we can consider an order-preserving Gather
3285 * Merge.
3286 */
3287 foreach(lc, rel->partial_pathlist)
3288 {
3289 Path *subpath = (Path *) lfirst(lc);
3290 GatherMergePath *path;
3291
3292 if (subpath->pathkeys == NIL)
3293 continue;
3294
3297 subpath->pathkeys, NULL, rowsp);
3298 add_path(rel, &path->path);
3299 }
3300}
double compute_gather_rows(Path *path)
Definition costsize.c:6769
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition pathnode.c:1813
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition pathnode.c:1865
struct PathTarget * reltarget
Definition pathnodes.h:1045
List * partial_pathlist
Definition pathnodes.h:1052

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

3511{
3512 RelAggInfo *agg_info = grouped_rel->agg_info;
3514 bool can_hash;
3515 bool can_sort;
3516 Path *cheapest_total_path = NULL;
3518 double dNumGroups = 0;
3519 double dNumPartialGroups = 0;
3520 List *group_pathkeys = NIL;
3521
3522 if (IS_DUMMY_REL(rel))
3523 {
3524 mark_dummy_rel(grouped_rel);
3525 return;
3526 }
3527
3528 /*
3529 * We push partial aggregation only to the lowest possible level in the
3530 * join tree that is deemed useful.
3531 */
3532 if (!bms_equal(agg_info->apply_agg_at, rel->relids) ||
3533 !agg_info->agg_useful)
3534 return;
3535
3536 MemSet(&agg_costs, 0, sizeof(AggClauseCosts));
3538
3539 /*
3540 * Determine whether it's possible to perform sort-based implementations
3541 * of grouping, and generate the pathkeys that represent the grouping
3542 * requirements in that case.
3543 */
3545 if (can_sort)
3546 {
3549
3551 rel->top_parent->grouped_rel : grouped_rel;
3554
3555 group_pathkeys =
3558 }
3559
3560 /*
3561 * Determine whether we should consider hash-based implementations of
3562 * grouping.
3563 */
3564 Assert(root->numOrderedAggs == 0);
3565 can_hash = (agg_info->group_clauses != NIL &&
3567
3568 /*
3569 * Consider whether we should generate partially aggregated non-partial
3570 * paths. We can only do this if we have a non-partial path.
3571 */
3572 if (rel->pathlist != NIL)
3573 {
3574 cheapest_total_path = rel->cheapest_total_path;
3575 Assert(cheapest_total_path != NULL);
3576 }
3577
3578 /*
3579 * If parallelism is possible for grouped_rel, then we should consider
3580 * generating partially-grouped partial paths. However, if the ungrouped
3581 * rel has no partial paths, then we can't.
3582 */
3583 if (grouped_rel->consider_parallel && rel->partial_pathlist != NIL)
3584 {
3587 }
3588
3589 /* Estimate number of partial groups. */
3590 if (cheapest_total_path != NULL)
3592 agg_info->group_exprs,
3593 cheapest_total_path->rows,
3594 NULL, NULL);
3597 agg_info->group_exprs,
3599 NULL, NULL);
3600
3601 if (can_sort && cheapest_total_path != NULL)
3602 {
3603 ListCell *lc;
3604
3605 /*
3606 * Use any available suitably-sorted path as input, and also consider
3607 * sorting the cheapest-total path and incremental sort on any paths
3608 * with presorted keys.
3609 *
3610 * To save planning time, we ignore parameterized input paths unless
3611 * they are the cheapest-total path.
3612 */
3613 foreach(lc, rel->pathlist)
3614 {
3615 Path *input_path = (Path *) lfirst(lc);
3616 Path *path;
3617 bool is_sorted;
3618 int presorted_keys;
3619
3620 /*
3621 * Ignore parameterized paths that are not the cheapest-total
3622 * path.
3623 */
3624 if (input_path->param_info &&
3625 input_path != cheapest_total_path)
3626 continue;
3627
3628 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3629 input_path->pathkeys,
3630 &presorted_keys);
3631
3632 /*
3633 * Ignore paths that are not suitably or partially sorted, unless
3634 * they are the cheapest total path (no need to deal with paths
3635 * which have presorted keys when incremental sort is disabled).
3636 */
3637 if (!is_sorted && input_path != cheapest_total_path &&
3638 (presorted_keys == 0 || !enable_incremental_sort))
3639 continue;
3640
3641 /*
3642 * Since the path originates from a non-grouped relation that is
3643 * not aware of eager aggregation, we must ensure that it provides
3644 * the correct input for partial aggregation.
3645 */
3646 path = (Path *) create_projection_path(root,
3647 grouped_rel,
3648 input_path,
3649 agg_info->agg_input);
3650
3651 if (!is_sorted)
3652 {
3653 /*
3654 * We've no need to consider both a sort and incremental sort.
3655 * We'll just do a sort if there are no presorted keys and an
3656 * incremental sort when there are presorted keys.
3657 */
3658 if (presorted_keys == 0 || !enable_incremental_sort)
3659 path = (Path *) create_sort_path(root,
3660 grouped_rel,
3661 path,
3662 group_pathkeys,
3663 -1.0);
3664 else
3666 grouped_rel,
3667 path,
3668 group_pathkeys,
3669 presorted_keys,
3670 -1.0);
3671 }
3672
3673 /*
3674 * qual is NIL because the HAVING clause cannot be evaluated until
3675 * the final value of the aggregate is known.
3676 */
3677 path = (Path *) create_agg_path(root,
3678 grouped_rel,
3679 path,
3680 agg_info->target,
3681 AGG_SORTED,
3683 agg_info->group_clauses,
3684 NIL,
3685 &agg_costs,
3686 dNumGroups);
3687
3688 add_path(grouped_rel, path);
3689 }
3690 }
3691
3693 {
3694 ListCell *lc;
3695
3696 /* Similar to above logic, but for partial paths. */
3697 foreach(lc, rel->partial_pathlist)
3698 {
3699 Path *input_path = (Path *) lfirst(lc);
3700 Path *path;
3701 bool is_sorted;
3702 int presorted_keys;
3703
3704 is_sorted = pathkeys_count_contained_in(group_pathkeys,
3705 input_path->pathkeys,
3706 &presorted_keys);
3707
3708 /*
3709 * Ignore paths that are not suitably or partially sorted, unless
3710 * they are the cheapest partial path (no need to deal with paths
3711 * which have presorted keys when incremental sort is disabled).
3712 */
3714 (presorted_keys == 0 || !enable_incremental_sort))
3715 continue;
3716
3717 /*
3718 * Since the path originates from a non-grouped relation that is
3719 * not aware of eager aggregation, we must ensure that it provides
3720 * the correct input for partial aggregation.
3721 */
3722 path = (Path *) create_projection_path(root,
3723 grouped_rel,
3724 input_path,
3725 agg_info->agg_input);
3726
3727 if (!is_sorted)
3728 {
3729 /*
3730 * We've no need to consider both a sort and incremental sort.
3731 * We'll just do a sort if there are no presorted keys and an
3732 * incremental sort when there are presorted keys.
3733 */
3734 if (presorted_keys == 0 || !enable_incremental_sort)
3735 path = (Path *) create_sort_path(root,
3736 grouped_rel,
3737 path,
3738 group_pathkeys,
3739 -1.0);
3740 else
3742 grouped_rel,
3743 path,
3744 group_pathkeys,
3745 presorted_keys,
3746 -1.0);
3747 }
3748
3749 /*
3750 * qual is NIL because the HAVING clause cannot be evaluated until
3751 * the final value of the aggregate is known.
3752 */
3753 path = (Path *) create_agg_path(root,
3754 grouped_rel,
3755 path,
3756 agg_info->target,
3757 AGG_SORTED,
3759 agg_info->group_clauses,
3760 NIL,
3761 &agg_costs,
3763
3764 add_partial_path(grouped_rel, path);
3765 }
3766 }
3767
3768 /*
3769 * Add a partially-grouped HashAgg Path where possible
3770 */
3771 if (can_hash && cheapest_total_path != NULL)
3772 {
3773 Path *path;
3774
3775 /*
3776 * Since the path originates from a non-grouped relation that is not
3777 * aware of eager aggregation, we must ensure that it provides the
3778 * correct input for partial aggregation.
3779 */
3780 path = (Path *) create_projection_path(root,
3781 grouped_rel,
3782 cheapest_total_path,
3783 agg_info->agg_input);
3784
3785 /*
3786 * qual is NIL because the HAVING clause cannot be evaluated until the
3787 * final value of the aggregate is known.
3788 */
3789 path = (Path *) create_agg_path(root,
3790 grouped_rel,
3791 path,
3792 agg_info->target,
3793 AGG_HASHED,
3795 agg_info->group_clauses,
3796 NIL,
3797 &agg_costs,
3798 dNumGroups);
3799
3800 add_path(grouped_rel, path);
3801 }
3802
3803 /*
3804 * Now add a partially-grouped HashAgg partial Path where possible
3805 */
3807 {
3808 Path *path;
3809
3810 /*
3811 * Since the path originates from a non-grouped relation that is not
3812 * aware of eager aggregation, we must ensure that it provides the
3813 * correct input for partial aggregation.
3814 */
3815 path = (Path *) create_projection_path(root,
3816 grouped_rel,
3818 agg_info->agg_input);
3819
3820 /*
3821 * qual is NIL because the HAVING clause cannot be evaluated until the
3822 * final value of the aggregate is known.
3823 */
3824 path = (Path *) create_agg_path(root,
3825 grouped_rel,
3826 path,
3827 agg_info->target,
3828 AGG_HASHED,
3830 agg_info->group_clauses,
3831 NIL,
3832 &agg_costs,
3834
3835 add_partial_path(grouped_rel, path);
3836 }
3837}
#define MemSet(start, val, len)
Definition c.h:1166
bool enable_incremental_sort
Definition costsize.c:152
void mark_dummy_rel(RelOptInfo *rel)
Definition joinrels.c:1513
@ AGG_SORTED
Definition nodes.h:363
@ AGG_HASHED
Definition nodes.h:364
@ AGGSPLIT_INITIAL_SERIAL
Definition nodes.h:387
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:2587
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition pathnode.c:2855
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition pathnode.c:2904
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:3057
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2299
#define IS_OTHER_REL(rel)
Definition pathnodes.h:1004
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:3802
Cardinality rows
Definition pathnodes.h:2005
Relids apply_agg_at
Definition pathnodes.h:1302
List * group_exprs
Definition pathnodes.h:1299
bool agg_useful
Definition pathnodes.h:1308
List * group_clauses
Definition pathnodes.h:1297
struct PathTarget * agg_input
Definition pathnodes.h:1294
struct PathTarget * target
Definition pathnodes.h:1291
Relids relids
Definition pathnodes.h:1021
struct RelAggInfo * agg_info
Definition pathnodes.h:1162
List * pathlist
Definition pathnodes.h:1050
struct Path * cheapest_total_path
Definition pathnodes.h:1054
struct RelOptInfo * grouped_rel
Definition pathnodes.h:1164
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 1852 of file allpaths.c.

1855{
1856 ListCell *lcp;
1859 bool partition_pathkeys_partial = true;
1861
1862 /*
1863 * Some partitioned table setups may allow us to use an Append node
1864 * instead of a MergeAppend. This is possible in cases such as RANGE
1865 * partitioned tables where it's guaranteed that an earlier partition must
1866 * contain rows which come earlier in the sort order. To detect whether
1867 * this is relevant, build pathkey descriptions of the partition ordering,
1868 * for both forward and reverse scans.
1869 */
1870 if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1871 partitions_are_ordered(rel->boundinfo, rel->live_parts))
1872 {
1876
1880
1881 /*
1882 * You might think we should truncate_useless_pathkeys here, but
1883 * allowing partition keys which are a subset of the query's pathkeys
1884 * can often be useful. For example, consider a table partitioned by
1885 * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1886 * paths that can produce the a, b, c ordering (perhaps via indexes on
1887 * (a, b, c)) then it works to consider the appendrel output as
1888 * ordered by a, b, c.
1889 */
1890 }
1891
1892 /* Now consider each interesting sort ordering */
1893 foreach(lcp, all_child_pathkeys)
1894 {
1895 List *pathkeys = (List *) lfirst(lcp);
1896 AppendPathInput startup = {0};
1897 AppendPathInput total = {0};
1899 bool startup_neq_total = false;
1900 bool fraction_neq_total = false;
1903 int end_index;
1904 int first_index;
1905 int direction;
1906
1907 /*
1908 * Determine if this sort ordering matches any partition pathkeys we
1909 * have, for both ascending and descending partition order. If the
1910 * partition pathkeys happen to be contained in pathkeys then it still
1911 * works, as described above, providing that the partition pathkeys
1912 * are complete and not just a prefix of the partition keys. (In such
1913 * cases we'll be relying on the child paths to have sorted the
1914 * lower-order columns of the required pathkeys.)
1915 */
1920
1925
1926 /*
1927 * When the required pathkeys match the reverse of the partition
1928 * order, we must build the list of paths in reverse starting with the
1929 * last matching partition first. We can get away without making any
1930 * special cases for this in the loop below by just looping backward
1931 * over the child relations in this case.
1932 */
1934 {
1935 /* loop backward */
1937 end_index = -1;
1938 direction = -1;
1939
1940 /*
1941 * Set this to true to save us having to check for
1942 * match_partition_order_desc in the loop below.
1943 */
1944 match_partition_order = true;
1945 }
1946 else
1947 {
1948 /* for all other case, loop forward */
1949 first_index = 0;
1951 direction = 1;
1952 }
1953
1954 /* Select the child paths for this ordering... */
1955 for (int i = first_index; i != end_index; i += direction)
1956 {
1961
1962 /* Locate the right paths, if they are available. */
1965 pathkeys,
1966 NULL,
1968 false);
1971 pathkeys,
1972 NULL,
1973 TOTAL_COST,
1974 false);
1975
1976 /*
1977 * If we can't find any paths with the right order just use the
1978 * cheapest-total path; we'll have to sort it later.
1979 */
1981 {
1983 childrel->cheapest_total_path;
1984 /* Assert we do have an unparameterized path for this child */
1985 Assert(cheapest_total->param_info == NULL);
1986 }
1987
1988 /*
1989 * When building a fractional path, determine a cheapest
1990 * fractional path for each child relation too. Looking at startup
1991 * and total costs is not enough, because the cheapest fractional
1992 * path may be dominated by two separate paths (one for startup,
1993 * one for total).
1994 *
1995 * When needed (building fractional path), determine the cheapest
1996 * fractional path too.
1997 */
1998 if (root->tuple_fraction > 0)
1999 {
2000 double path_fraction = root->tuple_fraction;
2001
2002 /*
2003 * We should not have a dummy child relation here. However,
2004 * we cannot use childrel->rows to compute the tuple fraction,
2005 * as childrel can be an upper relation with an unset row
2006 * estimate. Instead, we use the row estimate from the
2007 * cheapest_total path, which should already have been forced
2008 * to a sane value.
2009 */
2010 Assert(cheapest_total->rows > 0);
2011
2012 /* Convert absolute limit to a path fraction */
2013 if (path_fraction >= 1.0)
2015
2018 pathkeys,
2019 NULL,
2021
2022 /*
2023 * If we found no path with matching pathkeys, use the
2024 * cheapest total path instead.
2025 *
2026 * XXX We might consider partially sorted paths too (with an
2027 * incremental sort on top). But we'd have to build all the
2028 * incremental paths, do the costing etc.
2029 *
2030 * Also, notice whether we actually have different paths for
2031 * the "fractional" and "total" cases. This helps avoid
2032 * generating two identical ordered append paths.
2033 */
2037 fraction_neq_total = true;
2038 }
2039
2040 /*
2041 * Notice whether we actually have different paths for the
2042 * "cheapest" and "total" cases. This helps avoid generating two
2043 * identical ordered append paths.
2044 */
2046 startup_neq_total = true;
2047
2048 /*
2049 * Collect the appropriate child paths. The required logic varies
2050 * for the Append and MergeAppend cases.
2051 */
2053 {
2054 /*
2055 * We're going to make a plain Append path. We don't need
2056 * most of what accumulate_append_subpath would do, but we do
2057 * want to cut out child Appends or MergeAppends if they have
2058 * just a single subpath (and hence aren't doing anything
2059 * useful).
2060 */
2063 &startup.child_append_relid_sets);
2066 &total.child_append_relid_sets);
2067
2068 startup.subpaths = lappend(startup.subpaths, cheapest_startup);
2069 total.subpaths = lappend(total.subpaths, cheapest_total);
2070
2072 {
2075 &fractional.child_append_relid_sets);
2076 fractional.subpaths =
2078 }
2079 }
2080 else
2081 {
2082 /*
2083 * Otherwise, rely on accumulate_append_subpath to collect the
2084 * child paths for the MergeAppend.
2085 */
2087 &startup.subpaths, NULL,
2088 &startup.child_append_relid_sets);
2090 &total.subpaths, NULL,
2091 &total.child_append_relid_sets);
2092
2095 &fractional.subpaths, NULL,
2096 &fractional.child_append_relid_sets);
2097 }
2098 }
2099
2100 /* ... and build the Append or MergeAppend paths */
2102 {
2103 /* We only need Append */
2105 rel,
2106 startup,
2107 pathkeys,
2108 NULL,
2109 0,
2110 false,
2111 -1));
2114 rel,
2115 total,
2116 pathkeys,
2117 NULL,
2118 0,
2119 false,
2120 -1));
2121
2122 if (fractional.subpaths && fraction_neq_total)
2124 rel,
2125 fractional,
2126 pathkeys,
2127 NULL,
2128 0,
2129 false,
2130 -1));
2131 }
2132 else
2133 {
2134 /* We need MergeAppend */
2136 rel,
2137 startup.subpaths,
2138 startup.child_append_relid_sets,
2139 pathkeys,
2140 NULL));
2143 rel,
2144 total.subpaths,
2145 total.child_append_relid_sets,
2146 pathkeys,
2147 NULL));
2148
2149 if (fractional.subpaths && fraction_neq_total)
2151 rel,
2152 fractional.subpaths,
2153 fractional.child_append_relid_sets,
2154 pathkeys,
2155 NULL));
2156 }
2157 }
2158}
static Path * get_singleton_append_subpath(Path *path, List **child_append_relid_sets)
Definition allpaths.c:2322
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:1524
#define IS_SIMPLE_REL(rel)
Definition pathnodes.h:989
@ TOTAL_COST
Definition pathnodes.h:111
@ STARTUP_COST
Definition pathnodes.h:111
#define list_nth_node(type, list, n)
Definition pg_list.h:359
@ BackwardScanDirection
Definition sdir.h:26
@ ForwardScanDirection
Definition sdir.h:28
Bitmapset * live_parts
Definition pathnodes.h:1204

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

5062{
5064 int cnt_parts;
5065 int num_parts;
5067
5068 /* Handle only join relations here. */
5069 if (!IS_JOIN_REL(rel))
5070 return;
5071
5072 /* We've nothing to do if the relation is not partitioned. */
5073 if (!IS_PARTITIONED_REL(rel))
5074 return;
5075
5076 /* The relation should have consider_partitionwise_join set. */
5078
5079 /* Guard against stack overflow due to overly deep partition hierarchy. */
5081
5082 num_parts = rel->nparts;
5083 part_rels = rel->part_rels;
5084
5085 /* Collect non-dummy child-joins. */
5086 for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
5087 {
5089
5090 /* If it's been pruned entirely, it's certainly dummy. */
5091 if (child_rel == NULL)
5092 continue;
5093
5094 /* Make partitionwise join paths for this partitioned child-join. */
5096
5097 /* If we failed to make any path for this child, we must give up. */
5098 if (child_rel->pathlist == NIL)
5099 {
5100 /*
5101 * Mark the parent joinrel as unpartitioned so that later
5102 * functions treat it correctly.
5103 */
5104 rel->nparts = 0;
5105 return;
5106 }
5107
5108 /* Else, identify the cheapest path for it. */
5110
5111 /* Dummy children need not be scanned, so ignore those. */
5113 continue;
5114
5115 /*
5116 * Except for the topmost scan/join rel, consider generating partial
5117 * aggregation paths for the grouped relation on top of the paths of
5118 * this partitioned child-join. After that, we're done creating paths
5119 * for the grouped relation, so run set_cheapest().
5120 */
5121 if (child_rel->grouped_rel != NULL &&
5122 !bms_equal(IS_OTHER_REL(rel) ?
5123 rel->top_parent_relids : rel->relids,
5124 root->all_query_rels))
5125 {
5126 RelOptInfo *grouped_rel = child_rel->grouped_rel;
5127
5128 Assert(IS_GROUPED_REL(grouped_rel));
5129
5130 generate_grouped_paths(root, grouped_rel, child_rel);
5131 set_cheapest(grouped_rel);
5132 }
5133
5134#ifdef OPTIMIZER_DEBUG
5136#endif
5137
5139 }
5140
5141 /* If all child-joins are dummy, parent join is also dummy. */
5142 if (!live_children)
5143 {
5144 mark_dummy_rel(rel);
5145 return;
5146 }
5147
5148 /* Build additional paths for this rel from child-join paths. */
5151}
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:5061
void generate_grouped_paths(PlannerInfo *root, RelOptInfo *grouped_rel, RelOptInfo *rel)
Definition allpaths.c:3509
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition allpaths.c:1420
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:994
#define IS_PARTITIONED_REL(rel)
Definition pathnodes.h:1231
#define IS_GROUPED_REL(rel)
Definition pathnodes.h:1257
void check_stack_depth(void)
Definition stack_depth.c:96
Relids top_parent_relids
Definition pathnodes.h:1174
bool consider_partitionwise_join
Definition pathnodes.h:1156

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

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

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

2170{
2171 Path *cheapest;
2172 ListCell *lc;
2173
2174 /*
2175 * Look up the cheapest existing path with no more than the needed
2176 * parameterization. If it has exactly the needed parameterization, we're
2177 * done.
2178 */
2180 NIL,
2182 TOTAL_COST,
2183 false);
2184 Assert(cheapest != NULL);
2186 return cheapest;
2187
2188 /*
2189 * Otherwise, we can "reparameterize" an existing path to match the given
2190 * parameterization, which effectively means pushing down additional
2191 * joinquals to be checked within the path's scan. However, some existing
2192 * paths might check the available joinquals already while others don't;
2193 * therefore, it's not clear which existing path will be cheapest after
2194 * reparameterization. We have to go through them all and find out.
2195 */
2196 cheapest = NULL;
2197 foreach(lc, rel->pathlist)
2198 {
2199 Path *path = (Path *) lfirst(lc);
2200
2201 /* Can't use it if it needs more than requested parameterization */
2203 continue;
2204
2205 /*
2206 * Reparameterization can only increase the path's cost, so if it's
2207 * already more expensive than the current cheapest, forget it.
2208 */
2209 if (cheapest != NULL &&
2211 continue;
2212
2213 /* Reparameterize if needed, then recheck cost */
2215 {
2216 path = reparameterize_path(root, path, required_outer, 1.0);
2217 if (path == NULL)
2218 continue; /* failed to reparameterize this one */
2220
2221 if (cheapest != NULL &&
2223 continue;
2224 }
2225
2226 /* We have a new best path */
2227 cheapest = path;
2228 }
2229
2230 /* Return the best path, or NULL if we found no suitable candidate */
2231 return cheapest;
2232}
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:3917

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

2323{
2324 Assert(!path->parallel_aware);
2325
2326 if (IsA(path, AppendPath))
2327 {
2328 AppendPath *apath = (AppendPath *) path;
2329
2330 if (list_length(apath->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 apath->child_append_relid_sets);
2337 return (Path *) linitial(apath->subpaths);
2338 }
2339 }
2340 else if (IsA(path, MergeAppendPath))
2341 {
2343
2344 if (list_length(mpath->subpaths) == 1)
2345 {
2346 *child_append_relid_sets =
2347 lappend(*child_append_relid_sets, path->parent->relids);
2348 *child_append_relid_sets =
2349 list_concat(*child_append_relid_sets,
2350 mpath->child_append_relid_sets);
2351 return (Path *) linitial(mpath->subpaths);
2352 }
2353 }
2354
2355 return path;
2356}
bool parallel_aware
Definition pathnodes.h:1998

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

3326{
3328
3329 /*
3330 * Considering query_pathkeys is always worth it, because it might allow
3331 * us to avoid a total sort when we have a partially presorted path
3332 * available or to push the total sort into the parallel portion of the
3333 * query.
3334 */
3335 if (root->query_pathkeys)
3336 {
3337 ListCell *lc;
3338 int npathkeys = 0; /* useful pathkeys */
3339
3340 foreach(lc, root->query_pathkeys)
3341 {
3343 EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3344
3345 /*
3346 * We can only build a sort for pathkeys that contain a
3347 * safe-to-compute-early EC member computable from the current
3348 * relation's reltarget, so ignore the remainder of the list as
3349 * soon as we find a pathkey without such a member.
3350 *
3351 * It's still worthwhile to return any prefix of the pathkeys list
3352 * that meets this requirement, as we may be able to do an
3353 * incremental sort.
3354 *
3355 * If requested, ensure the sort expression is parallel-safe too.
3356 */
3359 break;
3360
3361 npathkeys++;
3362 }
3363
3364 /*
3365 * The whole query_pathkeys list matches, so append it directly, to
3366 * allow comparing pathkeys easily by comparing list pointer. If we
3367 * have to truncate the pathkeys, we gotta do a copy though.
3368 */
3369 if (npathkeys == list_length(root->query_pathkeys))
3371 root->query_pathkeys);
3372 else if (npathkeys > 0)
3374 list_copy_head(root->query_pathkeys,
3375 npathkeys));
3376 }
3377
3378 return useful_pathkeys_list;
3379}
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 183 of file allpaths.c.

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

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

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

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().

◆ pushdown_var_grouping_eqop()

static Oid pushdown_var_grouping_eqop ( Var var,
void context 
)
static

Definition at line 4579 of file allpaths.c.

4580{
4581 Query *subquery = (Query *) context;
4582 Oid eqop;
4583
4584 if (var->varlevelsup != 0)
4585 return InvalidOid;
4586
4587 eqop = subquery_column_grouping_eqop(subquery, var->varattno);
4588
4589 /*
4590 * qual_is_pushdown_safe ensures any level-0 subquery Var that reaches us
4591 * references a grouping column.
4592 */
4593 Assert(OidIsValid(eqop));
4594
4595 return eqop;
4596}
static Oid subquery_column_grouping_eqop(Query *subquery, AttrNumber attno)
Definition allpaths.c:4612
AttrNumber varattno
Definition primnodes.h:275
Index varlevelsup
Definition primnodes.h:295

References Assert, InvalidOid, OidIsValid, subquery_column_grouping_eqop(), Var::varattno, and Var::varlevelsup.

Referenced by qual_is_pushdown_safe().

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

4461{
4463 Node *qual = (Node *) rinfo->clause;
4464 List *vars;
4465 ListCell *vl;
4466
4467 /* Refuse subselects (point 1) */
4468 if (contain_subplans(qual))
4469 return PUSHDOWN_UNSAFE;
4470
4471 /* Refuse volatile quals if we found they'd be unsafe (point 2) */
4472 if (safetyInfo->unsafeVolatile &&
4474 return PUSHDOWN_UNSAFE;
4475
4476 /* Refuse leaky quals if told to (point 3) */
4477 if (safetyInfo->unsafeLeaky &&
4478 contain_leaked_vars(qual))
4479 return PUSHDOWN_UNSAFE;
4480
4481 /*
4482 * Examine all Vars used in clause. Since it's a restriction clause, all
4483 * such Vars must refer to subselect output columns ... unless this is
4484 * part of a LATERAL subquery, in which case there could be lateral
4485 * references.
4486 *
4487 * By omitting the relevant flags, this also gives us a cheap sanity check
4488 * that no aggregates or window functions appear in the qual. Those would
4489 * be unsafe to push down, but at least for the moment we could never see
4490 * any in a qual anyhow.
4491 */
4493 foreach(vl, vars)
4494 {
4495 Var *var = (Var *) lfirst(vl);
4496
4497 /*
4498 * XXX Punt if we find any PlaceHolderVars in the restriction clause.
4499 * It's not clear whether a PHV could safely be pushed down, and even
4500 * less clear whether such a situation could arise in any cases of
4501 * practical interest anyway. So for the moment, just refuse to push
4502 * down.
4503 */
4504 if (!IsA(var, Var))
4505 {
4507 break;
4508 }
4509
4510 /*
4511 * Punt if we find any lateral references. It would be safe to push
4512 * these down, but we'd have to convert them into outer references,
4513 * which subquery_push_qual lacks the infrastructure to do. The case
4514 * arises so seldom that it doesn't seem worth working hard on.
4515 */
4516 if (var->varno != rti)
4517 {
4519 break;
4520 }
4521
4522 /* Subqueries have no system columns */
4523 Assert(var->varattno >= 0);
4524
4525 /* Check point 4 */
4526 if (var->varattno == 0)
4527 {
4529 break;
4530 }
4531
4532 /* Check point 5 */
4533 if (safetyInfo->unsafeFlags[var->varattno] != 0)
4534 {
4535 if (safetyInfo->unsafeFlags[var->varattno] &
4538 {
4540 break;
4541 }
4542 else
4543 {
4544 /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
4546 /* don't break, we might find another Var that's unsafe */
4547 }
4548 }
4549 }
4550
4551 list_free(vars);
4552
4553 /* Check point 6 */
4554 if (safe == PUSHDOWN_SAFE &&
4555 (subquery->hasWindowFuncs ||
4556 subquery->distinctClause != NIL ||
4557 (subquery->setOperations != NULL &&
4558 setop_has_grouping(subquery->setOperations))))
4559 {
4561 subquery))
4563 }
4564
4565 return safe;
4566}
static bool setop_has_grouping(Node *setop)
Definition allpaths.c:4707
static Oid pushdown_var_grouping_eqop(Var *var, void *context)
Definition allpaths.c:4579
bool expression_has_grouping_conflict(Node *expr, grouping_eqop_callback get_eqop, void *context)
Definition clauses.c:6318
bool contain_leaked_vars(Node *clause)
Definition clauses.c:1294
#define PVC_INCLUDE_PLACEHOLDERS
Definition optimizer.h:201
Node * setOperations
Definition parsenodes.h:241
Expr * clause
Definition pathnodes.h:2901
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(), Query::distinctClause, expression_has_grouping_conflict(), fb(), IsA, lfirst, list_free(), NIL, pull_var_clause(), PUSHDOWN_SAFE, PUSHDOWN_UNSAFE, pushdown_var_grouping_eqop(), PUSHDOWN_WINDOWCLAUSE_RUNCOND, PVC_INCLUDE_PLACEHOLDERS, setop_has_grouping(), Query::setOperations, 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 4773 of file allpaths.c.

4775{
4776 if (IsA(setOp, RangeTblRef))
4777 {
4779 RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4780 Query *subquery = subrte->subquery;
4781
4782 Assert(subquery != NULL);
4783 subquery_push_qual(subquery, rte, rti, qual);
4784 }
4785 else if (IsA(setOp, SetOperationStmt))
4786 {
4788
4789 recurse_push_qual(op->larg, topquery, rte, rti, qual);
4790 recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4791 }
4792 else
4793 {
4794 elog(ERROR, "unrecognized node type: %d",
4795 (int) nodeTag(setOp));
4796 }
4797}
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4725
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition allpaths.c:4773
#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 4203 of file allpaths.c.

4205{
4206 if (IsA(setOp, RangeTblRef))
4207 {
4209 RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
4210 Query *subquery = rte->subquery;
4211
4212 Assert(subquery != NULL);
4214 }
4215 else if (IsA(setOp, SetOperationStmt))
4216 {
4218
4219 /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
4220 if (op->op == SETOP_EXCEPT)
4221 return false;
4222 /* Else recurse */
4224 return false;
4226 return false;
4227 }
4228 else
4229 {
4230 elog(ERROR, "unrecognized node type: %d",
4231 (int) nodeTag(setOp));
4232 }
4233 return true;
4234}
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4147
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4203
@ 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 4825 of file allpaths.c.

4827{
4828 Bitmapset *attrs_used;
4829 ListCell *lc;
4830
4831 /*
4832 * Just point directly to extra_used_attrs. No need to bms_copy as none of
4833 * the current callers use the Bitmapset after calling this function.
4834 */
4835 attrs_used = extra_used_attrs;
4836
4837 /*
4838 * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4839 * could update all the child SELECTs' tlists, but it seems not worth the
4840 * trouble presently.
4841 */
4842 if (subquery->setOperations)
4843 return;
4844
4845 /*
4846 * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4847 * time: all its output columns must be used in the distinctClause.
4848 */
4849 if (subquery->distinctClause && !subquery->hasDistinctOn)
4850 return;
4851
4852 /*
4853 * Collect a bitmap of all the output column numbers used by the upper
4854 * query.
4855 *
4856 * Add all the attributes needed for joins or final output. Note: we must
4857 * look at rel's targetlist, not the attr_needed data, because attr_needed
4858 * isn't computed for inheritance child rels, cf set_append_rel_size().
4859 * (XXX might be worth changing that sometime.)
4860 */
4861 pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4862
4863 /* Add all the attributes used by un-pushed-down restriction clauses. */
4864 foreach(lc, rel->baserestrictinfo)
4865 {
4866 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4867
4868 pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4869 }
4870
4871 /*
4872 * If there's a whole-row reference to the subquery, we can't remove
4873 * anything.
4874 */
4876 return;
4877
4878 /*
4879 * Run through the tlist and zap entries we don't need. It's okay to
4880 * modify the tlist items in-place because set_subquery_pathlist made a
4881 * copy of the subquery.
4882 */
4883 foreach(lc, subquery->targetList)
4884 {
4886 Node *texpr = (Node *) tle->expr;
4887
4888 /*
4889 * If it has a sortgroupref number, it's used in some sort/group
4890 * clause so we'd better not remove it. Also, don't remove any
4891 * resjunk columns, since their reason for being has nothing to do
4892 * with anybody reading the subquery's output. (It's likely that
4893 * resjunk columns in a sub-SELECT would always have ressortgroupref
4894 * set, but even if they don't, it seems imprudent to remove them.)
4895 */
4896 if (tle->ressortgroupref || tle->resjunk)
4897 continue;
4898
4899 /*
4900 * If it's used by the upper query, we can't remove it.
4901 */
4903 attrs_used))
4904 continue;
4905
4906 /*
4907 * If it contains a set-returning function, we can't remove it since
4908 * that could change the number of rows returned by the subquery.
4909 */
4910 if (subquery->hasTargetSRFs &&
4912 continue;
4913
4914 /*
4915 * If it contains volatile functions, we daren't remove it for fear
4916 * that the user is expecting their side-effects to happen.
4917 */
4919 continue;
4920
4921 /*
4922 * OK, we don't need it. Replace the expression with a NULL constant.
4923 * Preserve the exposed type of the expression, in case something
4924 * looks at the rowtype of the subquery's result.
4925 */
4926 tle->expr = (Expr *) makeNullConst(exprType(texpr),
4929 }
4930}
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:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
List * exprs
Definition pathnodes.h:1878
List * baserestrictinfo
Definition pathnodes.h:1142
Index relid
Definition pathnodes.h:1069
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 1321 of file allpaths.c.

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

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

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

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

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

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

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

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

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

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

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

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

2371{
2372 AppendPathInput in = {0};
2373
2374 /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2375 rel->rows = 0;
2376 rel->reltarget->width = 0;
2377
2378 /* Discard any pre-existing paths; no further need for them */
2379 rel->pathlist = NIL;
2380 rel->partial_pathlist = NIL;
2381
2382 /* Set up the dummy path */
2383 add_path(rel, (Path *) create_append_path(NULL, rel, in,
2384 NIL, rel->lateral_relids,
2385 0, false, -1));
2386
2387 /*
2388 * We set the cheapest-path fields immediately, just in case they were
2389 * pointing at some discarded path. This is redundant in current usage
2390 * because set_rel_pathlist will do it later, but it's cheap so we keep it
2391 * for safety and consistency with mark_dummy_rel.
2392 */
2393 set_cheapest(rel);
2394}

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

1009{
1010 /* Call the FDW's GetForeignPaths function to generate path(s) */
1011 rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
1012}

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

985{
986 /* Mark rel with estimated output rows, width, etc */
988
989 /* Let FDW adjust the size estimates, if it can */
990 rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
991
992 /* ... but do not let it set the rows estimate to zero */
993 rel->rows = clamp_row_est(rel->rows);
994
995 /*
996 * Also, make sure rel->tuples is not insane relative to rel->rows.
997 * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
998 * FDW doesn't do anything to replace that.
999 */
1000 rel->tuples = Max(rel->tuples, rel->rows);
1001}
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6319
double clamp_row_est(double nrows)
Definition costsize.c:214

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

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

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

1385{
1386 RelOptInfo *grouped_rel;
1387
1388 /*
1389 * If there are no aggregate expressions or grouping expressions, eager
1390 * aggregation is not possible.
1391 */
1392 if (root->agg_clause_list == NIL ||
1393 root->group_expr_list == NIL)
1394 return;
1395
1396 /* Add paths to the grouped base relation if one exists. */
1397 grouped_rel = rel->grouped_rel;
1398 if (grouped_rel)
1399 {
1400 Assert(IS_GROUPED_REL(grouped_rel));
1401
1402 generate_grouped_paths(root, grouped_rel, rel);
1403 set_cheapest(grouped_rel);
1404 }
1405}

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

3144{
3146
3147 /* Mark rel with estimated output rows, width, etc */
3149
3150 /*
3151 * We don't support pushing join clauses into the quals of a tuplestore
3152 * scan, but it could still have required parameterization due to LATERAL
3153 * refs in its tlist.
3154 */
3156
3157 /* Generate appropriate path */
3159}
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6257
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2043

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

839{
841
842 /*
843 * We don't support pushing join clauses into the quals of a seqscan, but
844 * it could still have required parameterization due to LATERAL refs in
845 * its tlist.
846 */
848
849 /*
850 * Consider TID scans.
851 *
852 * If create_tidscan_paths returns true, then a TID scan path is forced.
853 * This happens when rel->baserestrictinfo contains CurrentOfExpr, because
854 * the executor can't handle any other type of path for such queries.
855 * Hence, we return without adding any other paths.
856 */
857 if (create_tidscan_paths(root, rel))
858 return;
859
860 /* Consider sequential scan */
862
863 /* If appropriate, consider parallel sequential scan */
866
867 /* Consider index scans */
869}
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition allpaths.c:876
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition indxpath.c:239
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 632 of file allpaths.c.

633{
634 /*
635 * Test any partial indexes of rel for applicability. We must do this
636 * first since partial unique indexes can affect size estimates.
637 */
639
640 /* Mark rel with estimated output rows, width, etc */
642}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:5493
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition indxpath.c:3940

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

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

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_GRAPH_TABLE, 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 520 of file allpaths.c.

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

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

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

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

3171{
3173
3174 /* Mark rel with estimated output rows, width, etc */
3176
3177 /*
3178 * We don't support pushing join clauses into the quals of a Result scan,
3179 * but it could still have required parameterization due to LATERAL refs
3180 * in its tlist.
3181 */
3183
3184 /* Generate appropriate path */
3186}
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:6290
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:2069

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

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

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

3040{
3042
3043 /*
3044 * We don't support pushing join clauses into the quals of a tablefunc
3045 * scan, but it could still have required parameterization due to LATERAL
3046 * refs in the function expression.
3047 */
3049
3050 /* Generate appropriate path */
3053}
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1965

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

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

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

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

3020{
3022
3023 /*
3024 * We don't support pushing join clauses into the quals of a values scan,
3025 * but it could still have required parameterization due to LATERAL refs
3026 * in the values expressions.
3027 */
3029
3030 /* Generate appropriate path */
3032}
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition pathnode.c:1991

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

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

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().

◆ setop_column_grouping_eqop()

static Oid setop_column_grouping_eqop ( Node setop,
AttrNumber  attno 
)
static

Definition at line 4675 of file allpaths.c.

4676{
4677 SetOperationStmt *op;
4678 Oid eqop;
4679
4680 if (setop == NULL || !IsA(setop, SetOperationStmt))
4681 return InvalidOid;
4682
4683 op = (SetOperationStmt *) setop;
4684
4685 if (op->groupClauses != NIL &&
4686 attno >= 1 && attno <= list_length(op->groupClauses))
4687 {
4689 op->groupClauses, attno - 1);
4690
4691 return sgc->eqop;
4692 }
4693
4694 /* Recurse into children to find any inner grouping */
4695 eqop = setop_column_grouping_eqop(op->larg, attno);
4696 if (OidIsValid(eqop))
4697 return eqop;
4698 return setop_column_grouping_eqop(op->rarg, attno);
4699}
static Oid setop_column_grouping_eqop(Node *setop, AttrNumber attno)
Definition allpaths.c:4675

References fb(), InvalidOid, IsA, SetOperationStmt::larg, list_length(), list_nth_node, NIL, OidIsValid, SetOperationStmt::rarg, and setop_column_grouping_eqop().

Referenced by setop_column_grouping_eqop(), and subquery_column_grouping_eqop().

◆ setop_has_grouping()

static bool setop_has_grouping ( Node setop)
static

Definition at line 4707 of file allpaths.c.

4708{
4709 SetOperationStmt *op;
4710
4711 if (setop == NULL || !IsA(setop, SetOperationStmt))
4712 return false;
4713
4714 op = (SetOperationStmt *) setop;
4715 if (op->groupClauses != NIL)
4716 return true;
4717
4718 return setop_has_grouping(op->larg) || setop_has_grouping(op->rarg);
4719}

References fb(), IsA, SetOperationStmt::larg, NIL, SetOperationStmt::rarg, and setop_has_grouping().

Referenced by qual_is_pushdown_safe(), and setop_has_grouping().

◆ setup_simple_grouped_rels()

static void setup_simple_grouped_rels ( PlannerInfo root)
static

Definition at line 350 of file allpaths.c.

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

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

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

static Oid subquery_column_grouping_eqop ( Query subquery,
AttrNumber  attno 
)
static

Definition at line 4612 of file allpaths.c.

4613{
4615 ListCell *lc;
4616
4618 return InvalidOid;
4619
4620 tle = list_nth_node(TargetEntry, subquery->targetList, attno - 1);
4621
4622 /* DISTINCT or DISTINCT ON */
4623 foreach(lc, subquery->distinctClause)
4624 {
4626
4627 if (sgc->tleSortGroupRef == tle->ressortgroupref)
4628 return sgc->eqop;
4629 }
4630
4631 /* Window function PARTITION BY: must appear in every window's list. */
4632 if (subquery->hasWindowFuncs && subquery->windowClause != NIL)
4633 {
4634 Oid eqop = InvalidOid;
4635
4636 foreach(lc, subquery->windowClause)
4637 {
4639 ListCell *lc2;
4640
4641 foreach(lc2, wc->partitionClause)
4642 {
4644
4645 if (sgc->tleSortGroupRef == tle->ressortgroupref)
4646 break;
4647 }
4648 if (lc2 == NULL)
4649 break; /* not present in this window's list */
4650 eqop = lfirst_node(SortGroupClause, lc2)->eqop;
4651 }
4652 if (lc == NULL)
4653 return eqop; /* matched in every window */
4654 }
4655
4656 /* Set operation */
4657 if (subquery->setOperations != NULL)
4658 return setop_column_grouping_eqop(subquery->setOperations, attno);
4659
4660 return InvalidOid;
4661}
#define lfirst_node(type, lc)
Definition pg_list.h:176
List * partitionClause

References Query::distinctClause, fb(), InvalidOid, lfirst, lfirst_node, list_length(), list_nth_node, NIL, WindowClause::partitionClause, setop_column_grouping_eqop(), Query::setOperations, Query::targetList, and Query::windowClause.

Referenced by pushdown_var_grouping_eqop().

◆ subquery_is_pushdown_safe()

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

Definition at line 4147 of file allpaths.c.

4149{
4151
4152 /* Check point 1 */
4153 if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
4154 return false;
4155
4156 /* Check point 6 */
4157 if (subquery->groupClause && subquery->groupingSets)
4158 return false;
4159
4160 /* Check points 3, 4, and 5 */
4161 if (subquery->distinctClause ||
4162 subquery->hasWindowFuncs ||
4163 subquery->hasTargetSRFs)
4164 safetyInfo->unsafeVolatile = true;
4165
4166 /*
4167 * If we're at a leaf query, check for unsafe expressions in its target
4168 * list, and mark any reasons why they're unsafe in unsafeFlags[].
4169 * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
4170 * so no need to check them.)
4171 */
4172 if (subquery->setOperations == NULL)
4174
4175 /* Are we at top level, or looking at a setop component? */
4176 if (subquery == topquery)
4177 {
4178 /* Top level, so check any component queries */
4179 if (subquery->setOperations != NULL)
4181 safetyInfo))
4182 return false;
4183 }
4184 else
4185 {
4186 /* Setop component must not have more components (too weird) */
4187 if (subquery->setOperations != NULL)
4188 return false;
4189 /* Check whether setop component output types match top level */
4190 topop = castNode(SetOperationStmt, topquery->setOperations);
4191 Assert(topop);
4193 topop->colTypes,
4194 safetyInfo);
4195 }
4196 return true;
4197}
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4373
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition allpaths.c:4272
Node * limitCount
Definition parsenodes.h:236
List * groupClause
Definition parsenodes.h:221
Node * limitOffset
Definition parsenodes.h:235
List * groupingSets
Definition parsenodes.h:225

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

4726{
4727 if (subquery->setOperations != NULL)
4728 {
4729 /* Recurse to push it separately to each component query */
4730 recurse_push_qual(subquery->setOperations, subquery,
4731 rte, rti, qual);
4732 }
4733 else
4734 {
4735 /*
4736 * We need to replace Vars in the qual (which must refer to outputs of
4737 * the subquery) with copies of the subquery's targetlist expressions.
4738 * Note that at this point, any uplevel Vars in the qual should have
4739 * been replaced with Params, so they need no work.
4740 *
4741 * This step also ensures that when we are pushing into a setop tree,
4742 * each component query gets its own copy of the qual.
4743 */
4744 qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
4745 subquery->targetList,
4746 subquery->resultRelation,
4748 &subquery->hasSubLinks);
4749
4750 /*
4751 * Now attach the qual to the proper place: normally WHERE, but if the
4752 * subquery uses grouping or aggregation, put it in HAVING (since the
4753 * qual really refers to the group-result rows).
4754 */
4755 if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
4756 subquery->havingQual = make_and_qual(subquery->havingQual, qual);
4757 else
4758 subquery->jointree->quals =
4759 make_and_qual(subquery->jointree->quals, qual);
4760
4761 /*
4762 * We need not change the subquery's hasAggs or hasSubLinks flags,
4763 * since we can't be pushing down any aggregates that weren't there
4764 * before, and we don't push down subselects at all.
4765 */
4766 }
4767}
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:2378
FromExpr * jointree
Definition parsenodes.h:187
Node * havingQual
Definition parsenodes.h:227

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

4407{
4408 ListCell *lc;
4409
4410 foreach(lc, query->windowClause)
4411 {
4413
4415 return false;
4416 }
4417 return true;
4418}

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().