PostgreSQL Source Code  git master
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/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 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 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 generate_orderedappend_paths (PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
 
static Pathget_cheapest_parameterized_child_path (PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
 
static void accumulate_append_subpath (Path *path, List **subpaths, List **special_subpaths)
 
static Pathget_singleton_append_subpath (Path *path)
 
static void set_dummy_rel_pathlist (RelOptInfo *rel)
 
static void set_subquery_pathlist (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
static void set_function_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_values_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_tablefunc_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_cte_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_namedtuplestore_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_result_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static void set_worktable_pathlist (PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
 
static RelOptInfomake_rel_from_joinlist (PlannerInfo *root, List *joinlist)
 
static bool subquery_is_pushdown_safe (Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
 
static bool recurse_pushdown_safe (Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
 
static void check_output_expressions (Query *subquery, pushdown_safety_info *safetyInfo)
 
static void compare_tlist_datatypes (List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
 
static bool targetIsInAllPartitionLists (TargetEntry *tle, Query *query)
 
static pushdown_safe_type qual_is_pushdown_safe (Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
 
static void subquery_push_qual (Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
 
static void recurse_push_qual (Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
 
static void remove_unused_subquery_outputs (Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
 
RelOptInfomake_one_rel (PlannerInfo *root, List *joinlist)
 
void add_paths_to_append_rel (PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
 
static bool find_window_run_conditions (Query *subquery, RangeTblEntry *rte, Index rti, 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, RangeTblEntry *rte, Index rti, 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)
 
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
 
int geqo_threshold
 
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 54 of file allpaths.c.

◆ UNSAFE_HAS_VOLATILE_FUNC

#define UNSAFE_HAS_VOLATILE_FUNC   (1 << 0)

Definition at line 53 of file allpaths.c.

◆ UNSAFE_NOTIN_DISTINCTON_CLAUSE

#define UNSAFE_NOTIN_DISTINCTON_CLAUSE   (1 << 2)

Definition at line 55 of file allpaths.c.

◆ UNSAFE_NOTIN_PARTITIONBY_CLAUSE

#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE   (1 << 3)

Definition at line 56 of file allpaths.c.

◆ UNSAFE_TYPE_MISMATCH

#define UNSAFE_TYPE_MISMATCH   (1 << 4)

Definition at line 57 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 70 of file allpaths.c.

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

Function Documentation

◆ accumulate_append_subpath()

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

Definition at line 2087 of file allpaths.c.

2088 {
2089  if (IsA(path, AppendPath))
2090  {
2091  AppendPath *apath = (AppendPath *) path;
2092 
2093  if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2094  {
2095  *subpaths = list_concat(*subpaths, apath->subpaths);
2096  return;
2097  }
2098  else if (special_subpaths != NULL)
2099  {
2100  List *new_special_subpaths;
2101 
2102  /* Split Parallel Append into partial and non-partial subpaths */
2103  *subpaths = list_concat(*subpaths,
2104  list_copy_tail(apath->subpaths,
2105  apath->first_partial_path));
2106  new_special_subpaths = list_copy_head(apath->subpaths,
2107  apath->first_partial_path);
2108  *special_subpaths = list_concat(*special_subpaths,
2109  new_special_subpaths);
2110  return;
2111  }
2112  }
2113  else if (IsA(path, MergeAppendPath))
2114  {
2115  MergeAppendPath *mpath = (MergeAppendPath *) path;
2116 
2117  *subpaths = list_concat(*subpaths, mpath->subpaths);
2118  return;
2119  }
2120 
2121  *subpaths = lappend(*subpaths, path);
2122 }
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_copy_head(const List *oldlist, int len)
Definition: list.c:1593
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
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
int first_partial_path
Definition: pathnodes.h:1923
List * subpaths
Definition: pathnodes.h:1921
Definition: pg_list.h:54
bool parallel_aware
Definition: pathnodes.h:1642

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

Referenced by add_paths_to_append_rel(), and generate_orderedappend_paths().

◆ add_paths_to_append_rel()

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

Definition at line 1302 of file allpaths.c.

1304 {
1305  List *subpaths = NIL;
1306  bool subpaths_valid = true;
1307  List *startup_subpaths = NIL;
1308  bool startup_subpaths_valid = true;
1309  List *partial_subpaths = NIL;
1310  List *pa_partial_subpaths = NIL;
1311  List *pa_nonpartial_subpaths = NIL;
1312  bool partial_subpaths_valid = true;
1313  bool pa_subpaths_valid;
1314  List *all_child_pathkeys = NIL;
1315  List *all_child_outers = NIL;
1316  ListCell *l;
1317  double partial_rows = -1;
1318 
1319  /* If appropriate, consider parallel append */
1320  pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1321 
1322  /*
1323  * For every non-dummy child, remember the cheapest path. Also, identify
1324  * all pathkeys (orderings) and parameterizations (required_outer sets)
1325  * available for the non-dummy member relations.
1326  */
1327  foreach(l, live_childrels)
1328  {
1329  RelOptInfo *childrel = lfirst(l);
1330  ListCell *lcp;
1331  Path *cheapest_partial_path = NULL;
1332 
1333  /*
1334  * If child has an unparameterized cheapest-total path, add that to
1335  * the unparameterized Append path we are constructing for the parent.
1336  * If not, there's no workable unparameterized path.
1337  *
1338  * With partitionwise aggregates, the child rel's pathlist may be
1339  * empty, so don't assume that a path exists here.
1340  */
1341  if (childrel->pathlist != NIL &&
1342  childrel->cheapest_total_path->param_info == NULL)
1344  &subpaths, NULL);
1345  else
1346  subpaths_valid = false;
1347 
1348  /*
1349  * When the planner is considering cheap startup plans, we'll also
1350  * collect all the cheapest_startup_paths (if set) and build an
1351  * AppendPath containing those as subpaths.
1352  */
1353  if (rel->consider_startup && childrel->cheapest_startup_path != NULL)
1354  {
1355  /* cheapest_startup_path must not be a parameterized path. */
1356  Assert(childrel->cheapest_startup_path->param_info == NULL);
1358  &startup_subpaths,
1359  NULL);
1360  }
1361  else
1362  startup_subpaths_valid = false;
1363 
1364 
1365  /* Same idea, but for a partial plan. */
1366  if (childrel->partial_pathlist != NIL)
1367  {
1368  cheapest_partial_path = linitial(childrel->partial_pathlist);
1369  accumulate_append_subpath(cheapest_partial_path,
1370  &partial_subpaths, NULL);
1371  }
1372  else
1373  partial_subpaths_valid = false;
1374 
1375  /*
1376  * Same idea, but for a parallel append mixing partial and non-partial
1377  * paths.
1378  */
1379  if (pa_subpaths_valid)
1380  {
1381  Path *nppath = NULL;
1382 
1383  nppath =
1385 
1386  if (cheapest_partial_path == NULL && nppath == NULL)
1387  {
1388  /* Neither a partial nor a parallel-safe path? Forget it. */
1389  pa_subpaths_valid = false;
1390  }
1391  else if (nppath == NULL ||
1392  (cheapest_partial_path != NULL &&
1393  cheapest_partial_path->total_cost < nppath->total_cost))
1394  {
1395  /* Partial path is cheaper or the only option. */
1396  Assert(cheapest_partial_path != NULL);
1397  accumulate_append_subpath(cheapest_partial_path,
1398  &pa_partial_subpaths,
1399  &pa_nonpartial_subpaths);
1400  }
1401  else
1402  {
1403  /*
1404  * Either we've got only a non-partial path, or we think that
1405  * a single backend can execute the best non-partial path
1406  * faster than all the parallel backends working together can
1407  * execute the best partial path.
1408  *
1409  * It might make sense to be more aggressive here. Even if
1410  * the best non-partial path is more expensive than the best
1411  * partial path, it could still be better to choose the
1412  * non-partial path if there are several such paths that can
1413  * be given to different workers. For now, we don't try to
1414  * figure that out.
1415  */
1417  &pa_nonpartial_subpaths,
1418  NULL);
1419  }
1420  }
1421 
1422  /*
1423  * Collect lists of all the available path orderings and
1424  * parameterizations for all the children. We use these as a
1425  * heuristic to indicate which sort orderings and parameterizations we
1426  * should build Append and MergeAppend paths for.
1427  */
1428  foreach(lcp, childrel->pathlist)
1429  {
1430  Path *childpath = (Path *) lfirst(lcp);
1431  List *childkeys = childpath->pathkeys;
1432  Relids childouter = PATH_REQ_OUTER(childpath);
1433 
1434  /* Unsorted paths don't contribute to pathkey list */
1435  if (childkeys != NIL)
1436  {
1437  ListCell *lpk;
1438  bool found = false;
1439 
1440  /* Have we already seen this ordering? */
1441  foreach(lpk, all_child_pathkeys)
1442  {
1443  List *existing_pathkeys = (List *) lfirst(lpk);
1444 
1445  if (compare_pathkeys(existing_pathkeys,
1446  childkeys) == PATHKEYS_EQUAL)
1447  {
1448  found = true;
1449  break;
1450  }
1451  }
1452  if (!found)
1453  {
1454  /* No, so add it to all_child_pathkeys */
1455  all_child_pathkeys = lappend(all_child_pathkeys,
1456  childkeys);
1457  }
1458  }
1459 
1460  /* Unparameterized paths don't contribute to param-set list */
1461  if (childouter)
1462  {
1463  ListCell *lco;
1464  bool found = false;
1465 
1466  /* Have we already seen this param set? */
1467  foreach(lco, all_child_outers)
1468  {
1469  Relids existing_outers = (Relids) lfirst(lco);
1470 
1471  if (bms_equal(existing_outers, childouter))
1472  {
1473  found = true;
1474  break;
1475  }
1476  }
1477  if (!found)
1478  {
1479  /* No, so add it to all_child_outers */
1480  all_child_outers = lappend(all_child_outers,
1481  childouter);
1482  }
1483  }
1484  }
1485  }
1486 
1487  /*
1488  * If we found unparameterized paths for all children, build an unordered,
1489  * unparameterized Append path for the rel. (Note: this is correct even
1490  * if we have zero or one live subpath due to constraint exclusion.)
1491  */
1492  if (subpaths_valid)
1493  add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1494  NIL, NULL, 0, false,
1495  -1));
1496 
1497  /* build an AppendPath for the cheap startup paths, if valid */
1498  if (startup_subpaths_valid)
1499  add_path(rel, (Path *) create_append_path(root, rel, startup_subpaths,
1500  NIL, NIL, NULL, 0, false, -1));
1501 
1502  /*
1503  * Consider an append of unordered, unparameterized partial paths. Make
1504  * it parallel-aware if possible.
1505  */
1506  if (partial_subpaths_valid && partial_subpaths != NIL)
1507  {
1508  AppendPath *appendpath;
1509  ListCell *lc;
1510  int parallel_workers = 0;
1511 
1512  /* Find the highest number of workers requested for any subpath. */
1513  foreach(lc, partial_subpaths)
1514  {
1515  Path *path = lfirst(lc);
1516 
1517  parallel_workers = Max(parallel_workers, path->parallel_workers);
1518  }
1519  Assert(parallel_workers > 0);
1520 
1521  /*
1522  * If the use of parallel append is permitted, always request at least
1523  * log2(# of children) workers. We assume it can be useful to have
1524  * extra workers in this case because they will be spread out across
1525  * the children. The precise formula is just a guess, but we don't
1526  * want to end up with a radically different answer for a table with N
1527  * partitions vs. an unpartitioned table with the same data, so the
1528  * use of some kind of log-scaling here seems to make some sense.
1529  */
1531  {
1532  parallel_workers = Max(parallel_workers,
1533  pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1534  parallel_workers = Min(parallel_workers,
1536  }
1537  Assert(parallel_workers > 0);
1538 
1539  /* Generate a partial append path. */
1540  appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1541  NIL, NULL, parallel_workers,
1543  -1);
1544 
1545  /*
1546  * Make sure any subsequent partial paths use the same row count
1547  * estimate.
1548  */
1549  partial_rows = appendpath->path.rows;
1550 
1551  /* Add the path. */
1552  add_partial_path(rel, (Path *) appendpath);
1553  }
1554 
1555  /*
1556  * Consider a parallel-aware append using a mix of partial and non-partial
1557  * paths. (This only makes sense if there's at least one child which has
1558  * a non-partial path that is substantially cheaper than any partial path;
1559  * otherwise, we should use the append path added in the previous step.)
1560  */
1561  if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1562  {
1563  AppendPath *appendpath;
1564  ListCell *lc;
1565  int parallel_workers = 0;
1566 
1567  /*
1568  * Find the highest number of workers requested for any partial
1569  * subpath.
1570  */
1571  foreach(lc, pa_partial_subpaths)
1572  {
1573  Path *path = lfirst(lc);
1574 
1575  parallel_workers = Max(parallel_workers, path->parallel_workers);
1576  }
1577 
1578  /*
1579  * Same formula here as above. It's even more important in this
1580  * instance because the non-partial paths won't contribute anything to
1581  * the planned number of parallel workers.
1582  */
1583  parallel_workers = Max(parallel_workers,
1584  pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1585  parallel_workers = Min(parallel_workers,
1587  Assert(parallel_workers > 0);
1588 
1589  appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1590  pa_partial_subpaths,
1591  NIL, NULL, parallel_workers, true,
1592  partial_rows);
1593  add_partial_path(rel, (Path *) appendpath);
1594  }
1595 
1596  /*
1597  * Also build unparameterized ordered append paths based on the collected
1598  * list of child pathkeys.
1599  */
1600  if (subpaths_valid)
1601  generate_orderedappend_paths(root, rel, live_childrels,
1602  all_child_pathkeys);
1603 
1604  /*
1605  * Build Append paths for each parameterization seen among the child rels.
1606  * (This may look pretty expensive, but in most cases of practical
1607  * interest, the child rels will expose mostly the same parameterizations,
1608  * so that not that many cases actually get considered here.)
1609  *
1610  * The Append node itself cannot enforce quals, so all qual checking must
1611  * be done in the child paths. This means that to have a parameterized
1612  * Append path, we must have the exact same parameterization for each
1613  * child path; otherwise some children might be failing to check the
1614  * moved-down quals. To make them match up, we can try to increase the
1615  * parameterization of lesser-parameterized paths.
1616  */
1617  foreach(l, all_child_outers)
1618  {
1619  Relids required_outer = (Relids) lfirst(l);
1620  ListCell *lcr;
1621 
1622  /* Select the child paths for an Append with this parameterization */
1623  subpaths = NIL;
1624  subpaths_valid = true;
1625  foreach(lcr, live_childrels)
1626  {
1627  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1628  Path *subpath;
1629 
1630  if (childrel->pathlist == NIL)
1631  {
1632  /* failed to make a suitable path for this child */
1633  subpaths_valid = false;
1634  break;
1635  }
1636 
1638  childrel,
1639  required_outer);
1640  if (subpath == NULL)
1641  {
1642  /* failed to make a suitable path for this child */
1643  subpaths_valid = false;
1644  break;
1645  }
1646  accumulate_append_subpath(subpath, &subpaths, NULL);
1647  }
1648 
1649  if (subpaths_valid)
1650  add_path(rel, (Path *)
1651  create_append_path(root, rel, subpaths, NIL,
1652  NIL, required_outer, 0, false,
1653  -1));
1654  }
1655 
1656  /*
1657  * When there is only a single child relation, the Append path can inherit
1658  * any ordering available for the child rel's path, so that it's useful to
1659  * consider ordered partial paths. Above we only considered the cheapest
1660  * partial path for each child, but let's also make paths using any
1661  * partial paths that have pathkeys.
1662  */
1663  if (list_length(live_childrels) == 1)
1664  {
1665  RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1666 
1667  /* skip the cheapest partial path, since we already used that above */
1668  for_each_from(l, childrel->partial_pathlist, 1)
1669  {
1670  Path *path = (Path *) lfirst(l);
1671  AppendPath *appendpath;
1672 
1673  /* skip paths with no pathkeys. */
1674  if (path->pathkeys == NIL)
1675  continue;
1676 
1677  appendpath = create_append_path(root, rel, NIL, list_make1(path),
1678  NIL, NULL,
1679  path->parallel_workers, true,
1680  partial_rows);
1681  add_partial_path(rel, (Path *) appendpath);
1682  }
1683  }
1684 }
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:1999
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition: allpaths.c:1714
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2087
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
#define Min(x, y)
Definition: c.h:1004
#define Max(x, y)
Definition: c.h:998
#define Assert(condition)
Definition: c.h:858
int max_parallel_workers_per_gather
Definition: costsize.c:132
bool enable_parallel_append
Definition: costsize.c:150
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:310
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition: pathkeys.c:714
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:302
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1244
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:747
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:420
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1658
Bitmapset * Relids
Definition: pathnodes.h:30
@ PATHKEYS_EQUAL
Definition: paths.h:205
static int pg_leftmost_one_pos32(uint32 word)
Definition: pg_bitutils.h:41
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
tree ctl root
Definition: radixtree.h:1884
List * pathkeys
Definition: pathnodes.h:1654
Cardinality rows
Definition: pathnodes.h:1649
int parallel_workers
Definition: pathnodes.h:1646
Cost total_cost
Definition: pathnodes.h:1651
bool consider_parallel
Definition: pathnodes.h:877
List * pathlist
Definition: pathnodes.h:888
struct Path * cheapest_startup_path
Definition: pathnodes.h:891
struct Path * cheapest_total_path
Definition: pathnodes.h:892
bool consider_startup
Definition: pathnodes.h:873
List * partial_pathlist
Definition: pathnodes.h:890

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

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

◆ check_and_push_window_quals()

static bool check_and_push_window_quals ( Query subquery,
RangeTblEntry rte,
Index  rti,
Node clause,
Bitmapset **  run_cond_attrs 
)
static

Definition at line 2419 of file allpaths.c.

2421 {
2422  OpExpr *opexpr = (OpExpr *) clause;
2423  bool keep_original = true;
2424  Var *var1;
2425  Var *var2;
2426 
2427  /* We're only able to use OpExprs with 2 operands */
2428  if (!IsA(opexpr, OpExpr))
2429  return true;
2430 
2431  if (list_length(opexpr->args) != 2)
2432  return true;
2433 
2434  /*
2435  * Currently, we restrict this optimization to strict OpExprs. The reason
2436  * for this is that during execution, once the runcondition becomes false,
2437  * we stop evaluating WindowFuncs. To avoid leaving around stale window
2438  * function result values, we set them to NULL. Having only strict
2439  * OpExprs here ensures that we properly filter out the tuples with NULLs
2440  * in the top-level WindowAgg.
2441  */
2442  set_opfuncid(opexpr);
2443  if (!func_strict(opexpr->opfuncid))
2444  return true;
2445 
2446  /*
2447  * Check for plain Vars that reference window functions in the subquery.
2448  * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2449  * be used as part of the run condition.
2450  */
2451 
2452  /* Check the left side of the OpExpr */
2453  var1 = linitial(opexpr->args);
2454  if (IsA(var1, Var) && var1->varattno > 0)
2455  {
2456  TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2457  WindowFunc *wfunc = (WindowFunc *) tle->expr;
2458 
2459  if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2460  opexpr, true, &keep_original,
2461  run_cond_attrs))
2462  return keep_original;
2463  }
2464 
2465  /* and check the right side */
2466  var2 = lsecond(opexpr->args);
2467  if (IsA(var2, Var) && var2->varattno > 0)
2468  {
2469  TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2470  WindowFunc *wfunc = (WindowFunc *) tle->expr;
2471 
2472  if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2473  opexpr, false, &keep_original,
2474  run_cond_attrs))
2475  return keep_original;
2476  }
2477 
2478  return true;
2479 }
static bool find_window_run_conditions(Query *subquery, RangeTblEntry *rte, Index rti, AttrNumber attno, WindowFunc *wfunc, OpExpr *opexpr, bool wfunc_left, bool *keep_original, Bitmapset **run_cond_attrs)
Definition: allpaths.c:2214
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
bool func_strict(Oid funcid)
Definition: lsyscache.c:1761
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1868
#define lsecond(l)
Definition: pg_list.h:183
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
List * args
Definition: primnodes.h:806
List * targetList
Definition: parsenodes.h:191
Expr * expr
Definition: primnodes.h:2162
AttrNumber resno
Definition: primnodes.h:2164
Definition: primnodes.h:248
AttrNumber varattno
Definition: primnodes.h:260

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

Referenced by set_subquery_pathlist().

◆ check_output_expressions()

static void check_output_expressions ( Query subquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 3719 of file allpaths.c.

3720 {
3721  ListCell *lc;
3722 
3723  foreach(lc, subquery->targetList)
3724  {
3725  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3726 
3727  if (tle->resjunk)
3728  continue; /* ignore resjunk columns */
3729 
3730  /* Functions returning sets are unsafe (point 1) */
3731  if (subquery->hasTargetSRFs &&
3732  (safetyInfo->unsafeFlags[tle->resno] &
3733  UNSAFE_HAS_SET_FUNC) == 0 &&
3734  expression_returns_set((Node *) tle->expr))
3735  {
3736  safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_SET_FUNC;
3737  continue;
3738  }
3739 
3740  /* Volatile functions are unsafe (point 2) */
3741  if ((safetyInfo->unsafeFlags[tle->resno] &
3742  UNSAFE_HAS_VOLATILE_FUNC) == 0 &&
3744  {
3745  safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_HAS_VOLATILE_FUNC;
3746  continue;
3747  }
3748 
3749  /* If subquery uses DISTINCT ON, check point 3 */
3750  if (subquery->hasDistinctOn &&
3751  (safetyInfo->unsafeFlags[tle->resno] &
3753  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3754  {
3755  /* non-DISTINCT column, so mark it unsafe */
3756  safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_DISTINCTON_CLAUSE;
3757  continue;
3758  }
3759 
3760  /* If subquery uses window functions, check point 4 */
3761  if (subquery->hasWindowFuncs &&
3762  (safetyInfo->unsafeFlags[tle->resno] &
3764  !targetIsInAllPartitionLists(tle, subquery))
3765  {
3766  /* not present in all PARTITION BY clauses, so mark it unsafe */
3767  safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_NOTIN_PARTITIONBY_CLAUSE;
3768  continue;
3769  }
3770  }
3771 }
#define UNSAFE_HAS_VOLATILE_FUNC
Definition: allpaths.c:53
#define UNSAFE_NOTIN_DISTINCTON_CLAUSE
Definition: allpaths.c:55
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:3824
#define UNSAFE_HAS_SET_FUNC
Definition: allpaths.c:54
#define UNSAFE_NOTIN_PARTITIONBY_CLAUSE
Definition: allpaths.c:56
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:538
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:758
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition: postgres_ext.h:36
Definition: nodes.h:129
List * distinctClause
Definition: parsenodes.h:209
unsigned char * unsafeFlags
Definition: allpaths.c:62

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

Referenced by subquery_is_pushdown_safe().

◆ compare_tlist_datatypes()

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

Definition at line 3791 of file allpaths.c.

3793 {
3794  ListCell *l;
3795  ListCell *colType = list_head(colTypes);
3796 
3797  foreach(l, tlist)
3798  {
3799  TargetEntry *tle = (TargetEntry *) lfirst(l);
3800 
3801  if (tle->resjunk)
3802  continue; /* ignore resjunk columns */
3803  if (colType == NULL)
3804  elog(ERROR, "wrong number of tlist entries");
3805  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3806  safetyInfo->unsafeFlags[tle->resno] |= UNSAFE_TYPE_MISMATCH;
3807  colType = lnext(colTypes, colType);
3808  }
3809  if (colType != NULL)
3810  elog(ERROR, "wrong number of tlist entries");
3811 }
#define UNSAFE_TYPE_MISMATCH
Definition: allpaths.c:57
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define lfirst_oid(lc)
Definition: pg_list.h:174

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

Referenced by subquery_is_pushdown_safe().

◆ compute_parallel_worker()

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

Definition at line 4215 of file allpaths.c.

4217 {
4218  int parallel_workers = 0;
4219 
4220  /*
4221  * If the user has set the parallel_workers reloption, use that; otherwise
4222  * select a default number of workers.
4223  */
4224  if (rel->rel_parallel_workers != -1)
4225  parallel_workers = rel->rel_parallel_workers;
4226  else
4227  {
4228  /*
4229  * If the number of pages being scanned is insufficient to justify a
4230  * parallel scan, just return zero ... unless it's an inheritance
4231  * child. In that case, we want to generate a parallel path here
4232  * anyway. It might not be worthwhile just for this relation, but
4233  * when combined with all of its inheritance siblings it may well pay
4234  * off.
4235  */
4236  if (rel->reloptkind == RELOPT_BASEREL &&
4237  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4238  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4239  return 0;
4240 
4241  if (heap_pages >= 0)
4242  {
4243  int heap_parallel_threshold;
4244  int heap_parallel_workers = 1;
4245 
4246  /*
4247  * Select the number of workers based on the log of the size of
4248  * the relation. This probably needs to be a good deal more
4249  * sophisticated, but we need something here for now. Note that
4250  * the upper limit of the min_parallel_table_scan_size GUC is
4251  * chosen to prevent overflow here.
4252  */
4253  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4254  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4255  {
4256  heap_parallel_workers++;
4257  heap_parallel_threshold *= 3;
4258  if (heap_parallel_threshold > INT_MAX / 3)
4259  break; /* avoid overflow */
4260  }
4261 
4262  parallel_workers = heap_parallel_workers;
4263  }
4264 
4265  if (index_pages >= 0)
4266  {
4267  int index_parallel_workers = 1;
4268  int index_parallel_threshold;
4269 
4270  /* same calculation as for heap_pages above */
4271  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4272  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4273  {
4274  index_parallel_workers++;
4275  index_parallel_threshold *= 3;
4276  if (index_parallel_threshold > INT_MAX / 3)
4277  break; /* avoid overflow */
4278  }
4279 
4280  if (parallel_workers > 0)
4281  parallel_workers = Min(parallel_workers, index_parallel_workers);
4282  else
4283  parallel_workers = index_parallel_workers;
4284  }
4285  }
4286 
4287  /* In no case use more than caller supplied maximum number of workers */
4288  parallel_workers = Min(parallel_workers, max_workers);
4289 
4290  return parallel_workers;
4291 }
int min_parallel_index_scan_size
Definition: allpaths.c:82
int min_parallel_table_scan_size
Definition: allpaths.c:81
uint32 BlockNumber
Definition: block.h:31
@ RELOPT_BASEREL
Definition: pathnodes.h:817
RelOptKind reloptkind
Definition: pathnodes.h:855
int rel_parallel_workers
Definition: pathnodes.h:946

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

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

◆ create_partial_bitmap_paths()

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

Definition at line 4179 of file allpaths.c.

4181 {
4182  int parallel_workers;
4183  double pages_fetched;
4184 
4185  /* Compute heap pages for bitmap heap scan */
4186  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4187  NULL, NULL);
4188 
4189  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4191 
4192  if (parallel_workers <= 0)
4193  return;
4194 
4196  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4197 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4215
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6403
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1042
Relids lateral_relids
Definition: pathnodes.h:903

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

Referenced by create_index_paths().

◆ create_plain_partial_paths()

static void create_plain_partial_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 794 of file allpaths.c.

795 {
796  int parallel_workers;
797 
798  parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
800 
801  /* If any limit was set to zero, the user doesn't want a parallel scan. */
802  if (parallel_workers <= 0)
803  return;
804 
805  /* Add an unordered partial path based on a parallel sequential scan. */
806  add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
807 }
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:927
BlockNumber pages
Definition: pathnodes.h:938

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

Referenced by set_plain_rel_pathlist().

◆ find_window_run_conditions()

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

Definition at line 2214 of file allpaths.c.

2218 {
2219  Oid prosupport;
2220  Expr *otherexpr;
2223  WindowClause *wclause;
2224  List *opinfos;
2225  OpExpr *runopexpr;
2226  Oid runoperator;
2227  ListCell *lc;
2228 
2229  *keep_original = true;
2230 
2231  while (IsA(wfunc, RelabelType))
2232  wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2233 
2234  /* we can only work with window functions */
2235  if (!IsA(wfunc, WindowFunc))
2236  return false;
2237 
2238  /* can't use it if there are subplans in the WindowFunc */
2239  if (contain_subplans((Node *) wfunc))
2240  return false;
2241 
2242  prosupport = get_func_support(wfunc->winfnoid);
2243 
2244  /* Check if there's a support function for 'wfunc' */
2245  if (!OidIsValid(prosupport))
2246  return false;
2247 
2248  /* get the Expr from the other side of the OpExpr */
2249  if (wfunc_left)
2250  otherexpr = lsecond(opexpr->args);
2251  else
2252  otherexpr = linitial(opexpr->args);
2253 
2254  /*
2255  * The value being compared must not change during the evaluation of the
2256  * window partition.
2257  */
2258  if (!is_pseudo_constant_clause((Node *) otherexpr))
2259  return false;
2260 
2261  /* find the window clause belonging to the window function */
2262  wclause = (WindowClause *) list_nth(subquery->windowClause,
2263  wfunc->winref - 1);
2264 
2265  req.type = T_SupportRequestWFuncMonotonic;
2266  req.window_func = wfunc;
2267  req.window_clause = wclause;
2268 
2269  /* call the support function */
2271  DatumGetPointer(OidFunctionCall1(prosupport,
2272  PointerGetDatum(&req)));
2273 
2274  /*
2275  * Nothing to do if the function is neither monotonically increasing nor
2276  * monotonically decreasing.
2277  */
2278  if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2279  return false;
2280 
2281  runopexpr = NULL;
2282  runoperator = InvalidOid;
2283  opinfos = get_op_btree_interpretation(opexpr->opno);
2284 
2285  foreach(lc, opinfos)
2286  {
2288  int strategy = opinfo->strategy;
2289 
2290  /* handle < / <= */
2291  if (strategy == BTLessStrategyNumber ||
2292  strategy == BTLessEqualStrategyNumber)
2293  {
2294  /*
2295  * < / <= is supported for monotonically increasing functions in
2296  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2297  * for monotonically decreasing functions.
2298  */
2299  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2300  (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2301  {
2302  *keep_original = false;
2303  runopexpr = opexpr;
2304  runoperator = opexpr->opno;
2305  }
2306  break;
2307  }
2308  /* handle > / >= */
2309  else if (strategy == BTGreaterStrategyNumber ||
2310  strategy == BTGreaterEqualStrategyNumber)
2311  {
2312  /*
2313  * > / >= is supported for monotonically decreasing functions in
2314  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2315  * for monotonically increasing functions.
2316  */
2317  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2318  (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2319  {
2320  *keep_original = false;
2321  runopexpr = opexpr;
2322  runoperator = opexpr->opno;
2323  }
2324  break;
2325  }
2326  /* handle = */
2327  else if (strategy == BTEqualStrategyNumber)
2328  {
2329  int16 newstrategy;
2330 
2331  /*
2332  * When both monotonically increasing and decreasing then the
2333  * return value of the window function will be the same each time.
2334  * We can simply use 'opexpr' as the run condition without
2335  * modifying it.
2336  */
2337  if ((res->monotonic & MONOTONICFUNC_BOTH) == MONOTONICFUNC_BOTH)
2338  {
2339  *keep_original = false;
2340  runopexpr = opexpr;
2341  runoperator = opexpr->opno;
2342  break;
2343  }
2344 
2345  /*
2346  * When monotonically increasing we make a qual with <wfunc> <=
2347  * <value> or <value> >= <wfunc> in order to filter out values
2348  * which are above the value in the equality condition. For
2349  * monotonically decreasing functions we want to filter values
2350  * below the value in the equality condition.
2351  */
2352  if (res->monotonic & MONOTONICFUNC_INCREASING)
2353  newstrategy = wfunc_left ? BTLessEqualStrategyNumber : BTGreaterEqualStrategyNumber;
2354  else
2355  newstrategy = wfunc_left ? BTGreaterEqualStrategyNumber : BTLessEqualStrategyNumber;
2356 
2357  /* We must keep the original equality qual */
2358  *keep_original = true;
2359  runopexpr = opexpr;
2360 
2361  /* determine the operator to use for the runCondition qual */
2362  runoperator = get_opfamily_member(opinfo->opfamily_id,
2363  opinfo->oplefttype,
2364  opinfo->oprighttype,
2365  newstrategy);
2366  break;
2367  }
2368  }
2369 
2370  if (runopexpr != NULL)
2371  {
2372  Expr *newexpr;
2373 
2374  /*
2375  * Build the qual required for the run condition keeping the
2376  * WindowFunc on the same side as it was originally.
2377  */
2378  if (wfunc_left)
2379  newexpr = make_opclause(runoperator,
2380  runopexpr->opresulttype,
2381  runopexpr->opretset, (Expr *) wfunc,
2382  otherexpr, runopexpr->opcollid,
2383  runopexpr->inputcollid);
2384  else
2385  newexpr = make_opclause(runoperator,
2386  runopexpr->opresulttype,
2387  runopexpr->opretset,
2388  otherexpr, (Expr *) wfunc,
2389  runopexpr->opcollid,
2390  runopexpr->inputcollid);
2391 
2392  wclause->runCondition = lappend(wclause->runCondition, newexpr);
2393 
2394  /* record that this attno was used in a run condition */
2395  *run_cond_attrs = bms_add_member(*run_cond_attrs,
2397  return true;
2398  }
2399 
2400  /* unsupported OpExpr */
2401  return false;
2402 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
signed short int16
Definition: c.h:493
#define OidIsValid(objectId)
Definition: c.h:775
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:2088
bool contain_subplans(Node *clause)
Definition: clauses.c:330
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1858
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:166
List * get_op_btree_interpretation(Oid opno)
Definition: lsyscache.c:601
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: makefuncs.c:628
void * arg
@ MONOTONICFUNC_NONE
Definition: plannodes.h:1587
@ MONOTONICFUNC_DECREASING
Definition: plannodes.h:1589
@ MONOTONICFUNC_INCREASING
Definition: plannodes.h:1588
@ MONOTONICFUNC_BOTH
Definition: plannodes.h:1590
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
unsigned int Oid
Definition: postgres_ext.h:31
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define BTLessStrategyNumber
Definition: stratnum.h:29
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define BTLessEqualStrategyNumber
Definition: stratnum.h:30
#define BTGreaterEqualStrategyNumber
Definition: stratnum.h:32
Oid opno
Definition: primnodes.h:788
List * windowClause
Definition: parsenodes.h:207
struct WindowClause * window_clause
Definition: supportnodes.h:296
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References arg, OpExpr::args, bms_add_member(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, contain_subplans(), DatumGetPointer(), FirstLowInvalidHeapAttributeNumber, get_func_support(), get_op_btree_interpretation(), get_opfamily_member(), InvalidOid, is_pseudo_constant_clause(), IsA, lappend(), lfirst, linitial, list_nth(), lsecond, make_opclause(), MONOTONICFUNC_BOTH, MONOTONICFUNC_DECREASING, MONOTONICFUNC_INCREASING, MONOTONICFUNC_NONE, OidFunctionCall1, OidIsValid, OpBtreeInterpretation::opfamily_id, OpBtreeInterpretation::oplefttype, OpExpr::opno, OpBtreeInterpretation::oprighttype, PointerGetDatum(), res, OpBtreeInterpretation::strategy, SupportRequestWFuncMonotonic::type, SupportRequestWFuncMonotonic::window_clause, SupportRequestWFuncMonotonic::window_func, Query::windowClause, WindowFunc::winfnoid, and WindowFunc::winref.

Referenced by check_and_push_window_quals().

◆ generate_gather_paths()

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

Definition at line 3064 of file allpaths.c.

3065 {
3066  Path *cheapest_partial_path;
3067  Path *simple_gather_path;
3068  ListCell *lc;
3069  double rows;
3070  double *rowsp = NULL;
3071 
3072  /* If there are no partial paths, there's nothing to do here. */
3073  if (rel->partial_pathlist == NIL)
3074  return;
3075 
3076  /* Should we override the rel's rowcount estimate? */
3077  if (override_rows)
3078  rowsp = &rows;
3079 
3080  /*
3081  * The output of Gather is always unsorted, so there's only one partial
3082  * path of interest: the cheapest one. That will be the one at the front
3083  * of partial_pathlist because of the way add_partial_path works.
3084  */
3085  cheapest_partial_path = linitial(rel->partial_pathlist);
3086  rows =
3087  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
3088  simple_gather_path = (Path *)
3089  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
3090  NULL, rowsp);
3091  add_path(rel, simple_gather_path);
3092 
3093  /*
3094  * For each useful ordering, we can consider an order-preserving Gather
3095  * Merge.
3096  */
3097  foreach(lc, rel->partial_pathlist)
3098  {
3099  Path *subpath = (Path *) lfirst(lc);
3100  GatherMergePath *path;
3101 
3102  if (subpath->pathkeys == NIL)
3103  continue;
3104 
3105  rows = subpath->rows * subpath->parallel_workers;
3106  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
3107  subpath->pathkeys, NULL, rowsp);
3108  add_path(rel, &path->path);
3109  }
3110 }
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1881
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1972
struct PathTarget * reltarget
Definition: pathnodes.h:883

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

Referenced by generate_useful_gather_paths().

◆ generate_orderedappend_paths()

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

Definition at line 1714 of file allpaths.c.

1717 {
1718  ListCell *lcp;
1719  List *partition_pathkeys = NIL;
1720  List *partition_pathkeys_desc = NIL;
1721  bool partition_pathkeys_partial = true;
1722  bool partition_pathkeys_desc_partial = true;
1723 
1724  /*
1725  * Some partitioned table setups may allow us to use an Append node
1726  * instead of a MergeAppend. This is possible in cases such as RANGE
1727  * partitioned tables where it's guaranteed that an earlier partition must
1728  * contain rows which come earlier in the sort order. To detect whether
1729  * this is relevant, build pathkey descriptions of the partition ordering,
1730  * for both forward and reverse scans.
1731  */
1732  if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1733  partitions_are_ordered(rel->boundinfo, rel->live_parts))
1734  {
1735  partition_pathkeys = build_partition_pathkeys(root, rel,
1737  &partition_pathkeys_partial);
1738 
1739  partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1741  &partition_pathkeys_desc_partial);
1742 
1743  /*
1744  * You might think we should truncate_useless_pathkeys here, but
1745  * allowing partition keys which are a subset of the query's pathkeys
1746  * can often be useful. For example, consider a table partitioned by
1747  * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1748  * paths that can produce the a, b, c ordering (perhaps via indexes on
1749  * (a, b, c)) then it works to consider the appendrel output as
1750  * ordered by a, b, c.
1751  */
1752  }
1753 
1754  /* Now consider each interesting sort ordering */
1755  foreach(lcp, all_child_pathkeys)
1756  {
1757  List *pathkeys = (List *) lfirst(lcp);
1758  List *startup_subpaths = NIL;
1759  List *total_subpaths = NIL;
1760  List *fractional_subpaths = NIL;
1761  bool startup_neq_total = false;
1762  bool match_partition_order;
1763  bool match_partition_order_desc;
1764  int end_index;
1765  int first_index;
1766  int direction;
1767 
1768  /*
1769  * Determine if this sort ordering matches any partition pathkeys we
1770  * have, for both ascending and descending partition order. If the
1771  * partition pathkeys happen to be contained in pathkeys then it still
1772  * works, as described above, providing that the partition pathkeys
1773  * are complete and not just a prefix of the partition keys. (In such
1774  * cases we'll be relying on the child paths to have sorted the
1775  * lower-order columns of the required pathkeys.)
1776  */
1777  match_partition_order =
1778  pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1779  (!partition_pathkeys_partial &&
1780  pathkeys_contained_in(partition_pathkeys, pathkeys));
1781 
1782  match_partition_order_desc = !match_partition_order &&
1783  (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1784  (!partition_pathkeys_desc_partial &&
1785  pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1786 
1787  /*
1788  * When the required pathkeys match the reverse of the partition
1789  * order, we must build the list of paths in reverse starting with the
1790  * last matching partition first. We can get away without making any
1791  * special cases for this in the loop below by just looping backward
1792  * over the child relations in this case.
1793  */
1794  if (match_partition_order_desc)
1795  {
1796  /* loop backward */
1797  first_index = list_length(live_childrels) - 1;
1798  end_index = -1;
1799  direction = -1;
1800 
1801  /*
1802  * Set this to true to save us having to check for
1803  * match_partition_order_desc in the loop below.
1804  */
1805  match_partition_order = true;
1806  }
1807  else
1808  {
1809  /* for all other case, loop forward */
1810  first_index = 0;
1811  end_index = list_length(live_childrels);
1812  direction = 1;
1813  }
1814 
1815  /* Select the child paths for this ordering... */
1816  for (int i = first_index; i != end_index; i += direction)
1817  {
1818  RelOptInfo *childrel = list_nth_node(RelOptInfo, live_childrels, i);
1819  Path *cheapest_startup,
1820  *cheapest_total,
1821  *cheapest_fractional = NULL;
1822 
1823  /* Locate the right paths, if they are available. */
1824  cheapest_startup =
1826  pathkeys,
1827  NULL,
1828  STARTUP_COST,
1829  false);
1830  cheapest_total =
1832  pathkeys,
1833  NULL,
1834  TOTAL_COST,
1835  false);
1836 
1837  /*
1838  * If we can't find any paths with the right order just use the
1839  * cheapest-total path; we'll have to sort it later.
1840  */
1841  if (cheapest_startup == NULL || cheapest_total == NULL)
1842  {
1843  cheapest_startup = cheapest_total =
1844  childrel->cheapest_total_path;
1845  /* Assert we do have an unparameterized path for this child */
1846  Assert(cheapest_total->param_info == NULL);
1847  }
1848 
1849  /*
1850  * When building a fractional path, determine a cheapest
1851  * fractional path for each child relation too. Looking at startup
1852  * and total costs is not enough, because the cheapest fractional
1853  * path may be dominated by two separate paths (one for startup,
1854  * one for total).
1855  *
1856  * When needed (building fractional path), determine the cheapest
1857  * fractional path too.
1858  */
1859  if (root->tuple_fraction > 0)
1860  {
1861  double path_fraction = (1.0 / root->tuple_fraction);
1862 
1863  cheapest_fractional =
1865  pathkeys,
1866  NULL,
1867  path_fraction);
1868 
1869  /*
1870  * If we found no path with matching pathkeys, use the
1871  * cheapest total path instead.
1872  *
1873  * XXX We might consider partially sorted paths too (with an
1874  * incremental sort on top). But we'd have to build all the
1875  * incremental paths, do the costing etc.
1876  */
1877  if (!cheapest_fractional)
1878  cheapest_fractional = cheapest_total;
1879  }
1880 
1881  /*
1882  * Notice whether we actually have different paths for the
1883  * "cheapest" and "total" cases; frequently there will be no point
1884  * in two create_merge_append_path() calls.
1885  */
1886  if (cheapest_startup != cheapest_total)
1887  startup_neq_total = true;
1888 
1889  /*
1890  * Collect the appropriate child paths. The required logic varies
1891  * for the Append and MergeAppend cases.
1892  */
1893  if (match_partition_order)
1894  {
1895  /*
1896  * We're going to make a plain Append path. We don't need
1897  * most of what accumulate_append_subpath would do, but we do
1898  * want to cut out child Appends or MergeAppends if they have
1899  * just a single subpath (and hence aren't doing anything
1900  * useful).
1901  */
1902  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1903  cheapest_total = get_singleton_append_subpath(cheapest_total);
1904 
1905  startup_subpaths = lappend(startup_subpaths, cheapest_startup);
1906  total_subpaths = lappend(total_subpaths, cheapest_total);
1907 
1908  if (cheapest_fractional)
1909  {
1910  cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1911  fractional_subpaths = lappend(fractional_subpaths, cheapest_fractional);
1912  }
1913  }
1914  else
1915  {
1916  /*
1917  * Otherwise, rely on accumulate_append_subpath to collect the
1918  * child paths for the MergeAppend.
1919  */
1920  accumulate_append_subpath(cheapest_startup,
1921  &startup_subpaths, NULL);
1922  accumulate_append_subpath(cheapest_total,
1923  &total_subpaths, NULL);
1924 
1925  if (cheapest_fractional)
1926  accumulate_append_subpath(cheapest_fractional,
1927  &fractional_subpaths, NULL);
1928  }
1929  }
1930 
1931  /* ... and build the Append or MergeAppend paths */
1932  if (match_partition_order)
1933  {
1934  /* We only need Append */
1936  rel,
1937  startup_subpaths,
1938  NIL,
1939  pathkeys,
1940  NULL,
1941  0,
1942  false,
1943  -1));
1944  if (startup_neq_total)
1946  rel,
1947  total_subpaths,
1948  NIL,
1949  pathkeys,
1950  NULL,
1951  0,
1952  false,
1953  -1));
1954 
1955  if (fractional_subpaths)
1957  rel,
1958  fractional_subpaths,
1959  NIL,
1960  pathkeys,
1961  NULL,
1962  0,
1963  false,
1964  -1));
1965  }
1966  else
1967  {
1968  /* We need MergeAppend */
1970  rel,
1971  startup_subpaths,
1972  pathkeys,
1973  NULL));
1974  if (startup_neq_total)
1976  rel,
1977  total_subpaths,
1978  pathkeys,
1979  NULL));
1980 
1981  if (fractional_subpaths)
1983  rel,
1984  fractional_subpaths,
1985  pathkeys,
1986  NULL));
1987  }
1988  }
1989 }
static Path * get_singleton_append_subpath(Path *path)
Definition: allpaths.c:2132
int i
Definition: isn.c:73
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2852
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:635
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:681
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:341
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:934
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1415
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:829
@ TOTAL_COST
Definition: pathnodes.h:38
@ STARTUP_COST
Definition: pathnodes.h:38
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
@ BackwardScanDirection
Definition: sdir.h:26
@ ForwardScanDirection
Definition: sdir.h:28
Bitmapset * live_parts
Definition: pathnodes.h:1029

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

Referenced by add_paths_to_append_rel().

◆ generate_partitionwise_join_paths()

void generate_partitionwise_join_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4303 of file allpaths.c.

4304 {
4305  List *live_children = NIL;
4306  int cnt_parts;
4307  int num_parts;
4308  RelOptInfo **part_rels;
4309 
4310  /* Handle only join relations here. */
4311  if (!IS_JOIN_REL(rel))
4312  return;
4313 
4314  /* We've nothing to do if the relation is not partitioned. */
4315  if (!IS_PARTITIONED_REL(rel))
4316  return;
4317 
4318  /* The relation should have consider_partitionwise_join set. */
4320 
4321  /* Guard against stack overflow due to overly deep partition hierarchy. */
4323 
4324  num_parts = rel->nparts;
4325  part_rels = rel->part_rels;
4326 
4327  /* Collect non-dummy child-joins. */
4328  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4329  {
4330  RelOptInfo *child_rel = part_rels[cnt_parts];
4331 
4332  /* If it's been pruned entirely, it's certainly dummy. */
4333  if (child_rel == NULL)
4334  continue;
4335 
4336  /* Make partitionwise join paths for this partitioned child-join. */
4338 
4339  /* If we failed to make any path for this child, we must give up. */
4340  if (child_rel->pathlist == NIL)
4341  {
4342  /*
4343  * Mark the parent joinrel as unpartitioned so that later
4344  * functions treat it correctly.
4345  */
4346  rel->nparts = 0;
4347  return;
4348  }
4349 
4350  /* Else, identify the cheapest path for it. */
4351  set_cheapest(child_rel);
4352 
4353  /* Dummy children need not be scanned, so ignore those. */
4354  if (IS_DUMMY_REL(child_rel))
4355  continue;
4356 
4357 #ifdef OPTIMIZER_DEBUG
4358  pprint(child_rel);
4359 #endif
4360 
4361  live_children = lappend(live_children, child_rel);
4362  }
4363 
4364  /* If all child-joins are dummy, parent join is also dummy. */
4365  if (!live_children)
4366  {
4367  mark_dummy_rel(rel);
4368  return;
4369  }
4370 
4371  /* Build additional paths for this rel from child-join paths. */
4372  add_paths_to_append_rel(root, rel, live_children);
4373  list_free(live_children);
4374 }
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:4303
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1302
void pprint(const void *obj)
Definition: print.c:54
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1381
void list_free(List *list)
Definition: list.c:1546
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:242
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1935
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:834
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1052
void check_stack_depth(void)
Definition: postgres.c:3531
bool consider_partitionwise_join
Definition: pathnodes.h:989

References add_paths_to_append_rel(), Assert, check_stack_depth(), RelOptInfo::consider_partitionwise_join, IS_DUMMY_REL, IS_JOIN_REL, IS_PARTITIONED_REL, lappend(), list_free(), mark_dummy_rel(), NIL, RelOptInfo::nparts, RelOptInfo::pathlist, pprint(), root, and set_cheapest().

Referenced by 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 3202 of file allpaths.c.

3203 {
3204  ListCell *lc;
3205  double rows;
3206  double *rowsp = NULL;
3207  List *useful_pathkeys_list = NIL;
3208  Path *cheapest_partial_path = NULL;
3209 
3210  /* If there are no partial paths, there's nothing to do here. */
3211  if (rel->partial_pathlist == NIL)
3212  return;
3213 
3214  /* Should we override the rel's rowcount estimate? */
3215  if (override_rows)
3216  rowsp = &rows;
3217 
3218  /* generate the regular gather (merge) paths */
3219  generate_gather_paths(root, rel, override_rows);
3220 
3221  /* consider incremental sort for interesting orderings */
3222  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3223 
3224  /* used for explicit (full) sort paths */
3225  cheapest_partial_path = linitial(rel->partial_pathlist);
3226 
3227  /*
3228  * Consider sorted paths for each interesting ordering. We generate both
3229  * incremental and full sort.
3230  */
3231  foreach(lc, useful_pathkeys_list)
3232  {
3233  List *useful_pathkeys = lfirst(lc);
3234  ListCell *lc2;
3235  bool is_sorted;
3236  int presorted_keys;
3237 
3238  foreach(lc2, rel->partial_pathlist)
3239  {
3240  Path *subpath = (Path *) lfirst(lc2);
3241  GatherMergePath *path;
3242 
3243  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3244  subpath->pathkeys,
3245  &presorted_keys);
3246 
3247  /*
3248  * We don't need to consider the case where a subpath is already
3249  * fully sorted because generate_gather_paths already creates a
3250  * gather merge path for every subpath that has pathkeys present.
3251  *
3252  * But since the subpath is already sorted, we know we don't need
3253  * to consider adding a sort (full or incremental) on top of it,
3254  * so we can continue here.
3255  */
3256  if (is_sorted)
3257  continue;
3258 
3259  /*
3260  * Try at least sorting the cheapest path and also try
3261  * incrementally sorting any path which is partially sorted
3262  * already (no need to deal with paths which have presorted keys
3263  * when incremental sort is disabled unless it's the cheapest
3264  * input path).
3265  */
3266  if (subpath != cheapest_partial_path &&
3267  (presorted_keys == 0 || !enable_incremental_sort))
3268  continue;
3269 
3270  /*
3271  * Consider regular sort for any path that's not presorted or if
3272  * incremental sort is disabled. We've no need to consider both
3273  * sort and incremental sort on the same path. We assume that
3274  * incremental sort is always faster when there are presorted
3275  * keys.
3276  *
3277  * This is not redundant with the gather paths created in
3278  * generate_gather_paths, because that doesn't generate ordered
3279  * output. Here we add an explicit sort to match the useful
3280  * ordering.
3281  */
3282  if (presorted_keys == 0 || !enable_incremental_sort)
3283  {
3285  rel,
3286  subpath,
3287  useful_pathkeys,
3288  -1.0);
3289  rows = subpath->rows * subpath->parallel_workers;
3290  }
3291  else
3293  rel,
3294  subpath,
3295  useful_pathkeys,
3296  presorted_keys,
3297  -1);
3298  path = create_gather_merge_path(root, rel,
3299  subpath,
3300  rel->reltarget,
3301  subpath->pathkeys,
3302  NULL,
3303  rowsp);
3304 
3305  add_path(rel, &path->path);
3306  }
3307  }
3308 }
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3064
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:3134
bool enable_incremental_sort
Definition: costsize.c:140
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:573
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:3000
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2951

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

Referenced by apply_scanjoin_target_to_paths(), create_partial_distinct_paths(), 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 1999 of file allpaths.c.

2001 {
2002  Path *cheapest;
2003  ListCell *lc;
2004 
2005  /*
2006  * Look up the cheapest existing path with no more than the needed
2007  * parameterization. If it has exactly the needed parameterization, we're
2008  * done.
2009  */
2010  cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
2011  NIL,
2012  required_outer,
2013  TOTAL_COST,
2014  false);
2015  Assert(cheapest != NULL);
2016  if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
2017  return cheapest;
2018 
2019  /*
2020  * Otherwise, we can "reparameterize" an existing path to match the given
2021  * parameterization, which effectively means pushing down additional
2022  * joinquals to be checked within the path's scan. However, some existing
2023  * paths might check the available joinquals already while others don't;
2024  * therefore, it's not clear which existing path will be cheapest after
2025  * reparameterization. We have to go through them all and find out.
2026  */
2027  cheapest = NULL;
2028  foreach(lc, rel->pathlist)
2029  {
2030  Path *path = (Path *) lfirst(lc);
2031 
2032  /* Can't use it if it needs more than requested parameterization */
2033  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
2034  continue;
2035 
2036  /*
2037  * Reparameterization can only increase the path's cost, so if it's
2038  * already more expensive than the current cheapest, forget it.
2039  */
2040  if (cheapest != NULL &&
2041  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2042  continue;
2043 
2044  /* Reparameterize if needed, then recheck cost */
2045  if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
2046  {
2047  path = reparameterize_path(root, path, required_outer, 1.0);
2048  if (path == NULL)
2049  continue; /* failed to reparameterize this one */
2050  Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
2051 
2052  if (cheapest != NULL &&
2053  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2054  continue;
2055  }
2056 
2057  /* We have a new best path */
2058  cheapest = path;
2059  }
2060 
2061  /* Return the best path, or NULL if we found no suitable candidate */
2062  return cheapest;
2063 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3946
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:69

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

Referenced by add_paths_to_append_rel().

◆ get_singleton_append_subpath()

static Path * get_singleton_append_subpath ( Path path)
static

Definition at line 2132 of file allpaths.c.

2133 {
2134  Assert(!path->parallel_aware);
2135 
2136  if (IsA(path, AppendPath))
2137  {
2138  AppendPath *apath = (AppendPath *) path;
2139 
2140  if (list_length(apath->subpaths) == 1)
2141  return (Path *) linitial(apath->subpaths);
2142  }
2143  else if (IsA(path, MergeAppendPath))
2144  {
2145  MergeAppendPath *mpath = (MergeAppendPath *) path;
2146 
2147  if (list_length(mpath->subpaths) == 1)
2148  return (Path *) linitial(mpath->subpaths);
2149  }
2150 
2151  return path;
2152 }

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

Referenced by generate_orderedappend_paths().

◆ get_useful_pathkeys_for_relation()

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

Definition at line 3134 of file allpaths.c.

3136 {
3137  List *useful_pathkeys_list = NIL;
3138 
3139  /*
3140  * Considering query_pathkeys is always worth it, because it might allow
3141  * us to avoid a total sort when we have a partially presorted path
3142  * available or to push the total sort into the parallel portion of the
3143  * query.
3144  */
3145  if (root->query_pathkeys)
3146  {
3147  ListCell *lc;
3148  int npathkeys = 0; /* useful pathkeys */
3149 
3150  foreach(lc, root->query_pathkeys)
3151  {
3152  PathKey *pathkey = (PathKey *) lfirst(lc);
3153  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3154 
3155  /*
3156  * We can only build a sort for pathkeys that contain a
3157  * safe-to-compute-early EC member computable from the current
3158  * relation's reltarget, so ignore the remainder of the list as
3159  * soon as we find a pathkey without such a member.
3160  *
3161  * It's still worthwhile to return any prefix of the pathkeys list
3162  * that meets this requirement, as we may be able to do an
3163  * incremental sort.
3164  *
3165  * If requested, ensure the sort expression is parallel-safe too.
3166  */
3167  if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
3168  require_parallel_safe))
3169  break;
3170 
3171  npathkeys++;
3172  }
3173 
3174  /*
3175  * The whole query_pathkeys list matches, so append it directly, to
3176  * allow comparing pathkeys easily by comparing list pointer. If we
3177  * have to truncate the pathkeys, we gotta do a copy though.
3178  */
3179  if (npathkeys == list_length(root->query_pathkeys))
3180  useful_pathkeys_list = lappend(useful_pathkeys_list,
3181  root->query_pathkeys);
3182  else if (npathkeys > 0)
3183  useful_pathkeys_list = lappend(useful_pathkeys_list,
3184  list_copy_head(root->query_pathkeys,
3185  npathkeys));
3186  }
3187 
3188  return useful_pathkeys_list;
3189 }
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
Definition: equivclass.c:933

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

Referenced by generate_useful_gather_paths().

◆ make_one_rel()

RelOptInfo* make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 171 of file allpaths.c.

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

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

Referenced by query_planner().

◆ make_rel_from_joinlist()

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

Definition at line 3318 of file allpaths.c.

3319 {
3320  int levels_needed;
3321  List *initial_rels;
3322  ListCell *jl;
3323 
3324  /*
3325  * Count the number of child joinlist nodes. This is the depth of the
3326  * dynamic-programming algorithm we must employ to consider all ways of
3327  * joining the child nodes.
3328  */
3329  levels_needed = list_length(joinlist);
3330 
3331  if (levels_needed <= 0)
3332  return NULL; /* nothing to do? */
3333 
3334  /*
3335  * Construct a list of rels corresponding to the child joinlist nodes.
3336  * This may contain both base rels and rels constructed according to
3337  * sub-joinlists.
3338  */
3339  initial_rels = NIL;
3340  foreach(jl, joinlist)
3341  {
3342  Node *jlnode = (Node *) lfirst(jl);
3343  RelOptInfo *thisrel;
3344 
3345  if (IsA(jlnode, RangeTblRef))
3346  {
3347  int varno = ((RangeTblRef *) jlnode)->rtindex;
3348 
3349  thisrel = find_base_rel(root, varno);
3350  }
3351  else if (IsA(jlnode, List))
3352  {
3353  /* Recurse to handle subproblem */
3354  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
3355  }
3356  else
3357  {
3358  elog(ERROR, "unrecognized joinlist node type: %d",
3359  (int) nodeTag(jlnode));
3360  thisrel = NULL; /* keep compiler quiet */
3361  }
3362 
3363  initial_rels = lappend(initial_rels, thisrel);
3364  }
3365 
3366  if (levels_needed == 1)
3367  {
3368  /*
3369  * Single joinlist node, so we're done.
3370  */
3371  return (RelOptInfo *) linitial(initial_rels);
3372  }
3373  else
3374  {
3375  /*
3376  * Consider the different orders in which we could join the rels,
3377  * using a plugin, GEQO, or the regular join search code.
3378  *
3379  * We put the initial_rels list into a PlannerInfo field because
3380  * has_legal_joinclause() needs to look at it (ugly :-().
3381  */
3382  root->initial_rels = initial_rels;
3383 
3384  if (join_search_hook)
3385  return (*join_search_hook) (root, levels_needed, initial_rels);
3386  else if (enable_geqo && levels_needed >= geqo_threshold)
3387  return geqo(root, levels_needed, initial_rels);
3388  else
3389  return standard_join_search(root, levels_needed, initial_rels);
3390  }
3391 }
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3423
int geqo_threshold
Definition: allpaths.c:80
join_search_hook_type join_search_hook
Definition: allpaths.c:88
bool enable_geqo
Definition: allpaths.c:79
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:72
#define nodeTag(nodeptr)
Definition: nodes.h:133
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414

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

Referenced by make_one_rel().

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

3869 {
3871  Node *qual = (Node *) rinfo->clause;
3872  List *vars;
3873  ListCell *vl;
3874 
3875  /* Refuse subselects (point 1) */
3876  if (contain_subplans(qual))
3877  return PUSHDOWN_UNSAFE;
3878 
3879  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3880  if (safetyInfo->unsafeVolatile &&
3881  contain_volatile_functions((Node *) rinfo))
3882  return PUSHDOWN_UNSAFE;
3883 
3884  /* Refuse leaky quals if told to (point 3) */
3885  if (safetyInfo->unsafeLeaky &&
3886  contain_leaked_vars(qual))
3887  return PUSHDOWN_UNSAFE;
3888 
3889  /*
3890  * Examine all Vars used in clause. Since it's a restriction clause, all
3891  * such Vars must refer to subselect output columns ... unless this is
3892  * part of a LATERAL subquery, in which case there could be lateral
3893  * references.
3894  *
3895  * By omitting the relevant flags, this also gives us a cheap sanity check
3896  * that no aggregates or window functions appear in the qual. Those would
3897  * be unsafe to push down, but at least for the moment we could never see
3898  * any in a qual anyhow.
3899  */
3901  foreach(vl, vars)
3902  {
3903  Var *var = (Var *) lfirst(vl);
3904 
3905  /*
3906  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3907  * It's not clear whether a PHV could safely be pushed down, and even
3908  * less clear whether such a situation could arise in any cases of
3909  * practical interest anyway. So for the moment, just refuse to push
3910  * down.
3911  */
3912  if (!IsA(var, Var))
3913  {
3914  safe = PUSHDOWN_UNSAFE;
3915  break;
3916  }
3917 
3918  /*
3919  * Punt if we find any lateral references. It would be safe to push
3920  * these down, but we'd have to convert them into outer references,
3921  * which subquery_push_qual lacks the infrastructure to do. The case
3922  * arises so seldom that it doesn't seem worth working hard on.
3923  */
3924  if (var->varno != rti)
3925  {
3926  safe = PUSHDOWN_UNSAFE;
3927  break;
3928  }
3929 
3930  /* Subqueries have no system columns */
3931  Assert(var->varattno >= 0);
3932 
3933  /* Check point 4 */
3934  if (var->varattno == 0)
3935  {
3936  safe = PUSHDOWN_UNSAFE;
3937  break;
3938  }
3939 
3940  /* Check point 5 */
3941  if (safetyInfo->unsafeFlags[var->varattno] != 0)
3942  {
3943  if (safetyInfo->unsafeFlags[var->varattno] &
3946  {
3947  safe = PUSHDOWN_UNSAFE;
3948  break;
3949  }
3950  else
3951  {
3952  /* UNSAFE_NOTIN_PARTITIONBY_CLAUSE is ok for run conditions */
3954  /* don't break, we might find another Var that's unsafe */
3955  }
3956  }
3957  }
3958 
3959  list_free(vars);
3960 
3961  return safe;
3962 }
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1263
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
Expr * clause
Definition: pathnodes.h:2552
int varno
Definition: primnodes.h:255
Definition: regcomp.c:281
List * pull_var_clause(Node *node, int flags)
Definition: var.c:607

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

Referenced by set_subquery_pathlist().

◆ recurse_push_qual()

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

Definition at line 4015 of file allpaths.c.

4017 {
4018  if (IsA(setOp, RangeTblRef))
4019  {
4020  RangeTblRef *rtr = (RangeTblRef *) setOp;
4021  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
4022  Query *subquery = subrte->subquery;
4023 
4024  Assert(subquery != NULL);
4025  subquery_push_qual(subquery, rte, rti, qual);
4026  }
4027  else if (IsA(setOp, SetOperationStmt))
4028  {
4029  SetOperationStmt *op = (SetOperationStmt *) setOp;
4030 
4031  recurse_push_qual(op->larg, topquery, rte, rti, qual);
4032  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
4033  }
4034  else
4035  {
4036  elog(ERROR, "unrecognized node type: %d",
4037  (int) nodeTag(setOp));
4038  }
4039 }
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3968
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:4015
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * rtable
Definition: parsenodes.h:168
Query * subquery
Definition: parsenodes.h:1114

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

Referenced by subquery_push_qual().

◆ recurse_pushdown_safe()

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

Definition at line 3650 of file allpaths.c.

3652 {
3653  if (IsA(setOp, RangeTblRef))
3654  {
3655  RangeTblRef *rtr = (RangeTblRef *) setOp;
3656  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3657  Query *subquery = rte->subquery;
3658 
3659  Assert(subquery != NULL);
3660  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3661  }
3662  else if (IsA(setOp, SetOperationStmt))
3663  {
3664  SetOperationStmt *op = (SetOperationStmt *) setOp;
3665 
3666  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3667  if (op->op == SETOP_EXCEPT)
3668  return false;
3669  /* Else recurse */
3670  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3671  return false;
3672  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3673  return false;
3674  }
3675  else
3676  {
3677  elog(ERROR, "unrecognized node type: %d",
3678  (int) nodeTag(setOp));
3679  }
3680  return true;
3681 }
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3594
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3650
@ SETOP_EXCEPT
Definition: parsenodes.h:2118
SetOperation op
Definition: parsenodes.h:2193

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

Referenced by 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 4067 of file allpaths.c.

4069 {
4070  Bitmapset *attrs_used;
4071  ListCell *lc;
4072 
4073  /*
4074  * Just point directly to extra_used_attrs. No need to bms_copy as none of
4075  * the current callers use the Bitmapset after calling this function.
4076  */
4077  attrs_used = extra_used_attrs;
4078 
4079  /*
4080  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4081  * could update all the child SELECTs' tlists, but it seems not worth the
4082  * trouble presently.
4083  */
4084  if (subquery->setOperations)
4085  return;
4086 
4087  /*
4088  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4089  * time: all its output columns must be used in the distinctClause.
4090  */
4091  if (subquery->distinctClause && !subquery->hasDistinctOn)
4092  return;
4093 
4094  /*
4095  * Collect a bitmap of all the output column numbers used by the upper
4096  * query.
4097  *
4098  * Add all the attributes needed for joins or final output. Note: we must
4099  * look at rel's targetlist, not the attr_needed data, because attr_needed
4100  * isn't computed for inheritance child rels, cf set_append_rel_size().
4101  * (XXX might be worth changing that sometime.)
4102  */
4103  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4104 
4105  /* Add all the attributes used by un-pushed-down restriction clauses. */
4106  foreach(lc, rel->baserestrictinfo)
4107  {
4108  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4109 
4110  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4111  }
4112 
4113  /*
4114  * If there's a whole-row reference to the subquery, we can't remove
4115  * anything.
4116  */
4118  return;
4119 
4120  /*
4121  * Run through the tlist and zap entries we don't need. It's okay to
4122  * modify the tlist items in-place because set_subquery_pathlist made a
4123  * copy of the subquery.
4124  */
4125  foreach(lc, subquery->targetList)
4126  {
4127  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4128  Node *texpr = (Node *) tle->expr;
4129 
4130  /*
4131  * If it has a sortgroupref number, it's used in some sort/group
4132  * clause so we'd better not remove it. Also, don't remove any
4133  * resjunk columns, since their reason for being has nothing to do
4134  * with anybody reading the subquery's output. (It's likely that
4135  * resjunk columns in a sub-SELECT would always have ressortgroupref
4136  * set, but even if they don't, it seems imprudent to remove them.)
4137  */
4138  if (tle->ressortgroupref || tle->resjunk)
4139  continue;
4140 
4141  /*
4142  * If it's used by the upper query, we can't remove it.
4143  */
4145  attrs_used))
4146  continue;
4147 
4148  /*
4149  * If it contains a set-returning function, we can't remove it since
4150  * that could change the number of rows returned by the subquery.
4151  */
4152  if (subquery->hasTargetSRFs &&
4153  expression_returns_set(texpr))
4154  continue;
4155 
4156  /*
4157  * If it contains volatile functions, we daren't remove it for fear
4158  * that the user is expecting their side-effects to happen.
4159  */
4160  if (contain_volatile_functions(texpr))
4161  continue;
4162 
4163  /*
4164  * OK, we don't need it. Replace the expression with a NULL constant.
4165  * Preserve the exposed type of the expression, in case something
4166  * looks at the rowtype of the subquery's result.
4167  */
4168  tle->expr = (Expr *) makeNullConst(exprType(texpr),
4169  exprTypmod(texpr),
4170  exprCollation(texpr));
4171  }
4172 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:339
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
List * exprs
Definition: pathnodes.h:1522
Node * setOperations
Definition: parsenodes.h:219
List * baserestrictinfo
Definition: pathnodes.h:975
Index ressortgroupref
Definition: primnodes.h:2168
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:291

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

Referenced by set_subquery_pathlist().

◆ set_append_rel_pathlist()

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

Definition at line 1232 of file allpaths.c.

1234 {
1235  int parentRTindex = rti;
1236  List *live_childrels = NIL;
1237  ListCell *l;
1238 
1239  /*
1240  * Generate access paths for each member relation, and remember the
1241  * non-dummy children.
1242  */
1243  foreach(l, root->append_rel_list)
1244  {
1245  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1246  int childRTindex;
1247  RangeTblEntry *childRTE;
1248  RelOptInfo *childrel;
1249 
1250  /* append_rel_list contains all append rels; ignore others */
1251  if (appinfo->parent_relid != parentRTindex)
1252  continue;
1253 
1254  /* Re-locate the child RTE and RelOptInfo */
1255  childRTindex = appinfo->child_relid;
1256  childRTE = root->simple_rte_array[childRTindex];
1257  childrel = root->simple_rel_array[childRTindex];
1258 
1259  /*
1260  * If set_append_rel_size() decided the parent appendrel was
1261  * parallel-unsafe at some point after visiting this child rel, we
1262  * need to propagate the unsafety marking down to the child, so that
1263  * we don't generate useless partial paths for it.
1264  */
1265  if (!rel->consider_parallel)
1266  childrel->consider_parallel = false;
1267 
1268  /*
1269  * Compute the child's access paths.
1270  */
1271  set_rel_pathlist(root, childrel, childRTindex, childRTE);
1272 
1273  /*
1274  * If child is dummy, ignore it.
1275  */
1276  if (IS_DUMMY_REL(childrel))
1277  continue;
1278 
1279  /*
1280  * Child is live, so add it to the live_childrels list for use below.
1281  */
1282  live_childrels = lappend(live_childrels, childrel);
1283  }
1284 
1285  /* Add paths to the append relation. */
1286  add_paths_to_append_rel(root, rel, live_childrels);
1287 }
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:469
Index child_relid
Definition: pathnodes.h:2958
Index parent_relid
Definition: pathnodes.h:2957

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

Referenced by set_rel_pathlist().

◆ set_append_rel_size()

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

Definition at line 944 of file allpaths.c.

946 {
947  int parentRTindex = rti;
948  bool has_live_children;
949  double parent_rows;
950  double parent_size;
951  double *parent_attrsizes;
952  int nattrs;
953  ListCell *l;
954 
955  /* Guard against stack overflow due to overly deep inheritance tree. */
957 
958  Assert(IS_SIMPLE_REL(rel));
959 
960  /*
961  * If this is a partitioned baserel, set the consider_partitionwise_join
962  * flag; currently, we only consider partitionwise joins with the baserel
963  * if its targetlist doesn't contain a whole-row Var.
964  */
966  rel->reloptkind == RELOPT_BASEREL &&
967  rte->relkind == RELKIND_PARTITIONED_TABLE &&
968  bms_is_empty(rel->attr_needed[InvalidAttrNumber - rel->min_attr]))
969  rel->consider_partitionwise_join = true;
970 
971  /*
972  * Initialize to compute size estimates for whole append relation.
973  *
974  * We handle width estimates by weighting the widths of different child
975  * rels proportionally to their number of rows. This is sensible because
976  * the use of width estimates is mainly to compute the total relation
977  * "footprint" if we have to sort or hash it. To do this, we sum the
978  * total equivalent size (in "double" arithmetic) and then divide by the
979  * total rowcount estimate. This is done separately for the total rel
980  * width and each attribute.
981  *
982  * Note: if you consider changing this logic, beware that child rels could
983  * have zero rows and/or width, if they were excluded by constraints.
984  */
985  has_live_children = false;
986  parent_rows = 0;
987  parent_size = 0;
988  nattrs = rel->max_attr - rel->min_attr + 1;
989  parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
990 
991  foreach(l, root->append_rel_list)
992  {
993  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
994  int childRTindex;
995  RangeTblEntry *childRTE;
996  RelOptInfo *childrel;
997  List *childrinfos;
998  ListCell *parentvars;
999  ListCell *childvars;
1000  ListCell *lc;
1001 
1002  /* append_rel_list contains all append rels; ignore others */
1003  if (appinfo->parent_relid != parentRTindex)
1004  continue;
1005 
1006  childRTindex = appinfo->child_relid;
1007  childRTE = root->simple_rte_array[childRTindex];
1008 
1009  /*
1010  * The child rel's RelOptInfo was already created during
1011  * add_other_rels_to_query.
1012  */
1013  childrel = find_base_rel(root, childRTindex);
1015 
1016  /* We may have already proven the child to be dummy. */
1017  if (IS_DUMMY_REL(childrel))
1018  continue;
1019 
1020  /*
1021  * We have to copy the parent's targetlist and quals to the child,
1022  * with appropriate substitution of variables. However, the
1023  * baserestrictinfo quals were already copied/substituted when the
1024  * child RelOptInfo was built. So we don't need any additional setup
1025  * before applying constraint exclusion.
1026  */
1027  if (relation_excluded_by_constraints(root, childrel, childRTE))
1028  {
1029  /*
1030  * This child need not be scanned, so we can omit it from the
1031  * appendrel.
1032  */
1033  set_dummy_rel_pathlist(childrel);
1034  continue;
1035  }
1036 
1037  /*
1038  * Constraint exclusion failed, so copy the parent's join quals and
1039  * targetlist to the child, with appropriate variable substitutions.
1040  *
1041  * We skip join quals that came from above outer joins that can null
1042  * this rel, since they would be of no value while generating paths
1043  * for the child. This saves some effort while processing the child
1044  * rel, and it also avoids an implementation restriction in
1045  * adjust_appendrel_attrs (it can't apply nullingrels to a non-Var).
1046  */
1047  childrinfos = NIL;
1048  foreach(lc, rel->joininfo)
1049  {
1050  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1051 
1052  if (!bms_overlap(rinfo->clause_relids, rel->nulling_relids))
1053  childrinfos = lappend(childrinfos,
1055  (Node *) rinfo,
1056  1, &appinfo));
1057  }
1058  childrel->joininfo = childrinfos;
1059 
1060  /*
1061  * Now for the child's targetlist.
1062  *
1063  * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1064  * expressions, which otherwise would not occur in a rel's targetlist.
1065  * Code that might be looking at an appendrel child must cope with
1066  * such. (Normally, a rel's targetlist would only include Vars and
1067  * PlaceHolderVars.) XXX we do not bother to update the cost or width
1068  * fields of childrel->reltarget; not clear if that would be useful.
1069  */
1070  childrel->reltarget->exprs = (List *)
1072  (Node *) rel->reltarget->exprs,
1073  1, &appinfo);
1074 
1075  /*
1076  * We have to make child entries in the EquivalenceClass data
1077  * structures as well. This is needed either if the parent
1078  * participates in some eclass joins (because we will want to consider
1079  * inner-indexscan joins on the individual children) or if the parent
1080  * has useful pathkeys (because we should try to build MergeAppend
1081  * paths that produce those sort orderings).
1082  */
1083  if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1084  add_child_rel_equivalences(root, appinfo, rel, childrel);
1085  childrel->has_eclass_joins = rel->has_eclass_joins;
1086 
1087  /*
1088  * Note: we could compute appropriate attr_needed data for the child's
1089  * variables, by transforming the parent's attr_needed through the
1090  * translated_vars mapping. However, currently there's no need
1091  * because attr_needed is only examined for base relations not
1092  * otherrels. So we just leave the child's attr_needed empty.
1093  */
1094 
1095  /*
1096  * If we consider partitionwise joins with the parent rel, do the same
1097  * for partitioned child rels.
1098  *
1099  * Note: here we abuse the consider_partitionwise_join flag by setting
1100  * it for child rels that are not themselves partitioned. We do so to
1101  * tell try_partitionwise_join() that the child rel is sufficiently
1102  * valid to be used as a per-partition input, even if it later gets
1103  * proven to be dummy. (It's not usable until we've set up the
1104  * reltarget and EC entries, which we just did.)
1105  */
1106  if (rel->consider_partitionwise_join)
1107  childrel->consider_partitionwise_join = true;
1108 
1109  /*
1110  * If parallelism is allowable for this query in general, see whether
1111  * it's allowable for this childrel in particular. But if we've
1112  * already decided the appendrel is not parallel-safe as a whole,
1113  * there's no point in considering parallelism for this child. For
1114  * consistency, do this before calling set_rel_size() for the child.
1115  */
1116  if (root->glob->parallelModeOK && rel->consider_parallel)
1117  set_rel_consider_parallel(root, childrel, childRTE);
1118 
1119  /*
1120  * Compute the child's size.
1121  */
1122  set_rel_size(root, childrel, childRTindex, childRTE);
1123 
1124  /*
1125  * It is possible that constraint exclusion detected a contradiction
1126  * within a child subquery, even though we didn't prove one above. If
1127  * so, we can skip this child.
1128  */
1129  if (IS_DUMMY_REL(childrel))
1130  continue;
1131 
1132  /* We have at least one live child. */
1133  has_live_children = true;
1134 
1135  /*
1136  * If any live child is not parallel-safe, treat the whole appendrel
1137  * as not parallel-safe. In future we might be able to generate plans
1138  * in which some children are farmed out to workers while others are
1139  * not; but we don't have that today, so it's a waste to consider
1140  * partial paths anywhere in the appendrel unless it's all safe.
1141  * (Child rels visited before this one will be unmarked in
1142  * set_append_rel_pathlist().)
1143  */
1144  if (!childrel->consider_parallel)
1145  rel->consider_parallel = false;
1146 
1147  /*
1148  * Accumulate size information from each live child.
1149  */
1150  Assert(childrel->rows > 0);
1151 
1152  parent_rows += childrel->rows;
1153  parent_size += childrel->reltarget->width * childrel->rows;
1154 
1155  /*
1156  * Accumulate per-column estimates too. We need not do anything for
1157  * PlaceHolderVars in the parent list. If child expression isn't a
1158  * Var, or we didn't record a width estimate for it, we have to fall
1159  * back on a datatype-based estimate.
1160  *
1161  * By construction, child's targetlist is 1-to-1 with parent's.
1162  */
1163  forboth(parentvars, rel->reltarget->exprs,
1164  childvars, childrel->reltarget->exprs)
1165  {
1166  Var *parentvar = (Var *) lfirst(parentvars);
1167  Node *childvar = (Node *) lfirst(childvars);
1168 
1169  if (IsA(parentvar, Var) && parentvar->varno == parentRTindex)
1170  {
1171  int pndx = parentvar->varattno - rel->min_attr;
1172  int32 child_width = 0;
1173 
1174  if (IsA(childvar, Var) &&
1175  ((Var *) childvar)->varno == childrel->relid)
1176  {
1177  int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1178 
1179  child_width = childrel->attr_widths[cndx];
1180  }
1181  if (child_width <= 0)
1182  child_width = get_typavgwidth(exprType(childvar),
1183  exprTypmod(childvar));
1184  Assert(child_width > 0);
1185  parent_attrsizes[pndx] += child_width * childrel->rows;
1186  }
1187  }
1188  }
1189 
1190  if (has_live_children)
1191  {
1192  /*
1193  * Save the finished size estimates.
1194  */
1195  int i;
1196 
1197  Assert(parent_rows > 0);
1198  rel->rows = parent_rows;
1199  rel->reltarget->width = rint(parent_size / parent_rows);
1200  for (i = 0; i < nattrs; i++)
1201  rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1202 
1203  /*
1204  * Set "raw tuples" count equal to "rows" for the appendrel; needed
1205  * because some places assume rel->tuples is valid for any baserel.
1206  */
1207  rel->tuples = parent_rows;
1208 
1209  /*
1210  * Note that we leave rel->pages as zero; this is important to avoid
1211  * double-counting the appendrel tree in total_table_pages.
1212  */
1213  }
1214  else
1215  {
1216  /*
1217  * All children were excluded by constraints, so mark the whole
1218  * appendrel dummy. We must do this in this phase so that the rel's
1219  * dummy-ness is visible when we generate paths for other rels.
1220  */
1222  }
1223 
1224  pfree(parent_attrsizes);
1225 }
static void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:2166
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:589
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:360
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:196
#define InvalidAttrNumber
Definition: attnum.h:23
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
#define bms_is_empty(a)
Definition: bitmapset.h:118
signed int int32
Definition: c.h:494
bool enable_partitionwise_join
Definition: costsize.c:148
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
Definition: equivclass.c:2647
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2578
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc0(Size size)
Definition: mcxt.c:1346
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:2261
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:819
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1557
List * joininfo
Definition: pathnodes.h:981
Cardinality tuples
Definition: pathnodes.h:939
bool has_eclass_joins
Definition: pathnodes.h:983
AttrNumber max_attr
Definition: pathnodes.h:916
Relids nulling_relids
Definition: pathnodes.h:928
Cardinality rows
Definition: pathnodes.h:867
AttrNumber min_attr
Definition: pathnodes.h:914

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

Referenced by set_rel_size().

◆ set_base_rel_consider_startup()

static void set_base_rel_consider_startup ( PlannerInfo root)
static

Definition at line 247 of file allpaths.c.

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

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

Referenced by make_one_rel().

◆ set_base_rel_pathlists()

static void set_base_rel_pathlists ( PlannerInfo root)
static

Definition at line 333 of file allpaths.c.

334 {
335  Index rti;
336 
337  for (rti = 1; rti < root->simple_rel_array_size; rti++)
338  {
339  RelOptInfo *rel = root->simple_rel_array[rti];
340 
341  /* there may be empty slots corresponding to non-baserel RTEs */
342  if (rel == NULL)
343  continue;
344 
345  Assert(rel->relid == rti); /* sanity check on array */
346 
347  /* ignore RTEs that are "other rels" */
348  if (rel->reloptkind != RELOPT_BASEREL)
349  continue;
350 
351  set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
352  }
353 }

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

Referenced by make_one_rel().

◆ set_base_rel_sizes()

static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 290 of file allpaths.c.

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

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

Referenced by make_one_rel().

◆ set_cte_pathlist()

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

Definition at line 2872 of file allpaths.c.

2873 {
2874  Path *ctepath;
2875  Plan *cteplan;
2876  PlannerInfo *cteroot;
2877  Index levelsup;
2878  List *pathkeys;
2879  int ndx;
2880  ListCell *lc;
2881  int plan_id;
2882  Relids required_outer;
2883 
2884  /*
2885  * Find the referenced CTE, and locate the path and plan previously made
2886  * for it.
2887  */
2888  levelsup = rte->ctelevelsup;
2889  cteroot = root;
2890  while (levelsup-- > 0)
2891  {
2892  cteroot = cteroot->parent_root;
2893  if (!cteroot) /* shouldn't happen */
2894  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2895  }
2896 
2897  /*
2898  * Note: cte_plan_ids can be shorter than cteList, if we are still working
2899  * on planning the CTEs (ie, this is a side-reference from another CTE).
2900  * So we mustn't use forboth here.
2901  */
2902  ndx = 0;
2903  foreach(lc, cteroot->parse->cteList)
2904  {
2905  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2906 
2907  if (strcmp(cte->ctename, rte->ctename) == 0)
2908  break;
2909  ndx++;
2910  }
2911  if (lc == NULL) /* shouldn't happen */
2912  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2913  if (ndx >= list_length(cteroot->cte_plan_ids))
2914  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2915  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2916  if (plan_id <= 0)
2917  elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
2918 
2919  Assert(list_length(root->glob->subpaths) == list_length(root->glob->subplans));
2920  ctepath = (Path *) list_nth(root->glob->subpaths, plan_id - 1);
2921  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2922 
2923  /* Mark rel with estimated output rows, width, etc */
2924  set_cte_size_estimates(root, rel, cteplan->plan_rows);
2925 
2926  /* Convert the ctepath's pathkeys to outer query's representation */
2927  pathkeys = convert_subquery_pathkeys(root,
2928  rel,
2929  ctepath->pathkeys,
2930  cteplan->targetlist);
2931 
2932  /*
2933  * We don't support pushing join clauses into the quals of a CTE scan, but
2934  * it could still have required parameterization due to LATERAL refs in
2935  * its tlist.
2936  */
2937  required_outer = rel->lateral_relids;
2938 
2939  /* Generate appropriate path */
2940  add_path(rel, create_ctescan_path(root, rel, pathkeys, required_outer));
2941 }
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:5964
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:1069
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2124
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:310
Cardinality plan_rows
Definition: plannodes.h:134
List * targetlist
Definition: plannodes.h:152
List * cte_plan_ids
Definition: pathnodes.h:305
Query * parse
Definition: pathnodes.h:202
List * cteList
Definition: parsenodes.h:166
char * ctename
Definition: parsenodes.h:1206
Index ctelevelsup
Definition: parsenodes.h:1208

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

Referenced by set_rel_size().

◆ set_dummy_rel_pathlist()

static void set_dummy_rel_pathlist ( RelOptInfo rel)
static

Definition at line 2166 of file allpaths.c.

2167 {
2168  /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2169  rel->rows = 0;
2170  rel->reltarget->width = 0;
2171 
2172  /* Discard any pre-existing paths; no further need for them */
2173  rel->pathlist = NIL;
2174  rel->partial_pathlist = NIL;
2175 
2176  /* Set up the dummy path */
2177  add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2178  NIL, rel->lateral_relids,
2179  0, false, -1));
2180 
2181  /*
2182  * We set the cheapest-path fields immediately, just in case they were
2183  * pointing at some discarded path. This is redundant in current usage
2184  * because set_rel_pathlist will do it later, but it's cheap so we keep it
2185  * for safety and consistency with mark_dummy_rel.
2186  */
2187  set_cheapest(rel);
2188 }

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

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

◆ set_foreign_pathlist()

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

Definition at line 926 of file allpaths.c.

927 {
928  /* Call the FDW's GetForeignPaths function to generate path(s) */
929  rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
930 }

References RangeTblEntry::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 902 of file allpaths.c.

903 {
904  /* Mark rel with estimated output rows, width, etc */
906 
907  /* Let FDW adjust the size estimates, if it can */
908  rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
909 
910  /* ... but do not let it set the rows estimate to zero */
911  rel->rows = clamp_row_est(rel->rows);
912 
913  /*
914  * Also, make sure rel->tuples is not insane relative to rel->rows.
915  * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
916  * FDW doesn't do anything to replace that.
917  */
918  rel->tuples = Max(rel->tuples, rel->rows);
919 }
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6064
double clamp_row_est(double nrows)
Definition: costsize.c:202

References clamp_row_est(), Max, RangeTblEntry::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 2761 of file allpaths.c.

2762 {
2763  Relids required_outer;
2764  List *pathkeys = NIL;
2765 
2766  /*
2767  * We don't support pushing join clauses into the quals of a function
2768  * scan, but it could still have required parameterization due to LATERAL
2769  * refs in the function expression.
2770  */
2771  required_outer = rel->lateral_relids;
2772 
2773  /*
2774  * The result is considered unordered unless ORDINALITY was used, in which
2775  * case it is ordered by the ordinal column (the last one). See if we
2776  * care, by checking for uses of that Var in equivalence classes.
2777  */
2778  if (rte->funcordinality)
2779  {
2780  AttrNumber ordattno = rel->max_attr;
2781  Var *var = NULL;
2782  ListCell *lc;
2783 
2784  /*
2785  * Is there a Var for it in rel's targetlist? If not, the query did
2786  * not reference the ordinality column, or at least not in any way
2787  * that would be interesting for sorting.
2788  */
2789  foreach(lc, rel->reltarget->exprs)
2790  {
2791  Var *node = (Var *) lfirst(lc);
2792 
2793  /* checking varno/varlevelsup is just paranoia */
2794  if (IsA(node, Var) &&
2795  node->varattno == ordattno &&
2796  node->varno == rel->relid &&
2797  node->varlevelsup == 0)
2798  {
2799  var = node;
2800  break;
2801  }
2802  }
2803 
2804  /*
2805  * Try to build pathkeys for this Var with int8 sorting. We tell
2806  * build_expression_pathkey not to build any new equivalence class; if
2807  * the Var isn't already mentioned in some EC, it means that nothing
2808  * cares about the ordering.
2809  */
2810  if (var)
2811  pathkeys = build_expression_pathkey(root,
2812  (Expr *) var,
2813  Int8LessOperator,
2814  rel->relids,
2815  false);
2816  }
2817 
2818  /* Generate appropriate path */
2820  pathkeys, required_outer));
2821 }
int16 AttrNumber
Definition: attnum.h:21
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:1015
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2046
bool funcordinality
Definition: parsenodes.h:1189
Index varlevelsup
Definition: primnodes.h:280

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

Referenced by set_rel_pathlist().

◆ set_namedtuplestore_pathlist()

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

Definition at line 2951 of file allpaths.c.

2953 {
2954  Relids required_outer;
2955 
2956  /* Mark rel with estimated output rows, width, etc */
2958 
2959  /*
2960  * We don't support pushing join clauses into the quals of a tuplestore
2961  * scan, but it could still have required parameterization due to LATERAL
2962  * refs in its tlist.
2963  */
2964  required_outer = rel->lateral_relids;
2965 
2966  /* Generate appropriate path */
2967  add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2968 }
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6002
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2150

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

Referenced by set_rel_size().

◆ set_plain_rel_pathlist()

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

Definition at line 764 of file allpaths.c.

765 {
766  Relids required_outer;
767 
768  /*
769  * We don't support pushing join clauses into the quals of a seqscan, but
770  * it could still have required parameterization due to LATERAL refs in
771  * its tlist.
772  */
773  required_outer = rel->lateral_relids;
774 
775  /* Consider sequential scan */
776  add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
777 
778  /* If appropriate, consider parallel sequential scan */
779  if (rel->consider_parallel && required_outer == NULL)
781 
782  /* Consider index scans */
783  create_index_paths(root, rel);
784 
785  /* Consider TID scans */
787 }
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:794
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:234
void create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: tidpath.c:459

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

Referenced by set_rel_pathlist().

◆ set_plain_rel_size()

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

Definition at line 572 of file allpaths.c.

573 {
574  /*
575  * Test any partial indexes of rel for applicability. We must do this
576  * first since partial unique indexes can affect size estimates.
577  */
579 
580  /* Mark rel with estimated output rows, width, etc */
582 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5239
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:3244

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

591 {
592  /*
593  * The flag has previously been initialized to false, so we can just
594  * return if it becomes clear that we can't safely set it.
595  */
596  Assert(!rel->consider_parallel);
597 
598  /* Don't call this if parallelism is disallowed for the entire query. */
599  Assert(root->glob->parallelModeOK);
600 
601  /* This should only be called for baserels and appendrel children. */
602  Assert(IS_SIMPLE_REL(rel));
603 
604  /* Assorted checks based on rtekind. */
605  switch (rte->rtekind)
606  {
607  case RTE_RELATION:
608 
609  /*
610  * Currently, parallel workers can't access the leader's temporary
611  * tables. We could possibly relax this if we wrote all of its
612  * local buffers at the start of the query and made no changes
613  * thereafter (maybe we could allow hint bit changes), and if we
614  * taught the workers to read them. Writing a large number of
615  * temporary buffers could be expensive, though, and we don't have
616  * the rest of the necessary infrastructure right now anyway. So
617  * for now, bail out if we see a temporary table.
618  */
619  if (get_rel_persistence(rte->relid) == RELPERSISTENCE_TEMP)
620  return;
621 
622  /*
623  * Table sampling can be pushed down to workers if the sample
624  * function and its arguments are safe.
625  */
626  if (rte->tablesample != NULL)
627  {
628  char proparallel = func_parallel(rte->tablesample->tsmhandler);
629 
630  if (proparallel != PROPARALLEL_SAFE)
631  return;
632  if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
633  return;
634  }
635 
636  /*
637  * Ask FDWs whether they can support performing a ForeignScan
638  * within a worker. Most often, the answer will be no. For
639  * example, if the nature of the FDW is such that it opens a TCP
640  * connection with a remote server, each parallel worker would end
641  * up with a separate connection, and these connections might not
642  * be appropriately coordinated between workers and the leader.
643  */
644  if (rte->relkind == RELKIND_FOREIGN_TABLE)
645  {
646  Assert(rel->fdwroutine);
647  if (!rel->fdwroutine->IsForeignScanParallelSafe)
648  return;
649  if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
650  return;
651  }
652 
653  /*
654  * There are additional considerations for appendrels, which we'll
655  * deal with in set_append_rel_size and set_append_rel_pathlist.
656  * For now, just set consider_parallel based on the rel's own
657  * quals and targetlist.
658  */
659  break;
660 
661  case RTE_SUBQUERY:
662 
663  /*
664  * There's no intrinsic problem with scanning a subquery-in-FROM
665  * (as distinct from a SubPlan or InitPlan) in a parallel worker.
666  * If the subquery doesn't happen to have any parallel-safe paths,
667  * then flagging it as consider_parallel won't change anything,
668  * but that's true for plain tables, too. We must set
669  * consider_parallel based on the rel's own quals and targetlist,
670  * so that if a subquery path is parallel-safe but the quals and
671  * projection we're sticking onto it are not, we correctly mark
672  * the SubqueryScanPath as not parallel-safe. (Note that
673  * set_subquery_pathlist() might push some of these quals down
674  * into the subquery itself, but that doesn't change anything.)
675  *
676  * We can't push sub-select containing LIMIT/OFFSET to workers as
677  * there is no guarantee that the row order will be fully
678  * deterministic, and applying LIMIT/OFFSET will lead to
679  * inconsistent results at the top-level. (In some cases, where
680  * the result is ordered, we could relax this restriction. But it
681  * doesn't currently seem worth expending extra effort to do so.)
682  */
683  {
684  Query *subquery = castNode(Query, rte->subquery);
685 
686  if (limit_needed(subquery))
687  return;
688  }
689  break;
690 
691  case RTE_JOIN:
692  /* Shouldn't happen; we're only considering baserels here. */
693  Assert(false);
694  return;
695 
696  case RTE_FUNCTION:
697  /* Check for parallel-restricted functions. */
698  if (!is_parallel_safe(root, (Node *) rte->functions))
699  return;
700  break;
701 
702  case RTE_TABLEFUNC:
703  /* not parallel safe */
704  return;
705 
706  case RTE_VALUES:
707  /* Check for parallel-restricted functions. */
708  if (!is_parallel_safe(root, (Node *) rte->values_lists))
709  return;
710  break;
711 
712  case RTE_CTE:
713 
714  /*
715  * CTE tuplestores aren't shared among parallel workers, so we
716  * force all CTE scans to happen in the leader. Also, populating
717  * the CTE would require executing a subplan that's not available
718  * in the worker, might be parallel-restricted, and must get
719  * executed only once.
720  */
721  return;
722 
723  case RTE_NAMEDTUPLESTORE:
724 
725  /*
726  * tuplestore cannot be shared, at least without more
727  * infrastructure to support that.
728  */
729  return;
730 
731  case RTE_RESULT:
732  /* RESULT RTEs, in themselves, are no problem. */
733  break;
734  }
735 
736  /*
737  * If there's anything in baserestrictinfo that's parallel-restricted, we
738  * give up on parallelizing access to this relation. We could consider
739  * instead postponing application of the restricted quals until we're
740  * above all the parallelism in the plan tree, but it's not clear that
741  * that would be a win in very many cases, and it might be tricky to make
742  * outer join clauses work correctly. It would likely break equivalence
743  * classes, too.
744  */
745  if (!is_parallel_safe(root, (Node *) rel->baserestrictinfo))
746  return;
747 
748  /*
749  * Likewise, if the relation's outputs are not parallel-safe, give up.
750  * (Usually, they're just Vars, but sometimes they're not.)
751  */
752  if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
753  return;
754 
755  /* We have a winner. */
756  rel->consider_parallel = true;
757 }
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:753
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2078
char func_parallel(Oid funcid)
Definition: lsyscache.c:1799
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ RTE_JOIN
Definition: parsenodes.h:1030
@ RTE_CTE
Definition: parsenodes.h:1034
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1035
@ RTE_VALUES
Definition: parsenodes.h:1033
@ RTE_SUBQUERY
Definition: parsenodes.h:1029
@ RTE_RESULT
Definition: parsenodes.h:1036
@ RTE_FUNCTION
Definition: parsenodes.h:1031
@ RTE_TABLEFUNC
Definition: parsenodes.h:1032
@ RTE_RELATION
Definition: parsenodes.h:1028
bool limit_needed(Query *parse)
Definition: planner.c:2628
struct TableSampleClause * tablesample
Definition: parsenodes.h:1108
List * values_lists
Definition: parsenodes.h:1200
List * functions
Definition: parsenodes.h:1187
RTEKind rtekind
Definition: parsenodes.h:1057

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

Referenced by set_append_rel_size(), and set_base_rel_sizes().

◆ set_rel_pathlist()

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

Definition at line 469 of file allpaths.c.

471 {
472  if (IS_DUMMY_REL(rel))
473  {
474  /* We already proved the relation empty, so nothing more to do */
475  }
476  else if (rte->inh)
477  {
478  /* It's an "append relation", process accordingly */
479  set_append_rel_pathlist(root, rel, rti, rte);
480  }
481  else
482  {
483  switch (rel->rtekind)
484  {
485  case RTE_RELATION:
486  if (rte->relkind == RELKIND_FOREIGN_TABLE)
487  {
488  /* Foreign table */
489  set_foreign_pathlist(root, rel, rte);
490  }
491  else if (rte->tablesample != NULL)
492  {
493  /* Sampled relation */
495  }
496  else
497  {
498  /* Plain relation */
499  set_plain_rel_pathlist(root, rel, rte);
500  }
501  break;
502  case RTE_SUBQUERY:
503  /* Subquery --- fully handled during set_rel_size */
504  break;
505  case RTE_FUNCTION:
506  /* RangeFunction */
507  set_function_pathlist(root, rel, rte);
508  break;
509  case RTE_TABLEFUNC:
510  /* Table Function */
511  set_tablefunc_pathlist(root, rel, rte);
512  break;
513  case RTE_VALUES:
514  /* Values list */
515  set_values_pathlist(root, rel, rte);
516  break;
517  case RTE_CTE:
518  /* CTE reference --- fully handled during set_rel_size */
519  break;
520  case RTE_NAMEDTUPLESTORE:
521  /* tuplestore reference --- fully handled during set_rel_size */
522  break;
523  case RTE_RESULT:
524  /* simple Result --- fully handled during set_rel_size */
525  break;
526  default:
527  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
528  break;
529  }
530  }
531 
532  /*
533  * Allow a plugin to editorialize on the set of Paths for this base
534  * relation. It could add new paths (such as CustomPaths) by calling
535  * add_path(), or add_partial_path() if parallel aware. It could also
536  * delete or modify paths added by the core code.
537  */
539  (*set_rel_pathlist_hook) (root, rel, rti, rte);
540 
541  /*
542  * If this is a baserel, we should normally consider gathering any partial
543  * paths we may have created for it. We have to do this after calling the
544  * set_rel_pathlist_hook, else it cannot add partial paths to be included
545  * here.
546  *
547  * However, if this is an inheritance child, skip it. Otherwise, we could
548  * end up with a very large number of gather nodes, each trying to grab
549  * its own pool of workers. Instead, we'll consider gathering partial
550  * paths for the parent appendrel.
551  *
552  * Also, if this is the topmost scan/join rel, we postpone gathering until
553  * the final scan/join targetlist is available (see grouping_planner).
554  */
555  if (rel->reloptkind == RELOPT_BASEREL &&
556  !bms_equal(rel->relids, root->all_query_rels))
557  generate_useful_gather_paths(root, rel, false);
558 
559  /* Now find the cheapest of the paths for this rel */
560  set_cheapest(rel);
561 
562 #ifdef OPTIMIZER_DEBUG
563  pprint(rel);
564 #endif
565 }
static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:854
static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:926
static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1232
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3202
static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2761
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:764
static void set_tablefunc_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2848
set_rel_pathlist_hook_type set_rel_pathlist_hook
Definition: allpaths.c:85
static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2828
RTEKind rtekind
Definition: pathnodes.h:912

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

Referenced by set_append_rel_pathlist(), and set_base_rel_pathlists().

◆ set_rel_size()

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

Definition at line 360 of file allpaths.c.

362 {
363  if (rel->reloptkind == RELOPT_BASEREL &&
365  {
366  /*
367  * We proved we don't need to scan the rel via constraint exclusion,
368  * so set up a single dummy path for it. Here we only check this for
369  * regular baserels; if it's an otherrel, CE was already checked in
370  * set_append_rel_size().
371  *
372  * In this case, we go ahead and set up the relation's path right away
373  * instead of leaving it for set_rel_pathlist to do. This is because
374  * we don't have a convention for marking a rel as dummy except by
375  * assigning a dummy path to it.
376  */
378  }
379  else if (rte->inh)
380  {
381  /* It's an "append relation", process accordingly */
382  set_append_rel_size(root, rel, rti, rte);
383  }
384  else
385  {
386  switch (rel->rtekind)
387  {
388  case RTE_RELATION:
389  if (rte->relkind == RELKIND_FOREIGN_TABLE)
390  {
391  /* Foreign table */
392  set_foreign_size(root, rel, rte);
393  }
394  else if (rte->relkind == RELKIND_PARTITIONED_TABLE)
395  {
396  /*
397  * We could get here if asked to scan a partitioned table
398  * with ONLY. In that case we shouldn't scan any of the
399  * partitions, so mark it as a dummy rel.
400  */
402  }
403  else if (rte->tablesample != NULL)
404  {
405  /* Sampled relation */
406  set_tablesample_rel_size(root, rel, rte);
407  }
408  else
409  {
410  /* Plain relation */
411  set_plain_rel_size(root, rel, rte);
412  }
413  break;
414  case RTE_SUBQUERY:
415 
416  /*
417  * Subqueries don't support making a choice between
418  * parameterized and unparameterized paths, so just go ahead
419  * and build their paths immediately.
420  */
421  set_subquery_pathlist(root, rel, rti, rte);
422  break;
423  case RTE_FUNCTION:
425  break;
426  case RTE_TABLEFUNC:
428  break;
429  case RTE_VALUES:
431  break;
432  case RTE_CTE:
433 
434  /*
435  * CTEs don't support making a choice between parameterized
436  * and unparameterized paths, so just go ahead and build their
437  * paths immediately.
438  */
439  if (rte->self_reference)
440  set_worktable_pathlist(root, rel, rte);
441  else
442  set_cte_pathlist(root, rel, rte);
443  break;
444  case RTE_NAMEDTUPLESTORE:
445  /* Might as well just build the path immediately */
447  break;
448  case RTE_RESULT:
449  /* Might as well just build the path immediately */
450  set_result_pathlist(root, rel, rte);
451  break;
452  default:
453  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
454  break;
455  }
456  }
457 
458  /*
459  * We insist that all non-dummy rels have a nonzero rowcount estimate.
460  */
461  Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
462 }
static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:2494
static void set_namedtuplestore_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2951
static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:814
static void set_result_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2978
static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:3005
static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:902
static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2872
static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:944
static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:572
void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5872
void set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5910
void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5932

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

Referenced by set_append_rel_size(), and set_base_rel_sizes().

◆ set_result_pathlist()

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

Definition at line 2978 of file allpaths.c.

2980 {
2981  Relids required_outer;
2982 
2983  /* Mark rel with estimated output rows, width, etc */
2985 
2986  /*
2987  * We don't support pushing join clauses into the quals of a Result scan,
2988  * but it could still have required parameterization due to LATERAL refs
2989  * in its tlist.
2990  */
2991  required_outer = rel->lateral_relids;
2992 
2993  /* Generate appropriate path */
2994  add_path(rel, create_resultscan_path(root, rel, required_outer));
2995 }
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6035
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2176

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

Referenced by set_rel_size().

◆ set_subquery_pathlist()

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

Definition at line 2494 of file allpaths.c.

2496 {
2497  Query *parse = root->parse;
2498  Query *subquery = rte->subquery;
2499  bool trivial_pathtarget;
2500  Relids required_outer;
2501  pushdown_safety_info safetyInfo;
2502  double tuple_fraction;
2503  RelOptInfo *sub_final_rel;
2504  Bitmapset *run_cond_attrs = NULL;
2505  ListCell *lc;
2506 
2507  /*
2508  * Must copy the Query so that planning doesn't mess up the RTE contents
2509  * (really really need to fix the planner to not scribble on its input,
2510  * someday ... but see remove_unused_subquery_outputs to start with).
2511  */
2512  subquery = copyObject(subquery);
2513 
2514  /*
2515  * If it's a LATERAL subquery, it might contain some Vars of the current
2516  * query level, requiring it to be treated as parameterized, even though
2517  * we don't support pushing down join quals into subqueries.
2518  */
2519  required_outer = rel->lateral_relids;
2520 
2521  /*
2522  * Zero out result area for subquery_is_pushdown_safe, so that it can set
2523  * flags as needed while recursing. In particular, we need a workspace
2524  * for keeping track of the reasons why columns are unsafe to reference.
2525  * These reasons are stored in the bits inside unsafeFlags[i] when we
2526  * discover reasons that column i of the subquery is unsafe to be used in
2527  * a pushed-down qual.
2528  */
2529  memset(&safetyInfo, 0, sizeof(safetyInfo));
2530  safetyInfo.unsafeFlags = (unsigned char *)
2531  palloc0((list_length(subquery->targetList) + 1) * sizeof(unsigned char));
2532 
2533  /*
2534  * If the subquery has the "security_barrier" flag, it means the subquery
2535  * originated from a view that must enforce row-level security. Then we
2536  * must not push down quals that contain leaky functions. (Ideally this
2537  * would be checked inside subquery_is_pushdown_safe, but since we don't
2538  * currently pass the RTE to that function, we must do it here.)
2539  */
2540  safetyInfo.unsafeLeaky = rte->security_barrier;
2541 
2542  /*
2543  * If there are any restriction clauses that have been attached to the
2544  * subquery relation, consider pushing them down to become WHERE or HAVING
2545  * quals of the subquery itself. This transformation is useful because it
2546  * may allow us to generate a better plan for the subquery than evaluating
2547  * all the subquery output rows and then filtering them.
2548  *
2549  * There are several cases where we cannot push down clauses. Restrictions
2550  * involving the subquery are checked by subquery_is_pushdown_safe().
2551  * Restrictions on individual clauses are checked by
2552  * qual_is_pushdown_safe(). Also, we don't want to push down
2553  * pseudoconstant clauses; better to have the gating node above the
2554  * subquery.
2555  *
2556  * Non-pushed-down clauses will get evaluated as qpquals of the
2557  * SubqueryScan node.
2558  *
2559  * XXX Are there any cases where we want to make a policy decision not to
2560  * push down a pushable qual, because it'd result in a worse plan?
2561  */
2562  if (rel->baserestrictinfo != NIL &&
2563  subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2564  {
2565  /* OK to consider pushing down individual quals */
2566  List *upperrestrictlist = NIL;
2567  ListCell *l;
2568 
2569  foreach(l, rel->baserestrictinfo)
2570  {
2571  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2572  Node *clause = (Node *) rinfo->clause;
2573 
2574  if (rinfo->pseudoconstant)
2575  {
2576  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2577  continue;
2578  }
2579 
2580  switch (qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2581  {
2582  case PUSHDOWN_SAFE:
2583  /* Push it down */
2584  subquery_push_qual(subquery, rte, rti, clause);
2585  break;
2586 
2588 
2589  /*
2590  * Since we can't push the qual down into the subquery,
2591  * check if it happens to reference a window function. If
2592  * so then it might be useful to use for the WindowAgg's
2593  * runCondition.
2594  */
2595  if (!subquery->hasWindowFuncs ||
2596  check_and_push_window_quals(subquery, rte, rti, clause,
2597  &run_cond_attrs))
2598  {
2599  /*
2600  * subquery has no window funcs or the clause is not a
2601  * suitable window run condition qual or it is, but
2602  * the original must also be kept in the upper query.
2603  */
2604  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2605  }
2606  break;
2607 
2608  case PUSHDOWN_UNSAFE:
2609  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2610  break;
2611  }
2612  }
2613  rel->baserestrictinfo = upperrestrictlist;
2614  /* We don't bother recomputing baserestrict_min_security */
2615  }
2616 
2617  pfree(safetyInfo.unsafeFlags);
2618 
2619  /*
2620  * The upper query might not use all the subquery's output columns; if
2621  * not, we can simplify. Pass the attributes that were pushed down into
2622  * WindowAgg run conditions to ensure we don't accidentally think those
2623  * are unused.
2624  */
2625  remove_unused_subquery_outputs(subquery, rel, run_cond_attrs);
2626 
2627  /*
2628  * We can safely pass the outer tuple_fraction down to the subquery if the
2629  * outer level has no joining, aggregation, or sorting to do. Otherwise
2630  * we'd better tell the subquery to plan for full retrieval. (XXX This
2631  * could probably be made more intelligent ...)
2632  */
2633  if (parse->hasAggs ||
2634  parse->groupClause ||
2635  parse->groupingSets ||
2636  root->hasHavingQual ||
2637  parse->distinctClause ||
2638  parse->sortClause ||
2639  bms_membership(root->all_baserels) == BMS_MULTIPLE)
2640  tuple_fraction = 0.0; /* default case */
2641  else
2642  tuple_fraction = root->tuple_fraction;
2643 
2644  /* plan_params should not be in use in current query level */
2645  Assert(root->plan_params == NIL);
2646 
2647  /* Generate a subroot and Paths for the subquery */
2648  rel->subroot = subquery_planner(root->glob, subquery, root, false,
2649  tuple_fraction, NULL);
2650 
2651  /* Isolate the params needed by this specific subplan */
2652  rel->subplan_params = root->plan_params;
2653  root->plan_params = NIL;
2654 
2655  /*
2656  * It's possible that constraint exclusion proved the subquery empty. If
2657  * so, it's desirable to produce an unadorned dummy path so that we will
2658  * recognize appropriate optimizations at this query level.
2659  */
2660  sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2661 
2662  if (IS_DUMMY_REL(sub_final_rel))
2663  {
2665  return;
2666  }
2667 
2668  /*
2669  * Mark rel with estimated output rows, width, etc. Note that we have to
2670  * do this before generating outer-query paths, else cost_subqueryscan is
2671  * not happy.
2672  */
2674 
2675  /*
2676  * Also detect whether the reltarget is trivial, so that we can pass that
2677  * info to cost_subqueryscan (rather than re-deriving it multiple times).
2678  * It's trivial if it fetches all the subplan output columns in order.
2679  */
2680  if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2681  trivial_pathtarget = false;
2682  else
2683  {
2684  trivial_pathtarget = true;
2685  foreach(lc, rel->reltarget->exprs)
2686  {
2687  Node *node = (Node *) lfirst(lc);
2688  Var *var;
2689 
2690  if (!IsA(node, Var))
2691  {
2692  trivial_pathtarget = false;
2693  break;
2694  }
2695  var = (Var *) node;
2696  if (var->varno != rti ||
2697  var->varattno != foreach_current_index(lc) + 1)
2698  {
2699  trivial_pathtarget = false;
2700  break;
2701  }
2702  }
2703  }
2704 
2705  /*
2706  * For each Path that subquery_planner produced, make a SubqueryScanPath
2707  * in the outer query.
2708  */
2709  foreach(lc, sub_final_rel->pathlist)
2710  {
2711  Path *subpath = (Path *) lfirst(lc);
2712  List *pathkeys;
2713 
2714  /* Convert subpath's pathkeys to outer representation */
2715  pathkeys = convert_subquery_pathkeys(root,
2716  rel,
2717  subpath->pathkeys,
2718  make_tlist_from_pathtarget(subpath->pathtarget));
2719 
2720  /* Generate outer path using this subpath */
2721  add_path(rel, (Path *)
2723  trivial_pathtarget,
2724  pathkeys, required_outer));
2725  }
2726 
2727  /* If outer rel allows parallelism, do same for partial paths. */
2728  if (rel->consider_parallel && bms_is_empty(required_outer))
2729  {
2730  /* If consider_parallel is false, there should be no partial paths. */
2731  Assert(sub_final_rel->consider_parallel ||
2732  sub_final_rel->partial_pathlist == NIL);
2733 
2734  /* Same for partial paths. */
2735  foreach(lc, sub_final_rel->partial_pathlist)
2736  {
2737  Path *subpath = (Path *) lfirst(lc);
2738  List *pathkeys;
2739 
2740  /* Convert subpath's pathkeys to outer representation */
2741  pathkeys = convert_subquery_pathkeys(root,
2742  rel,
2743  subpath->pathkeys,
2744  make_tlist_from_pathtarget(subpath->pathtarget));
2745 
2746  /* Generate outer path using this subpath */
2747  add_partial_path(rel, (Path *)
2749  trivial_pathtarget,
2750  pathkeys,
2751  required_outer));
2752  }
2753  }
2754 }
static pushdown_safe_type qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3867
static bool check_and_push_window_quals(Query *subquery, RangeTblEntry *rte, Index rti, Node *clause, Bitmapset **run_cond_attrs)
Definition: allpaths.c:2419
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
Definition: allpaths.c:4067
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
@ BMS_MULTIPLE
Definition: bitmapset.h:73
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5792
#define copyObject(obj)
Definition: nodes.h:224
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, bool trivial_pathtarget, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2016
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, SetOperationStmt *setops)
Definition: planner.c:628
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1470
List * subplan_params
Definition: pathnodes.h:944
PlannerInfo * subroot
Definition: pathnodes.h:943
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:624

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

Referenced by set_rel_size().

◆ set_tablefunc_pathlist()

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

Definition at line 2848 of file allpaths.c.

2849 {
2850  Relids required_outer;
2851 
2852  /*
2853  * We don't support pushing join clauses into the quals of a tablefunc
2854  * scan, but it could still have required parameterization due to LATERAL
2855  * refs in the function expression.
2856  */
2857  required_outer = rel->lateral_relids;
2858 
2859  /* Generate appropriate path */
2861  required_outer));
2862 }
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2072

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

Referenced by set_rel_pathlist().

◆ set_tablesample_rel_pathlist()

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

Definition at line 854 of file allpaths.c.

855 {
856  Relids required_outer;
857  Path *path;
858 
859  /*
860  * We don't support pushing join clauses into the quals of a samplescan,
861  * but it could still have required parameterization due to LATERAL refs
862  * in its tlist or TABLESAMPLE arguments.
863  */
864  required_outer = rel->lateral_relids;
865 
866  /* Consider sampled scan */
867  path = create_samplescan_path(root, rel, required_outer);
868 
869  /*
870  * If the sampling method does not support repeatable scans, we must avoid
871  * plans that would scan the rel multiple times. Ideally, we'd simply
872  * avoid putting the rel on the inside of a nestloop join; but adding such
873  * a consideration to the planner seems like a great deal of complication
874  * to support an uncommon usage of second-rate sampling methods. Instead,
875  * if there is a risk that the query might perform an unsafe join, just
876  * wrap the SampleScan in a Materialize node. We can check for joins by
877  * counting the membership of all_query_rels (note that this correctly
878  * counts inheritance trees as single rels). If we're inside a subquery,
879  * we can't easily check whether a join might occur in the outer query, so
880  * just assume one is possible.
881  *
882  * GetTsmRoutine is relatively expensive compared to the other tests here,
883  * so check repeatable_across_scans last, even though that's a bit odd.
884  */
885  if ((root->query_level > 1 ||
886  bms_membership(root->all_query_rels) != BMS_SINGLETON) &&
888  {
889  path = (Path *) create_material_path(rel, path);
890  }
891 
892  add_path(rel, path);
893 
894  /* For the moment, at least, there are no other paths to consider */
895 }
@ BMS_SINGLETON
Definition: bitmapset.h:72
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:952
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1566
bool repeatable_across_scans
Definition: tsmapi.h:65
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

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

Referenced by set_rel_pathlist().

◆ set_tablesample_rel_size()

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

Definition at line 814 of file allpaths.c.

815 {
816  TableSampleClause *tsc = rte->tablesample;
817  TsmRoutine *tsm;
818  BlockNumber pages;
819  double tuples;
820 
821  /*
822  * Test any partial indexes of rel for applicability. We must do this
823  * first since partial unique indexes can affect size estimates.
824  */
826 
827  /*
828  * Call the sampling method's estimation function to estimate the number
829  * of pages it will read and the number of tuples it will return. (Note:
830  * we assume the function returns sane values.)
831  */
832  tsm = GetTsmRoutine(tsc->tsmhandler);
833  tsm->SampleScanGetSampleSize(root, rel, tsc->args,
834  &pages, &tuples);
835 
836  /*
837  * For the moment, because we will only consider a SampleScan path for the
838  * rel, it's okay to just overwrite the pages and tuples estimates for the
839  * whole relation. If we ever consider multiple path types for sampled
840  * rels, we'll need more complication.
841  */
842  rel->pages = pages;
843  rel->tuples = tuples;
844 
845  /* Mark rel with estimated output rows, width, etc */
847 }
SampleScanGetSampleSize_function SampleScanGetSampleSize
Definition: tsmapi.h:68

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

Referenced by set_rel_size().

◆ set_values_pathlist()

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

Definition at line 2828 of file allpaths.c.

2829 {
2830  Relids required_outer;
2831 
2832  /*
2833  * We don't support pushing join clauses into the quals of a values scan,
2834  * but it could still have required parameterization due to LATERAL refs
2835  * in the values expressions.
2836  */
2837  required_outer = rel->lateral_relids;
2838 
2839  /* Generate appropriate path */
2840  add_path(rel, create_valuesscan_path(root, rel, required_outer));
2841 }
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2098

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

Referenced by set_rel_pathlist().

◆ set_worktable_pathlist()

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

Definition at line 3005 of file allpaths.c.

3006 {
3007  Path *ctepath;
3008  PlannerInfo *cteroot;
3009  Index levelsup;
3010  Relids required_outer;
3011 
3012  /*
3013  * We need to find the non-recursive term's path, which is in the plan
3014  * level that's processing the recursive UNION, which is one level *below*
3015  * where the CTE comes from.
3016  */
3017  levelsup = rte->ctelevelsup;
3018  if (levelsup == 0) /* shouldn't happen */
3019  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3020  levelsup--;
3021  cteroot = root;
3022  while (levelsup-- > 0)
3023  {
3024  cteroot = cteroot->parent_root;
3025  if (!cteroot) /* shouldn't happen */
3026  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3027  }
3028  ctepath = cteroot->non_recursive_path;
3029  if (!ctepath) /* shouldn't happen */
3030  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
3031 
3032  /* Mark rel with estimated output rows, width, etc */
3033  set_cte_size_estimates(root, rel, ctepath->rows);
3034 
3035  /*
3036  * We don't support pushing join clauses into the quals of a worktable
3037  * scan, but it could still have required parameterization due to LATERAL
3038  * refs in its tlist. (I'm not sure this is actually possible given the
3039  * restrictions on recursive references, but it's easy enough to support.)
3040  */
3041  required_outer = rel->lateral_relids;
3042 
3043  /* Generate appropriate path */
3044  add_path(rel, create_worktablescan_path(root, rel, required_outer));
3045 }
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2202
struct Path * non_recursive_path
Definition: pathnodes.h:528

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

Referenced by set_rel_size().

◆ standard_join_search()

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

Definition at line 3423 of file allpaths.c.

3424 {
3425  int lev;
3426  RelOptInfo *rel;
3427 
3428  /*
3429  * This function cannot be invoked recursively within any one planning
3430  * problem, so join_rel_level[] can't be in use already.
3431  */
3432  Assert(root->join_rel_level == NULL);
3433 
3434  /*
3435  * We employ a simple "dynamic programming" algorithm: we first find all
3436  * ways to build joins of two jointree items, then all ways to build joins
3437  * of three items (from two-item joins and single items), then four-item
3438  * joins, and so on until we have considered all ways to join all the
3439  * items into one rel.
3440  *
3441  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3442  * set root->join_rel_level[1] to represent all the single-jointree-item
3443  * relations.
3444  */
3445  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3446 
3447  root->join_rel_level[1] = initial_rels;
3448 
3449  for (lev = 2; lev <= levels_needed; lev++)
3450  {
3451  ListCell *lc;
3452 
3453  /*
3454  * Determine all possible pairs of relations to be joined at this
3455  * level, and build paths for making each one from every available
3456  * pair of lower-level relations.
3457  */
3459 
3460  /*
3461  * Run generate_partitionwise_join_paths() and
3462  * generate_useful_gather_paths() for each just-processed joinrel. We
3463  * could not do this earlier because both regular and partial paths
3464  * can get added to a particular joinrel at multiple times within
3465  * join_search_one_level.
3466  *
3467  * After that, we're done creating paths for the joinrel, so run
3468  * set_cheapest().
3469  */
3470  foreach(lc, root->join_rel_level[lev])
3471  {
3472  rel = (RelOptInfo *) lfirst(lc);
3473 
3474  /* Create paths for partitionwise joins. */
3476 
3477  /*
3478  * Except for the topmost scan/join rel, consider gathering
3479  * partial paths. We'll do the same for the topmost scan/join rel
3480  * once we know the final targetlist (see grouping_planner's and
3481  * its call to apply_scanjoin_target_to_paths).
3482  */
3483  if (!bms_equal(rel->relids, root->all_query_rels))
3484  generate_useful_gather_paths(root, rel, false);
3485 
3486  /* Find and save the cheapest paths for this rel */
3487  set_cheapest(rel);
3488 
3489 #ifdef OPTIMIZER_DEBUG
3490  pprint(rel);
3491 #endif
3492  }
3493  }
3494 
3495  /*
3496  * We should have a single rel at the final level.
3497  */
3498  if (root->join_rel_level[levels_needed] == NIL)
3499  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3500  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3501 
3502  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3503 
3504  root->join_rel_level = NULL;
3505 
3506  return rel;
3507 }
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:72

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

Referenced by make_rel_from_joinlist().

◆ subquery_is_pushdown_safe()

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

Definition at line 3594 of file allpaths.c.

3596 {
3597  SetOperationStmt *topop;
3598 
3599  /* Check point 1 */
3600  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3601  return false;
3602 
3603  /* Check point 6 */
3604  if (subquery->groupClause && subquery->groupingSets)
3605  return false;
3606 
3607  /* Check points 3, 4, and 5 */
3608  if (subquery->distinctClause ||
3609  subquery->hasWindowFuncs ||
3610  subquery->hasTargetSRFs)
3611  safetyInfo->unsafeVolatile = true;
3612 
3613  /*
3614  * If we're at a leaf query, check for unsafe expressions in its target
3615  * list, and mark any reasons why they're unsafe in unsafeFlags[].
3616  * (Non-leaf nodes in setop trees have only simple Vars in their tlists,
3617  * so no need to check them.)
3618  */
3619  if (subquery->setOperations == NULL)
3620  check_output_expressions(subquery, safetyInfo);
3621 
3622  /* Are we at top level, or looking at a setop component? */
3623  if (subquery == topquery)
3624  {
3625  /* Top level, so check any component queries */
3626  if (subquery->setOperations != NULL)
3627  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3628  safetyInfo))
3629  return false;
3630  }
3631  else
3632  {
3633  /* Setop component must not have more components (too weird) */
3634  if (subquery->setOperations != NULL)
3635  return false;
3636  /* Check whether setop component output types match top level */
3637  topop = castNode(SetOperationStmt, topquery->setOperations);
3638  Assert(topop);
3640  topop->colTypes,
3641  safetyInfo);
3642  }
3643  return true;
3644 }
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3791
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3719
Node * limitCount
Definition: parsenodes.h:214
List * groupClause
Definition: parsenodes.h:200
Node * limitOffset
Definition: parsenodes.h:213
List * groupingSets
Definition: parsenodes.h:203

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

Referenced by recurse_pushdown_safe(), and set_subquery_pathlist().

◆ subquery_push_qual()

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

Definition at line 3968 of file allpaths.c.

3969 {
3970  if (subquery->setOperations != NULL)
3971  {
3972  /* Recurse to push it separately to each component query */
3973  recurse_push_qual(subquery->setOperations, subquery,
3974  rte, rti, qual);
3975  }
3976  else
3977  {
3978  /*
3979  * We need to replace Vars in the qual (which must refer to outputs of
3980  * the subquery) with copies of the subquery's targetlist expressions.
3981  * Note that at this point, any uplevel Vars in the qual should have
3982  * been replaced with Params, so they need no work.
3983  *
3984  * This step also ensures that when we are pushing into a setop tree,
3985  * each component query gets its own copy of the qual.
3986  */
3987  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3988  subquery->targetList,
3990  &subquery->hasSubLinks);
3991 
3992  /*
3993  * Now attach the qual to the proper place: normally WHERE, but if the
3994  * subquery uses grouping or aggregation, put it in HAVING (since the
3995  * qual really refers to the group-result rows).
3996  */
3997  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
3998  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
3999  else
4000  subquery->jointree->quals =
4001  make_and_qual(subquery->jointree->quals, qual);
4002 
4003  /*
4004  * We need not change the subquery's hasAggs or hasSubLinks flags,
4005  * since we can't be pushing down any aggregates that weren't there
4006  * before, and we don't push down subselects at all.
4007  */
4008  }
4009 }
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:707
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
@ REPLACEVARS_REPORT_ERROR
Definition: rewriteManip.h:38
Node * quals
Definition: primnodes.h:2281
FromExpr * jointree
Definition: parsenodes.h:175
Node * havingQual
Definition: parsenodes.h:205

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

Referenced by recurse_push_qual(), and set_subquery_pathlist().

◆ targetIsInAllPartitionLists()

static bool targetIsInAllPartitionLists ( TargetEntry tle,
Query query 
)
static

Definition at line 3824 of file allpaths.c.

3825 {
3826  ListCell *lc;
3827 
3828  foreach(lc, query->windowClause)
3829  {
3830  WindowClause *wc = (WindowClause *) lfirst(lc);
3831 
3833  return false;
3834  }
3835  return true;
3836 }
List * partitionClause
Definition: parsenodes.h:1546

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

Referenced by check_output_expressions().

Variable Documentation

◆ enable_geqo

bool enable_geqo = false

Definition at line 79 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ geqo_threshold

int geqo_threshold

Definition at line 80 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

join_search_hook_type join_search_hook = NULL

Definition at line 88 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_parallel_index_scan_size

int min_parallel_index_scan_size

Definition at line 82 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 81 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 85 of file allpaths.c.

Referenced by set_rel_pathlist().