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/inherit.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planner.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "partitioning/partbounds.h"
#include "partitioning/partprune.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
 

Typedefs

typedef struct pushdown_safety_info pushdown_safety_info
 

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 bool 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 has_multiple_baserels (PlannerInfo *root)
 
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
 

Typedef Documentation

◆ pushdown_safety_info

Function Documentation

◆ accumulate_append_subpath()

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

Definition at line 2037 of file allpaths.c.

2038 {
2039  if (IsA(path, AppendPath))
2040  {
2041  AppendPath *apath = (AppendPath *) path;
2042 
2043  if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2044  {
2045  *subpaths = list_concat(*subpaths, apath->subpaths);
2046  return;
2047  }
2048  else if (special_subpaths != NULL)
2049  {
2050  List *new_special_subpaths;
2051 
2052  /* Split Parallel Append into partial and non-partial subpaths */
2053  *subpaths = list_concat(*subpaths,
2054  list_copy_tail(apath->subpaths,
2055  apath->first_partial_path));
2056  new_special_subpaths = list_copy_head(apath->subpaths,
2057  apath->first_partial_path);
2058  *special_subpaths = list_concat(*special_subpaths,
2059  new_special_subpaths);
2060  return;
2061  }
2062  }
2063  else if (IsA(path, MergeAppendPath))
2064  {
2065  MergeAppendPath *mpath = (MergeAppendPath *) path;
2066 
2067  *subpaths = list_concat(*subpaths, mpath->subpaths);
2068  return;
2069  }
2070 
2071  *subpaths = lappend(*subpaths, path);
2072 }
List * lappend(List *list, void *datum)
Definition: list.c:338
List * list_copy_head(const List *oldlist, int len)
Definition: list.c:1592
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1612
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
int first_partial_path
Definition: pathnodes.h:1808
List * subpaths
Definition: pathnodes.h:1806
Definition: pg_list.h:52
bool parallel_aware
Definition: pathnodes.h:1537

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

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

References accumulate_append_subpath(), add_partial_path(), add_path(), Assert(), bms_equal(), RelOptInfo::cheapest_total_path, compare_pathkeys(), RelOptInfo::consider_parallel, 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(), 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 2387 of file allpaths.c.

2389 {
2390  OpExpr *opexpr = (OpExpr *) clause;
2391  bool keep_original = true;
2392  Var *var1;
2393  Var *var2;
2394 
2395  /* We're only able to use OpExprs with 2 operands */
2396  if (!IsA(opexpr, OpExpr))
2397  return true;
2398 
2399  if (list_length(opexpr->args) != 2)
2400  return true;
2401 
2402  /*
2403  * Check for plain Vars that reference window functions in the subquery.
2404  * If we find any, we'll ask find_window_run_conditions() if 'opexpr' can
2405  * be used as part of the run condition.
2406  */
2407 
2408  /* Check the left side of the OpExpr */
2409  var1 = linitial(opexpr->args);
2410  if (IsA(var1, Var) && var1->varattno > 0)
2411  {
2412  TargetEntry *tle = list_nth(subquery->targetList, var1->varattno - 1);
2413  WindowFunc *wfunc = (WindowFunc *) tle->expr;
2414 
2415  if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2416  opexpr, true, &keep_original,
2417  run_cond_attrs))
2418  return keep_original;
2419  }
2420 
2421  /* and check the right side */
2422  var2 = lsecond(opexpr->args);
2423  if (IsA(var2, Var) && var2->varattno > 0)
2424  {
2425  TargetEntry *tle = list_nth(subquery->targetList, var2->varattno - 1);
2426  WindowFunc *wfunc = (WindowFunc *) tle->expr;
2427 
2428  if (find_window_run_conditions(subquery, rte, rti, tle->resno, wfunc,
2429  opexpr, false, &keep_original,
2430  run_cond_attrs))
2431  return keep_original;
2432  }
2433 
2434  return true;
2435 }
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:2186
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define lsecond(l)
Definition: pg_list.h:181
static void * list_nth(const List *list, int n)
Definition: pg_list.h:297
List * args
Definition: primnodes.h:666
List * targetList
Definition: parsenodes.h:162
Expr * expr
Definition: primnodes.h:1555
AttrNumber resno
Definition: primnodes.h:1556
Definition: primnodes.h:205
AttrNumber varattno
Definition: primnodes.h:217

References OpExpr::args, TargetEntry::expr, find_window_run_conditions(), if(), IsA, linitial, list_length(), list_nth(), lsecond, TargetEntry::resno, 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 3672 of file allpaths.c.

3673 {
3674  ListCell *lc;
3675 
3676  foreach(lc, subquery->targetList)
3677  {
3678  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3679 
3680  if (tle->resjunk)
3681  continue; /* ignore resjunk columns */
3682 
3683  /* We need not check further if output col is already known unsafe */
3684  if (safetyInfo->unsafeColumns[tle->resno])
3685  continue;
3686 
3687  /* Functions returning sets are unsafe (point 1) */
3688  if (subquery->hasTargetSRFs &&
3689  expression_returns_set((Node *) tle->expr))
3690  {
3691  safetyInfo->unsafeColumns[tle->resno] = true;
3692  continue;
3693  }
3694 
3695  /* Volatile functions are unsafe (point 2) */
3696  if (contain_volatile_functions((Node *) tle->expr))
3697  {
3698  safetyInfo->unsafeColumns[tle->resno] = true;
3699  continue;
3700  }
3701 
3702  /* If subquery uses DISTINCT ON, check point 3 */
3703  if (subquery->hasDistinctOn &&
3704  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3705  {
3706  /* non-DISTINCT column, so mark it unsafe */
3707  safetyInfo->unsafeColumns[tle->resno] = true;
3708  continue;
3709  }
3710 
3711  /* If subquery uses window functions, check point 4 */
3712  if (subquery->hasWindowFuncs &&
3713  !targetIsInAllPartitionLists(tle, subquery))
3714  {
3715  /* not present in all PARTITION BY clauses, so mark it unsafe */
3716  safetyInfo->unsafeColumns[tle->resno] = true;
3717  continue;
3718  }
3719  }
3720 }
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:3773
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:448
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:706
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition: postgres_ext.h:36
Definition: nodes.h:118
bool hasWindowFuncs
Definition: parsenodes.h:142
bool hasTargetSRFs
Definition: parsenodes.h:143
bool hasDistinctOn
Definition: parsenodes.h:145
List * distinctClause
Definition: parsenodes.h:179
bool resjunk
Definition: primnodes.h:1562
bool * unsafeColumns
Definition: allpaths.c:58

References contain_volatile_functions(), Query::distinctClause, TargetEntry::expr, expression_returns_set(), Query::hasDistinctOn, Query::hasTargetSRFs, Query::hasWindowFuncs, InvalidOid, lfirst, TargetEntry::resjunk, TargetEntry::resno, targetIsInAllPartitionLists(), targetIsInSortList(), Query::targetList, and pushdown_safety_info::unsafeColumns.

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

3742 {
3743  ListCell *l;
3744  ListCell *colType = list_head(colTypes);
3745 
3746  foreach(l, tlist)
3747  {
3748  TargetEntry *tle = (TargetEntry *) lfirst(l);
3749 
3750  if (tle->resjunk)
3751  continue; /* ignore resjunk columns */
3752  if (colType == NULL)
3753  elog(ERROR, "wrong number of tlist entries");
3754  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3755  safetyInfo->unsafeColumns[tle->resno] = true;
3756  colType = lnext(colTypes, colType);
3757  }
3758  if (colType != NULL)
3759  elog(ERROR, "wrong number of tlist entries");
3760 }
#define ERROR
Definition: elog.h:35
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
static ListCell * list_head(const List *l)
Definition: pg_list.h:126
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
#define lfirst_oid(lc)
Definition: pg_list.h:172

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

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

4157 {
4158  int parallel_workers = 0;
4159 
4160  /*
4161  * If the user has set the parallel_workers reloption, use that; otherwise
4162  * select a default number of workers.
4163  */
4164  if (rel->rel_parallel_workers != -1)
4165  parallel_workers = rel->rel_parallel_workers;
4166  else
4167  {
4168  /*
4169  * If the number of pages being scanned is insufficient to justify a
4170  * parallel scan, just return zero ... unless it's an inheritance
4171  * child. In that case, we want to generate a parallel path here
4172  * anyway. It might not be worthwhile just for this relation, but
4173  * when combined with all of its inheritance siblings it may well pay
4174  * off.
4175  */
4176  if (rel->reloptkind == RELOPT_BASEREL &&
4177  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4178  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4179  return 0;
4180 
4181  if (heap_pages >= 0)
4182  {
4183  int heap_parallel_threshold;
4184  int heap_parallel_workers = 1;
4185 
4186  /*
4187  * Select the number of workers based on the log of the size of
4188  * the relation. This probably needs to be a good deal more
4189  * sophisticated, but we need something here for now. Note that
4190  * the upper limit of the min_parallel_table_scan_size GUC is
4191  * chosen to prevent overflow here.
4192  */
4193  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4194  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4195  {
4196  heap_parallel_workers++;
4197  heap_parallel_threshold *= 3;
4198  if (heap_parallel_threshold > INT_MAX / 3)
4199  break; /* avoid overflow */
4200  }
4201 
4202  parallel_workers = heap_parallel_workers;
4203  }
4204 
4205  if (index_pages >= 0)
4206  {
4207  int index_parallel_workers = 1;
4208  int index_parallel_threshold;
4209 
4210  /* same calculation as for heap_pages above */
4211  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4212  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4213  {
4214  index_parallel_workers++;
4215  index_parallel_threshold *= 3;
4216  if (index_parallel_threshold > INT_MAX / 3)
4217  break; /* avoid overflow */
4218  }
4219 
4220  if (parallel_workers > 0)
4221  parallel_workers = Min(parallel_workers, index_parallel_workers);
4222  else
4223  parallel_workers = index_parallel_workers;
4224  }
4225  }
4226 
4227  /* In no case use more than caller supplied maximum number of workers */
4228  parallel_workers = Min(parallel_workers, max_workers);
4229 
4230  return parallel_workers;
4231 }
int min_parallel_index_scan_size
Definition: allpaths.c:67
int min_parallel_table_scan_size
Definition: allpaths.c:66
uint32 BlockNumber
Definition: block.h:31
@ RELOPT_BASEREL
Definition: pathnodes.h:776
RelOptKind reloptkind
Definition: pathnodes.h:815
int rel_parallel_workers
Definition: pathnodes.h:901

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

4121 {
4122  int parallel_workers;
4123  double pages_fetched;
4124 
4125  /* Compute heap pages for bitmap heap scan */
4126  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4127  NULL, NULL);
4128 
4129  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4131 
4132  if (parallel_workers <= 0)
4133  return;
4134 
4135  add_partial_path(rel, (Path *) create_bitmap_heap_path(root, rel,
4136  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4137 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4155
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:6139
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1046
Relids lateral_relids
Definition: pathnodes.h:863

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

Referenced by create_index_paths().

◆ create_plain_partial_paths()

static void create_plain_partial_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 799 of file allpaths.c.

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

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

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

2190 {
2191  Oid prosupport;
2192  Expr *otherexpr;
2195  WindowClause *wclause;
2196  List *opinfos;
2197  OpExpr *runopexpr;
2198  Oid runoperator;
2199  ListCell *lc;
2200 
2201  *keep_original = true;
2202 
2203  while (IsA(wfunc, RelabelType))
2204  wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2205 
2206  /* we can only work with window functions */
2207  if (!IsA(wfunc, WindowFunc))
2208  return false;
2209 
2210  prosupport = get_func_support(wfunc->winfnoid);
2211 
2212  /* Check if there's a support function for 'wfunc' */
2213  if (!OidIsValid(prosupport))
2214  return false;
2215 
2216  /* get the Expr from the other side of the OpExpr */
2217  if (wfunc_left)
2218  otherexpr = lsecond(opexpr->args);
2219  else
2220  otherexpr = linitial(opexpr->args);
2221 
2222  /*
2223  * The value being compared must not change during the evaluation of the
2224  * window partition.
2225  */
2226  if (!is_pseudo_constant_clause((Node *) otherexpr))
2227  return false;
2228 
2229  /* find the window clause belonging to the window function */
2230  wclause = (WindowClause *) list_nth(subquery->windowClause,
2231  wfunc->winref - 1);
2232 
2233  req.type = T_SupportRequestWFuncMonotonic;
2234  req.window_func = wfunc;
2235  req.window_clause = wclause;
2236 
2237  /* call the support function */
2239  DatumGetPointer(OidFunctionCall1(prosupport,
2240  PointerGetDatum(&req)));
2241 
2242  /*
2243  * Nothing to do if the function is neither monotonically increasing nor
2244  * monotonically decreasing.
2245  */
2246  if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2247  return false;
2248 
2249  runopexpr = NULL;
2250  runoperator = InvalidOid;
2251  opinfos = get_op_btree_interpretation(opexpr->opno);
2252 
2253  foreach(lc, opinfos)
2254  {
2256  int strategy = opinfo->strategy;
2257 
2258  /* handle < / <= */
2259  if (strategy == BTLessStrategyNumber ||
2260  strategy == BTLessEqualStrategyNumber)
2261  {
2262  /*
2263  * < / <= is supported for monotonically increasing functions in
2264  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2265  * for monotonically decreasing functions.
2266  */
2267  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2268  (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2269  {
2270  *keep_original = false;
2271  runopexpr = opexpr;
2272  runoperator = opexpr->opno;
2273  }
2274  break;
2275  }
2276  /* handle > / >= */
2277  else if (strategy == BTGreaterStrategyNumber ||
2278  strategy == BTGreaterEqualStrategyNumber)
2279  {
2280  /*
2281  * > / >= is supported for monotonically decreasing functions in
2282  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2283  * for monotonically increasing functions.
2284  */
2285  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2286  (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2287  {
2288  *keep_original = false;
2289  runopexpr = opexpr;
2290  runoperator = opexpr->opno;
2291  }
2292  break;
2293  }
2294  /* handle = */
2295  else if (strategy == BTEqualStrategyNumber)
2296  {
2297  int16 newstrategy;
2298 
2299  /*
2300  * When both monotonically increasing and decreasing then the
2301  * return value of the window function will be the same each time.
2302  * We can simply use 'opexpr' as the run condition without
2303  * modifying it.
2304  */
2305  if ((res->monotonic & MONOTONICFUNC_BOTH) == MONOTONICFUNC_BOTH)
2306  {
2307  *keep_original = false;
2308  runopexpr = opexpr;
2309  runoperator = opexpr->opno;
2310  break;
2311  }
2312 
2313  /*
2314  * When monotonically increasing we make a qual with <wfunc> <=
2315  * <value> or <value> >= <wfunc> in order to filter out values
2316  * which are above the value in the equality condition. For
2317  * monotonically decreasing functions we want to filter values
2318  * below the value in the equality condition.
2319  */
2320  if (res->monotonic & MONOTONICFUNC_INCREASING)
2321  newstrategy = wfunc_left ? BTLessEqualStrategyNumber : BTGreaterEqualStrategyNumber;
2322  else
2323  newstrategy = wfunc_left ? BTGreaterEqualStrategyNumber : BTLessEqualStrategyNumber;
2324 
2325  /* We must keep the original equality qual */
2326  *keep_original = true;
2327  runopexpr = opexpr;
2328 
2329  /* determine the operator to use for the runCondition qual */
2330  runoperator = get_opfamily_member(opinfo->opfamily_id,
2331  opinfo->oplefttype,
2332  opinfo->oprighttype,
2333  newstrategy);
2334  break;
2335  }
2336  }
2337 
2338  if (runopexpr != NULL)
2339  {
2340  Expr *newexpr;
2341 
2342  /*
2343  * Build the qual required for the run condition keeping the
2344  * WindowFunc on the same side as it was originally.
2345  */
2346  if (wfunc_left)
2347  newexpr = make_opclause(runoperator,
2348  runopexpr->opresulttype,
2349  runopexpr->opretset, (Expr *) wfunc,
2350  otherexpr, runopexpr->opcollid,
2351  runopexpr->inputcollid);
2352  else
2353  newexpr = make_opclause(runoperator,
2354  runopexpr->opresulttype,
2355  runopexpr->opretset,
2356  otherexpr, (Expr *) wfunc,
2357  runopexpr->opcollid,
2358  runopexpr->inputcollid);
2359 
2360  wclause->runCondition = lappend(wclause->runCondition, newexpr);
2361 
2362  /* record that this attno was used in a run condition */
2363  *run_cond_attrs = bms_add_member(*run_cond_attrs,
2365  return true;
2366  }
2367 
2368  /* unsupported OpExpr */
2369  return false;
2370 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
signed short int16
Definition: c.h:429
#define OidIsValid(objectId)
Definition: c.h:711
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:1968
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:680
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1840
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:165
List * get_op_btree_interpretation(Oid opno)
Definition: lsyscache.c:600
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: makefuncs.c:610
void * arg
@ MONOTONICFUNC_NONE
Definition: plannodes.h:1586
@ MONOTONICFUNC_DECREASING
Definition: plannodes.h:1588
@ MONOTONICFUNC_INCREASING
Definition: plannodes.h:1587
@ MONOTONICFUNC_BOTH
Definition: plannodes.h:1589
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:670
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:660
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
bool opretset
Definition: primnodes.h:657
Oid opno
Definition: primnodes.h:648
Oid opcollid
Definition: primnodes.h:660
Oid inputcollid
Definition: primnodes.h:663
Oid opresulttype
Definition: primnodes.h:654
List * windowClause
Definition: parsenodes.h:177
struct WindowClause * window_clause
Definition: supportnodes.h:296
List * runCondition
Definition: parsenodes.h:1421
Index winref
Definition: primnodes.h:495
Oid winfnoid
Definition: primnodes.h:489
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27

References arg, OpExpr::args, bms_add_member(), BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, DatumGetPointer(), FirstLowInvalidHeapAttributeNumber, get_func_support(), get_op_btree_interpretation(), get_opfamily_member(), OpExpr::inputcollid, InvalidOid, is_pseudo_constant_clause(), IsA, lappend(), lfirst, linitial, list_nth(), lsecond, make_opclause(), MONOTONICFUNC_BOTH, MONOTONICFUNC_DECREASING, MONOTONICFUNC_INCREASING, MONOTONICFUNC_NONE, OidFunctionCall1, OidIsValid, OpExpr::opcollid, OpBtreeInterpretation::opfamily_id, OpBtreeInterpretation::oplefttype, OpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OpBtreeInterpretation::oprighttype, PointerGetDatum(), res, WindowClause::runCondition, 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 3002 of file allpaths.c.

3003 {
3004  Path *cheapest_partial_path;
3005  Path *simple_gather_path;
3006  ListCell *lc;
3007  double rows;
3008  double *rowsp = NULL;
3009 
3010  /* If there are no partial paths, there's nothing to do here. */
3011  if (rel->partial_pathlist == NIL)
3012  return;
3013 
3014  /* Should we override the rel's rowcount estimate? */
3015  if (override_rows)
3016  rowsp = &rows;
3017 
3018  /*
3019  * The output of Gather is always unsorted, so there's only one partial
3020  * path of interest: the cheapest one. That will be the one at the front
3021  * of partial_pathlist because of the way add_partial_path works.
3022  */
3023  cheapest_partial_path = linitial(rel->partial_pathlist);
3024  rows =
3025  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
3026  simple_gather_path = (Path *)
3027  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
3028  NULL, rowsp);
3029  add_path(rel, simple_gather_path);
3030 
3031  /*
3032  * For each useful ordering, we can consider an order-preserving Gather
3033  * Merge.
3034  */
3035  foreach(lc, rel->partial_pathlist)
3036  {
3037  Path *subpath = (Path *) lfirst(lc);
3038  GatherMergePath *path;
3039 
3040  if (subpath->pathkeys == NIL)
3041  continue;
3042 
3043  rows = subpath->rows * subpath->parallel_workers;
3044  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
3045  subpath->pathkeys, NULL, rowsp);
3046  add_path(rel, &path->path);
3047  }
3048 }
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1873
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1964
struct PathTarget * reltarget
Definition: pathnodes.h:843

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

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

1678 {
1679  ListCell *lcp;
1680  List *partition_pathkeys = NIL;
1681  List *partition_pathkeys_desc = NIL;
1682  bool partition_pathkeys_partial = true;
1683  bool partition_pathkeys_desc_partial = true;
1684 
1685  /*
1686  * Some partitioned table setups may allow us to use an Append node
1687  * instead of a MergeAppend. This is possible in cases such as RANGE
1688  * partitioned tables where it's guaranteed that an earlier partition must
1689  * contain rows which come earlier in the sort order. To detect whether
1690  * this is relevant, build pathkey descriptions of the partition ordering,
1691  * for both forward and reverse scans.
1692  */
1693  if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1694  partitions_are_ordered(rel->boundinfo, rel->live_parts))
1695  {
1696  partition_pathkeys = build_partition_pathkeys(root, rel,
1698  &partition_pathkeys_partial);
1699 
1700  partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1702  &partition_pathkeys_desc_partial);
1703 
1704  /*
1705  * You might think we should truncate_useless_pathkeys here, but
1706  * allowing partition keys which are a subset of the query's pathkeys
1707  * can often be useful. For example, consider a table partitioned by
1708  * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1709  * paths that can produce the a, b, c ordering (perhaps via indexes on
1710  * (a, b, c)) then it works to consider the appendrel output as
1711  * ordered by a, b, c.
1712  */
1713  }
1714 
1715  /* Now consider each interesting sort ordering */
1716  foreach(lcp, all_child_pathkeys)
1717  {
1718  List *pathkeys = (List *) lfirst(lcp);
1719  List *startup_subpaths = NIL;
1720  List *total_subpaths = NIL;
1721  List *fractional_subpaths = NIL;
1722  bool startup_neq_total = false;
1723  ListCell *lcr;
1724  bool match_partition_order;
1725  bool match_partition_order_desc;
1726 
1727  /*
1728  * Determine if this sort ordering matches any partition pathkeys we
1729  * have, for both ascending and descending partition order. If the
1730  * partition pathkeys happen to be contained in pathkeys then it still
1731  * works, as described above, providing that the partition pathkeys
1732  * are complete and not just a prefix of the partition keys. (In such
1733  * cases we'll be relying on the child paths to have sorted the
1734  * lower-order columns of the required pathkeys.)
1735  */
1736  match_partition_order =
1737  pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1738  (!partition_pathkeys_partial &&
1739  pathkeys_contained_in(partition_pathkeys, pathkeys));
1740 
1741  match_partition_order_desc = !match_partition_order &&
1742  (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1743  (!partition_pathkeys_desc_partial &&
1744  pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1745 
1746  /* Select the child paths for this ordering... */
1747  foreach(lcr, live_childrels)
1748  {
1749  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1750  Path *cheapest_startup,
1751  *cheapest_total,
1752  *cheapest_fractional = NULL;
1753 
1754  /* Locate the right paths, if they are available. */
1755  cheapest_startup =
1757  pathkeys,
1758  NULL,
1759  STARTUP_COST,
1760  false);
1761  cheapest_total =
1763  pathkeys,
1764  NULL,
1765  TOTAL_COST,
1766  false);
1767 
1768  /*
1769  * If we can't find any paths with the right order just use the
1770  * cheapest-total path; we'll have to sort it later.
1771  */
1772  if (cheapest_startup == NULL || cheapest_total == NULL)
1773  {
1774  cheapest_startup = cheapest_total =
1775  childrel->cheapest_total_path;
1776  /* Assert we do have an unparameterized path for this child */
1777  Assert(cheapest_total->param_info == NULL);
1778  }
1779 
1780  /*
1781  * When building a fractional path, determine a cheapest
1782  * fractional path for each child relation too. Looking at startup
1783  * and total costs is not enough, because the cheapest fractional
1784  * path may be dominated by two separate paths (one for startup,
1785  * one for total).
1786  *
1787  * When needed (building fractional path), determine the cheapest
1788  * fractional path too.
1789  */
1790  if (root->tuple_fraction > 0)
1791  {
1792  double path_fraction = (1.0 / root->tuple_fraction);
1793 
1794  cheapest_fractional =
1796  pathkeys,
1797  NULL,
1798  path_fraction);
1799 
1800  /*
1801  * If we found no path with matching pathkeys, use the
1802  * cheapest total path instead.
1803  *
1804  * XXX We might consider partially sorted paths too (with an
1805  * incremental sort on top). But we'd have to build all the
1806  * incremental paths, do the costing etc.
1807  */
1808  if (!cheapest_fractional)
1809  cheapest_fractional = cheapest_total;
1810  }
1811 
1812  /*
1813  * Notice whether we actually have different paths for the
1814  * "cheapest" and "total" cases; frequently there will be no point
1815  * in two create_merge_append_path() calls.
1816  */
1817  if (cheapest_startup != cheapest_total)
1818  startup_neq_total = true;
1819 
1820  /*
1821  * Collect the appropriate child paths. The required logic varies
1822  * for the Append and MergeAppend cases.
1823  */
1824  if (match_partition_order)
1825  {
1826  /*
1827  * We're going to make a plain Append path. We don't need
1828  * most of what accumulate_append_subpath would do, but we do
1829  * want to cut out child Appends or MergeAppends if they have
1830  * just a single subpath (and hence aren't doing anything
1831  * useful).
1832  */
1833  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1834  cheapest_total = get_singleton_append_subpath(cheapest_total);
1835 
1836  startup_subpaths = lappend(startup_subpaths, cheapest_startup);
1837  total_subpaths = lappend(total_subpaths, cheapest_total);
1838 
1839  if (cheapest_fractional)
1840  {
1841  cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1842  fractional_subpaths = lappend(fractional_subpaths, cheapest_fractional);
1843  }
1844  }
1845  else if (match_partition_order_desc)
1846  {
1847  /*
1848  * As above, but we need to reverse the order of the children,
1849  * because nodeAppend.c doesn't know anything about reverse
1850  * ordering and will scan the children in the order presented.
1851  */
1852  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1853  cheapest_total = get_singleton_append_subpath(cheapest_total);
1854 
1855  startup_subpaths = lcons(cheapest_startup, startup_subpaths);
1856  total_subpaths = lcons(cheapest_total, total_subpaths);
1857 
1858  if (cheapest_fractional)
1859  {
1860  cheapest_fractional = get_singleton_append_subpath(cheapest_fractional);
1861  fractional_subpaths = lcons(cheapest_fractional, fractional_subpaths);
1862  }
1863  }
1864  else
1865  {
1866  /*
1867  * Otherwise, rely on accumulate_append_subpath to collect the
1868  * child paths for the MergeAppend.
1869  */
1870  accumulate_append_subpath(cheapest_startup,
1871  &startup_subpaths, NULL);
1872  accumulate_append_subpath(cheapest_total,
1873  &total_subpaths, NULL);
1874 
1875  if (cheapest_fractional)
1876  accumulate_append_subpath(cheapest_fractional,
1877  &fractional_subpaths, NULL);
1878  }
1879  }
1880 
1881  /* ... and build the Append or MergeAppend paths */
1882  if (match_partition_order || match_partition_order_desc)
1883  {
1884  /* We only need Append */
1885  add_path(rel, (Path *) create_append_path(root,
1886  rel,
1887  startup_subpaths,
1888  NIL,
1889  pathkeys,
1890  NULL,
1891  0,
1892  false,
1893  -1));
1894  if (startup_neq_total)
1895  add_path(rel, (Path *) create_append_path(root,
1896  rel,
1897  total_subpaths,
1898  NIL,
1899  pathkeys,
1900  NULL,
1901  0,
1902  false,
1903  -1));
1904 
1905  if (fractional_subpaths)
1906  add_path(rel, (Path *) create_append_path(root,
1907  rel,
1908  fractional_subpaths,
1909  NIL,
1910  pathkeys,
1911  NULL,
1912  0,
1913  false,
1914  -1));
1915  }
1916  else
1917  {
1918  /* We need MergeAppend */
1919  add_path(rel, (Path *) create_merge_append_path(root,
1920  rel,
1921  startup_subpaths,
1922  pathkeys,
1923  NULL));
1924  if (startup_neq_total)
1925  add_path(rel, (Path *) create_merge_append_path(root,
1926  rel,
1927  total_subpaths,
1928  pathkeys,
1929  NULL));
1930 
1931  if (fractional_subpaths)
1932  add_path(rel, (Path *) create_merge_append_path(root,
1933  rel,
1934  fractional_subpaths,
1935  pathkeys,
1936  NULL));
1937  }
1938  }
1939 }
static Path * get_singleton_append_subpath(Path *path)
Definition: allpaths.c:2082
List * lcons(void *datum, List *list)
Definition: list.c:494
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2853
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:426
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:471
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:346
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:726
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1413
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:789
@ TOTAL_COST
Definition: pathnodes.h:38
@ STARTUP_COST
Definition: pathnodes.h:38
@ BackwardScanDirection
Definition: sdir.h:24
@ ForwardScanDirection
Definition: sdir.h:26
Selectivity tuple_fraction
Definition: pathnodes.h:440
Bitmapset * live_parts
Definition: pathnodes.h:984

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(), IS_SIMPLE_REL, lappend(), lcons(), lfirst, RelOptInfo::live_parts, NIL, partitions_are_ordered(), pathkeys_contained_in(), RelOptInfo::pathlist, STARTUP_COST, TOTAL_COST, and PlannerInfo::tuple_fraction.

Referenced by add_paths_to_append_rel().

◆ generate_partitionwise_join_paths()

void generate_partitionwise_join_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4243 of file allpaths.c.

4244 {
4245  List *live_children = NIL;
4246  int cnt_parts;
4247  int num_parts;
4248  RelOptInfo **part_rels;
4249 
4250  /* Handle only join relations here. */
4251  if (!IS_JOIN_REL(rel))
4252  return;
4253 
4254  /* We've nothing to do if the relation is not partitioned. */
4255  if (!IS_PARTITIONED_REL(rel))
4256  return;
4257 
4258  /* The relation should have consider_partitionwise_join set. */
4260 
4261  /* Guard against stack overflow due to overly deep partition hierarchy. */
4263 
4264  num_parts = rel->nparts;
4265  part_rels = rel->part_rels;
4266 
4267  /* Collect non-dummy child-joins. */
4268  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4269  {
4270  RelOptInfo *child_rel = part_rels[cnt_parts];
4271 
4272  /* If it's been pruned entirely, it's certainly dummy. */
4273  if (child_rel == NULL)
4274  continue;
4275 
4276  /* Make partitionwise join paths for this partitioned child-join. */
4277  generate_partitionwise_join_paths(root, child_rel);
4278 
4279  /* If we failed to make any path for this child, we must give up. */
4280  if (child_rel->pathlist == NIL)
4281  {
4282  /*
4283  * Mark the parent joinrel as unpartitioned so that later
4284  * functions treat it correctly.
4285  */
4286  rel->nparts = 0;
4287  return;
4288  }
4289 
4290  /* Else, identify the cheapest path for it. */
4291  set_cheapest(child_rel);
4292 
4293  /* Dummy children need not be scanned, so ignore those. */
4294  if (IS_DUMMY_REL(child_rel))
4295  continue;
4296 
4297 #ifdef OPTIMIZER_DEBUG
4298  debug_print_rel(root, child_rel);
4299 #endif
4300 
4301  live_children = lappend(live_children, child_rel);
4302  }
4303 
4304  /* If all child-joins are dummy, parent join is also dummy. */
4305  if (!live_children)
4306  {
4307  mark_dummy_rel(rel);
4308  return;
4309  }
4310 
4311  /* Build additional paths for this rel from child-join paths. */
4312  add_paths_to_append_rel(root, rel, live_children);
4313  list_free(live_children);
4314 }
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:4243
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1287
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1261
void list_free(List *list)
Definition: list.c:1545
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1820
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:794
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1007
void check_stack_depth(void)
Definition: postgres.c:3440
int nparts
Definition: pathnodes.h:966
bool consider_partitionwise_join
Definition: pathnodes.h:944

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

3141 {
3142  ListCell *lc;
3143  double rows;
3144  double *rowsp = NULL;
3145  List *useful_pathkeys_list = NIL;
3146  Path *cheapest_partial_path = NULL;
3147 
3148  /* If there are no partial paths, there's nothing to do here. */
3149  if (rel->partial_pathlist == NIL)
3150  return;
3151 
3152  /* Should we override the rel's rowcount estimate? */
3153  if (override_rows)
3154  rowsp = &rows;
3155 
3156  /* generate the regular gather (merge) paths */
3157  generate_gather_paths(root, rel, override_rows);
3158 
3159  /* consider incremental sort for interesting orderings */
3160  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3161 
3162  /* used for explicit (full) sort paths */
3163  cheapest_partial_path = linitial(rel->partial_pathlist);
3164 
3165  /*
3166  * Consider sorted paths for each interesting ordering. We generate both
3167  * incremental and full sort.
3168  */
3169  foreach(lc, useful_pathkeys_list)
3170  {
3171  List *useful_pathkeys = lfirst(lc);
3172  ListCell *lc2;
3173  bool is_sorted;
3174  int presorted_keys;
3175 
3176  foreach(lc2, rel->partial_pathlist)
3177  {
3178  Path *subpath = (Path *) lfirst(lc2);
3179  GatherMergePath *path;
3180 
3181  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3182  subpath->pathkeys,
3183  &presorted_keys);
3184 
3185  /*
3186  * We don't need to consider the case where a subpath is already
3187  * fully sorted because generate_gather_paths already creates a
3188  * gather merge path for every subpath that has pathkeys present.
3189  *
3190  * But since the subpath is already sorted, we know we don't need
3191  * to consider adding a sort (full or incremental) on top of it,
3192  * so we can continue here.
3193  */
3194  if (is_sorted)
3195  continue;
3196 
3197  /*
3198  * Consider regular sort for the cheapest partial path (for each
3199  * useful pathkeys). We know the path is not sorted, because we'd
3200  * not get here otherwise.
3201  *
3202  * This is not redundant with the gather paths created in
3203  * generate_gather_paths, because that doesn't generate ordered
3204  * output. Here we add an explicit sort to match the useful
3205  * ordering.
3206  */
3207  if (cheapest_partial_path == subpath)
3208  {
3209  Path *tmp;
3210 
3211  tmp = (Path *) create_sort_path(root,
3212  rel,
3213  subpath,
3214  useful_pathkeys,
3215  -1.0);
3216 
3217  rows = tmp->rows * tmp->parallel_workers;
3218 
3219  path = create_gather_merge_path(root, rel,
3220  tmp,
3221  rel->reltarget,
3222  tmp->pathkeys,
3223  NULL,
3224  rowsp);
3225 
3226  add_path(rel, &path->path);
3227 
3228  /* Fall through */
3229  }
3230 
3231  /*
3232  * Consider incremental sort, but only when the subpath is already
3233  * partially sorted on a pathkey prefix.
3234  */
3235  if (enable_incremental_sort && presorted_keys > 0)
3236  {
3237  Path *tmp;
3238 
3239  /*
3240  * We should have already excluded pathkeys of length 1
3241  * because then presorted_keys > 0 would imply is_sorted was
3242  * true.
3243  */
3244  Assert(list_length(useful_pathkeys) != 1);
3245 
3246  tmp = (Path *) create_incremental_sort_path(root,
3247  rel,
3248  subpath,
3249  useful_pathkeys,
3250  presorted_keys,
3251  -1);
3252 
3253  path = create_gather_merge_path(root, rel,
3254  tmp,
3255  rel->reltarget,
3256  tmp->pathkeys,
3257  NULL,
3258  rowsp);
3259 
3260  add_path(rel, &path->path);
3261  }
3262  }
3263  }
3264 }
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3002
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:3072
bool enable_incremental_sort
Definition: costsize.c:141
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:365
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2961
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2912

References add_path(), Assert(), create_gather_merge_path(), create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, generate_gather_paths(), get_useful_pathkeys_for_relation(), lfirst, linitial, list_length(), NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, GatherMergePath::path, Path::pathkeys, pathkeys_count_contained_in(), RelOptInfo::reltarget, Path::rows, and subpath().

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

1951 {
1952  Path *cheapest;
1953  ListCell *lc;
1954 
1955  /*
1956  * Look up the cheapest existing path with no more than the needed
1957  * parameterization. If it has exactly the needed parameterization, we're
1958  * done.
1959  */
1960  cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
1961  NIL,
1962  required_outer,
1963  TOTAL_COST,
1964  false);
1965  Assert(cheapest != NULL);
1966  if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
1967  return cheapest;
1968 
1969  /*
1970  * Otherwise, we can "reparameterize" an existing path to match the given
1971  * parameterization, which effectively means pushing down additional
1972  * joinquals to be checked within the path's scan. However, some existing
1973  * paths might check the available joinquals already while others don't;
1974  * therefore, it's not clear which existing path will be cheapest after
1975  * reparameterization. We have to go through them all and find out.
1976  */
1977  cheapest = NULL;
1978  foreach(lc, rel->pathlist)
1979  {
1980  Path *path = (Path *) lfirst(lc);
1981 
1982  /* Can't use it if it needs more than requested parameterization */
1983  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
1984  continue;
1985 
1986  /*
1987  * Reparameterization can only increase the path's cost, so if it's
1988  * already more expensive than the current cheapest, forget it.
1989  */
1990  if (cheapest != NULL &&
1991  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
1992  continue;
1993 
1994  /* Reparameterize if needed, then recheck cost */
1995  if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
1996  {
1997  path = reparameterize_path(root, path, required_outer, 1.0);
1998  if (path == NULL)
1999  continue; /* failed to reparameterize this one */
2000  Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
2001 
2002  if (cheapest != NULL &&
2003  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
2004  continue;
2005  }
2006 
2007  /* We have a new best path */
2008  cheapest = path;
2009  }
2010 
2011  /* Return the best path, or NULL if we found no suitable candidate */
2012  return cheapest;
2013 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:316
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3877
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:71

References Assert(), bms_equal(), bms_is_subset(), compare_path_costs(), get_cheapest_path_for_pathkeys(), lfirst, NIL, PATH_REQ_OUTER, RelOptInfo::pathlist, reparameterize_path(), 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 2082 of file allpaths.c.

2083 {
2084  Assert(!path->parallel_aware);
2085 
2086  if (IsA(path, AppendPath))
2087  {
2088  AppendPath *apath = (AppendPath *) path;
2089 
2090  if (list_length(apath->subpaths) == 1)
2091  return (Path *) linitial(apath->subpaths);
2092  }
2093  else if (IsA(path, MergeAppendPath))
2094  {
2095  MergeAppendPath *mpath = (MergeAppendPath *) path;
2096 
2097  if (list_length(mpath->subpaths) == 1)
2098  return (Path *) linitial(mpath->subpaths);
2099  }
2100 
2101  return path;
2102 }

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

3074 {
3075  List *useful_pathkeys_list = NIL;
3076 
3077  /*
3078  * Considering query_pathkeys is always worth it, because it might allow
3079  * us to avoid a total sort when we have a partially presorted path
3080  * available or to push the total sort into the parallel portion of the
3081  * query.
3082  */
3083  if (root->query_pathkeys)
3084  {
3085  ListCell *lc;
3086  int npathkeys = 0; /* useful pathkeys */
3087 
3088  foreach(lc, root->query_pathkeys)
3089  {
3090  PathKey *pathkey = (PathKey *) lfirst(lc);
3091  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3092 
3093  /*
3094  * We can only build a sort for pathkeys that contain a
3095  * safe-to-compute-early EC member computable from the current
3096  * relation's reltarget, so ignore the remainder of the list as
3097  * soon as we find a pathkey without such a member.
3098  *
3099  * It's still worthwhile to return any prefix of the pathkeys list
3100  * that meets this requirement, as we may be able to do an
3101  * incremental sort.
3102  *
3103  * If requested, ensure the sort expression is parallel-safe too.
3104  */
3105  if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
3106  require_parallel_safe))
3107  break;
3108 
3109  npathkeys++;
3110  }
3111 
3112  /*
3113  * The whole query_pathkeys list matches, so append it directly, to
3114  * allow comparing pathkeys easily by comparing list pointer. If we
3115  * have to truncate the pathkeys, we gotta do a copy though.
3116  */
3117  if (npathkeys == list_length(root->query_pathkeys))
3118  useful_pathkeys_list = lappend(useful_pathkeys_list,
3119  root->query_pathkeys);
3120  else if (npathkeys > 0)
3121  useful_pathkeys_list = lappend(useful_pathkeys_list,
3123  npathkeys));
3124  }
3125 
3126  return useful_pathkeys_list;
3127 }
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
Definition: equivclass.c:948
List * query_pathkeys
Definition: pathnodes.h:372

References lappend(), lfirst, list_copy_head(), list_length(), NIL, PlannerInfo::query_pathkeys, and relation_can_be_sorted_early().

Referenced by generate_useful_gather_paths().

◆ has_multiple_baserels()

static bool has_multiple_baserels ( PlannerInfo root)
static

Definition at line 2142 of file allpaths.c.

2143 {
2144  int num_base_rels = 0;
2145  Index rti;
2146 
2147  for (rti = 1; rti < root->simple_rel_array_size; rti++)
2148  {
2149  RelOptInfo *brel = root->simple_rel_array[rti];
2150 
2151  if (brel == NULL)
2152  continue;
2153 
2154  /* ignore RTEs that are "other rels" */
2155  if (brel->reloptkind == RELOPT_BASEREL)
2156  if (++num_base_rels > 1)
2157  return true;
2158  }
2159  return false;
2160 }
unsigned int Index
Definition: c.h:550
int simple_rel_array_size
Definition: pathnodes.h:229

References RELOPT_BASEREL, RelOptInfo::reloptkind, and PlannerInfo::simple_rel_array_size.

Referenced by set_subquery_pathlist().

◆ make_one_rel()

RelOptInfo* make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 156 of file allpaths.c.

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

References PlannerInfo::all_baserels, Assert(), bms_add_member(), bms_equal(), IS_DUMMY_REL, IS_SIMPLE_REL, make_rel_from_joinlist(), RelOptInfo::pages, RelOptInfo::relid, RelOptInfo::relids, RELOPT_BASEREL, RelOptInfo::reloptkind, set_base_rel_consider_startup(), set_base_rel_pathlists(), set_base_rel_sizes(), PlannerInfo::simple_rel_array_size, and PlannerInfo::total_table_pages.

Referenced by query_planner().

◆ make_rel_from_joinlist()

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

Definition at line 3274 of file allpaths.c.

3275 {
3276  int levels_needed;
3277  List *initial_rels;
3278  ListCell *jl;
3279 
3280  /*
3281  * Count the number of child joinlist nodes. This is the depth of the
3282  * dynamic-programming algorithm we must employ to consider all ways of
3283  * joining the child nodes.
3284  */
3285  levels_needed = list_length(joinlist);
3286 
3287  if (levels_needed <= 0)
3288  return NULL; /* nothing to do? */
3289 
3290  /*
3291  * Construct a list of rels corresponding to the child joinlist nodes.
3292  * This may contain both base rels and rels constructed according to
3293  * sub-joinlists.
3294  */
3295  initial_rels = NIL;
3296  foreach(jl, joinlist)
3297  {
3298  Node *jlnode = (Node *) lfirst(jl);
3299  RelOptInfo *thisrel;
3300 
3301  if (IsA(jlnode, RangeTblRef))
3302  {
3303  int varno = ((RangeTblRef *) jlnode)->rtindex;
3304 
3305  thisrel = find_base_rel(root, varno);
3306  }
3307  else if (IsA(jlnode, List))
3308  {
3309  /* Recurse to handle subproblem */
3310  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
3311  }
3312  else
3313  {
3314  elog(ERROR, "unrecognized joinlist node type: %d",
3315  (int) nodeTag(jlnode));
3316  thisrel = NULL; /* keep compiler quiet */
3317  }
3318 
3319  initial_rels = lappend(initial_rels, thisrel);
3320  }
3321 
3322  if (levels_needed == 1)
3323  {
3324  /*
3325  * Single joinlist node, so we're done.
3326  */
3327  return (RelOptInfo *) linitial(initial_rels);
3328  }
3329  else
3330  {
3331  /*
3332  * Consider the different orders in which we could join the rels,
3333  * using a plugin, GEQO, or the regular join search code.
3334  *
3335  * We put the initial_rels list into a PlannerInfo field because
3336  * has_legal_joinclause() needs to look at it (ugly :-().
3337  */
3338  root->initial_rels = initial_rels;
3339 
3340  if (join_search_hook)
3341  return (*join_search_hook) (root, levels_needed, initial_rels);
3342  else if (enable_geqo && levels_needed >= geqo_threshold)
3343  return geqo(root, levels_needed, initial_rels);
3344  else
3345  return standard_join_search(root, levels_needed, initial_rels);
3346  }
3347 }
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3379
int geqo_threshold
Definition: allpaths.c:65
join_search_hook_type join_search_hook
Definition: allpaths.c:73
bool enable_geqo
Definition: allpaths.c:64
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:67
#define nodeTag(nodeptr)
Definition: nodes.h:122
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:360

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

Referenced by make_one_rel().

◆ qual_is_pushdown_safe()

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

Definition at line 3816 of file allpaths.c.

3818 {
3819  bool safe = true;
3820  Node *qual = (Node *) rinfo->clause;
3821  List *vars;
3822  ListCell *vl;
3823 
3824  /* Refuse subselects (point 1) */
3825  if (contain_subplans(qual))
3826  return false;
3827 
3828  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3829  if (safetyInfo->unsafeVolatile &&
3830  contain_volatile_functions((Node *) rinfo))
3831  return false;
3832 
3833  /* Refuse leaky quals if told to (point 3) */
3834  if (safetyInfo->unsafeLeaky &&
3835  contain_leaked_vars(qual))
3836  return false;
3837 
3838  /*
3839  * It would be unsafe to push down window function calls, but at least for
3840  * the moment we could never see any in a qual anyhow. (The same applies
3841  * to aggregates, which we check for in pull_var_clause below.)
3842  */
3844 
3845  /*
3846  * Examine all Vars used in clause. Since it's a restriction clause, all
3847  * such Vars must refer to subselect output columns ... unless this is
3848  * part of a LATERAL subquery, in which case there could be lateral
3849  * references.
3850  */
3852  foreach(vl, vars)
3853  {
3854  Var *var = (Var *) lfirst(vl);
3855 
3856  /*
3857  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3858  * It's not clear whether a PHV could safely be pushed down, and even
3859  * less clear whether such a situation could arise in any cases of
3860  * practical interest anyway. So for the moment, just refuse to push
3861  * down.
3862  */
3863  if (!IsA(var, Var))
3864  {
3865  safe = false;
3866  break;
3867  }
3868 
3869  /*
3870  * Punt if we find any lateral references. It would be safe to push
3871  * these down, but we'd have to convert them into outer references,
3872  * which subquery_push_qual lacks the infrastructure to do. The case
3873  * arises so seldom that it doesn't seem worth working hard on.
3874  */
3875  if (var->varno != rti)
3876  {
3877  safe = false;
3878  break;
3879  }
3880 
3881  /* Subqueries have no system columns */
3882  Assert(var->varattno >= 0);
3883 
3884  /* Check point 4 */
3885  if (var->varattno == 0)
3886  {
3887  safe = false;
3888  break;
3889  }
3890 
3891  /* Check point 5 */
3892  if (safetyInfo->unsafeColumns[var->varattno])
3893  {
3894  safe = false;
3895  break;
3896  }
3897  }
3898 
3899  list_free(vars);
3900 
3901  return safe;
3902 }
bool contain_window_function(Node *clause)
Definition: clauses.c:214
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1144
bool contain_subplans(Node *clause)
Definition: clauses.c:330
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:187
Expr * clause
Definition: pathnodes.h:2432
int varno
Definition: primnodes.h:212
Definition: regcomp.c:282
List * pull_var_clause(Node *node, int flags)
Definition: var.c:597

References Assert(), RestrictInfo::clause, contain_leaked_vars(), contain_subplans(), contain_volatile_functions(), contain_window_function(), if(), IsA, lfirst, list_free(), pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, pushdown_safety_info::unsafeColumns, 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 3955 of file allpaths.c.

3957 {
3958  if (IsA(setOp, RangeTblRef))
3959  {
3960  RangeTblRef *rtr = (RangeTblRef *) setOp;
3961  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
3962  Query *subquery = subrte->subquery;
3963 
3964  Assert(subquery != NULL);
3965  subquery_push_qual(subquery, rte, rti, qual);
3966  }
3967  else if (IsA(setOp, SetOperationStmt))
3968  {
3969  SetOperationStmt *op = (SetOperationStmt *) setOp;
3970 
3971  recurse_push_qual(op->larg, topquery, rte, rti, qual);
3972  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
3973  }
3974  else
3975  {
3976  elog(ERROR, "unrecognized node type: %d",
3977  (int) nodeTag(setOp));
3978  }
3979 }
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3908
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3955
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * rtable
Definition: parsenodes.h:155
Query * subquery
Definition: parsenodes.h:1065

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

3607 {
3608  if (IsA(setOp, RangeTblRef))
3609  {
3610  RangeTblRef *rtr = (RangeTblRef *) setOp;
3611  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3612  Query *subquery = rte->subquery;
3613 
3614  Assert(subquery != NULL);
3615  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3616  }
3617  else if (IsA(setOp, SetOperationStmt))
3618  {
3619  SetOperationStmt *op = (SetOperationStmt *) setOp;
3620 
3621  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3622  if (op->op == SETOP_EXCEPT)
3623  return false;
3624  /* Else recurse */
3625  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3626  return false;
3627  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3628  return false;
3629  }
3630  else
3631  {
3632  elog(ERROR, "unrecognized node type: %d",
3633  (int) nodeTag(setOp));
3634  }
3635  return true;
3636 }
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3549
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3605
@ SETOP_EXCEPT
Definition: parsenodes.h:1721
SetOperation op
Definition: parsenodes.h:1796

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

4009 {
4010  Bitmapset *attrs_used;
4011  ListCell *lc;
4012 
4013  /*
4014  * Just point directly to extra_used_attrs. No need to bms_copy as none of
4015  * the current callers use the Bitmapset after calling this function.
4016  */
4017  attrs_used = extra_used_attrs;
4018 
4019  /*
4020  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
4021  * could update all the child SELECTs' tlists, but it seems not worth the
4022  * trouble presently.
4023  */
4024  if (subquery->setOperations)
4025  return;
4026 
4027  /*
4028  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
4029  * time: all its output columns must be used in the distinctClause.
4030  */
4031  if (subquery->distinctClause && !subquery->hasDistinctOn)
4032  return;
4033 
4034  /*
4035  * Collect a bitmap of all the output column numbers used by the upper
4036  * query.
4037  *
4038  * Add all the attributes needed for joins or final output. Note: we must
4039  * look at rel's targetlist, not the attr_needed data, because attr_needed
4040  * isn't computed for inheritance child rels, cf set_append_rel_size().
4041  * (XXX might be worth changing that sometime.)
4042  */
4043  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4044 
4045  /* Add all the attributes used by un-pushed-down restriction clauses. */
4046  foreach(lc, rel->baserestrictinfo)
4047  {
4048  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4049 
4050  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4051  }
4052 
4053  /*
4054  * If there's a whole-row reference to the subquery, we can't remove
4055  * anything.
4056  */
4058  return;
4059 
4060  /*
4061  * Run through the tlist and zap entries we don't need. It's okay to
4062  * modify the tlist items in-place because set_subquery_pathlist made a
4063  * copy of the subquery.
4064  */
4065  foreach(lc, subquery->targetList)
4066  {
4067  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4068  Node *texpr = (Node *) tle->expr;
4069 
4070  /*
4071  * If it has a sortgroupref number, it's used in some sort/group
4072  * clause so we'd better not remove it. Also, don't remove any
4073  * resjunk columns, since their reason for being has nothing to do
4074  * with anybody reading the subquery's output. (It's likely that
4075  * resjunk columns in a sub-SELECT would always have ressortgroupref
4076  * set, but even if they don't, it seems imprudent to remove them.)
4077  */
4078  if (tle->ressortgroupref || tle->resjunk)
4079  continue;
4080 
4081  /*
4082  * If it's used by the upper query, we can't remove it.
4083  */
4085  attrs_used))
4086  continue;
4087 
4088  /*
4089  * If it contains a set-returning function, we can't remove it since
4090  * that could change the number of rows returned by the subquery.
4091  */
4092  if (subquery->hasTargetSRFs &&
4093  expression_returns_set(texpr))
4094  continue;
4095 
4096  /*
4097  * If it contains volatile functions, we daren't remove it for fear
4098  * that the user is expecting their side-effects to happen.
4099  */
4100  if (contain_volatile_functions(texpr))
4101  continue;
4102 
4103  /*
4104  * OK, we don't need it. Replace the expression with a NULL constant.
4105  * Preserve the exposed type of the expression, in case something
4106  * looks at the rowtype of the subquery's result.
4107  */
4108  tle->expr = (Expr *) makeNullConst(exprType(texpr),
4109  exprTypmod(texpr),
4110  exprCollation(texpr));
4111  }
4112 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:428
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:266
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
List * exprs
Definition: pathnodes.h:1424
Node * setOperations
Definition: parsenodes.h:189
List * baserestrictinfo
Definition: pathnodes.h:930
Index ressortgroupref
Definition: primnodes.h:1558
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:281

References RelOptInfo::baserestrictinfo, bms_is_member(), RestrictInfo::clause, contain_volatile_functions(), Query::distinctClause, TargetEntry::expr, exprCollation(), expression_returns_set(), PathTarget::exprs, exprType(), exprTypmod(), FirstLowInvalidHeapAttributeNumber, Query::hasDistinctOn, Query::hasTargetSRFs, if(), lfirst, makeNullConst(), pull_varattnos(), RelOptInfo::relid, RelOptInfo::reltarget, TargetEntry::resjunk, 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 1217 of file allpaths.c.

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

References add_paths_to_append_rel(), PlannerInfo::append_rel_list, AppendRelInfo::child_relid, RelOptInfo::consider_parallel, IS_DUMMY_REL, lappend(), lfirst, NIL, AppendRelInfo::parent_relid, 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 949 of file allpaths.c.

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

References add_child_rel_equivalences(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert(), 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(), PlannerInfo::glob, RelOptInfo::has_eclass_joins, has_useful_pathkeys(), i, InvalidAttrNumber, IS_DUMMY_REL, IS_SIMPLE_REL, IsA, RelOptInfo::joininfo, lfirst, RelOptInfo::max_attr, RelOptInfo::min_attr, palloc0(), PlannerGlobal::parallelModeOK, AppendRelInfo::parent_relid, pfree(), relation_excluded_by_constraints(), RelOptInfo::relid, RangeTblEntry::relkind, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, 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 252 of file allpaths.c.

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

References bms_get_singleton_member(), RelOptInfo::consider_param_startup, find_base_rel(), JOIN_ANTI, PlannerInfo::join_info_list, JOIN_SEMI, SpecialJoinInfo::jointype, lfirst, 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 338 of file allpaths.c.

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

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

Referenced by make_one_rel().

◆ set_base_rel_sizes()

static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 295 of file allpaths.c.

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

References Assert(), PlannerInfo::glob, PlannerGlobal::parallelModeOK, RelOptInfo::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, set_rel_consider_parallel(), set_rel_size(), and PlannerInfo::simple_rel_array_size.

Referenced by make_one_rel().

◆ set_cte_pathlist()

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

Definition at line 2816 of file allpaths.c.

2817 {
2818  Plan *cteplan;
2819  PlannerInfo *cteroot;
2820  Index levelsup;
2821  int ndx;
2822  ListCell *lc;
2823  int plan_id;
2824  Relids required_outer;
2825 
2826  /*
2827  * Find the referenced CTE, and locate the plan previously made for it.
2828  */
2829  levelsup = rte->ctelevelsup;
2830  cteroot = root;
2831  while (levelsup-- > 0)
2832  {
2833  cteroot = cteroot->parent_root;
2834  if (!cteroot) /* shouldn't happen */
2835  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2836  }
2837 
2838  /*
2839  * Note: cte_plan_ids can be shorter than cteList, if we are still working
2840  * on planning the CTEs (ie, this is a side-reference from another CTE).
2841  * So we mustn't use forboth here.
2842  */
2843  ndx = 0;
2844  foreach(lc, cteroot->parse->cteList)
2845  {
2846  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2847 
2848  if (strcmp(cte->ctename, rte->ctename) == 0)
2849  break;
2850  ndx++;
2851  }
2852  if (lc == NULL) /* shouldn't happen */
2853  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2854  if (ndx >= list_length(cteroot->cte_plan_ids))
2855  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2856  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2857  if (plan_id <= 0)
2858  elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
2859  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2860 
2861  /* Mark rel with estimated output rows, width, etc */
2862  set_cte_size_estimates(root, rel, cteplan->plan_rows);
2863 
2864  /*
2865  * We don't support pushing join clauses into the quals of a CTE scan, but
2866  * it could still have required parameterization due to LATERAL refs in
2867  * its tlist.
2868  */
2869  required_outer = rel->lateral_relids;
2870 
2871  /* Generate appropriate path */
2872  add_path(rel, create_ctescan_path(root, rel, required_outer));
2873 }
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:5713
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2116
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:308
Cardinality plan_rows
Definition: plannodes.h:135
List * subplans
Definition: pathnodes.h:105
List * cte_plan_ids
Definition: pathnodes.h:298
Query * parse
Definition: pathnodes.h:199
List * cteList
Definition: parsenodes.h:153
char * ctename
Definition: parsenodes.h:1140
Index ctelevelsup
Definition: parsenodes.h:1141

References add_path(), create_ctescan_path(), PlannerInfo::cte_plan_ids, RangeTblEntry::ctelevelsup, Query::cteList, RangeTblEntry::ctename, CommonTableExpr::ctename, elog(), ERROR, PlannerInfo::glob, RelOptInfo::lateral_relids, lfirst, list_length(), list_nth(), list_nth_int(), PlannerInfo::parse, Plan::plan_rows, set_cte_size_estimates(), and PlannerGlobal::subplans.

Referenced by set_rel_size().

◆ set_dummy_rel_pathlist()

static void set_dummy_rel_pathlist ( RelOptInfo rel)
static

Definition at line 2116 of file allpaths.c.

2117 {
2118  /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2119  rel->rows = 0;
2120  rel->reltarget->width = 0;
2121 
2122  /* Discard any pre-existing paths; no further need for them */
2123  rel->pathlist = NIL;
2124  rel->partial_pathlist = NIL;
2125 
2126  /* Set up the dummy path */
2127  add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2128  NIL, rel->lateral_relids,
2129  0, false, -1));
2130 
2131  /*
2132  * We set the cheapest-path fields immediately, just in case they were
2133  * pointing at some discarded path. This is redundant when we're called
2134  * from set_rel_size(), but not when called from elsewhere, and doing it
2135  * twice is harmless anyway.
2136  */
2137  set_cheapest(rel);
2138 }

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

932 {
933  /* Call the FDW's GetForeignPaths function to generate path(s) */
934  rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
935 }

References RangeTblEntry::relid.

Referenced by set_rel_pathlist().

◆ set_foreign_size()

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

Definition at line 907 of file allpaths.c.

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

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

2705 {
2706  Relids required_outer;
2707  List *pathkeys = NIL;
2708 
2709  /*
2710  * We don't support pushing join clauses into the quals of a function
2711  * scan, but it could still have required parameterization due to LATERAL
2712  * refs in the function expression.
2713  */
2714  required_outer = rel->lateral_relids;
2715 
2716  /*
2717  * The result is considered unordered unless ORDINALITY was used, in which
2718  * case it is ordered by the ordinal column (the last one). See if we
2719  * care, by checking for uses of that Var in equivalence classes.
2720  */
2721  if (rte->funcordinality)
2722  {
2723  AttrNumber ordattno = rel->max_attr;
2724  Var *var = NULL;
2725  ListCell *lc;
2726 
2727  /*
2728  * Is there a Var for it in rel's targetlist? If not, the query did
2729  * not reference the ordinality column, or at least not in any way
2730  * that would be interesting for sorting.
2731  */
2732  foreach(lc, rel->reltarget->exprs)
2733  {
2734  Var *node = (Var *) lfirst(lc);
2735 
2736  /* checking varno/varlevelsup is just paranoia */
2737  if (IsA(node, Var) &&
2738  node->varattno == ordattno &&
2739  node->varno == rel->relid &&
2740  node->varlevelsup == 0)
2741  {
2742  var = node;
2743  break;
2744  }
2745  }
2746 
2747  /*
2748  * Try to build pathkeys for this Var with int8 sorting. We tell
2749  * build_expression_pathkey not to build any new equivalence class; if
2750  * the Var isn't already mentioned in some EC, it means that nothing
2751  * cares about the ordering.
2752  */
2753  if (var)
2754  pathkeys = build_expression_pathkey(root,
2755  (Expr *) var,
2756  NULL, /* below outer joins */
2757  Int8LessOperator,
2758  rel->relids,
2759  false);
2760  }
2761 
2762  /* Generate appropriate path */
2763  add_path(rel, create_functionscan_path(root, rel,
2764  pathkeys, required_outer));
2765 }
int16 AttrNumber
Definition: attnum.h:21
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:809
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2038
bool funcordinality
Definition: parsenodes.h:1125
Index varlevelsup
Definition: primnodes.h:230

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

2885 {
2886  Relids required_outer;
2887 
2888  /* Mark rel with estimated output rows, width, etc */
2890 
2891  /*
2892  * We don't support pushing join clauses into the quals of a tuplestore
2893  * scan, but it could still have required parameterization due to LATERAL
2894  * refs in its tlist.
2895  */
2896  required_outer = rel->lateral_relids;
2897 
2898  /* Generate appropriate path */
2899  add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2900 
2901  /* Select cheapest path (pretty easy in this case...) */
2902  set_cheapest(rel);
2903 }
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5751
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2141

References add_path(), create_namedtuplestorescan_path(), RelOptInfo::lateral_relids, set_cheapest(), 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 769 of file allpaths.c.

770 {
771  Relids required_outer;
772 
773  /*
774  * We don't support pushing join clauses into the quals of a seqscan, but
775  * it could still have required parameterization due to LATERAL refs in
776  * its tlist.
777  */
778  required_outer = rel->lateral_relids;
779 
780  /* Consider sequential scan */
781  add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
782 
783  /* If appropriate, consider parallel sequential scan */
784  if (rel->consider_parallel && required_outer == NULL)
785  create_plain_partial_paths(root, rel);
786 
787  /* Consider index scans */
788  create_index_paths(root, rel);
789 
790  /* Consider TID scans */
791  create_tidscan_paths(root, rel);
792 }
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:799
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:235
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(), and RelOptInfo::lateral_relids.

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

578 {
579  /*
580  * Test any partial indexes of rel for applicability. We must do this
581  * first since partial unique indexes can affect size estimates.
582  */
583  check_index_predicates(root, rel);
584 
585  /* Mark rel with estimated output rows, width, etc */
586  set_baserel_size_estimates(root, rel);
587 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4988
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:3302

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

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

References TableSampleClause::args, Assert(), RelOptInfo::baserestrictinfo, castNode, RelOptInfo::consider_parallel, PathTarget::exprs, func_parallel(), RangeTblEntry::functions, get_rel_persistence(), PlannerInfo::glob, is_parallel_safe(), IS_SIMPLE_REL, limit_needed(), PlannerGlobal::parallelModeOK, RangeTblEntry::relid, RangeTblEntry::relkind, RelOptInfo::reltarget, 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 474 of file allpaths.c.

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

References PlannerInfo::all_baserels, bms_equal(), elog(), ERROR, generate_useful_gather_paths(), RangeTblEntry::inh, IS_DUMMY_REL, RelOptInfo::relids, RangeTblEntry::relkind, RELOPT_BASEREL, RelOptInfo::reloptkind, 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 365 of file allpaths.c.

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

References Assert(), elog(), ERROR, RangeTblEntry::inh, IS_DUMMY_REL, relation_excluded_by_constraints(), RangeTblEntry::relkind, RELOPT_BASEREL, RelOptInfo::reloptkind, RelOptInfo::rows, RTE_CTE, RTE_FUNCTION, RTE_NAMEDTUPLESTORE, RTE_RELATION, RTE_RESULT, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RelOptInfo::rtekind, RangeTblEntry::self_reference, 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 2913 of file allpaths.c.

2915 {
2916  Relids required_outer;
2917 
2918  /* Mark rel with estimated output rows, width, etc */
2919  set_result_size_estimates(root, rel);
2920 
2921  /*
2922  * We don't support pushing join clauses into the quals of a Result scan,
2923  * but it could still have required parameterization due to LATERAL refs
2924  * in its tlist.
2925  */
2926  required_outer = rel->lateral_relids;
2927 
2928  /* Generate appropriate path */
2929  add_path(rel, create_resultscan_path(root, rel, required_outer));
2930 
2931  /* Select cheapest path (pretty easy in this case...) */
2932  set_cheapest(rel);
2933 }
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5784
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2167

References add_path(), create_resultscan_path(), RelOptInfo::lateral_relids, set_cheapest(), 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 2450 of file allpaths.c.

2452 {
2453  Query *parse = root->parse;
2454  Query *subquery = rte->subquery;
2455  bool trivial_pathtarget;
2456  Relids required_outer;
2457  pushdown_safety_info safetyInfo;
2458  double tuple_fraction;
2459  RelOptInfo *sub_final_rel;
2460  Bitmapset *run_cond_attrs = NULL;
2461  ListCell *lc;
2462 
2463  /*
2464  * Must copy the Query so that planning doesn't mess up the RTE contents
2465  * (really really need to fix the planner to not scribble on its input,
2466  * someday ... but see remove_unused_subquery_outputs to start with).
2467  */
2468  subquery = copyObject(subquery);
2469 
2470  /*
2471  * If it's a LATERAL subquery, it might contain some Vars of the current
2472  * query level, requiring it to be treated as parameterized, even though
2473  * we don't support pushing down join quals into subqueries.
2474  */
2475  required_outer = rel->lateral_relids;
2476 
2477  /*
2478  * Zero out result area for subquery_is_pushdown_safe, so that it can set
2479  * flags as needed while recursing. In particular, we need a workspace
2480  * for keeping track of unsafe-to-reference columns. unsafeColumns[i]
2481  * will be set true if we find that output column i of the subquery is
2482  * unsafe to use in a pushed-down qual.
2483  */
2484  memset(&safetyInfo, 0, sizeof(safetyInfo));
2485  safetyInfo.unsafeColumns = (bool *)
2486  palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
2487 
2488  /*
2489  * If the subquery has the "security_barrier" flag, it means the subquery
2490  * originated from a view that must enforce row-level security. Then we
2491  * must not push down quals that contain leaky functions. (Ideally this
2492  * would be checked inside subquery_is_pushdown_safe, but since we don't
2493  * currently pass the RTE to that function, we must do it here.)
2494  */
2495  safetyInfo.unsafeLeaky = rte->security_barrier;
2496 
2497  /*
2498  * If there are any restriction clauses that have been attached to the
2499  * subquery relation, consider pushing them down to become WHERE or HAVING
2500  * quals of the subquery itself. This transformation is useful because it
2501  * may allow us to generate a better plan for the subquery than evaluating
2502  * all the subquery output rows and then filtering them.
2503  *
2504  * There are several cases where we cannot push down clauses. Restrictions
2505  * involving the subquery are checked by subquery_is_pushdown_safe().
2506  * Restrictions on individual clauses are checked by
2507  * qual_is_pushdown_safe(). Also, we don't want to push down
2508  * pseudoconstant clauses; better to have the gating node above the
2509  * subquery.
2510  *
2511  * Non-pushed-down clauses will get evaluated as qpquals of the
2512  * SubqueryScan node.
2513  *
2514  * XXX Are there any cases where we want to make a policy decision not to
2515  * push down a pushable qual, because it'd result in a worse plan?
2516  */
2517  if (rel->baserestrictinfo != NIL &&
2518  subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2519  {
2520  /* OK to consider pushing down individual quals */
2521  List *upperrestrictlist = NIL;
2522  ListCell *l;
2523 
2524  foreach(l, rel->baserestrictinfo)
2525  {
2526  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2527  Node *clause = (Node *) rinfo->clause;
2528 
2529  if (!rinfo->pseudoconstant &&
2530  qual_is_pushdown_safe(subquery, rti, rinfo, &safetyInfo))
2531  {
2532  /* Push it down */
2533  subquery_push_qual(subquery, rte, rti, clause);
2534  }
2535  else
2536  {
2537  /*
2538  * Since we can't push the qual down into the subquery, check
2539  * if it happens to reference a window function. If so then
2540  * it might be useful to use for the WindowAgg's runCondition.
2541  */
2542  if (!subquery->hasWindowFuncs ||
2543  check_and_push_window_quals(subquery, rte, rti, clause,
2544  &run_cond_attrs))
2545  {
2546  /*
2547  * subquery has no window funcs or the clause is not a
2548  * suitable window run condition qual or it is, but the
2549  * original must also be kept in the upper query.
2550  */
2551  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2552  }
2553  }
2554  }
2555  rel->baserestrictinfo = upperrestrictlist;
2556  /* We don't bother recomputing baserestrict_min_security */
2557  }
2558 
2559  pfree(safetyInfo.unsafeColumns);
2560 
2561  /*
2562  * The upper query might not use all the subquery's output columns; if
2563  * not, we can simplify. Pass the attributes that were pushed down into
2564  * WindowAgg run conditions to ensure we don't accidentally think those
2565  * are unused.
2566  */
2567  remove_unused_subquery_outputs(subquery, rel, run_cond_attrs);
2568 
2569  /*
2570  * We can safely pass the outer tuple_fraction down to the subquery if the
2571  * outer level has no joining, aggregation, or sorting to do. Otherwise
2572  * we'd better tell the subquery to plan for full retrieval. (XXX This
2573  * could probably be made more intelligent ...)
2574  */
2575  if (parse->hasAggs ||
2576  parse->groupClause ||
2577  parse->groupingSets ||
2578  root->hasHavingQual ||
2579  parse->distinctClause ||
2580  parse->sortClause ||
2581  has_multiple_baserels(root))
2582  tuple_fraction = 0.0; /* default case */
2583  else
2584  tuple_fraction = root->tuple_fraction;
2585 
2586  /* plan_params should not be in use in current query level */
2587  Assert(root->plan_params == NIL);
2588 
2589  /* Generate a subroot and Paths for the subquery */
2590  rel->subroot = subquery_planner(root->glob, subquery,
2591  root,
2592  false, tuple_fraction);
2593 
2594  /* Isolate the params needed by this specific subplan */
2595  rel->subplan_params = root->plan_params;
2596  root->plan_params = NIL;
2597 
2598  /*
2599  * It's possible that constraint exclusion proved the subquery empty. If
2600  * so, it's desirable to produce an unadorned dummy path so that we will
2601  * recognize appropriate optimizations at this query level.
2602  */
2603  sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2604 
2605  if (IS_DUMMY_REL(sub_final_rel))
2606  {
2608  return;
2609  }
2610 
2611  /*
2612  * Mark rel with estimated output rows, width, etc. Note that we have to
2613  * do this before generating outer-query paths, else cost_subqueryscan is
2614  * not happy.
2615  */
2616  set_subquery_size_estimates(root, rel);
2617 
2618  /*
2619  * Also detect whether the reltarget is trivial, so that we can pass that
2620  * info to cost_subqueryscan (rather than re-deriving it multiple times).
2621  * It's trivial if it fetches all the subplan output columns in order.
2622  */
2623  if (list_length(rel->reltarget->exprs) != list_length(subquery->targetList))
2624  trivial_pathtarget = false;
2625  else
2626  {
2627  trivial_pathtarget = true;
2628  foreach(lc, rel->reltarget->exprs)
2629  {
2630  Node *node = (Node *) lfirst(lc);
2631  Var *var;
2632 
2633  if (!IsA(node, Var))
2634  {
2635  trivial_pathtarget = false;
2636  break;
2637  }
2638  var = (Var *) node;
2639  if (var->varno != rti ||
2640  var->varattno != foreach_current_index(lc) + 1)
2641  {
2642  trivial_pathtarget = false;
2643  break;
2644  }
2645  }
2646  }
2647 
2648  /*
2649  * For each Path that subquery_planner produced, make a SubqueryScanPath
2650  * in the outer query.
2651  */
2652  foreach(lc, sub_final_rel->pathlist)
2653  {
2654  Path *subpath = (Path *) lfirst(lc);
2655  List *pathkeys;
2656 
2657  /* Convert subpath's pathkeys to outer representation */
2658  pathkeys = convert_subquery_pathkeys(root,
2659  rel,
2660  subpath->pathkeys,
2661  make_tlist_from_pathtarget(subpath->pathtarget));
2662 
2663  /* Generate outer path using this subpath */
2664  add_path(rel, (Path *)
2665  create_subqueryscan_path(root, rel, subpath,
2666  trivial_pathtarget,
2667  pathkeys, required_outer));
2668  }
2669 
2670  /* If outer rel allows parallelism, do same for partial paths. */
2671  if (rel->consider_parallel && bms_is_empty(required_outer))
2672  {
2673  /* If consider_parallel is false, there should be no partial paths. */
2674  Assert(sub_final_rel->consider_parallel ||
2675  sub_final_rel->partial_pathlist == NIL);
2676 
2677  /* Same for partial paths. */
2678  foreach(lc, sub_final_rel->partial_pathlist)
2679  {
2680  Path *subpath = (Path *) lfirst(lc);
2681  List *pathkeys;
2682 
2683  /* Convert subpath's pathkeys to outer representation */
2684  pathkeys = convert_subquery_pathkeys(root,
2685  rel,
2686  subpath->pathkeys,
2687  make_tlist_from_pathtarget(subpath->pathtarget));
2688 
2689  /* Generate outer path using this subpath */
2690  add_partial_path(rel, (Path *)
2691  create_subqueryscan_path(root, rel, subpath,
2692  trivial_pathtarget,
2693  pathkeys,
2694  required_outer));
2695  }
2696  }
2697 }
static bool qual_is_pushdown_safe(Query *subquery, Index rti, RestrictInfo *rinfo, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3816
static bool check_and_push_window_quals(Query *subquery, RangeTblEntry *rte, Index rti, Node *clause, Bitmapset **run_cond_attrs)
Definition: allpaths.c:2387
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel, Bitmapset *extra_used_attrs)
Definition: allpaths.c:4007
static bool has_multiple_baserels(PlannerInfo *root)
Definition: allpaths.c:2142
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:704
unsigned char bool
Definition: c.h:392
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5541
#define copyObject(obj)
Definition: nodes.h:233
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:865
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, bool trivial_pathtarget, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2008
@ UPPERREL_FINAL
Definition: pathnodes.h:79
#define foreach_current_index(cell)
Definition: pg_list.h:401
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:598
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1211
bool hasHavingQual
Definition: pathnodes.h:455
List * plan_params
Definition: pathnodes.h:217
bool security_barrier
Definition: parsenodes.h:1066
List * subplan_params
Definition: pathnodes.h:899
PlannerInfo * subroot
Definition: pathnodes.h:898
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:624

References add_partial_path(), add_path(), Assert(), RelOptInfo::baserestrictinfo, bms_is_empty(), 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, PlannerInfo::glob, has_multiple_baserels(), PlannerInfo::hasHavingQual, Query::hasWindowFuncs, if(), IS_DUMMY_REL, IsA, lappend(), RelOptInfo::lateral_relids, lfirst, list_length(), make_tlist_from_pathtarget(), NIL, palloc0(), parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, pfree(), PlannerInfo::plan_params, qual_is_pushdown_safe(), RelOptInfo::reltarget, remove_unused_subquery_outputs(), RangeTblEntry::security_barrier, 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, PlannerInfo::tuple_fraction, pushdown_safety_info::unsafeColumns, 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 2792 of file allpaths.c.

2793 {
2794  Relids required_outer;
2795 
2796  /*
2797  * We don't support pushing join clauses into the quals of a tablefunc
2798  * scan, but it could still have required parameterization due to LATERAL
2799  * refs in the function expression.
2800  */
2801  required_outer = rel->lateral_relids;
2802 
2803  /* Generate appropriate path */
2804  add_path(rel, create_tablefuncscan_path(root, rel,
2805  required_outer));
2806 }
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2064

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

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

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

References add_path(), PlannerInfo::all_baserels, bms_membership(), BMS_SINGLETON, create_material_path(), create_samplescan_path(), GetTsmRoutine(), RelOptInfo::lateral_relids, PlannerInfo::query_level, TsmRoutine::repeatable_across_scans, 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 819 of file allpaths.c.

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

References TableSampleClause::args, check_index_predicates(), GetTsmRoutine(), RelOptInfo::pages, 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 2772 of file allpaths.c.

2773 {
2774  Relids required_outer;
2775 
2776  /*
2777  * We don't support pushing join clauses into the quals of a values scan,
2778  * but it could still have required parameterization due to LATERAL refs
2779  * in the values expressions.
2780  */
2781  required_outer = rel->lateral_relids;
2782 
2783  /* Generate appropriate path */
2784  add_path(rel, create_valuesscan_path(root, rel, required_outer));
2785 }
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2090

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

Referenced by set_rel_pathlist().

◆ set_worktable_pathlist()

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

Definition at line 2943 of file allpaths.c.

2944 {
2945  Path *ctepath;
2946  PlannerInfo *cteroot;
2947  Index levelsup;
2948  Relids required_outer;
2949 
2950  /*
2951  * We need to find the non-recursive term's path, which is in the plan
2952  * level that's processing the recursive UNION, which is one level *below*
2953  * where the CTE comes from.
2954  */
2955  levelsup = rte->ctelevelsup;
2956  if (levelsup == 0) /* shouldn't happen */
2957  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2958  levelsup--;
2959  cteroot = root;
2960  while (levelsup-- > 0)
2961  {
2962  cteroot = cteroot->parent_root;
2963  if (!cteroot) /* shouldn't happen */
2964  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2965  }
2966  ctepath = cteroot->non_recursive_path;
2967  if (!ctepath) /* shouldn't happen */
2968  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
2969 
2970  /* Mark rel with estimated output rows, width, etc */
2971  set_cte_size_estimates(root, rel, ctepath->rows);
2972 
2973  /*
2974  * We don't support pushing join clauses into the quals of a worktable
2975  * scan, but it could still have required parameterization due to LATERAL
2976  * refs in its tlist. (I'm not sure this is actually possible given the
2977  * restrictions on recursive references, but it's easy enough to support.)
2978  */
2979  required_outer = rel->lateral_relids;
2980 
2981  /* Generate appropriate path */
2982  add_path(rel, create_worktablescan_path(root, rel, required_outer));
2983 }
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2193
struct Path * non_recursive_path
Definition: pathnodes.h:485

References add_path(), create_worktablescan_path(), RangeTblEntry::ctelevelsup, RangeTblEntry::ctename, elog(), ERROR, RelOptInfo::lateral_relids, PlannerInfo::non_recursive_path, 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 3379 of file allpaths.c.

3380 {
3381  int lev;
3382  RelOptInfo *rel;
3383 
3384  /*
3385  * This function cannot be invoked recursively within any one planning
3386  * problem, so join_rel_level[] can't be in use already.
3387  */
3388  Assert(root->join_rel_level == NULL);
3389 
3390  /*
3391  * We employ a simple "dynamic programming" algorithm: we first find all
3392  * ways to build joins of two jointree items, then all ways to build joins
3393  * of three items (from two-item joins and single items), then four-item
3394  * joins, and so on until we have considered all ways to join all the
3395  * items into one rel.
3396  *
3397  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3398  * set root->join_rel_level[1] to represent all the single-jointree-item
3399  * relations.
3400  */
3401  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3402 
3403  root->join_rel_level[1] = initial_rels;
3404 
3405  for (lev = 2; lev <= levels_needed; lev++)
3406  {
3407  ListCell *lc;
3408 
3409  /*
3410  * Determine all possible pairs of relations to be joined at this
3411  * level, and build paths for making each one from every available
3412  * pair of lower-level relations.
3413  */
3414  join_search_one_level(root, lev);
3415 
3416  /*
3417  * Run generate_partitionwise_join_paths() and
3418  * generate_useful_gather_paths() for each just-processed joinrel. We
3419  * could not do this earlier because both regular and partial paths
3420  * can get added to a particular joinrel at multiple times within
3421  * join_search_one_level.
3422  *
3423  * After that, we're done creating paths for the joinrel, so run
3424  * set_cheapest().
3425  */
3426  foreach(lc, root->join_rel_level[lev])
3427  {
3428  rel = (RelOptInfo *) lfirst(lc);
3429 
3430  /* Create paths for partitionwise joins. */
3432 
3433  /*
3434  * Except for the topmost scan/join rel, consider gathering
3435  * partial paths. We'll do the same for the topmost scan/join rel
3436  * once we know the final targetlist (see grouping_planner).
3437  */
3438  if (!bms_equal(rel->relids, root->all_baserels))
3439  generate_useful_gather_paths(root, rel, false);
3440 
3441  /* Find and save the cheapest paths for this rel */
3442  set_cheapest(rel);
3443 
3444 #ifdef OPTIMIZER_DEBUG
3445  debug_print_rel(root, rel);
3446 #endif
3447  }
3448  }
3449 
3450  /*
3451  * We should have a single rel at the final level.
3452  */
3453  if (root->join_rel_level[levels_needed] == NIL)
3454  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3455  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3456 
3457  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3458 
3459  root->join_rel_level = NULL;
3460 
3461  return rel;
3462 }
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:71

References PlannerInfo::all_baserels, Assert(), bms_equal(), elog(), ERROR, generate_partitionwise_join_paths(), generate_useful_gather_paths(), join_search_one_level(), lfirst, linitial, list_length(), NIL, palloc0(), RelOptInfo::relids, 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 3549 of file allpaths.c.

3551 {
3552  SetOperationStmt *topop;
3553 
3554  /* Check point 1 */
3555  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3556  return false;
3557 
3558  /* Check point 6 */
3559  if (subquery->groupClause && subquery->groupingSets)
3560  return false;
3561 
3562  /* Check points 3, 4, and 5 */
3563  if (subquery->distinctClause ||
3564  subquery->hasWindowFuncs ||
3565  subquery->hasTargetSRFs)
3566  safetyInfo->unsafeVolatile = true;
3567 
3568  /*
3569  * If we're at a leaf query, check for unsafe expressions in its target
3570  * list, and mark any unsafe ones in unsafeColumns[]. (Non-leaf nodes in
3571  * setop trees have only simple Vars in their tlists, so no need to check
3572  * them.)
3573  */
3574  if (subquery->setOperations == NULL)
3575  check_output_expressions(subquery, safetyInfo);
3576 
3577  /* Are we at top level, or looking at a setop component? */
3578  if (subquery == topquery)
3579  {
3580  /* Top level, so check any component queries */
3581  if (subquery->setOperations != NULL)
3582  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3583  safetyInfo))
3584  return false;
3585  }
3586  else
3587  {
3588  /* Setop component must not have more components (too weird) */
3589  if (subquery->setOperations != NULL)
3590  return false;
3591  /* Check whether setop component output types match top level */
3592  topop = castNode(SetOperationStmt, topquery->setOperations);
3593  Assert(topop);
3595  topop->colTypes,
3596  safetyInfo);
3597  }
3598  return true;
3599 }
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3740
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3672
Node * limitCount
Definition: parsenodes.h:184
List * groupClause
Definition: parsenodes.h:170
Node * limitOffset
Definition: parsenodes.h:183
List * groupingSets
Definition: parsenodes.h:173

References Assert(), castNode, check_output_expressions(), SetOperationStmt::colTypes, compare_tlist_datatypes(), Query::distinctClause, Query::groupClause, Query::groupingSets, Query::hasTargetSRFs, Query::hasWindowFuncs, 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 3908 of file allpaths.c.

3909 {
3910  if (subquery->setOperations != NULL)
3911  {
3912  /* Recurse to push it separately to each component query */
3913  recurse_push_qual(subquery->setOperations, subquery,
3914  rte, rti, qual);
3915  }
3916  else
3917  {
3918  /*
3919  * We need to replace Vars in the qual (which must refer to outputs of
3920  * the subquery) with copies of the subquery's targetlist expressions.
3921  * Note that at this point, any uplevel Vars in the qual should have
3922  * been replaced with Params, so they need no work.
3923  *
3924  * This step also ensures that when we are pushing into a setop tree,
3925  * each component query gets its own copy of the qual.
3926  */
3927  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3928  subquery->targetList,
3930  &subquery->hasSubLinks);
3931 
3932  /*
3933  * Now attach the qual to the proper place: normally WHERE, but if the
3934  * subquery uses grouping or aggregation, put it in HAVING (since the
3935  * qual really refers to the group-result rows).
3936  */
3937  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
3938  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
3939  else
3940  subquery->jointree->quals =
3941  make_and_qual(subquery->jointree->quals, qual);
3942 
3943  /*
3944  * We need not change the subquery's hasAggs or hasSubLinks flags,
3945  * since we can't be pushing down any aggregates that weren't there
3946  * before, and we don't push down subselects at all.
3947  */
3948  }
3949 }
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:689
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:1665
FromExpr * jointree
Definition: parsenodes.h:156
Node * havingQual
Definition: parsenodes.h:175
bool hasAggs
Definition: parsenodes.h:141
bool hasSubLinks
Definition: parsenodes.h:144

References Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, 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 3773 of file allpaths.c.

3774 {
3775  ListCell *lc;
3776 
3777  foreach(lc, query->windowClause)
3778  {
3779  WindowClause *wc = (WindowClause *) lfirst(lc);
3780 
3782  return false;
3783  }
3784  return true;
3785 }
List * partitionClause
Definition: parsenodes.h:1416

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

Referenced by make_rel_from_joinlist().

◆ geqo_threshold

int geqo_threshold

Definition at line 65 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

join_search_hook_type join_search_hook = NULL

Definition at line 73 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_parallel_index_scan_size

int min_parallel_index_scan_size

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

Referenced by set_rel_pathlist().