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 "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 =
2058  apath->first_partial_path);
2059  *special_subpaths = list_concat(*special_subpaths,
2060  new_special_subpaths);
2061  return;
2062  }
2063  }
2064  else if (IsA(path, MergeAppendPath))
2065  {
2066  MergeAppendPath *mpath = (MergeAppendPath *) path;
2067 
2068  *subpaths = list_concat(*subpaths, mpath->subpaths);
2069  return;
2070  }
2071 
2072  *subpaths = lappend(*subpaths, path);
2073 }
List * list_truncate(List *list, int new_size)
Definition: list.c:610
List * lappend(List *list, void *datum)
Definition: list.c:336
List * list_copy(const List *oldlist)
Definition: list.c:1532
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1551
List * list_concat(List *list1, const List *list2)
Definition: list.c:540
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
int first_partial_path
Definition: pathnodes.h:1466
List * subpaths
Definition: pathnodes.h:1464
Definition: pg_list.h:51
bool parallel_aware
Definition: pathnodes.h:1199

References AppendPath::first_partial_path, IsA, lappend(), list_concat(), list_copy(), list_copy_tail(), list_truncate(), 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  fls(list_length(live_childrels)));
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  fls(list_length(live_childrels)));
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:986
#define Max(x, y)
Definition: c.h:980
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:1005
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:290
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:1213
Bitmapset * Relids
Definition: pathnodes.h:28
@ PATHKEYS_EQUAL
Definition: paths.h:197
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define NIL
Definition: pg_list.h:65
#define list_make1(x1)
Definition: pg_list.h:206
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
#define linitial(l)
Definition: pg_list.h:174
int fls(int mask)
Definition: fls.c:55
List * pathkeys
Definition: pathnodes.h:1208
Cardinality rows
Definition: pathnodes.h:1204
int parallel_workers
Definition: pathnodes.h:1201
ParamPathInfo * param_info
Definition: pathnodes.h:1197
Cost total_cost
Definition: pathnodes.h:1206
bool consider_parallel
Definition: pathnodes.h:690
List * pathlist
Definition: pathnodes.h:696
struct Path * cheapest_total_path
Definition: pathnodes.h:700
List * partial_pathlist
Definition: pathnodes.h:698

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, fls(), 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, Path::param_info, RelOptInfo::partial_pathlist, AppendPath::path, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, RelOptInfo::pathlist, 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:2187
#define lsecond(l)
Definition: pg_list.h:179
static void * list_nth(const List *list, int n)
Definition: pg_list.h:278
List * args
Definition: primnodes.h:557
List * targetList
Definition: parsenodes.h:155
Expr * expr
Definition: primnodes.h:1716
AttrNumber resno
Definition: primnodes.h:1717
Definition: primnodes.h:196
AttrNumber varattno
Definition: primnodes.h:200

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

3640 {
3641  ListCell *lc;
3642 
3643  foreach(lc, subquery->targetList)
3644  {
3645  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3646 
3647  if (tle->resjunk)
3648  continue; /* ignore resjunk columns */
3649 
3650  /* We need not check further if output col is already known unsafe */
3651  if (safetyInfo->unsafeColumns[tle->resno])
3652  continue;
3653 
3654  /* Functions returning sets are unsafe (point 1) */
3655  if (subquery->hasTargetSRFs &&
3656  expression_returns_set((Node *) tle->expr))
3657  {
3658  safetyInfo->unsafeColumns[tle->resno] = true;
3659  continue;
3660  }
3661 
3662  /* Volatile functions are unsafe (point 2) */
3663  if (contain_volatile_functions((Node *) tle->expr))
3664  {
3665  safetyInfo->unsafeColumns[tle->resno] = true;
3666  continue;
3667  }
3668 
3669  /* If subquery uses DISTINCT ON, check point 3 */
3670  if (subquery->hasDistinctOn &&
3671  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3672  {
3673  /* non-DISTINCT column, so mark it unsafe */
3674  safetyInfo->unsafeColumns[tle->resno] = true;
3675  continue;
3676  }
3677 
3678  /* If subquery uses window functions, check point 4 */
3679  if (subquery->hasWindowFuncs &&
3680  !targetIsInAllPartitionLists(tle, subquery))
3681  {
3682  /* not present in all PARTITION BY clauses, so mark it unsafe */
3683  safetyInfo->unsafeColumns[tle->resno] = true;
3684  continue;
3685  }
3686  }
3687 }
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:3740
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:496
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:736
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define InvalidOid
Definition: postgres_ext.h:36
Definition: nodes.h:574
bool hasWindowFuncs
Definition: parsenodes.h:135
bool hasTargetSRFs
Definition: parsenodes.h:136
bool hasDistinctOn
Definition: parsenodes.h:138
List * distinctClause
Definition: parsenodes.h:172
bool resjunk
Definition: primnodes.h:1723
bool * unsafeColumns
Definition: allpaths.c:57

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

3709 {
3710  ListCell *l;
3711  ListCell *colType = list_head(colTypes);
3712 
3713  foreach(l, tlist)
3714  {
3715  TargetEntry *tle = (TargetEntry *) lfirst(l);
3716 
3717  if (tle->resjunk)
3718  continue; /* ignore resjunk columns */
3719  if (colType == NULL)
3720  elog(ERROR, "wrong number of tlist entries");
3721  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3722  safetyInfo->unsafeColumns[tle->resno] = true;
3723  colType = lnext(colTypes, colType);
3724  }
3725  if (colType != NULL)
3726  elog(ERROR, "wrong number of tlist entries");
3727 }
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
#define lfirst_oid(lc)
Definition: pg_list.h:171

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

4124 {
4125  int parallel_workers = 0;
4126 
4127  /*
4128  * If the user has set the parallel_workers reloption, use that; otherwise
4129  * select a default number of workers.
4130  */
4131  if (rel->rel_parallel_workers != -1)
4132  parallel_workers = rel->rel_parallel_workers;
4133  else
4134  {
4135  /*
4136  * If the number of pages being scanned is insufficient to justify a
4137  * parallel scan, just return zero ... unless it's an inheritance
4138  * child. In that case, we want to generate a parallel path here
4139  * anyway. It might not be worthwhile just for this relation, but
4140  * when combined with all of its inheritance siblings it may well pay
4141  * off.
4142  */
4143  if (rel->reloptkind == RELOPT_BASEREL &&
4144  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4145  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4146  return 0;
4147 
4148  if (heap_pages >= 0)
4149  {
4150  int heap_parallel_threshold;
4151  int heap_parallel_workers = 1;
4152 
4153  /*
4154  * Select the number of workers based on the log of the size of
4155  * the relation. This probably needs to be a good deal more
4156  * sophisticated, but we need something here for now. Note that
4157  * the upper limit of the min_parallel_table_scan_size GUC is
4158  * chosen to prevent overflow here.
4159  */
4160  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4161  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4162  {
4163  heap_parallel_workers++;
4164  heap_parallel_threshold *= 3;
4165  if (heap_parallel_threshold > INT_MAX / 3)
4166  break; /* avoid overflow */
4167  }
4168 
4169  parallel_workers = heap_parallel_workers;
4170  }
4171 
4172  if (index_pages >= 0)
4173  {
4174  int index_parallel_workers = 1;
4175  int index_parallel_threshold;
4176 
4177  /* same calculation as for heap_pages above */
4178  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4179  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4180  {
4181  index_parallel_workers++;
4182  index_parallel_threshold *= 3;
4183  if (index_parallel_threshold > INT_MAX / 3)
4184  break; /* avoid overflow */
4185  }
4186 
4187  if (parallel_workers > 0)
4188  parallel_workers = Min(parallel_workers, index_parallel_workers);
4189  else
4190  parallel_workers = index_parallel_workers;
4191  }
4192  }
4193 
4194  /* In no case use more than caller supplied maximum number of workers */
4195  parallel_workers = Min(parallel_workers, max_workers);
4196 
4197  return parallel_workers;
4198 }
int min_parallel_index_scan_size
Definition: allpaths.c:66
int min_parallel_table_scan_size
Definition: allpaths.c:65
uint32 BlockNumber
Definition: block.h:31
@ RELOPT_BASEREL
Definition: pathnodes.h:642
RelOptKind reloptkind
Definition: pathnodes.h:679
int rel_parallel_workers
Definition: pathnodes.h:728

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

4088 {
4089  int parallel_workers;
4090  double pages_fetched;
4091 
4092  /* Compute heap pages for bitmap heap scan */
4093  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4094  NULL, NULL);
4095 
4096  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4098 
4099  if (parallel_workers <= 0)
4100  return;
4101 
4102  add_partial_path(rel, (Path *) create_bitmap_heap_path(root, rel,
4103  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4104 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4122
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:6442
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:707

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:721

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

2191 {
2192  Oid prosupport;
2193  Expr *otherexpr;
2196  WindowClause *wclause;
2197  List *opinfos;
2198  OpExpr *runopexpr;
2199  Oid runoperator;
2200  ListCell *lc;
2201 
2202  *keep_original = true;
2203 
2204  while (IsA(wfunc, RelabelType))
2205  wfunc = (WindowFunc *) ((RelabelType *) wfunc)->arg;
2206 
2207  /* we can only work with window functions */
2208  if (!IsA(wfunc, WindowFunc))
2209  return false;
2210 
2211  prosupport = get_func_support(wfunc->winfnoid);
2212 
2213  /* Check if there's a support function for 'wfunc' */
2214  if (!OidIsValid(prosupport))
2215  return false;
2216 
2217  /* get the Expr from the other side of the OpExpr */
2218  if (wfunc_left)
2219  otherexpr = lsecond(opexpr->args);
2220  else
2221  otherexpr = linitial(opexpr->args);
2222 
2223  /*
2224  * The value being compared must not change during the evaluation of the
2225  * window partition.
2226  */
2227  if (!is_pseudo_constant_clause((Node *) otherexpr))
2228  return false;
2229 
2230  /* find the window clause belonging to the window function */
2231  wclause = (WindowClause *) list_nth(subquery->windowClause,
2232  wfunc->winref - 1);
2233 
2235  req.window_func = wfunc;
2236  req.window_clause = wclause;
2237 
2238  /* call the support function */
2240  DatumGetPointer(OidFunctionCall1(prosupport,
2241  PointerGetDatum(&req)));
2242 
2243  /*
2244  * Nothing to do if the function is neither monotonically increasing nor
2245  * monotonically decreasing.
2246  */
2247  if (res == NULL || res->monotonic == MONOTONICFUNC_NONE)
2248  return false;
2249 
2250  runopexpr = NULL;
2251  runoperator = InvalidOid;
2252  opinfos = get_op_btree_interpretation(opexpr->opno);
2253 
2254  foreach(lc, opinfos)
2255  {
2257  int strategy = opinfo->strategy;
2258 
2259  /* handle < / <= */
2260  if (strategy == BTLessStrategyNumber ||
2261  strategy == BTLessEqualStrategyNumber)
2262  {
2263  /*
2264  * < / <= is supported for monotonically increasing functions in
2265  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2266  * for monotonically decreasing functions.
2267  */
2268  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)) ||
2269  (!wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)))
2270  {
2271  *keep_original = false;
2272  runopexpr = opexpr;
2273  runoperator = opexpr->opno;
2274  }
2275  break;
2276  }
2277  /* handle > / >= */
2278  else if (strategy == BTGreaterStrategyNumber ||
2279  strategy == BTGreaterEqualStrategyNumber)
2280  {
2281  /*
2282  * > / >= is supported for monotonically decreasing functions in
2283  * the form <wfunc> op <pseudoconst> and <pseudoconst> op <wfunc>
2284  * for monotonically increasing functions.
2285  */
2286  if ((wfunc_left && (res->monotonic & MONOTONICFUNC_DECREASING)) ||
2287  (!wfunc_left && (res->monotonic & MONOTONICFUNC_INCREASING)))
2288  {
2289  *keep_original = false;
2290  runopexpr = opexpr;
2291  runoperator = opexpr->opno;
2292  }
2293  break;
2294  }
2295  /* handle = */
2296  else if (strategy == BTEqualStrategyNumber)
2297  {
2298  int16 newstrategy;
2299 
2300  /*
2301  * When both monotonically increasing and decreasing then the
2302  * return value of the window function will be the same each time.
2303  * We can simply use 'opexpr' as the run condition without
2304  * modifying it.
2305  */
2306  if ((res->monotonic & MONOTONICFUNC_BOTH) == MONOTONICFUNC_BOTH)
2307  {
2308  *keep_original = false;
2309  runopexpr = opexpr;
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:738
signed short int16
Definition: c.h:428
#define OidIsValid(objectId)
Definition: c.h:710
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:1986
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:669
RegProcedure get_func_support(Oid funcid)
Definition: lsyscache.c:1839
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
List * get_op_btree_interpretation(Oid opno)
Definition: lsyscache.c:599
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: makefuncs.c:611
@ T_SupportRequestWFuncMonotonic
Definition: nodes.h:564
void * arg
@ MONOTONICFUNC_NONE
Definition: plannodes.h:1343
@ MONOTONICFUNC_DECREASING
Definition: plannodes.h:1345
@ MONOTONICFUNC_INCREASING
Definition: plannodes.h:1344
@ MONOTONICFUNC_BOTH
Definition: plannodes.h:1346
#define DatumGetPointer(X)
Definition: postgres.h:593
#define PointerGetDatum(X)
Definition: postgres.h:600
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:554
Oid opno
Definition: primnodes.h:551
Oid opcollid
Definition: primnodes.h:555
Oid inputcollid
Definition: primnodes.h:556
Oid opresulttype
Definition: primnodes.h:553
List * windowClause
Definition: parsenodes.h:170
struct WindowClause * window_clause
Definition: supportnodes.h:296
List * runCondition
Definition: parsenodes.h:1406
Index winref
Definition: primnodes.h:401
Oid winfnoid
Definition: primnodes.h:395
#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, T_SupportRequestWFuncMonotonic, 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 2969 of file allpaths.c.

2970 {
2971  Path *cheapest_partial_path;
2972  Path *simple_gather_path;
2973  ListCell *lc;
2974  double rows;
2975  double *rowsp = NULL;
2976 
2977  /* If there are no partial paths, there's nothing to do here. */
2978  if (rel->partial_pathlist == NIL)
2979  return;
2980 
2981  /* Should we override the rel's rowcount estimate? */
2982  if (override_rows)
2983  rowsp = &rows;
2984 
2985  /*
2986  * The output of Gather is always unsorted, so there's only one partial
2987  * path of interest: the cheapest one. That will be the one at the front
2988  * of partial_pathlist because of the way add_partial_path works.
2989  */
2990  cheapest_partial_path = linitial(rel->partial_pathlist);
2991  rows =
2992  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
2993  simple_gather_path = (Path *)
2994  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
2995  NULL, rowsp);
2996  add_path(rel, simple_gather_path);
2997 
2998  /*
2999  * For each useful ordering, we can consider an order-preserving Gather
3000  * Merge.
3001  */
3002  foreach(lc, rel->partial_pathlist)
3003  {
3004  Path *subpath = (Path *) lfirst(lc);
3005  GatherMergePath *path;
3006 
3007  if (subpath->pathkeys == NIL)
3008  continue;
3009 
3010  rows = subpath->rows * subpath->parallel_workers;
3011  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
3012  subpath->pathkeys, NULL, rowsp);
3013  add_path(rel, &path->path);
3014  }
3015 }
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1861
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1952
struct PathTarget * reltarget
Definition: pathnodes.h:693

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) &&
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:2083
List * lcons(void *datum, List *list)
Definition: list.c:474
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2863
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:927
Path * get_cheapest_fractional_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, double fraction)
Definition: pathkeys.c:972
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:329
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:1222
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1404
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:655
@ TOTAL_COST
Definition: pathnodes.h:36
@ STARTUP_COST
Definition: pathnodes.h:36
@ BackwardScanDirection
Definition: sdir.h:24
@ ForwardScanDirection
Definition: sdir.h:26
Selectivity tuple_fraction
Definition: pathnodes.h:341
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:765
PartitionScheme part_scheme
Definition: pathnodes.h:761
Bitmapset * live_parts
Definition: pathnodes.h:771

References accumulate_append_subpath(), add_path(), Assert(), BackwardScanDirection, RelOptInfo::boundinfo, 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, Path::param_info, RelOptInfo::part_scheme, 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 4210 of file allpaths.c.

4211 {
4212  List *live_children = NIL;
4213  int cnt_parts;
4214  int num_parts;
4215  RelOptInfo **part_rels;
4216 
4217  /* Handle only join relations here. */
4218  if (!IS_JOIN_REL(rel))
4219  return;
4220 
4221  /* We've nothing to do if the relation is not partitioned. */
4222  if (!IS_PARTITIONED_REL(rel))
4223  return;
4224 
4225  /* The relation should have consider_partitionwise_join set. */
4227 
4228  /* Guard against stack overflow due to overly deep partition hierarchy. */
4230 
4231  num_parts = rel->nparts;
4232  part_rels = rel->part_rels;
4233 
4234  /* Collect non-dummy child-joins. */
4235  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4236  {
4237  RelOptInfo *child_rel = part_rels[cnt_parts];
4238 
4239  /* If it's been pruned entirely, it's certainly dummy. */
4240  if (child_rel == NULL)
4241  continue;
4242 
4243  /* Add partitionwise join paths for partitioned child-joins. */
4244  generate_partitionwise_join_paths(root, child_rel);
4245 
4246  set_cheapest(child_rel);
4247 
4248  /* Dummy children will not be scanned, so ignore those. */
4249  if (IS_DUMMY_REL(child_rel))
4250  continue;
4251 
4252 #ifdef OPTIMIZER_DEBUG
4253  debug_print_rel(root, child_rel);
4254 #endif
4255 
4256  live_children = lappend(live_children, child_rel);
4257  }
4258 
4259  /* If all child-joins are dummy, parent join is also dummy. */
4260  if (!live_children)
4261  {
4262  mark_dummy_rel(rel);
4263  return;
4264  }
4265 
4266  /* Build additional paths for this rel from child-join paths. */
4267  add_paths_to_append_rel(root, rel, live_children);
4268  list_free(live_children);
4269 }
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:4210
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:1505
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1478
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:660
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:787
void check_stack_depth(void)
Definition: postgres.c:3500
int nparts
Definition: pathnodes.h:762
struct RelOptInfo ** part_rels
Definition: pathnodes.h:769
bool consider_partitionwise_join
Definition: pathnodes.h:755

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::part_rels, 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 3107 of file allpaths.c.

3108 {
3109  ListCell *lc;
3110  double rows;
3111  double *rowsp = NULL;
3112  List *useful_pathkeys_list = NIL;
3113  Path *cheapest_partial_path = NULL;
3114 
3115  /* If there are no partial paths, there's nothing to do here. */
3116  if (rel->partial_pathlist == NIL)
3117  return;
3118 
3119  /* Should we override the rel's rowcount estimate? */
3120  if (override_rows)
3121  rowsp = &rows;
3122 
3123  /* generate the regular gather (merge) paths */
3124  generate_gather_paths(root, rel, override_rows);
3125 
3126  /* consider incremental sort for interesting orderings */
3127  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3128 
3129  /* used for explicit (full) sort paths */
3130  cheapest_partial_path = linitial(rel->partial_pathlist);
3131 
3132  /*
3133  * Consider sorted paths for each interesting ordering. We generate both
3134  * incremental and full sort.
3135  */
3136  foreach(lc, useful_pathkeys_list)
3137  {
3138  List *useful_pathkeys = lfirst(lc);
3139  ListCell *lc2;
3140  bool is_sorted;
3141  int presorted_keys;
3142 
3143  foreach(lc2, rel->partial_pathlist)
3144  {
3145  Path *subpath = (Path *) lfirst(lc2);
3146  GatherMergePath *path;
3147 
3148  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3149  subpath->pathkeys,
3150  &presorted_keys);
3151 
3152  /*
3153  * We don't need to consider the case where a subpath is already
3154  * fully sorted because generate_gather_paths already creates a
3155  * gather merge path for every subpath that has pathkeys present.
3156  *
3157  * But since the subpath is already sorted, we know we don't need
3158  * to consider adding a sort (full or incremental) on top of it,
3159  * so we can continue here.
3160  */
3161  if (is_sorted)
3162  continue;
3163 
3164  /*
3165  * Consider regular sort for the cheapest partial path (for each
3166  * useful pathkeys). We know the path is not sorted, because we'd
3167  * not get here otherwise.
3168  *
3169  * This is not redundant with the gather paths created in
3170  * generate_gather_paths, because that doesn't generate ordered
3171  * output. Here we add an explicit sort to match the useful
3172  * ordering.
3173  */
3174  if (cheapest_partial_path == subpath)
3175  {
3176  Path *tmp;
3177 
3178  tmp = (Path *) create_sort_path(root,
3179  rel,
3180  subpath,
3181  useful_pathkeys,
3182  -1.0);
3183 
3184  rows = tmp->rows * tmp->parallel_workers;
3185 
3186  path = create_gather_merge_path(root, rel,
3187  tmp,
3188  rel->reltarget,
3189  tmp->pathkeys,
3190  NULL,
3191  rowsp);
3192 
3193  add_path(rel, &path->path);
3194 
3195  /* Fall through */
3196  }
3197 
3198  /*
3199  * Consider incremental sort, but only when the subpath is already
3200  * partially sorted on a pathkey prefix.
3201  */
3202  if (enable_incremental_sort && presorted_keys > 0)
3203  {
3204  Path *tmp;
3205 
3206  /*
3207  * We should have already excluded pathkeys of length 1
3208  * because then presorted_keys > 0 would imply is_sorted was
3209  * true.
3210  */
3211  Assert(list_length(useful_pathkeys) != 1);
3212 
3213  tmp = (Path *) create_incremental_sort_path(root,
3214  rel,
3215  subpath,
3216  useful_pathkeys,
3217  presorted_keys,
3218  -1);
3219 
3220  path = create_gather_merge_path(root, rel,
3221  tmp,
3222  rel->reltarget,
3223  tmp->pathkeys,
3224  NULL,
3225  rowsp);
3226 
3227  add_path(rel, &path->path);
3228  }
3229  }
3230  }
3231 }
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2969
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:3039
bool enable_incremental_sort
Definition: costsize.c:141
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:866
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2942
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2893

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:315
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3859
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 2083 of file allpaths.c.

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

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

3041 {
3042  List *useful_pathkeys_list = NIL;
3043 
3044  /*
3045  * Considering query_pathkeys is always worth it, because it might allow
3046  * us to avoid a total sort when we have a partially presorted path
3047  * available or to push the total sort into the parallel portion of the
3048  * query.
3049  */
3050  if (root->query_pathkeys)
3051  {
3052  ListCell *lc;
3053  int npathkeys = 0; /* useful pathkeys */
3054 
3055  foreach(lc, root->query_pathkeys)
3056  {
3057  PathKey *pathkey = (PathKey *) lfirst(lc);
3058  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
3059 
3060  /*
3061  * We can only build a sort for pathkeys that contain a
3062  * safe-to-compute-early EC member computable from the current
3063  * relation's reltarget, so ignore the remainder of the list as
3064  * soon as we find a pathkey without such a member.
3065  *
3066  * It's still worthwhile to return any prefix of the pathkeys list
3067  * that meets this requirement, as we may be able to do an
3068  * incremental sort.
3069  *
3070  * If requested, ensure the sort expression is parallel-safe too.
3071  */
3072  if (!relation_can_be_sorted_early(root, rel, pathkey_ec,
3073  require_parallel_safe))
3074  break;
3075 
3076  npathkeys++;
3077  }
3078 
3079  /*
3080  * The whole query_pathkeys list matches, so append it directly, to
3081  * allow comparing pathkeys easily by comparing list pointer. If we
3082  * have to truncate the pathkeys, we gotta do a copy though.
3083  */
3084  if (npathkeys == list_length(root->query_pathkeys))
3085  useful_pathkeys_list = lappend(useful_pathkeys_list,
3086  root->query_pathkeys);
3087  else if (npathkeys > 0)
3088  useful_pathkeys_list = lappend(useful_pathkeys_list,
3090  npathkeys));
3091  }
3092 
3093  return useful_pathkeys_list;
3094 }
bool relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
Definition: equivclass.c:959
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1068
List * query_pathkeys
Definition: pathnodes.h:295

References lappend(), lfirst, list_copy(), list_length(), list_truncate(), NIL, PathKey::pk_eclass, 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 2143 of file allpaths.c.

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

References RELOPT_BASEREL, RelOptInfo::reloptkind, PlannerInfo::simple_rel_array, 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 155 of file allpaths.c.

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

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

3242 {
3243  int levels_needed;
3244  List *initial_rels;
3245  ListCell *jl;
3246 
3247  /*
3248  * Count the number of child joinlist nodes. This is the depth of the
3249  * dynamic-programming algorithm we must employ to consider all ways of
3250  * joining the child nodes.
3251  */
3252  levels_needed = list_length(joinlist);
3253 
3254  if (levels_needed <= 0)
3255  return NULL; /* nothing to do? */
3256 
3257  /*
3258  * Construct a list of rels corresponding to the child joinlist nodes.
3259  * This may contain both base rels and rels constructed according to
3260  * sub-joinlists.
3261  */
3262  initial_rels = NIL;
3263  foreach(jl, joinlist)
3264  {
3265  Node *jlnode = (Node *) lfirst(jl);
3266  RelOptInfo *thisrel;
3267 
3268  if (IsA(jlnode, RangeTblRef))
3269  {
3270  int varno = ((RangeTblRef *) jlnode)->rtindex;
3271 
3272  thisrel = find_base_rel(root, varno);
3273  }
3274  else if (IsA(jlnode, List))
3275  {
3276  /* Recurse to handle subproblem */
3277  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
3278  }
3279  else
3280  {
3281  elog(ERROR, "unrecognized joinlist node type: %d",
3282  (int) nodeTag(jlnode));
3283  thisrel = NULL; /* keep compiler quiet */
3284  }
3285 
3286  initial_rels = lappend(initial_rels, thisrel);
3287  }
3288 
3289  if (levels_needed == 1)
3290  {
3291  /*
3292  * Single joinlist node, so we're done.
3293  */
3294  return (RelOptInfo *) linitial(initial_rels);
3295  }
3296  else
3297  {
3298  /*
3299  * Consider the different orders in which we could join the rels,
3300  * using a plugin, GEQO, or the regular join search code.
3301  *
3302  * We put the initial_rels list into a PlannerInfo field because
3303  * has_legal_joinclause() needs to look at it (ugly :-().
3304  */
3305  root->initial_rels = initial_rels;
3306 
3307  if (join_search_hook)
3308  return (*join_search_hook) (root, levels_needed, initial_rels);
3309  else if (enable_geqo && levels_needed >= geqo_threshold)
3310  return geqo(root, levels_needed, initial_rels);
3311  else
3312  return standard_join_search(root, levels_needed, initial_rels);
3313  }
3314 }
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3346
int geqo_threshold
Definition: allpaths.c:64
join_search_hook_type join_search_hook
Definition: allpaths.c:72
bool enable_geqo
Definition: allpaths.c:63
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:67
#define nodeTag(nodeptr)
Definition: nodes.h:578
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:375
List * initial_rels
Definition: pathnodes.h:305

References elog, enable_geqo, ERROR, find_base_rel(), geqo(), geqo_threshold, PlannerInfo::initial_rels, 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 3783 of file allpaths.c.

3785 {
3786  bool safe = true;
3787  Node *qual = (Node *) rinfo->clause;
3788  List *vars;
3789  ListCell *vl;
3790 
3791  /* Refuse subselects (point 1) */
3792  if (contain_subplans(qual))
3793  return false;
3794 
3795  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3796  if (safetyInfo->unsafeVolatile &&
3797  contain_volatile_functions((Node *) rinfo))
3798  return false;
3799 
3800  /* Refuse leaky quals if told to (point 3) */
3801  if (safetyInfo->unsafeLeaky &&
3802  contain_leaked_vars(qual))
3803  return false;
3804 
3805  /*
3806  * It would be unsafe to push down window function calls, but at least for
3807  * the moment we could never see any in a qual anyhow. (The same applies
3808  * to aggregates, which we check for in pull_var_clause below.)
3809  */
3811 
3812  /*
3813  * Examine all Vars used in clause. Since it's a restriction clause, all
3814  * such Vars must refer to subselect output columns ... unless this is
3815  * part of a LATERAL subquery, in which case there could be lateral
3816  * references.
3817  */
3819  foreach(vl, vars)
3820  {
3821  Var *var = (Var *) lfirst(vl);
3822 
3823  /*
3824  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3825  * It's not clear whether a PHV could safely be pushed down, and even
3826  * less clear whether such a situation could arise in any cases of
3827  * practical interest anyway. So for the moment, just refuse to push
3828  * down.
3829  */
3830  if (!IsA(var, Var))
3831  {
3832  safe = false;
3833  break;
3834  }
3835 
3836  /*
3837  * Punt if we find any lateral references. It would be safe to push
3838  * these down, but we'd have to convert them into outer references,
3839  * which subquery_push_qual lacks the infrastructure to do. The case
3840  * arises so seldom that it doesn't seem worth working hard on.
3841  */
3842  if (var->varno != rti)
3843  {
3844  safe = false;
3845  break;
3846  }
3847 
3848  /* Subqueries have no system columns */
3849  Assert(var->varattno >= 0);
3850 
3851  /* Check point 4 */
3852  if (var->varattno == 0)
3853  {
3854  safe = false;
3855  break;
3856  }
3857 
3858  /* Check point 5 */
3859  if (safetyInfo->unsafeColumns[var->varattno])
3860  {
3861  safe = false;
3862  break;
3863  }
3864  }
3865 
3866  list_free(vars);
3867 
3868  return safe;
3869 }
bool contain_window_function(Node *clause)
Definition: clauses.c:217
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1205
bool contain_subplans(Node *clause)
Definition: clauses.c:333
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:192
Expr * clause
Definition: pathnodes.h:2075
int varno
Definition: primnodes.h:198
Definition: regcomp.c:238
List * pull_var_clause(Node *node, int flags)
Definition: var.c:604

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

3924 {
3925  if (IsA(setOp, RangeTblRef))
3926  {
3927  RangeTblRef *rtr = (RangeTblRef *) setOp;
3928  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
3929  Query *subquery = subrte->subquery;
3930 
3931  Assert(subquery != NULL);
3932  subquery_push_qual(subquery, rte, rti, qual);
3933  }
3934  else if (IsA(setOp, SetOperationStmt))
3935  {
3936  SetOperationStmt *op = (SetOperationStmt *) setOp;
3937 
3938  recurse_push_qual(op->larg, topquery, rte, rti, qual);
3939  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
3940  }
3941  else
3942  {
3943  elog(ERROR, "unrecognized node type: %d",
3944  (int) nodeTag(setOp));
3945  }
3946 }
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3875
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3922
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * rtable
Definition: parsenodes.h:148
Query * subquery
Definition: parsenodes.h:1050

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

3574 {
3575  if (IsA(setOp, RangeTblRef))
3576  {
3577  RangeTblRef *rtr = (RangeTblRef *) setOp;
3578  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3579  Query *subquery = rte->subquery;
3580 
3581  Assert(subquery != NULL);
3582  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3583  }
3584  else if (IsA(setOp, SetOperationStmt))
3585  {
3586  SetOperationStmt *op = (SetOperationStmt *) setOp;
3587 
3588  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3589  if (op->op == SETOP_EXCEPT)
3590  return false;
3591  /* Else recurse */
3592  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3593  return false;
3594  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3595  return false;
3596  }
3597  else
3598  {
3599  elog(ERROR, "unrecognized node type: %d",
3600  (int) nodeTag(setOp));
3601  }
3602  return true;
3603 }
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3516
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3572
@ SETOP_EXCEPT
Definition: parsenodes.h:1993
SetOperation op
Definition: parsenodes.h:2068

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

3976 {
3977  Bitmapset *attrs_used;
3978  ListCell *lc;
3979 
3980  /*
3981  * Just point directly to extra_used_attrs. No need to bms_copy as none of
3982  * the current callers use the Bitmapset after calling this function.
3983  */
3984  attrs_used = extra_used_attrs;
3985 
3986  /*
3987  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
3988  * could update all the child SELECTs' tlists, but it seems not worth the
3989  * trouble presently.
3990  */
3991  if (subquery->setOperations)
3992  return;
3993 
3994  /*
3995  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
3996  * time: all its output columns must be used in the distinctClause.
3997  */
3998  if (subquery->distinctClause && !subquery->hasDistinctOn)
3999  return;
4000 
4001  /*
4002  * Collect a bitmap of all the output column numbers used by the upper
4003  * query.
4004  *
4005  * Add all the attributes needed for joins or final output. Note: we must
4006  * look at rel's targetlist, not the attr_needed data, because attr_needed
4007  * isn't computed for inheritance child rels, cf set_append_rel_size().
4008  * (XXX might be worth changing that sometime.)
4009  */
4010  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
4011 
4012  /* Add all the attributes used by un-pushed-down restriction clauses. */
4013  foreach(lc, rel->baserestrictinfo)
4014  {
4015  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4016 
4017  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
4018  }
4019 
4020  /*
4021  * If there's a whole-row reference to the subquery, we can't remove
4022  * anything.
4023  */
4025  return;
4026 
4027  /*
4028  * Run through the tlist and zap entries we don't need. It's okay to
4029  * modify the tlist items in-place because set_subquery_pathlist made a
4030  * copy of the subquery.
4031  */
4032  foreach(lc, subquery->targetList)
4033  {
4034  TargetEntry *tle = (TargetEntry *) lfirst(lc);
4035  Node *texpr = (Node *) tle->expr;
4036 
4037  /*
4038  * If it has a sortgroupref number, it's used in some sort/group
4039  * clause so we'd better not remove it. Also, don't remove any
4040  * resjunk columns, since their reason for being has nothing to do
4041  * with anybody reading the subquery's output. (It's likely that
4042  * resjunk columns in a sub-SELECT would always have ressortgroupref
4043  * set, but even if they don't, it seems imprudent to remove them.)
4044  */
4045  if (tle->ressortgroupref || tle->resjunk)
4046  continue;
4047 
4048  /*
4049  * If it's used by the upper query, we can't remove it.
4050  */
4052  attrs_used))
4053  continue;
4054 
4055  /*
4056  * If it contains a set-returning function, we can't remove it since
4057  * that could change the number of rows returned by the subquery.
4058  */
4059  if (subquery->hasTargetSRFs &&
4060  expression_returns_set(texpr))
4061  continue;
4062 
4063  /*
4064  * If it contains volatile functions, we daren't remove it for fear
4065  * that the user is expecting their side-effects to happen.
4066  */
4067  if (contain_volatile_functions(texpr))
4068  continue;
4069 
4070  /*
4071  * OK, we don't need it. Replace the expression with a NULL constant.
4072  * Preserve the exposed type of the expression, in case something
4073  * looks at the rowtype of the subquery's result.
4074  */
4075  tle->expr = (Expr *) makeNullConst(exprType(texpr),
4076  exprTypmod(texpr),
4077  exprCollation(texpr));
4078  }
4079 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:338
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:286
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:788
List * exprs
Definition: pathnodes.h:1122
Node * setOperations
Definition: parsenodes.h:182
List * baserestrictinfo
Definition: pathnodes.h:746
Index ressortgroupref
Definition: primnodes.h:1719
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:288

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:473
Index child_relid
Definition: pathnodes.h:2327
Index parent_relid
Definition: pathnodes.h:2326
List * append_rel_list
Definition: pathnodes.h:285
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:194

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, set_rel_pathlist(), PlannerInfo::simple_rel_array, and PlannerInfo::simple_rte_array.

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:2117
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:364
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:429
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:2550
int i
Definition: isn.c:73
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2535
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc0(Size size)
Definition: mcxt.c:1099
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:2484
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:644
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1476
bool parallelModeOK
Definition: pathnodes.h:126
PlannerGlobal * glob
Definition: pathnodes.h:164
List * joininfo
Definition: pathnodes.h:750
int32 * attr_widths
Definition: pathnodes.h:716
Relids * attr_needed
Definition: pathnodes.h:715
Cardinality tuples
Definition: pathnodes.h:722
bool has_eclass_joins
Definition: pathnodes.h:752
AttrNumber max_attr
Definition: pathnodes.h:714
Cardinality rows
Definition: pathnodes.h:685
AttrNumber min_attr
Definition: pathnodes.h:713

References add_child_rel_equivalences(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert(), RelOptInfo::attr_needed, RelOptInfo::attr_widths, 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(), PlannerInfo::simple_rte_array, 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 251 of file allpaths.c.

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

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

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

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

Referenced by make_one_rel().

◆ set_base_rel_sizes()

static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 294 of file allpaths.c.

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

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

Referenced by make_one_rel().

◆ set_cte_pathlist()

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

Definition at line 2783 of file allpaths.c.

2784 {
2785  Plan *cteplan;
2786  PlannerInfo *cteroot;
2787  Index levelsup;
2788  int ndx;
2789  ListCell *lc;
2790  int plan_id;
2791  Relids required_outer;
2792 
2793  /*
2794  * Find the referenced CTE, and locate the plan previously made for it.
2795  */
2796  levelsup = rte->ctelevelsup;
2797  cteroot = root;
2798  while (levelsup-- > 0)
2799  {
2800  cteroot = cteroot->parent_root;
2801  if (!cteroot) /* shouldn't happen */
2802  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2803  }
2804 
2805  /*
2806  * Note: cte_plan_ids can be shorter than cteList, if we are still working
2807  * on planning the CTEs (ie, this is a side-reference from another CTE).
2808  * So we mustn't use forboth here.
2809  */
2810  ndx = 0;
2811  foreach(lc, cteroot->parse->cteList)
2812  {
2813  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2814 
2815  if (strcmp(cte->ctename, rte->ctename) == 0)
2816  break;
2817  ndx++;
2818  }
2819  if (lc == NULL) /* shouldn't happen */
2820  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2821  if (ndx >= list_length(cteroot->cte_plan_ids))
2822  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2823  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2824  if (plan_id <= 0)
2825  elog(ERROR, "no plan was made for CTE \"%s\"", rte->ctename);
2826  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2827 
2828  /* Mark rel with estimated output rows, width, etc */
2829  set_cte_size_estimates(root, rel, cteplan->plan_rows);
2830 
2831  /*
2832  * We don't support pushing join clauses into the quals of a CTE scan, but
2833  * it could still have required parameterization due to LATERAL refs in
2834  * its tlist.
2835  */
2836  required_outer = rel->lateral_relids;
2837 
2838  /* Generate appropriate path */
2839  add_path(rel, create_ctescan_path(root, rel, required_outer));
2840 }
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:6016
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2097
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:289
Cardinality plan_rows
Definition: plannodes.h:124
List * subplans
Definition: pathnodes.h:96
List * cte_plan_ids
Definition: pathnodes.h:244
PlannerInfo * parent_root
Definition: pathnodes.h:168
Query * parse
Definition: pathnodes.h:162
List * cteList
Definition: parsenodes.h:146
char * ctename
Definition: parsenodes.h:1125
Index ctelevelsup
Definition: parsenodes.h:1126

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::parent_root, 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 2117 of file allpaths.c.

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

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 }
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:210
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:737

References RelOptInfo::fdwroutine, FdwRoutine::GetForeignPaths, and 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:6116
double clamp_row_est(double nrows)
Definition: costsize.c:201
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:209

References clamp_row_est(), RelOptInfo::fdwroutine, FdwRoutine::GetForeignRelSize, 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 2671 of file allpaths.c.

2672 {
2673  Relids required_outer;
2674  List *pathkeys = NIL;
2675 
2676  /*
2677  * We don't support pushing join clauses into the quals of a function
2678  * scan, but it could still have required parameterization due to LATERAL
2679  * refs in the function expression.
2680  */
2681  required_outer = rel->lateral_relids;
2682 
2683  /*
2684  * The result is considered unordered unless ORDINALITY was used, in which
2685  * case it is ordered by the ordinal column (the last one). See if we
2686  * care, by checking for uses of that Var in equivalence classes.
2687  */
2688  if (rte->funcordinality)
2689  {
2690  AttrNumber ordattno = rel->max_attr;
2691  Var *var = NULL;
2692  ListCell *lc;
2693 
2694  /*
2695  * Is there a Var for it in rel's targetlist? If not, the query did
2696  * not reference the ordinality column, or at least not in any way
2697  * that would be interesting for sorting.
2698  */
2699  foreach(lc, rel->reltarget->exprs)
2700  {
2701  Var *node = (Var *) lfirst(lc);
2702 
2703  /* checking varno/varlevelsup is just paranoia */
2704  if (IsA(node, Var) &&
2705  node->varattno == ordattno &&
2706  node->varno == rel->relid &&
2707  node->varlevelsup == 0)
2708  {
2709  var = node;
2710  break;
2711  }
2712  }
2713 
2714  /*
2715  * Try to build pathkeys for this Var with int8 sorting. We tell
2716  * build_expression_pathkey not to build any new equivalence class; if
2717  * the Var isn't already mentioned in some EC, it means that nothing
2718  * cares about the ordering.
2719  */
2720  if (var)
2721  pathkeys = build_expression_pathkey(root,
2722  (Expr *) var,
2723  NULL, /* below outer joins */
2724  Int8LessOperator,
2725  rel->relids,
2726  false);
2727  }
2728 
2729  /* Generate appropriate path */
2730  add_path(rel, create_functionscan_path(root, rel,
2731  pathkeys, required_outer));
2732 }
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:1305
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:2019
bool funcordinality
Definition: parsenodes.h:1110
Index varlevelsup
Definition: primnodes.h:205

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

2852 {
2853  Relids required_outer;
2854 
2855  /* Mark rel with estimated output rows, width, etc */
2857 
2858  /*
2859  * We don't support pushing join clauses into the quals of a tuplestore
2860  * scan, but it could still have required parameterization due to LATERAL
2861  * refs in its tlist.
2862  */
2863  required_outer = rel->lateral_relids;
2864 
2865  /* Generate appropriate path */
2866  add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2867 
2868  /* Select cheapest path (pretty easy in this case...) */
2869  set_cheapest(rel);
2870 }
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6054
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2122

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:5289
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:3307

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);
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:683
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:2059
char func_parallel(Oid funcid)
Definition: lsyscache.c:1780
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
@ RTE_JOIN
Definition: parsenodes.h:1000
@ RTE_CTE
Definition: parsenodes.h:1004
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1005
@ RTE_VALUES
Definition: parsenodes.h:1003
@ RTE_SUBQUERY
Definition: parsenodes.h:999
@ RTE_RESULT
Definition: parsenodes.h:1006
@ RTE_FUNCTION
Definition: parsenodes.h:1001
@ RTE_TABLEFUNC
Definition: parsenodes.h:1002
@ RTE_RELATION
Definition: parsenodes.h:998
bool limit_needed(Query *parse)
Definition: planner.c:2551
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:266
struct TableSampleClause * tablesample
Definition: parsenodes.h:1045
List * values_lists
Definition: parsenodes.h:1120
List * functions
Definition: parsenodes.h:1109
RTEKind rtekind
Definition: parsenodes.h:1015

References TableSampleClause::args, Assert(), RelOptInfo::baserestrictinfo, castNode, RelOptInfo::consider_parallel, PathTarget::exprs, RelOptInfo::fdwroutine, func_parallel(), RangeTblEntry::functions, get_rel_persistence(), PlannerInfo::glob, is_parallel_safe(), IS_SIMPLE_REL, FdwRoutine::IsForeignScanParallelSafe, 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 473 of file allpaths.c.

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

References PlannerInfo::all_baserels, bms_membership(), BMS_SINGLETON, elog, ERROR, generate_useful_gather_paths(), RangeTblEntry::inh, IS_DUMMY_REL, 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 364 of file allpaths.c.

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

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

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

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

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(), fetch_upper_rel(), PlannerInfo::glob, has_multiple_baserels(), Query::hasWindowFuncs, if(), IS_DUMMY_REL, 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, RestrictInfo::pseudoconstant, qual_is_pushdown_safe(), 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, and UPPERREL_FINAL.

Referenced by set_rel_size().

◆ set_tablefunc_pathlist()

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

Definition at line 2759 of file allpaths.c.

2760 {
2761  Relids required_outer;
2762 
2763  /*
2764  * We don't support pushing join clauses into the quals of a tablefunc
2765  * scan, but it could still have required parameterization due to LATERAL
2766  * refs in the function expression.
2767  */
2768  required_outer = rel->lateral_relids;
2769 
2770  /* Generate appropriate path */
2771  add_path(rel, create_tablefuncscan_path(root, rel,
2772  required_outer));
2773 }
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2045

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 }
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:1552
Index query_level
Definition: pathnodes.h:166
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 2739 of file allpaths.c.

2740 {
2741  Relids required_outer;
2742 
2743  /*
2744  * We don't support pushing join clauses into the quals of a values scan,
2745  * but it could still have required parameterization due to LATERAL refs
2746  * in the values expressions.
2747  */
2748  required_outer = rel->lateral_relids;
2749 
2750  /* Generate appropriate path */
2751  add_path(rel, create_valuesscan_path(root, rel, required_outer));
2752 }
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2071

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

2911 {
2912  Path *ctepath;
2913  PlannerInfo *cteroot;
2914  Index levelsup;
2915  Relids required_outer;
2916 
2917  /*
2918  * We need to find the non-recursive term's path, which is in the plan
2919  * level that's processing the recursive UNION, which is one level *below*
2920  * where the CTE comes from.
2921  */
2922  levelsup = rte->ctelevelsup;
2923  if (levelsup == 0) /* shouldn't happen */
2924  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2925  levelsup--;
2926  cteroot = root;
2927  while (levelsup-- > 0)
2928  {
2929  cteroot = cteroot->parent_root;
2930  if (!cteroot) /* shouldn't happen */
2931  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2932  }
2933  ctepath = cteroot->non_recursive_path;
2934  if (!ctepath) /* shouldn't happen */
2935  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
2936 
2937  /* Mark rel with estimated output rows, width, etc */
2938  set_cte_size_estimates(root, rel, ctepath->rows);
2939 
2940  /*
2941  * We don't support pushing join clauses into the quals of a worktable
2942  * scan, but it could still have required parameterization due to LATERAL
2943  * refs in its tlist. (I'm not sure this is actually possible given the
2944  * restrictions on recursive references, but it's easy enough to support.)
2945  */
2946  required_outer = rel->lateral_relids;
2947 
2948  /* Generate appropriate path */
2949  add_path(rel, create_worktablescan_path(root, rel, required_outer));
2950 }
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2174
struct Path * non_recursive_path
Definition: pathnodes.h:366

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

Referenced by set_rel_size().

◆ standard_join_search()

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

Definition at line 3346 of file allpaths.c.

3347 {
3348  int lev;
3349  RelOptInfo *rel;
3350 
3351  /*
3352  * This function cannot be invoked recursively within any one planning
3353  * problem, so join_rel_level[] can't be in use already.
3354  */
3355  Assert(root->join_rel_level == NULL);
3356 
3357  /*
3358  * We employ a simple "dynamic programming" algorithm: we first find all
3359  * ways to build joins of two jointree items, then all ways to build joins
3360  * of three items (from two-item joins and single items), then four-item
3361  * joins, and so on until we have considered all ways to join all the
3362  * items into one rel.
3363  *
3364  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3365  * set root->join_rel_level[1] to represent all the single-jointree-item
3366  * relations.
3367  */
3368  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3369 
3370  root->join_rel_level[1] = initial_rels;
3371 
3372  for (lev = 2; lev <= levels_needed; lev++)
3373  {
3374  ListCell *lc;
3375 
3376  /*
3377  * Determine all possible pairs of relations to be joined at this
3378  * level, and build paths for making each one from every available
3379  * pair of lower-level relations.
3380  */
3381  join_search_one_level(root, lev);
3382 
3383  /*
3384  * Run generate_partitionwise_join_paths() and
3385  * generate_useful_gather_paths() for each just-processed joinrel. We
3386  * could not do this earlier because both regular and partial paths
3387  * can get added to a particular joinrel at multiple times within
3388  * join_search_one_level.
3389  *
3390  * After that, we're done creating paths for the joinrel, so run
3391  * set_cheapest().
3392  */
3393  foreach(lc, root->join_rel_level[lev])
3394  {
3395  rel = (RelOptInfo *) lfirst(lc);
3396 
3397  /* Create paths for partitionwise joins. */
3399 
3400  /*
3401  * Except for the topmost scan/join rel, consider gathering
3402  * partial paths. We'll do the same for the topmost scan/join rel
3403  * once we know the final targetlist (see grouping_planner).
3404  */
3405  if (lev < levels_needed)
3406  generate_useful_gather_paths(root, rel, false);
3407 
3408  /* Find and save the cheapest paths for this rel */
3409  set_cheapest(rel);
3410 
3411 #ifdef OPTIMIZER_DEBUG
3412  debug_print_rel(root, rel);
3413 #endif
3414  }
3415  }
3416 
3417  /*
3418  * We should have a single rel at the final level.
3419  */
3420  if (root->join_rel_level[levels_needed] == NIL)
3421  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3422  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3423 
3424  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3425 
3426  root->join_rel_level = NULL;
3427 
3428  return rel;
3429 }
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:71
List ** join_rel_level
Definition: pathnodes.h:239

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

3518 {
3519  SetOperationStmt *topop;
3520 
3521  /* Check point 1 */
3522  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3523  return false;
3524 
3525  /* Check point 6 */
3526  if (subquery->groupClause && subquery->groupingSets)
3527  return false;
3528 
3529  /* Check points 3, 4, and 5 */
3530  if (subquery->distinctClause ||
3531  subquery->hasWindowFuncs ||
3532  subquery->hasTargetSRFs)
3533  safetyInfo->unsafeVolatile = true;
3534 
3535  /*
3536  * If we're at a leaf query, check for unsafe expressions in its target
3537  * list, and mark any unsafe ones in unsafeColumns[]. (Non-leaf nodes in
3538  * setop trees have only simple Vars in their tlists, so no need to check
3539  * them.)
3540  */
3541  if (subquery->setOperations == NULL)
3542  check_output_expressions(subquery, safetyInfo);
3543 
3544  /* Are we at top level, or looking at a setop component? */
3545  if (subquery == topquery)
3546  {
3547  /* Top level, so check any component queries */
3548  if (subquery->setOperations != NULL)
3549  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3550  safetyInfo))
3551  return false;
3552  }
3553  else
3554  {
3555  /* Setop component must not have more components (too weird) */
3556  if (subquery->setOperations != NULL)
3557  return false;
3558  /* Check whether setop component output types match top level */
3559  topop = castNode(SetOperationStmt, topquery->setOperations);
3560  Assert(topop);
3562  topop->colTypes,
3563  safetyInfo);
3564  }
3565  return true;
3566 }
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3707
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3639
Node * limitCount
Definition: parsenodes.h:177
List * groupClause
Definition: parsenodes.h:163
Node * limitOffset
Definition: parsenodes.h:176
List * groupingSets
Definition: parsenodes.h:166

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

3876 {
3877  if (subquery->setOperations != NULL)
3878  {
3879  /* Recurse to push it separately to each component query */
3880  recurse_push_qual(subquery->setOperations, subquery,
3881  rte, rti, qual);
3882  }
3883  else
3884  {
3885  /*
3886  * We need to replace Vars in the qual (which must refer to outputs of
3887  * the subquery) with copies of the subquery's targetlist expressions.
3888  * Note that at this point, any uplevel Vars in the qual should have
3889  * been replaced with Params, so they need no work.
3890  *
3891  * This step also ensures that when we are pushing into a setop tree,
3892  * each component query gets its own copy of the qual.
3893  */
3894  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3895  subquery->targetList,
3897  &subquery->hasSubLinks);
3898 
3899  /*
3900  * Now attach the qual to the proper place: normally WHERE, but if the
3901  * subquery uses grouping or aggregation, put it in HAVING (since the
3902  * qual really refers to the group-result rows).
3903  */
3904  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
3905  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
3906  else
3907  subquery->jointree->quals =
3908  make_and_qual(subquery->jointree->quals, qual);
3909 
3910  /*
3911  * We need not change the subquery's hasAggs or hasSubLinks flags,
3912  * since we can't be pushing down any aggregates that weren't there
3913  * before, and we don't push down subselects at all.
3914  */
3915  }
3916 }
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:690
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:1826
FromExpr * jointree
Definition: parsenodes.h:149
Node * havingQual
Definition: parsenodes.h:168
bool hasAggs
Definition: parsenodes.h:134
bool hasSubLinks
Definition: parsenodes.h:137

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

3741 {
3742  ListCell *lc;
3743 
3744  foreach(lc, query->windowClause)
3745  {
3746  WindowClause *wc = (WindowClause *) lfirst(lc);
3747 
3749  return false;
3750  }
3751  return true;
3752 }
List * partitionClause
Definition: parsenodes.h:1401

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

Referenced by make_rel_from_joinlist().

◆ geqo_threshold

int geqo_threshold

Definition at line 64 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

join_search_hook_type join_search_hook = NULL

Definition at line 72 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_parallel_index_scan_size

int min_parallel_index_scan_size

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

Referenced by set_rel_pathlist().