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 "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, List *partitioned_rels)
 
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, Node *qual, 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)
 
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)
 
void generate_gather_paths (PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 
static Listget_useful_pathkeys_for_relation (PlannerInfo *root, RelOptInfo *rel)
 
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 2049 of file allpaths.c.

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

2050 {
2051  if (IsA(path, AppendPath))
2052  {
2053  AppendPath *apath = (AppendPath *) path;
2054 
2055  if (!apath->path.parallel_aware || apath->first_partial_path == 0)
2056  {
2057  *subpaths = list_concat(*subpaths, apath->subpaths);
2058  return;
2059  }
2060  else if (special_subpaths != NULL)
2061  {
2062  List *new_special_subpaths;
2063 
2064  /* Split Parallel Append into partial and non-partial subpaths */
2065  *subpaths = list_concat(*subpaths,
2066  list_copy_tail(apath->subpaths,
2067  apath->first_partial_path));
2068  new_special_subpaths =
2070  apath->first_partial_path);
2071  *special_subpaths = list_concat(*special_subpaths,
2072  new_special_subpaths);
2073  return;
2074  }
2075  }
2076  else if (IsA(path, MergeAppendPath))
2077  {
2078  MergeAppendPath *mpath = (MergeAppendPath *) path;
2079 
2080  *subpaths = list_concat(*subpaths, mpath->subpaths);
2081  return;
2082  }
2083 
2084  *subpaths = lappend(*subpaths, path);
2085 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * list_truncate(List *list, int new_size)
Definition: list.c:585
List * list_copy(const List *oldlist)
Definition: list.c:1403
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1422
int first_partial_path
Definition: pathnodes.h:1407
List * subpaths
Definition: pathnodes.h:1405
List * lappend(List *list, void *datum)
Definition: list.c:321
bool parallel_aware
Definition: pathnodes.h:1150
Definition: pg_list.h:50

◆ add_paths_to_append_rel()

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

Definition at line 1301 of file allpaths.c.

References accumulate_append_subpath(), add_partial_path(), add_path(), Assert, bms_equal(), bms_next_member(), RelOptInfo::cheapest_total_path, compare_pathkeys(), RelOptInfo::consider_parallel, create_append_path(), enable_parallel_append, fls(), generate_orderedappend_paths(), get_cheapest_parallel_safe_total_inner(), get_cheapest_parameterized_child_path(), IS_JOIN_REL, IS_SIMPLE_REL, lappend(), lfirst, linitial, list_concat(), list_length(), list_make1, Max, max_parallel_workers_per_gather, Min, NIL, Path::parallel_workers, Path::param_info, RelOptInfo::part_scheme, RelOptInfo::partial_pathlist, RelOptInfo::partitioned_child_rels, AppendPath::path, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, RelOptInfo::pathlist, RelOptInfo::relids, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, PlannerInfo::simple_rel_array, 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().

1303 {
1304  List *subpaths = NIL;
1305  bool subpaths_valid = true;
1306  List *partial_subpaths = NIL;
1307  List *pa_partial_subpaths = NIL;
1308  List *pa_nonpartial_subpaths = NIL;
1309  bool partial_subpaths_valid = true;
1310  bool pa_subpaths_valid;
1311  List *all_child_pathkeys = NIL;
1312  List *all_child_outers = NIL;
1313  ListCell *l;
1314  List *partitioned_rels = NIL;
1315  double partial_rows = -1;
1316 
1317  /* If appropriate, consider parallel append */
1318  pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1319 
1320  /*
1321  * AppendPath generated for partitioned tables must record the RT indexes
1322  * of partitioned tables that are direct or indirect children of this
1323  * Append rel.
1324  *
1325  * AppendPath may be for a sub-query RTE (UNION ALL), in which case, 'rel'
1326  * itself does not represent a partitioned relation, but the child sub-
1327  * queries may contain references to partitioned relations. The loop
1328  * below will look for such children and collect them in a list to be
1329  * passed to the path creation function. (This assumes that we don't need
1330  * to look through multiple levels of subquery RTEs; if we ever do, we
1331  * could consider stuffing the list we generate here into sub-query RTE's
1332  * RelOptInfo, just like we do for partitioned rels, which would be used
1333  * when populating our parent rel with paths. For the present, that
1334  * appears to be unnecessary.)
1335  */
1336  if (rel->part_scheme != NULL)
1337  {
1338  if (IS_SIMPLE_REL(rel))
1339  partitioned_rels = list_make1(rel->partitioned_child_rels);
1340  else if (IS_JOIN_REL(rel))
1341  {
1342  int relid = -1;
1343  List *partrels = NIL;
1344 
1345  /*
1346  * For a partitioned joinrel, concatenate the component rels'
1347  * partitioned_child_rels lists.
1348  */
1349  while ((relid = bms_next_member(rel->relids, relid)) >= 0)
1350  {
1351  RelOptInfo *component;
1352 
1353  Assert(relid >= 1 && relid < root->simple_rel_array_size);
1354  component = root->simple_rel_array[relid];
1355  Assert(component->part_scheme != NULL);
1356  Assert(list_length(component->partitioned_child_rels) >= 1);
1357  partrels = list_concat(partrels,
1358  component->partitioned_child_rels);
1359  }
1360 
1361  partitioned_rels = list_make1(partrels);
1362  }
1363 
1364  Assert(list_length(partitioned_rels) >= 1);
1365  }
1366 
1367  /*
1368  * For every non-dummy child, remember the cheapest path. Also, identify
1369  * all pathkeys (orderings) and parameterizations (required_outer sets)
1370  * available for the non-dummy member relations.
1371  */
1372  foreach(l, live_childrels)
1373  {
1374  RelOptInfo *childrel = lfirst(l);
1375  ListCell *lcp;
1376  Path *cheapest_partial_path = NULL;
1377 
1378  /*
1379  * For UNION ALLs with non-empty partitioned_child_rels, accumulate
1380  * the Lists of child relations.
1381  */
1382  if (rel->rtekind == RTE_SUBQUERY && childrel->partitioned_child_rels != NIL)
1383  partitioned_rels = lappend(partitioned_rels,
1384  childrel->partitioned_child_rels);
1385 
1386  /*
1387  * If child has an unparameterized cheapest-total path, add that to
1388  * the unparameterized Append path we are constructing for the parent.
1389  * If not, there's no workable unparameterized path.
1390  *
1391  * With partitionwise aggregates, the child rel's pathlist may be
1392  * empty, so don't assume that a path exists here.
1393  */
1394  if (childrel->pathlist != NIL &&
1395  childrel->cheapest_total_path->param_info == NULL)
1397  &subpaths, NULL);
1398  else
1399  subpaths_valid = false;
1400 
1401  /* Same idea, but for a partial plan. */
1402  if (childrel->partial_pathlist != NIL)
1403  {
1404  cheapest_partial_path = linitial(childrel->partial_pathlist);
1405  accumulate_append_subpath(cheapest_partial_path,
1406  &partial_subpaths, NULL);
1407  }
1408  else
1409  partial_subpaths_valid = false;
1410 
1411  /*
1412  * Same idea, but for a parallel append mixing partial and non-partial
1413  * paths.
1414  */
1415  if (pa_subpaths_valid)
1416  {
1417  Path *nppath = NULL;
1418 
1419  nppath =
1421 
1422  if (cheapest_partial_path == NULL && nppath == NULL)
1423  {
1424  /* Neither a partial nor a parallel-safe path? Forget it. */
1425  pa_subpaths_valid = false;
1426  }
1427  else if (nppath == NULL ||
1428  (cheapest_partial_path != NULL &&
1429  cheapest_partial_path->total_cost < nppath->total_cost))
1430  {
1431  /* Partial path is cheaper or the only option. */
1432  Assert(cheapest_partial_path != NULL);
1433  accumulate_append_subpath(cheapest_partial_path,
1434  &pa_partial_subpaths,
1435  &pa_nonpartial_subpaths);
1436 
1437  }
1438  else
1439  {
1440  /*
1441  * Either we've got only a non-partial path, or we think that
1442  * a single backend can execute the best non-partial path
1443  * faster than all the parallel backends working together can
1444  * execute the best partial path.
1445  *
1446  * It might make sense to be more aggressive here. Even if
1447  * the best non-partial path is more expensive than the best
1448  * partial path, it could still be better to choose the
1449  * non-partial path if there are several such paths that can
1450  * be given to different workers. For now, we don't try to
1451  * figure that out.
1452  */
1454  &pa_nonpartial_subpaths,
1455  NULL);
1456  }
1457  }
1458 
1459  /*
1460  * Collect lists of all the available path orderings and
1461  * parameterizations for all the children. We use these as a
1462  * heuristic to indicate which sort orderings and parameterizations we
1463  * should build Append and MergeAppend paths for.
1464  */
1465  foreach(lcp, childrel->pathlist)
1466  {
1467  Path *childpath = (Path *) lfirst(lcp);
1468  List *childkeys = childpath->pathkeys;
1469  Relids childouter = PATH_REQ_OUTER(childpath);
1470 
1471  /* Unsorted paths don't contribute to pathkey list */
1472  if (childkeys != NIL)
1473  {
1474  ListCell *lpk;
1475  bool found = false;
1476 
1477  /* Have we already seen this ordering? */
1478  foreach(lpk, all_child_pathkeys)
1479  {
1480  List *existing_pathkeys = (List *) lfirst(lpk);
1481 
1482  if (compare_pathkeys(existing_pathkeys,
1483  childkeys) == PATHKEYS_EQUAL)
1484  {
1485  found = true;
1486  break;
1487  }
1488  }
1489  if (!found)
1490  {
1491  /* No, so add it to all_child_pathkeys */
1492  all_child_pathkeys = lappend(all_child_pathkeys,
1493  childkeys);
1494  }
1495  }
1496 
1497  /* Unparameterized paths don't contribute to param-set list */
1498  if (childouter)
1499  {
1500  ListCell *lco;
1501  bool found = false;
1502 
1503  /* Have we already seen this param set? */
1504  foreach(lco, all_child_outers)
1505  {
1506  Relids existing_outers = (Relids) lfirst(lco);
1507 
1508  if (bms_equal(existing_outers, childouter))
1509  {
1510  found = true;
1511  break;
1512  }
1513  }
1514  if (!found)
1515  {
1516  /* No, so add it to all_child_outers */
1517  all_child_outers = lappend(all_child_outers,
1518  childouter);
1519  }
1520  }
1521  }
1522  }
1523 
1524  /*
1525  * If we found unparameterized paths for all children, build an unordered,
1526  * unparameterized Append path for the rel. (Note: this is correct even
1527  * if we have zero or one live subpath due to constraint exclusion.)
1528  */
1529  if (subpaths_valid)
1530  add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1531  NIL, NULL, 0, false,
1532  partitioned_rels, -1));
1533 
1534  /*
1535  * Consider an append of unordered, unparameterized partial paths. Make
1536  * it parallel-aware if possible.
1537  */
1538  if (partial_subpaths_valid && partial_subpaths != NIL)
1539  {
1540  AppendPath *appendpath;
1541  ListCell *lc;
1542  int parallel_workers = 0;
1543 
1544  /* Find the highest number of workers requested for any subpath. */
1545  foreach(lc, partial_subpaths)
1546  {
1547  Path *path = lfirst(lc);
1548 
1549  parallel_workers = Max(parallel_workers, path->parallel_workers);
1550  }
1551  Assert(parallel_workers > 0);
1552 
1553  /*
1554  * If the use of parallel append is permitted, always request at least
1555  * log2(# of children) workers. We assume it can be useful to have
1556  * extra workers in this case because they will be spread out across
1557  * the children. The precise formula is just a guess, but we don't
1558  * want to end up with a radically different answer for a table with N
1559  * partitions vs. an unpartitioned table with the same data, so the
1560  * use of some kind of log-scaling here seems to make some sense.
1561  */
1563  {
1564  parallel_workers = Max(parallel_workers,
1565  fls(list_length(live_childrels)));
1566  parallel_workers = Min(parallel_workers,
1568  }
1569  Assert(parallel_workers > 0);
1570 
1571  /* Generate a partial append path. */
1572  appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1573  NIL, NULL, parallel_workers,
1575  partitioned_rels, -1);
1576 
1577  /*
1578  * Make sure any subsequent partial paths use the same row count
1579  * estimate.
1580  */
1581  partial_rows = appendpath->path.rows;
1582 
1583  /* Add the path. */
1584  add_partial_path(rel, (Path *) appendpath);
1585  }
1586 
1587  /*
1588  * Consider a parallel-aware append using a mix of partial and non-partial
1589  * paths. (This only makes sense if there's at least one child which has
1590  * a non-partial path that is substantially cheaper than any partial path;
1591  * otherwise, we should use the append path added in the previous step.)
1592  */
1593  if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1594  {
1595  AppendPath *appendpath;
1596  ListCell *lc;
1597  int parallel_workers = 0;
1598 
1599  /*
1600  * Find the highest number of workers requested for any partial
1601  * subpath.
1602  */
1603  foreach(lc, pa_partial_subpaths)
1604  {
1605  Path *path = lfirst(lc);
1606 
1607  parallel_workers = Max(parallel_workers, path->parallel_workers);
1608  }
1609 
1610  /*
1611  * Same formula here as above. It's even more important in this
1612  * instance because the non-partial paths won't contribute anything to
1613  * the planned number of parallel workers.
1614  */
1615  parallel_workers = Max(parallel_workers,
1616  fls(list_length(live_childrels)));
1617  parallel_workers = Min(parallel_workers,
1619  Assert(parallel_workers > 0);
1620 
1621  appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1622  pa_partial_subpaths,
1623  NIL, NULL, parallel_workers, true,
1624  partitioned_rels, partial_rows);
1625  add_partial_path(rel, (Path *) appendpath);
1626  }
1627 
1628  /*
1629  * Also build unparameterized ordered append paths based on the collected
1630  * list of child pathkeys.
1631  */
1632  if (subpaths_valid)
1633  generate_orderedappend_paths(root, rel, live_childrels,
1634  all_child_pathkeys,
1635  partitioned_rels);
1636 
1637  /*
1638  * Build Append paths for each parameterization seen among the child rels.
1639  * (This may look pretty expensive, but in most cases of practical
1640  * interest, the child rels will expose mostly the same parameterizations,
1641  * so that not that many cases actually get considered here.)
1642  *
1643  * The Append node itself cannot enforce quals, so all qual checking must
1644  * be done in the child paths. This means that to have a parameterized
1645  * Append path, we must have the exact same parameterization for each
1646  * child path; otherwise some children might be failing to check the
1647  * moved-down quals. To make them match up, we can try to increase the
1648  * parameterization of lesser-parameterized paths.
1649  */
1650  foreach(l, all_child_outers)
1651  {
1652  Relids required_outer = (Relids) lfirst(l);
1653  ListCell *lcr;
1654 
1655  /* Select the child paths for an Append with this parameterization */
1656  subpaths = NIL;
1657  subpaths_valid = true;
1658  foreach(lcr, live_childrels)
1659  {
1660  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1661  Path *subpath;
1662 
1663  if (childrel->pathlist == NIL)
1664  {
1665  /* failed to make a suitable path for this child */
1666  subpaths_valid = false;
1667  break;
1668  }
1669 
1671  childrel,
1672  required_outer);
1673  if (subpath == NULL)
1674  {
1675  /* failed to make a suitable path for this child */
1676  subpaths_valid = false;
1677  break;
1678  }
1679  accumulate_append_subpath(subpath, &subpaths, NULL);
1680  }
1681 
1682  if (subpaths_valid)
1683  add_path(rel, (Path *)
1684  create_append_path(root, rel, subpaths, NIL,
1685  NIL, required_outer, 0, false,
1686  partitioned_rels, -1));
1687  }
1688 
1689  /*
1690  * When there is only a single child relation, the Append path can inherit
1691  * any ordering available for the child rel's path, so that it's useful to
1692  * consider ordered partial paths. Above we only considered the cheapest
1693  * partial path for each child, but let's also make paths using any
1694  * partial paths that have pathkeys.
1695  */
1696  if (list_length(live_childrels) == 1)
1697  {
1698  RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1699 
1700  foreach(l, childrel->partial_pathlist)
1701  {
1702  Path *path = (Path *) lfirst(l);
1703  AppendPath *appendpath;
1704 
1705  /*
1706  * Skip paths with no pathkeys. Also skip the cheapest partial
1707  * path, since we already used that above.
1708  */
1709  if (path->pathkeys == NIL ||
1710  path == linitial(childrel->partial_pathlist))
1711  continue;
1712 
1713  appendpath = create_append_path(root, rel, NIL, list_make1(path),
1714  NIL, NULL,
1715  path->parallel_workers, true,
1716  partitioned_rels, partial_rows);
1717  add_partial_path(rel, (Path *) appendpath);
1718  }
1719  }
1720 }
#define NIL
Definition: pg_list.h:65
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:1961
#define Min(x, y)
Definition: c.h:927
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
int parallel_workers
Definition: pathnodes.h:1152
ParamPathInfo * param_info
Definition: pathnodes.h:1148
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:644
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
List * partial_pathlist
Definition: pathnodes.h:682
bool enable_parallel_append
Definition: costsize.c:140
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:285
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:639
int fls(int mask)
Definition: fls.c:55
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:203
#define list_make1(x1)
Definition: pg_list.h:226
#define linitial(l)
Definition: pg_list.h:194
struct Path * cheapest_total_path
Definition: pathnodes.h:684
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1164
Relids relids
Definition: pathnodes.h:666
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition: pathkeys.c:482
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1215
List * lappend(List *list, void *datum)
Definition: list.c:321
RTEKind rtekind
Definition: pathnodes.h:696
Cost total_cost
Definition: pathnodes.h:1157
List * pathkeys
Definition: pathnodes.h:1159
#define Max(x, y)
Definition: c.h:921
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
double rows
Definition: pathnodes.h:1155
static int list_length(const List *l)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:674
Bitmapset * Relids
Definition: pathnodes.h:28
List * partitioned_child_rels
Definition: pathnodes.h:756
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
PartitionScheme part_scheme
Definition: pathnodes.h:743
List * pathlist
Definition: pathnodes.h:680
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys, List *partitioned_rels)
Definition: allpaths.c:1750
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2049
int max_parallel_workers_per_gather
Definition: costsize.c:123
Definition: pg_list.h:50
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:94

◆ check_output_expressions()

static void check_output_expressions ( Query subquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 3358 of file allpaths.c.

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

3359 {
3360  ListCell *lc;
3361 
3362  foreach(lc, subquery->targetList)
3363  {
3364  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3365 
3366  if (tle->resjunk)
3367  continue; /* ignore resjunk columns */
3368 
3369  /* We need not check further if output col is already known unsafe */
3370  if (safetyInfo->unsafeColumns[tle->resno])
3371  continue;
3372 
3373  /* Functions returning sets are unsafe (point 1) */
3374  if (subquery->hasTargetSRFs &&
3375  expression_returns_set((Node *) tle->expr))
3376  {
3377  safetyInfo->unsafeColumns[tle->resno] = true;
3378  continue;
3379  }
3380 
3381  /* Volatile functions are unsafe (point 2) */
3382  if (contain_volatile_functions((Node *) tle->expr))
3383  {
3384  safetyInfo->unsafeColumns[tle->resno] = true;
3385  continue;
3386  }
3387 
3388  /* If subquery uses DISTINCT ON, check point 3 */
3389  if (subquery->hasDistinctOn &&
3390  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
3391  {
3392  /* non-DISTINCT column, so mark it unsafe */
3393  safetyInfo->unsafeColumns[tle->resno] = true;
3394  continue;
3395  }
3396 
3397  /* If subquery uses window functions, check point 4 */
3398  if (subquery->hasWindowFuncs &&
3399  !targetIsInAllPartitionLists(tle, subquery))
3400  {
3401  /* not present in all PARTITION BY clauses, so mark it unsafe */
3402  safetyInfo->unsafeColumns[tle->resno] = true;
3403  continue;
3404  }
3405  }
3406 }
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:718
Definition: nodes.h:528
bool * unsafeColumns
Definition: allpaths.c:56
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:724
bool hasDistinctOn
Definition: parsenodes.h:129
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1417
List * distinctClause
Definition: parsenodes.h:156
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:3459
AttrNumber resno
Definition: primnodes.h:1411
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
bool hasTargetSRFs
Definition: parsenodes.h:127
#define lfirst(lc)
Definition: pg_list.h:189
bool hasWindowFuncs
Definition: parsenodes.h:126
Expr * expr
Definition: primnodes.h:1410

◆ compare_tlist_datatypes()

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

Definition at line 3426 of file allpaths.c.

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

3428 {
3429  ListCell *l;
3430  ListCell *colType = list_head(colTypes);
3431 
3432  foreach(l, tlist)
3433  {
3434  TargetEntry *tle = (TargetEntry *) lfirst(l);
3435 
3436  if (tle->resjunk)
3437  continue; /* ignore resjunk columns */
3438  if (colType == NULL)
3439  elog(ERROR, "wrong number of tlist entries");
3440  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
3441  safetyInfo->unsafeColumns[tle->resno] = true;
3442  colType = lnext(colTypes, colType);
3443  }
3444  if (colType != NULL)
3445  elog(ERROR, "wrong number of tlist entries");
3446 }
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:330
Definition: nodes.h:528
bool * unsafeColumns
Definition: allpaths.c:56
bool resjunk
Definition: primnodes.h:1417
#define ERROR
Definition: elog.h:43
AttrNumber resno
Definition: primnodes.h:1411
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
#define lfirst(lc)
Definition: pg_list.h:189
Expr * expr
Definition: primnodes.h:1410
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
#define elog(elevel,...)
Definition: elog.h:214
#define lfirst_oid(lc)
Definition: pg_list.h:191

◆ compute_parallel_worker()

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

Definition at line 3827 of file allpaths.c.

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

3829 {
3830  int parallel_workers = 0;
3831 
3832  /*
3833  * If the user has set the parallel_workers reloption, use that; otherwise
3834  * select a default number of workers.
3835  */
3836  if (rel->rel_parallel_workers != -1)
3837  parallel_workers = rel->rel_parallel_workers;
3838  else
3839  {
3840  /*
3841  * If the number of pages being scanned is insufficient to justify a
3842  * parallel scan, just return zero ... unless it's an inheritance
3843  * child. In that case, we want to generate a parallel path here
3844  * anyway. It might not be worthwhile just for this relation, but
3845  * when combined with all of its inheritance siblings it may well pay
3846  * off.
3847  */
3848  if (rel->reloptkind == RELOPT_BASEREL &&
3849  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
3850  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
3851  return 0;
3852 
3853  if (heap_pages >= 0)
3854  {
3855  int heap_parallel_threshold;
3856  int heap_parallel_workers = 1;
3857 
3858  /*
3859  * Select the number of workers based on the log of the size of
3860  * the relation. This probably needs to be a good deal more
3861  * sophisticated, but we need something here for now. Note that
3862  * the upper limit of the min_parallel_table_scan_size GUC is
3863  * chosen to prevent overflow here.
3864  */
3865  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
3866  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
3867  {
3868  heap_parallel_workers++;
3869  heap_parallel_threshold *= 3;
3870  if (heap_parallel_threshold > INT_MAX / 3)
3871  break; /* avoid overflow */
3872  }
3873 
3874  parallel_workers = heap_parallel_workers;
3875  }
3876 
3877  if (index_pages >= 0)
3878  {
3879  int index_parallel_workers = 1;
3880  int index_parallel_threshold;
3881 
3882  /* same calculation as for heap_pages above */
3883  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
3884  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
3885  {
3886  index_parallel_workers++;
3887  index_parallel_threshold *= 3;
3888  if (index_parallel_threshold > INT_MAX / 3)
3889  break; /* avoid overflow */
3890  }
3891 
3892  if (parallel_workers > 0)
3893  parallel_workers = Min(parallel_workers, index_parallel_workers);
3894  else
3895  parallel_workers = index_parallel_workers;
3896  }
3897  }
3898 
3899  /* In no case use more than caller supplied maximum number of workers */
3900  parallel_workers = Min(parallel_workers, max_workers);
3901 
3902  return parallel_workers;
3903 }
RelOptKind reloptkind
Definition: pathnodes.h:663
#define Min(x, y)
Definition: c.h:927
uint32 BlockNumber
Definition: block.h:31
int min_parallel_index_scan_size
Definition: allpaths.c:65
int rel_parallel_workers
Definition: pathnodes.h:712
#define Max(x, y)
Definition: c.h:921
int min_parallel_table_scan_size
Definition: allpaths.c:64

◆ create_partial_bitmap_paths()

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

Definition at line 3791 of file allpaths.c.

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

3793 {
3794  int parallel_workers;
3795  double pages_fetched;
3796 
3797  /* Compute heap pages for bitmap heap scan */
3798  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
3799  NULL, NULL);
3800 
3801  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
3803 
3804  if (parallel_workers <= 0)
3805  return;
3806 
3807  add_partial_path(rel, (Path *) create_bitmap_heap_path(root, rel,
3808  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
3809 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3827
Relids lateral_relids
Definition: pathnodes.h:691
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
int max_parallel_workers_per_gather
Definition: costsize.c:123
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:5745
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1046

◆ create_plain_partial_paths()

static void create_plain_partial_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 796 of file allpaths.c.

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

Referenced by set_plain_rel_pathlist().

797 {
798  int parallel_workers;
799 
800  parallel_workers = compute_parallel_worker(rel, rel->pages, -1,
802 
803  /* If any limit was set to zero, the user doesn't want a parallel scan. */
804  if (parallel_workers <= 0)
805  return;
806 
807  /* Add an unordered partial path based on a parallel sequential scan. */
808  add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
809 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3827
BlockNumber pages
Definition: pathnodes.h:705
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
int max_parallel_workers_per_gather
Definition: costsize.c:123
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929

◆ generate_gather_paths()

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

Definition at line 2689 of file allpaths.c.

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

Referenced by generate_useful_gather_paths().

2690 {
2691  Path *cheapest_partial_path;
2692  Path *simple_gather_path;
2693  ListCell *lc;
2694  double rows;
2695  double *rowsp = NULL;
2696 
2697  /* If there are no partial paths, there's nothing to do here. */
2698  if (rel->partial_pathlist == NIL)
2699  return;
2700 
2701  /* Should we override the rel's rowcount estimate? */
2702  if (override_rows)
2703  rowsp = &rows;
2704 
2705  /*
2706  * The output of Gather is always unsorted, so there's only one partial
2707  * path of interest: the cheapest one. That will be the one at the front
2708  * of partial_pathlist because of the way add_partial_path works.
2709  */
2710  cheapest_partial_path = linitial(rel->partial_pathlist);
2711  rows =
2712  cheapest_partial_path->rows * cheapest_partial_path->parallel_workers;
2713  simple_gather_path = (Path *)
2714  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
2715  NULL, rowsp);
2716  add_path(rel, simple_gather_path);
2717 
2718  /*
2719  * For each useful ordering, we can consider an order-preserving Gather
2720  * Merge.
2721  */
2722  foreach(lc, rel->partial_pathlist)
2723  {
2724  Path *subpath = (Path *) lfirst(lc);
2725  GatherMergePath *path;
2726 
2727  if (subpath->pathkeys == NIL)
2728  continue;
2729 
2730  rows = subpath->rows * subpath->parallel_workers;
2731  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
2732  subpath->pathkeys, NULL, rowsp);
2733  add_path(rel, &path->path);
2734  }
2735 }
#define NIL
Definition: pg_list.h:65
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1878
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
int parallel_workers
Definition: pathnodes.h:1152
List * partial_pathlist
Definition: pathnodes.h:682
#define linitial(l)
Definition: pg_list.h:194
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1787
List * pathkeys
Definition: pathnodes.h:1159
#define lfirst(lc)
Definition: pg_list.h:189
double rows
Definition: pathnodes.h:1155
struct PathTarget * reltarget
Definition: pathnodes.h:677
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ generate_orderedappend_paths()

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

Definition at line 1750 of file allpaths.c.

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_path_for_pathkeys(), get_singleton_append_subpath(), IS_SIMPLE_REL, lappend(), lcons(), lfirst, NIL, RelOptInfo::nparts, Path::param_info, RelOptInfo::part_scheme, partitions_are_ordered(), pathkeys_contained_in(), RelOptInfo::pathlist, STARTUP_COST, and TOTAL_COST.

Referenced by add_paths_to_append_rel().

1754 {
1755  ListCell *lcp;
1756  List *partition_pathkeys = NIL;
1757  List *partition_pathkeys_desc = NIL;
1758  bool partition_pathkeys_partial = true;
1759  bool partition_pathkeys_desc_partial = true;
1760 
1761  /*
1762  * Some partitioned table setups may allow us to use an Append node
1763  * instead of a MergeAppend. This is possible in cases such as RANGE
1764  * partitioned tables where it's guaranteed that an earlier partition must
1765  * contain rows which come earlier in the sort order. To detect whether
1766  * this is relevant, build pathkey descriptions of the partition ordering,
1767  * for both forward and reverse scans.
1768  */
1769  if (rel->part_scheme != NULL && IS_SIMPLE_REL(rel) &&
1771  {
1772  partition_pathkeys = build_partition_pathkeys(root, rel,
1774  &partition_pathkeys_partial);
1775 
1776  partition_pathkeys_desc = build_partition_pathkeys(root, rel,
1778  &partition_pathkeys_desc_partial);
1779 
1780  /*
1781  * You might think we should truncate_useless_pathkeys here, but
1782  * allowing partition keys which are a subset of the query's pathkeys
1783  * can often be useful. For example, consider a table partitioned by
1784  * RANGE (a, b), and a query with ORDER BY a, b, c. If we have child
1785  * paths that can produce the a, b, c ordering (perhaps via indexes on
1786  * (a, b, c)) then it works to consider the appendrel output as
1787  * ordered by a, b, c.
1788  */
1789  }
1790 
1791  /* Now consider each interesting sort ordering */
1792  foreach(lcp, all_child_pathkeys)
1793  {
1794  List *pathkeys = (List *) lfirst(lcp);
1795  List *startup_subpaths = NIL;
1796  List *total_subpaths = NIL;
1797  bool startup_neq_total = false;
1798  ListCell *lcr;
1799  bool match_partition_order;
1800  bool match_partition_order_desc;
1801 
1802  /*
1803  * Determine if this sort ordering matches any partition pathkeys we
1804  * have, for both ascending and descending partition order. If the
1805  * partition pathkeys happen to be contained in pathkeys then it still
1806  * works, as described above, providing that the partition pathkeys
1807  * are complete and not just a prefix of the partition keys. (In such
1808  * cases we'll be relying on the child paths to have sorted the
1809  * lower-order columns of the required pathkeys.)
1810  */
1811  match_partition_order =
1812  pathkeys_contained_in(pathkeys, partition_pathkeys) ||
1813  (!partition_pathkeys_partial &&
1814  pathkeys_contained_in(partition_pathkeys, pathkeys));
1815 
1816  match_partition_order_desc = !match_partition_order &&
1817  (pathkeys_contained_in(pathkeys, partition_pathkeys_desc) ||
1818  (!partition_pathkeys_desc_partial &&
1819  pathkeys_contained_in(partition_pathkeys_desc, pathkeys)));
1820 
1821  /* Select the child paths for this ordering... */
1822  foreach(lcr, live_childrels)
1823  {
1824  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1825  Path *cheapest_startup,
1826  *cheapest_total;
1827 
1828  /* Locate the right paths, if they are available. */
1829  cheapest_startup =
1831  pathkeys,
1832  NULL,
1833  STARTUP_COST,
1834  false);
1835  cheapest_total =
1837  pathkeys,
1838  NULL,
1839  TOTAL_COST,
1840  false);
1841 
1842  /*
1843  * If we can't find any paths with the right order just use the
1844  * cheapest-total path; we'll have to sort it later.
1845  */
1846  if (cheapest_startup == NULL || cheapest_total == NULL)
1847  {
1848  cheapest_startup = cheapest_total =
1849  childrel->cheapest_total_path;
1850  /* Assert we do have an unparameterized path for this child */
1851  Assert(cheapest_total->param_info == NULL);
1852  }
1853 
1854  /*
1855  * Notice whether we actually have different paths for the
1856  * "cheapest" and "total" cases; frequently there will be no point
1857  * in two create_merge_append_path() calls.
1858  */
1859  if (cheapest_startup != cheapest_total)
1860  startup_neq_total = true;
1861 
1862  /*
1863  * Collect the appropriate child paths. The required logic varies
1864  * for the Append and MergeAppend cases.
1865  */
1866  if (match_partition_order)
1867  {
1868  /*
1869  * We're going to make a plain Append path. We don't need
1870  * most of what accumulate_append_subpath would do, but we do
1871  * want to cut out child Appends or MergeAppends if they have
1872  * just a single subpath (and hence aren't doing anything
1873  * useful).
1874  */
1875  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1876  cheapest_total = get_singleton_append_subpath(cheapest_total);
1877 
1878  startup_subpaths = lappend(startup_subpaths, cheapest_startup);
1879  total_subpaths = lappend(total_subpaths, cheapest_total);
1880  }
1881  else if (match_partition_order_desc)
1882  {
1883  /*
1884  * As above, but we need to reverse the order of the children,
1885  * because nodeAppend.c doesn't know anything about reverse
1886  * ordering and will scan the children in the order presented.
1887  */
1888  cheapest_startup = get_singleton_append_subpath(cheapest_startup);
1889  cheapest_total = get_singleton_append_subpath(cheapest_total);
1890 
1891  startup_subpaths = lcons(cheapest_startup, startup_subpaths);
1892  total_subpaths = lcons(cheapest_total, total_subpaths);
1893  }
1894  else
1895  {
1896  /*
1897  * Otherwise, rely on accumulate_append_subpath to collect the
1898  * child paths for the MergeAppend.
1899  */
1900  accumulate_append_subpath(cheapest_startup,
1901  &startup_subpaths, NULL);
1902  accumulate_append_subpath(cheapest_total,
1903  &total_subpaths, NULL);
1904  }
1905  }
1906 
1907  /* ... and build the Append or MergeAppend paths */
1908  if (match_partition_order || match_partition_order_desc)
1909  {
1910  /* We only need Append */
1911  add_path(rel, (Path *) create_append_path(root,
1912  rel,
1913  startup_subpaths,
1914  NIL,
1915  pathkeys,
1916  NULL,
1917  0,
1918  false,
1919  partitioned_rels,
1920  -1));
1921  if (startup_neq_total)
1922  add_path(rel, (Path *) create_append_path(root,
1923  rel,
1924  total_subpaths,
1925  NIL,
1926  pathkeys,
1927  NULL,
1928  0,
1929  false,
1930  partitioned_rels,
1931  -1));
1932  }
1933  else
1934  {
1935  /* We need MergeAppend */
1936  add_path(rel, (Path *) create_merge_append_path(root,
1937  rel,
1938  startup_subpaths,
1939  pathkeys,
1940  NULL,
1941  partitioned_rels));
1942  if (startup_neq_total)
1943  add_path(rel, (Path *) create_merge_append_path(root,
1944  rel,
1945  total_subpaths,
1946  pathkeys,
1947  NULL,
1948  partitioned_rels));
1949  }
1950  }
1951 }
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
Definition: pathkeys.c:404
#define NIL
Definition: pg_list.h:65
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
Definition: pathkeys.c:699
ParamPathInfo * param_info
Definition: pathnodes.h:1148
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:639
struct Path * cheapest_total_path
Definition: pathnodes.h:684
int nparts
Definition: pathnodes.h:744
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer, List *partitioned_rels)
Definition: pathnode.c:1377
static Path * get_singleton_append_subpath(Path *path)
Definition: allpaths.c:2095
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1215
List * lappend(List *list, void *datum)
Definition: list.c:321
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
struct PartitionBoundInfoData * boundinfo
Definition: pathnodes.h:747
List * lcons(void *datum, List *list)
Definition: list.c:453
bool partitions_are_ordered(PartitionBoundInfo boundinfo, int nparts)
Definition: partbounds.c:2748
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
PartitionScheme part_scheme
Definition: pathnodes.h:743
List * pathlist
Definition: pathnodes.h:680
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2049
Definition: pg_list.h:50

◆ generate_partitionwise_join_paths()

void generate_partitionwise_join_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 3915 of file allpaths.c.

References add_paths_to_append_rel(), Alias::aliasname, Assert, RelOptInfo::baserestrictinfo, bms_next_member(), RelOptInfo::cheapest_parameterized_paths, RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, check_stack_depth(), RestrictInfo::clause, RelOptInfo::consider_partitionwise_join, RangeTblEntry::eref, generate_partitionwise_join_paths(), i, JoinPath::innerjoinpath, MergePath::innersortkeys, IS_DUMMY_REL, IS_JOIN_REL, IS_PARTITIONED_REL, IsA, RelOptInfo::joininfo, JoinPath::joinrestrictinfo, lappend(), lfirst, list_free(), lnext(), mark_dummy_rel(), MergePath::materialize_inner, NIL, nodeTag, RelOptInfo::nparts, JoinPath::outerjoinpath, MergePath::outersortkeys, Path::param_info, Path::parent, PlannerInfo::parse, RelOptInfo::part_rels, Path::pathkeys, RelOptInfo::pathlist, Path::pathtype, ParamPathInfo::ppi_req_outer, print_expr(), print_pathkeys(), printf, RelOptInfo::relids, RelOptInfo::reltarget, RelOptInfo::rows, Path::rows, Query::rtable, set_cheapest(), PlannerInfo::simple_rte_array, Path::startup_cost, generate_unaccent_rules::stdout, subpath(), T_AggPath, T_AppendPath, T_BitmapAndPath, T_BitmapHeapPath, T_BitmapOrPath, T_CteScan, T_CustomPath, T_ForeignPath, T_FunctionScan, T_GatherMergePath, T_GatherPath, T_GroupingSetsPath, T_GroupPath, T_GroupResultPath, T_HashPath, T_IncrementalSortPath, T_IndexPath, T_LimitPath, T_LockRowsPath, T_MaterialPath, T_MergeAppendPath, T_MergePath, T_MinMaxAggPath, T_ModifyTablePath, T_NamedTuplestoreScan, T_NestPath, T_Path, T_ProjectionPath, T_ProjectSetPath, T_RecursiveUnionPath, T_Result, T_SampleScan, T_SeqScan, T_SetOpPath, T_SortPath, T_SubqueryScanPath, T_TableFuncScan, T_TidPath, T_UniquePath, T_UpperUniquePath, T_ValuesScan, T_WindowAggPath, T_WorkTableScan, Path::total_cost, and PathTarget::width.

Referenced by generate_partitionwise_join_paths(), merge_clump(), and standard_join_search().

3916 {
3917  List *live_children = NIL;
3918  int cnt_parts;
3919  int num_parts;
3920  RelOptInfo **part_rels;
3921 
3922  /* Handle only join relations here. */
3923  if (!IS_JOIN_REL(rel))
3924  return;
3925 
3926  /* We've nothing to do if the relation is not partitioned. */
3927  if (!IS_PARTITIONED_REL(rel))
3928  return;
3929 
3930  /* The relation should have consider_partitionwise_join set. */
3932 
3933  /* Guard against stack overflow due to overly deep partition hierarchy. */
3935 
3936  num_parts = rel->nparts;
3937  part_rels = rel->part_rels;
3938 
3939  /* Collect non-dummy child-joins. */
3940  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
3941  {
3942  RelOptInfo *child_rel = part_rels[cnt_parts];
3943 
3944  /* If it's been pruned entirely, it's certainly dummy. */
3945  if (child_rel == NULL)
3946  continue;
3947 
3948  /* Add partitionwise join paths for partitioned child-joins. */
3949  generate_partitionwise_join_paths(root, child_rel);
3950 
3951  set_cheapest(child_rel);
3952 
3953  /* Dummy children will not be scanned, so ignore those. */
3954  if (IS_DUMMY_REL(child_rel))
3955  continue;
3956 
3957 #ifdef OPTIMIZER_DEBUG
3958  debug_print_rel(root, child_rel);
3959 #endif
3960 
3961  live_children = lappend(live_children, child_rel);
3962  }
3963 
3964  /* If all child-joins are dummy, parent join is also dummy. */
3965  if (!live_children)
3966  {
3967  mark_dummy_rel(rel);
3968  return;
3969  }
3970 
3971  /* Build additional paths for this rel from child-join paths. */
3972  add_paths_to_append_rel(root, rel, live_children);
3973  list_free(live_children);
3974 }
#define NIL
Definition: pg_list.h:65
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1301
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:3915
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:644
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1419
void check_stack_depth(void)
Definition: postgres.c:3312
int nparts
Definition: pathnodes.h:744
List * lappend(List *list, void *datum)
Definition: list.c:321
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
bool consider_partitionwise_join
Definition: pathnodes.h:737
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1261
#define Assert(condition)
Definition: c.h:745
struct RelOptInfo ** part_rels
Definition: pathnodes.h:751
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:767
void list_free(List *list)
Definition: list.c:1376
Definition: pg_list.h:50

◆ generate_useful_gather_paths()

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

Definition at line 2820 of file allpaths.c.

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

2821 {
2822  ListCell *lc;
2823  double rows;
2824  double *rowsp = NULL;
2825  List *useful_pathkeys_list = NIL;
2826  Path *cheapest_partial_path = NULL;
2827 
2828  /* If there are no partial paths, there's nothing to do here. */
2829  if (rel->partial_pathlist == NIL)
2830  return;
2831 
2832  /* Should we override the rel's rowcount estimate? */
2833  if (override_rows)
2834  rowsp = &rows;
2835 
2836  /* generate the regular gather (merge) paths */
2837  generate_gather_paths(root, rel, override_rows);
2838 
2839  /* consider incremental sort for interesting orderings */
2840  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel);
2841 
2842  /* used for explicit (full) sort paths */
2843  cheapest_partial_path = linitial(rel->partial_pathlist);
2844 
2845  /*
2846  * Consider incremental sort paths for each interesting ordering.
2847  */
2848  foreach(lc, useful_pathkeys_list)
2849  {
2850  List *useful_pathkeys = lfirst(lc);
2851  ListCell *lc2;
2852  bool is_sorted;
2853  int presorted_keys;
2854 
2855  foreach(lc2, rel->partial_pathlist)
2856  {
2857  Path *subpath = (Path *) lfirst(lc2);
2858  GatherMergePath *path;
2859 
2860  /*
2861  * If the path has no ordering at all, then we can't use either
2862  * incremental sort or rely on implict sorting with a gather
2863  * merge.
2864  */
2865  if (subpath->pathkeys == NIL)
2866  continue;
2867 
2868  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
2869  subpath->pathkeys,
2870  &presorted_keys);
2871 
2872  /*
2873  * We don't need to consider the case where a subpath is already
2874  * fully sorted because generate_gather_paths already creates a
2875  * gather merge path for every subpath that has pathkeys present.
2876  *
2877  * But since the subpath is already sorted, we know we don't need
2878  * to consider adding a sort (other either kind) on top of it, so
2879  * we can continue here.
2880  */
2881  if (is_sorted)
2882  continue;
2883 
2884  /*
2885  * Consider regular sort for the cheapest partial path (for each
2886  * useful pathkeys). We know the path is not sorted, because we'd
2887  * not get here otherwise.
2888  *
2889  * This is not redundant with the gather paths created in
2890  * generate_gather_paths, because that doesn't generate ordered
2891  * output. Here we add an explicit sort to match the useful
2892  * ordering.
2893  */
2894  if (cheapest_partial_path == subpath)
2895  {
2896  Path *tmp;
2897 
2898  tmp = (Path *) create_sort_path(root,
2899  rel,
2900  subpath,
2901  useful_pathkeys,
2902  -1.0);
2903 
2904  rows = tmp->rows * tmp->parallel_workers;
2905 
2906  path = create_gather_merge_path(root, rel,
2907  tmp,
2908  rel->reltarget,
2909  tmp->pathkeys,
2910  NULL,
2911  rowsp);
2912 
2913  add_path(rel, &path->path);
2914 
2915  /* Fall through */
2916  }
2917 
2918  /*
2919  * Consider incremental sort, but only when the subpath is already
2920  * partially sorted on a pathkey prefix.
2921  */
2922  if (enable_incremental_sort && presorted_keys > 0)
2923  {
2924  Path *tmp;
2925 
2926  /*
2927  * We should have already excluded pathkeys of length 1
2928  * because then presorted_keys > 0 would imply is_sorted was
2929  * true.
2930  */
2931  Assert(list_length(useful_pathkeys) != 1);
2932 
2933  tmp = (Path *) create_incremental_sort_path(root,
2934  rel,
2935  subpath,
2936  useful_pathkeys,
2937  presorted_keys,
2938  -1);
2939 
2940  path = create_gather_merge_path(root, rel,
2941  tmp,
2942  rel->reltarget,
2943  tmp->pathkeys,
2944  NULL,
2945  rowsp);
2946 
2947  add_path(rel, &path->path);
2948  }
2949  }
2950  }
2951 }
#define NIL
Definition: pg_list.h:65
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
bool enable_incremental_sort
Definition: costsize.c:131
SortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2802
int parallel_workers
Definition: pathnodes.h:1152
List * partial_pathlist
Definition: pathnodes.h:682
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2689
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:343
#define linitial(l)
Definition: pg_list.h:194
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:2756
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1787
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2851
List * pathkeys
Definition: pathnodes.h:1159
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
double rows
Definition: pathnodes.h:1155
static int list_length(const List *l)
Definition: pg_list.h:169
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ get_cheapest_parameterized_child_path()

static Path * get_cheapest_parameterized_child_path ( PlannerInfo root,
RelOptInfo rel,
Relids  required_outer 
)
static

Definition at line 1961 of file allpaths.c.

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

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

◆ get_singleton_append_subpath()

static Path * get_singleton_append_subpath ( Path path)
static

Definition at line 2095 of file allpaths.c.

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

Referenced by generate_orderedappend_paths().

2096 {
2097  Assert(!path->parallel_aware);
2098 
2099  if (IsA(path, AppendPath))
2100  {
2101  AppendPath *apath = (AppendPath *) path;
2102 
2103  if (list_length(apath->subpaths) == 1)
2104  return (Path *) linitial(apath->subpaths);
2105  }
2106  else if (IsA(path, MergeAppendPath))
2107  {
2108  MergeAppendPath *mpath = (MergeAppendPath *) path;
2109 
2110  if (list_length(mpath->subpaths) == 1)
2111  return (Path *) linitial(mpath->subpaths);
2112  }
2113 
2114  return path;
2115 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * subpaths
Definition: pathnodes.h:1405
#define linitial(l)
Definition: pg_list.h:194
#define Assert(condition)
Definition: c.h:745
static int list_length(const List *l)
Definition: pg_list.h:169
bool parallel_aware
Definition: pathnodes.h:1150

◆ get_useful_pathkeys_for_relation()

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

Definition at line 2756 of file allpaths.c.

References find_em_expr_for_rel(), lappend(), lfirst, list_copy(), list_length(), list_truncate(), NIL, PathKey::pk_eclass, and PlannerInfo::query_pathkeys.

Referenced by generate_useful_gather_paths().

2757 {
2758  List *useful_pathkeys_list = NIL;
2759 
2760  /*
2761  * Considering query_pathkeys is always worth it, because it might allow
2762  * us to avoid a total sort when we have a partially presorted path
2763  * available.
2764  */
2765  if (root->query_pathkeys)
2766  {
2767  ListCell *lc;
2768  int npathkeys = 0; /* useful pathkeys */
2769 
2770  foreach(lc, root->query_pathkeys)
2771  {
2772  PathKey *pathkey = (PathKey *) lfirst(lc);
2773  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
2774 
2775  /*
2776  * We can only build an Incremental Sort for pathkeys which
2777  * contain an EC member in the current relation, so ignore any
2778  * suffix of the list as soon as we find a pathkey without an EC
2779  * member the relation.
2780  *
2781  * By still returning the prefix of the pathkeys list that does
2782  * meet criteria of EC membership in the current relation, we
2783  * enable not just an incremental sort on the entirety of
2784  * query_pathkeys but also incremental sort below a JOIN.
2785  */
2786  if (!find_em_expr_for_rel(pathkey_ec, rel))
2787  break;
2788 
2789  npathkeys++;
2790  }
2791 
2792  /*
2793  * The whole query_pathkeys list matches, so append it directly, to
2794  * allow comparing pathkeys easily by comparing list pointer. If we
2795  * have to truncate the pathkeys, we gotta do a copy though.
2796  */
2797  if (npathkeys == list_length(root->query_pathkeys))
2798  useful_pathkeys_list = lappend(useful_pathkeys_list,
2799  root->query_pathkeys);
2800  else if (npathkeys > 0)
2801  useful_pathkeys_list = lappend(useful_pathkeys_list,
2803  npathkeys));
2804  }
2805 
2806  return useful_pathkeys_list;
2807 }
#define NIL
Definition: pg_list.h:65
List * query_pathkeys
Definition: pathnodes.h:298
List * list_truncate(List *list, int new_size)
Definition: list.c:585
List * list_copy(const List *oldlist)
Definition: list.c:1403
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * find_em_expr_for_rel(EquivalenceClass *ec, RelOptInfo *rel)
Definition: equivclass.c:773
#define lfirst(lc)
Definition: pg_list.h:189
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1042
static int list_length(const List *l)
Definition: pg_list.h:169
Definition: pg_list.h:50

◆ has_multiple_baserels()

static bool has_multiple_baserels ( PlannerInfo root)
static

Definition at line 2155 of file allpaths.c.

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

Referenced by set_subquery_pathlist().

2156 {
2157  int num_base_rels = 0;
2158  Index rti;
2159 
2160  for (rti = 1; rti < root->simple_rel_array_size; rti++)
2161  {
2162  RelOptInfo *brel = root->simple_rel_array[rti];
2163 
2164  if (brel == NULL)
2165  continue;
2166 
2167  /* ignore RTEs that are "other rels" */
2168  if (brel->reloptkind == RELOPT_BASEREL)
2169  if (++num_base_rels > 1)
2170  return true;
2171  }
2172  return false;
2173 }
RelOptKind reloptkind
Definition: pathnodes.h:663
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:203
int simple_rel_array_size
Definition: pathnodes.h:204
unsigned int Index
Definition: c.h:482

◆ make_one_rel()

RelOptInfo* make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 152 of file allpaths.c.

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

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

◆ make_rel_from_joinlist()

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

Definition at line 2961 of file allpaths.c.

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

2962 {
2963  int levels_needed;
2964  List *initial_rels;
2965  ListCell *jl;
2966 
2967  /*
2968  * Count the number of child joinlist nodes. This is the depth of the
2969  * dynamic-programming algorithm we must employ to consider all ways of
2970  * joining the child nodes.
2971  */
2972  levels_needed = list_length(joinlist);
2973 
2974  if (levels_needed <= 0)
2975  return NULL; /* nothing to do? */
2976 
2977  /*
2978  * Construct a list of rels corresponding to the child joinlist nodes.
2979  * This may contain both base rels and rels constructed according to
2980  * sub-joinlists.
2981  */
2982  initial_rels = NIL;
2983  foreach(jl, joinlist)
2984  {
2985  Node *jlnode = (Node *) lfirst(jl);
2986  RelOptInfo *thisrel;
2987 
2988  if (IsA(jlnode, RangeTblRef))
2989  {
2990  int varno = ((RangeTblRef *) jlnode)->rtindex;
2991 
2992  thisrel = find_base_rel(root, varno);
2993  }
2994  else if (IsA(jlnode, List))
2995  {
2996  /* Recurse to handle subproblem */
2997  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
2998  }
2999  else
3000  {
3001  elog(ERROR, "unrecognized joinlist node type: %d",
3002  (int) nodeTag(jlnode));
3003  thisrel = NULL; /* keep compiler quiet */
3004  }
3005 
3006  initial_rels = lappend(initial_rels, thisrel);
3007  }
3008 
3009  if (levels_needed == 1)
3010  {
3011  /*
3012  * Single joinlist node, so we're done.
3013  */
3014  return (RelOptInfo *) linitial(initial_rels);
3015  }
3016  else
3017  {
3018  /*
3019  * Consider the different orders in which we could join the rels,
3020  * using a plugin, GEQO, or the regular join search code.
3021  *
3022  * We put the initial_rels list into a PlannerInfo field because
3023  * has_legal_joinclause() needs to look at it (ugly :-().
3024  */
3025  root->initial_rels = initial_rels;
3026 
3027  if (join_search_hook)
3028  return (*join_search_hook) (root, levels_needed, initial_rels);
3029  else if (enable_geqo && levels_needed >= geqo_threshold)
3030  return geqo(root, levels_needed, initial_rels);
3031  else
3032  return standard_join_search(root, levels_needed, initial_rels);
3033  }
3034 }
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:3066
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Definition: nodes.h:528
#define linitial(l)
Definition: pg_list.h:194
#define ERROR
Definition: elog.h:43
bool enable_geqo
Definition: allpaths.c:62
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:2961
List * lappend(List *list, void *datum)
Definition: list.c:321
join_search_hook_type join_search_hook
Definition: allpaths.c:71
int geqo_threshold
Definition: allpaths.c:63
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:67
#define lfirst(lc)
Definition: pg_list.h:189
static int list_length(const List *l)
Definition: pg_list.h:169
#define nodeTag(nodeptr)
Definition: nodes.h:533
#define elog(elevel,...)
Definition: elog.h:214
List * initial_rels
Definition: pathnodes.h:308
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
Definition: pg_list.h:50

◆ qual_is_pushdown_safe()

static bool qual_is_pushdown_safe ( Query subquery,
Index  rti,
Node qual,
pushdown_safety_info safetyInfo 
)
static

Definition at line 3501 of file allpaths.c.

References Assert, contain_leaked_vars(), contain_subplans(), contain_volatile_functions(), contain_window_function(), 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().

3503 {
3504  bool safe = true;
3505  List *vars;
3506  ListCell *vl;
3507 
3508  /* Refuse subselects (point 1) */
3509  if (contain_subplans(qual))
3510  return false;
3511 
3512  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
3513  if (safetyInfo->unsafeVolatile &&
3515  return false;
3516 
3517  /* Refuse leaky quals if told to (point 3) */
3518  if (safetyInfo->unsafeLeaky &&
3519  contain_leaked_vars(qual))
3520  return false;
3521 
3522  /*
3523  * It would be unsafe to push down window function calls, but at least for
3524  * the moment we could never see any in a qual anyhow. (The same applies
3525  * to aggregates, which we check for in pull_var_clause below.)
3526  */
3528 
3529  /*
3530  * Examine all Vars used in clause. Since it's a restriction clause, all
3531  * such Vars must refer to subselect output columns ... unless this is
3532  * part of a LATERAL subquery, in which case there could be lateral
3533  * references.
3534  */
3536  foreach(vl, vars)
3537  {
3538  Var *var = (Var *) lfirst(vl);
3539 
3540  /*
3541  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
3542  * It's not clear whether a PHV could safely be pushed down, and even
3543  * less clear whether such a situation could arise in any cases of
3544  * practical interest anyway. So for the moment, just refuse to push
3545  * down.
3546  */
3547  if (!IsA(var, Var))
3548  {
3549  safe = false;
3550  break;
3551  }
3552 
3553  /*
3554  * Punt if we find any lateral references. It would be safe to push
3555  * these down, but we'd have to convert them into outer references,
3556  * which subquery_push_qual lacks the infrastructure to do. The case
3557  * arises so seldom that it doesn't seem worth working hard on.
3558  */
3559  if (var->varno != rti)
3560  {
3561  safe = false;
3562  break;
3563  }
3564 
3565  /* Subqueries have no system columns */
3566  Assert(var->varattno >= 0);
3567 
3568  /* Check point 4 */
3569  if (var->varattno == 0)
3570  {
3571  safe = false;
3572  break;
3573  }
3574 
3575  /* Check point 5 */
3576  if (safetyInfo->unsafeColumns[var->varattno])
3577  {
3578  safe = false;
3579  break;
3580  }
3581  }
3582 
3583  list_free(vars);
3584 
3585  return safe;
3586 }
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1361
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
AttrNumber varattno
Definition: primnodes.h:186
bool * unsafeColumns
Definition: allpaths.c:56
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:724
Definition: primnodes.h:181
bool contain_subplans(Node *clause)
Definition: clauses.c:610
bool contain_window_function(Node *clause)
Definition: clauses.c:494
Index varno
Definition: primnodes.h:184
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:175
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
void list_free(List *list)
Definition: list.c:1376
Definition: regcomp.c:224
Definition: pg_list.h:50

◆ recurse_push_qual()

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

Definition at line 3639 of file allpaths.c.

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

3641 {
3642  if (IsA(setOp, RangeTblRef))
3643  {
3644  RangeTblRef *rtr = (RangeTblRef *) setOp;
3645  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
3646  Query *subquery = subrte->subquery;
3647 
3648  Assert(subquery != NULL);
3649  subquery_push_qual(subquery, rte, rti, qual);
3650  }
3651  else if (IsA(setOp, SetOperationStmt))
3652  {
3653  SetOperationStmt *op = (SetOperationStmt *) setOp;
3654 
3655  recurse_push_qual(op->larg, topquery, rte, rti, qual);
3656  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
3657  }
3658  else
3659  {
3660  elog(ERROR, "unrecognized node type: %d",
3661  (int) nodeTag(setOp));
3662  }
3663 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define Assert(condition)
Definition: c.h:745
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3592
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3639
#define nodeTag(nodeptr)
Definition: nodes.h:533
Query * subquery
Definition: parsenodes.h:1012
#define elog(elevel,...)
Definition: elog.h:214

◆ recurse_pushdown_safe()

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

Definition at line 3291 of file allpaths.c.

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

3293 {
3294  if (IsA(setOp, RangeTblRef))
3295  {
3296  RangeTblRef *rtr = (RangeTblRef *) setOp;
3297  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
3298  Query *subquery = rte->subquery;
3299 
3300  Assert(subquery != NULL);
3301  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
3302  }
3303  else if (IsA(setOp, SetOperationStmt))
3304  {
3305  SetOperationStmt *op = (SetOperationStmt *) setOp;
3306 
3307  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
3308  if (op->op == SETOP_EXCEPT)
3309  return false;
3310  /* Else recurse */
3311  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
3312  return false;
3313  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
3314  return false;
3315  }
3316  else
3317  {
3318  elog(ERROR, "unrecognized node type: %d",
3319  (int) nodeTag(setOp));
3320  }
3321  return true;
3322 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3291
List * rtable
Definition: parsenodes.h:137
#define ERROR
Definition: elog.h:43
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define Assert(condition)
Definition: c.h:745
SetOperation op
Definition: parsenodes.h:1659
#define nodeTag(nodeptr)
Definition: nodes.h:533
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3235
Query * subquery
Definition: parsenodes.h:1012
#define elog(elevel,...)
Definition: elog.h:214

◆ remove_unused_subquery_outputs()

static void remove_unused_subquery_outputs ( Query subquery,
RelOptInfo rel 
)
static

Definition at line 3686 of file allpaths.c.

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, lfirst, makeNullConst(), pull_varattnos(), RelOptInfo::relid, RelOptInfo::reltarget, TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::setOperations, and Query::targetList.

Referenced by set_subquery_pathlist().

3687 {
3688  Bitmapset *attrs_used = NULL;
3689  ListCell *lc;
3690 
3691  /*
3692  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
3693  * could update all the child SELECTs' tlists, but it seems not worth the
3694  * trouble presently.
3695  */
3696  if (subquery->setOperations)
3697  return;
3698 
3699  /*
3700  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
3701  * time: all its output columns must be used in the distinctClause.
3702  */
3703  if (subquery->distinctClause && !subquery->hasDistinctOn)
3704  return;
3705 
3706  /*
3707  * Collect a bitmap of all the output column numbers used by the upper
3708  * query.
3709  *
3710  * Add all the attributes needed for joins or final output. Note: we must
3711  * look at rel's targetlist, not the attr_needed data, because attr_needed
3712  * isn't computed for inheritance child rels, cf set_append_rel_size().
3713  * (XXX might be worth changing that sometime.)
3714  */
3715  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
3716 
3717  /* Add all the attributes used by un-pushed-down restriction clauses. */
3718  foreach(lc, rel->baserestrictinfo)
3719  {
3720  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3721 
3722  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
3723  }
3724 
3725  /*
3726  * If there's a whole-row reference to the subquery, we can't remove
3727  * anything.
3728  */
3730  return;
3731 
3732  /*
3733  * Run through the tlist and zap entries we don't need. It's okay to
3734  * modify the tlist items in-place because set_subquery_pathlist made a
3735  * copy of the subquery.
3736  */
3737  foreach(lc, subquery->targetList)
3738  {
3739  TargetEntry *tle = (TargetEntry *) lfirst(lc);
3740  Node *texpr = (Node *) tle->expr;
3741 
3742  /*
3743  * If it has a sortgroupref number, it's used in some sort/group
3744  * clause so we'd better not remove it. Also, don't remove any
3745  * resjunk columns, since their reason for being has nothing to do
3746  * with anybody reading the subquery's output. (It's likely that
3747  * resjunk columns in a sub-SELECT would always have ressortgroupref
3748  * set, but even if they don't, it seems imprudent to remove them.)
3749  */
3750  if (tle->ressortgroupref || tle->resjunk)
3751  continue;
3752 
3753  /*
3754  * If it's used by the upper query, we can't remove it.
3755  */
3757  attrs_used))
3758  continue;
3759 
3760  /*
3761  * If it contains a set-returning function, we can't remove it since
3762  * that could change the number of rows returned by the subquery.
3763  */
3764  if (subquery->hasTargetSRFs &&
3765  expression_returns_set(texpr))
3766  continue;
3767 
3768  /*
3769  * If it contains volatile functions, we daren't remove it for fear
3770  * that the user is expecting their side-effects to happen.
3771  */
3772  if (contain_volatile_functions(texpr))
3773  continue;
3774 
3775  /*
3776  * OK, we don't need it. Replace the expression with a NULL constant.
3777  * Preserve the exposed type of the expression, in case something
3778  * looks at the rowtype of the subquery's result.
3779  */
3780  tle->expr = (Expr *) makeNullConst(exprType(texpr),
3781  exprTypmod(texpr),
3782  exprCollation(texpr));
3783  }
3784 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
List * baserestrictinfo
Definition: pathnodes.h:728
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:718
Definition: nodes.h:528
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:724
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
bool hasDistinctOn
Definition: parsenodes.h:129
List * targetList
Definition: parsenodes.h:140
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:337
bool resjunk
Definition: primnodes.h:1417
List * distinctClause
Definition: parsenodes.h:156
AttrNumber resno
Definition: primnodes.h:1411
Index relid
Definition: pathnodes.h:694
Expr * clause
Definition: pathnodes.h:1986
List * exprs
Definition: pathnodes.h:1075
bool hasTargetSRFs
Definition: parsenodes.h:127
#define lfirst(lc)
Definition: pg_list.h:189
Expr * expr
Definition: primnodes.h:1410
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:768
Node * setOperations
Definition: parsenodes.h:166
Index ressortgroupref
Definition: primnodes.h:1413
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
struct PathTarget * reltarget
Definition: pathnodes.h:677

◆ set_append_rel_pathlist()

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

Definition at line 1225 of file allpaths.c.

References add_paths_to_append_rel(), PlannerInfo::append_rel_list, AppendRelInfo::child_relid, RelOptInfo::consider_parallel, IS_DUMMY_REL, lappend(), lfirst, list_concat(), NIL, AppendRelInfo::parent_relid, RelOptInfo::part_scheme, RelOptInfo::partitioned_child_rels, set_rel_pathlist(), PlannerInfo::simple_rel_array, and PlannerInfo::simple_rte_array.

Referenced by set_rel_pathlist().

1227 {
1228  int parentRTindex = rti;
1229  List *live_childrels = NIL;
1230  ListCell *l;
1231 
1232  /*
1233  * Generate access paths for each member relation, and remember the
1234  * non-dummy children.
1235  */
1236  foreach(l, root->append_rel_list)
1237  {
1238  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1239  int childRTindex;
1240  RangeTblEntry *childRTE;
1241  RelOptInfo *childrel;
1242 
1243  /* append_rel_list contains all append rels; ignore others */
1244  if (appinfo->parent_relid != parentRTindex)
1245  continue;
1246 
1247  /* Re-locate the child RTE and RelOptInfo */
1248  childRTindex = appinfo->child_relid;
1249  childRTE = root->simple_rte_array[childRTindex];
1250  childrel = root->simple_rel_array[childRTindex];
1251 
1252  /*
1253  * If set_append_rel_size() decided the parent appendrel was
1254  * parallel-unsafe at some point after visiting this child rel, we
1255  * need to propagate the unsafety marking down to the child, so that
1256  * we don't generate useless partial paths for it.
1257  */
1258  if (!rel->consider_parallel)
1259  childrel->consider_parallel = false;
1260 
1261  /*
1262  * Compute the child's access paths.
1263  */
1264  set_rel_pathlist(root, childrel, childRTindex, childRTE);
1265 
1266  /*
1267  * If child is dummy, ignore it.
1268  */
1269  if (IS_DUMMY_REL(childrel))
1270  continue;
1271 
1272  /* Bubble up childrel's partitioned children. */
1273  if (rel->part_scheme)
1274  rel->partitioned_child_rels =
1276  childrel->partitioned_child_rels);
1277 
1278  /*
1279  * Child is live, so add it to the live_childrels list for use below.
1280  */
1281  live_childrels = lappend(live_childrels, childrel);
1282  }
1283 
1284  /* Add paths to the append relation. */
1285  add_paths_to_append_rel(root, rel, live_childrels);
1286 }
#define NIL
Definition: pg_list.h:65
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1301
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:203
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1419
List * lappend(List *list, void *datum)
Definition: list.c:321
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
List * append_rel_list
Definition: pathnodes.h:290
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:470
#define lfirst(lc)
Definition: pg_list.h:189
bool consider_parallel
Definition: pathnodes.h:674
List * partitioned_child_rels
Definition: pathnodes.h:756
PartitionScheme part_scheme
Definition: pathnodes.h:743
Index child_relid
Definition: pathnodes.h:2231
Index parent_relid
Definition: pathnodes.h:2230
Definition: pg_list.h:50

◆ set_append_rel_size()

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

Definition at line 946 of file allpaths.c.

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, list_make1_int, RelOptInfo::max_attr, RelOptInfo::min_attr, palloc0(), PlannerGlobal::parallelModeOK, AppendRelInfo::parent_relid, RelOptInfo::partitioned_child_rels, 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, and PathTarget::width.

Referenced by set_rel_size().

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

◆ set_base_rel_consider_startup()

static void set_base_rel_consider_startup ( PlannerInfo root)
static

Definition at line 248 of file allpaths.c.

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

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

◆ set_base_rel_pathlists()

static void set_base_rel_pathlists ( PlannerInfo root)
static

Definition at line 334 of file allpaths.c.

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

335 {
336  Index rti;
337 
338  for (rti = 1; rti < root->simple_rel_array_size; rti++)
339  {
340  RelOptInfo *rel = root->simple_rel_array[rti];
341 
342  /* there may be empty slots corresponding to non-baserel RTEs */
343  if (rel == NULL)
344  continue;
345 
346  Assert(rel->relid == rti); /* sanity check on array */
347 
348  /* ignore RTEs that are "other rels" */
349  if (rel->reloptkind != RELOPT_BASEREL)
350  continue;
351 
352  set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
353  }
354 }
RelOptKind reloptkind
Definition: pathnodes.h:663
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:203
int simple_rel_array_size
Definition: pathnodes.h:204
Index relid
Definition: pathnodes.h:694
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:211
unsigned int Index
Definition: c.h:482
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:470
#define Assert(condition)
Definition: c.h:745

◆ set_base_rel_sizes()

static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 291 of file allpaths.c.

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

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

◆ set_cte_pathlist()

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

Definition at line 2504 of file allpaths.c.

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

2505 {
2506  Plan *cteplan;
2507  PlannerInfo *cteroot;
2508  Index levelsup;
2509  int ndx;
2510  ListCell *lc;
2511  int plan_id;
2512  Relids required_outer;
2513 
2514  /*
2515  * Find the referenced CTE, and locate the plan previously made for it.
2516  */
2517  levelsup = rte->ctelevelsup;
2518  cteroot = root;
2519  while (levelsup-- > 0)
2520  {
2521  cteroot = cteroot->parent_root;
2522  if (!cteroot) /* shouldn't happen */
2523  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2524  }
2525 
2526  /*
2527  * Note: cte_plan_ids can be shorter than cteList, if we are still working
2528  * on planning the CTEs (ie, this is a side-reference from another CTE).
2529  * So we mustn't use forboth here.
2530  */
2531  ndx = 0;
2532  foreach(lc, cteroot->parse->cteList)
2533  {
2534  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
2535 
2536  if (strcmp(cte->ctename, rte->ctename) == 0)
2537  break;
2538  ndx++;
2539  }
2540  if (lc == NULL) /* shouldn't happen */
2541  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
2542  if (ndx >= list_length(cteroot->cte_plan_ids))
2543  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
2544  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
2545  Assert(plan_id > 0);
2546  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
2547 
2548  /* Mark rel with estimated output rows, width, etc */
2549  set_cte_size_estimates(root, rel, cteplan->plan_rows);
2550 
2551  /*
2552  * We don't support pushing join clauses into the quals of a CTE scan, but
2553  * it could still have required parameterization due to LATERAL refs in
2554  * its tlist.
2555  */
2556  required_outer = rel->lateral_relids;
2557 
2558  /* Generate appropriate path */
2559  add_path(rel, create_ctescan_path(root, rel, required_outer));
2560 }
double plan_rows
Definition: plannodes.h:129
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
PlannerInfo * parent_root
Definition: pathnodes.h:185
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:5321
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:297
Relids lateral_relids
Definition: pathnodes.h:691
#define ERROR
Definition: elog.h:43
static void * list_nth(const List *list, int n)
Definition: pg_list.h:286
List * subplans
Definition: pathnodes.h:111
PlannerGlobal * glob
Definition: pathnodes.h:181
List * cte_plan_ids
Definition: pathnodes.h:261
unsigned int Index
Definition: c.h:482
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
static int list_length(const List *l)
Definition: pg_list.h:169
Index ctelevelsup
Definition: parsenodes.h:1081
List * cteList
Definition: parsenodes.h:135
char * ctename
Definition: parsenodes.h:1080
#define elog(elevel,...)
Definition: elog.h:214
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2023

◆ set_dummy_rel_pathlist()

static void set_dummy_rel_pathlist ( RelOptInfo rel)
static

Definition at line 2129 of file allpaths.c.

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

2130 {
2131  /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
2132  rel->rows = 0;
2133  rel->reltarget->width = 0;
2134 
2135  /* Discard any pre-existing paths; no further need for them */
2136  rel->pathlist = NIL;
2137  rel->partial_pathlist = NIL;
2138 
2139  /* Set up the dummy path */
2140  add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
2141  NIL, rel->lateral_relids,
2142  0, false, NIL, -1));
2143 
2144  /*
2145  * We set the cheapest-path fields immediately, just in case they were
2146  * pointing at some discarded path. This is redundant when we're called
2147  * from set_rel_size(), but not when called from elsewhere, and doing it
2148  * twice is harmless anyway.
2149  */
2150  set_cheapest(rel);
2151 }
#define NIL
Definition: pg_list.h:65
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
List * partial_pathlist
Definition: pathnodes.h:682
Relids lateral_relids
Definition: pathnodes.h:691
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, List *partitioned_rels, double rows)
Definition: pathnode.c:1215
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
double rows
Definition: pathnodes.h:669
List * pathlist
Definition: pathnodes.h:680
struct PathTarget * reltarget
Definition: pathnodes.h:677

◆ set_foreign_pathlist()

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

Definition at line 928 of file allpaths.c.

References RelOptInfo::fdwroutine, FdwRoutine::GetForeignPaths, and RangeTblEntry::relid.

Referenced by set_rel_pathlist().

929 {
930  /* Call the FDW's GetForeignPaths function to generate path(s) */
931  rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
932 }
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:189

◆ set_foreign_size()

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

Definition at line 904 of file allpaths.c.

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

905 {
906  /* Mark rel with estimated output rows, width, etc */
907  set_foreign_size_estimates(root, rel);
908 
909  /* Let FDW adjust the size estimates, if it can */
910  rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
911 
912  /* ... but do not let it set the rows estimate to zero */
913  rel->rows = clamp_row_est(rel->rows);
914 
915  /*
916  * Also, make sure rel->tuples is not insane relative to rel->rows.
917  * Notably, this ensures sanity if pg_class.reltuples contains -1 and the
918  * FDW doesn't do anything to replace that.
919  */
920  rel->tuples = Max(rel->tuples, rel->rows);
921 }
double tuples
Definition: pathnodes.h:706
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:719
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:188
double rows
Definition: pathnodes.h:669
#define Max(x, y)
Definition: c.h:921
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5420
double clamp_row_est(double nrows)
Definition: costsize.c:189

◆ set_function_pathlist()

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

Definition at line 2392 of file allpaths.c.

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

2393 {
2394  Relids required_outer;
2395  List *pathkeys = NIL;
2396 
2397  /*
2398  * We don't support pushing join clauses into the quals of a function
2399  * scan, but it could still have required parameterization due to LATERAL
2400  * refs in the function expression.
2401  */
2402  required_outer = rel->lateral_relids;
2403 
2404  /*
2405  * The result is considered unordered unless ORDINALITY was used, in which
2406  * case it is ordered by the ordinal column (the last one). See if we
2407  * care, by checking for uses of that Var in equivalence classes.
2408  */
2409  if (rte->funcordinality)
2410  {
2411  AttrNumber ordattno = rel->max_attr;
2412  Var *var = NULL;
2413  ListCell *lc;
2414 
2415  /*
2416  * Is there a Var for it in rel's targetlist? If not, the query did
2417  * not reference the ordinality column, or at least not in any way
2418  * that would be interesting for sorting.
2419  */
2420  foreach(lc, rel->reltarget->exprs)
2421  {
2422  Var *node = (Var *) lfirst(lc);
2423 
2424  /* checking varno/varlevelsup is just paranoia */
2425  if (IsA(node, Var) &&
2426  node->varattno == ordattno &&
2427  node->varno == rel->relid &&
2428  node->varlevelsup == 0)
2429  {
2430  var = node;
2431  break;
2432  }
2433  }
2434 
2435  /*
2436  * Try to build pathkeys for this Var with int8 sorting. We tell
2437  * build_expression_pathkey not to build any new equivalence class; if
2438  * the Var isn't already mentioned in some EC, it means that nothing
2439  * cares about the ordering.
2440  */
2441  if (var)
2442  pathkeys = build_expression_pathkey(root,
2443  (Expr *) var,
2444  NULL, /* below outer joins */
2445  Int8LessOperator,
2446  rel->relids,
2447  false);
2448  }
2449 
2450  /* Generate appropriate path */
2451  add_path(rel, create_functionscan_path(root, rel,
2452  pathkeys, required_outer));
2453 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:782
Index varlevelsup
Definition: primnodes.h:191
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
AttrNumber varattno
Definition: primnodes.h:186
bool funcordinality
Definition: parsenodes.h:1065
Definition: primnodes.h:181
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1945
Relids lateral_relids
Definition: pathnodes.h:691
Relids relids
Definition: pathnodes.h:666
Index relid
Definition: pathnodes.h:694
Index varno
Definition: primnodes.h:184
List * exprs
Definition: pathnodes.h:1075
#define lfirst(lc)
Definition: pg_list.h:189
AttrNumber max_attr
Definition: pathnodes.h:698
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:677
int16 AttrNumber
Definition: attnum.h:21

◆ set_namedtuplestore_pathlist()

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

Definition at line 2570 of file allpaths.c.

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

Referenced by set_rel_size().

2572 {
2573  Relids required_outer;
2574 
2575  /* Mark rel with estimated output rows, width, etc */
2577 
2578  /*
2579  * We don't support pushing join clauses into the quals of a tuplestore
2580  * scan, but it could still have required parameterization due to LATERAL
2581  * refs in its tlist.
2582  */
2583  required_outer = rel->lateral_relids;
2584 
2585  /* Generate appropriate path */
2586  add_path(rel, create_namedtuplestorescan_path(root, rel, required_outer));
2587 
2588  /* Select cheapest path (pretty easy in this case...) */
2589  set_cheapest(rel);
2590 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Relids lateral_relids
Definition: pathnodes.h:691
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
void set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5358
Path * create_namedtuplestorescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2048

◆ set_plain_rel_pathlist()

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

Definition at line 766 of file allpaths.c.

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

767 {
768  Relids required_outer;
769 
770  /*
771  * We don't support pushing join clauses into the quals of a seqscan, but
772  * it could still have required parameterization due to LATERAL refs in
773  * its tlist.
774  */
775  required_outer = rel->lateral_relids;
776 
777  /* Consider sequential scan */
778  add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
779 
780  /* If appropriate, consider parallel sequential scan */
781  if (rel->consider_parallel && required_outer == NULL)
782  create_plain_partial_paths(root, rel);
783 
784  /* Consider index scans */
785  create_index_paths(root, rel);
786 
787  /* Consider TID scans */
788  create_tidscan_paths(root, rel);
789 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:231
Relids lateral_relids
Definition: pathnodes.h:691
void create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: tidpath.c:385
bool consider_parallel
Definition: pathnodes.h:674
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:796
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929

◆ set_plain_rel_size()

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

Definition at line 574 of file allpaths.c.

References check_index_predicates(), and set_baserel_size_estimates().

Referenced by set_rel_size().

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

◆ set_rel_consider_parallel()

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

Definition at line 591 of file allpaths.c.

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

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

◆ set_rel_pathlist()

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

Definition at line 470 of file allpaths.c.

References bms_membership(), BMS_SINGLETON, elog, ERROR, generate_useful_gather_paths(), RangeTblEntry::inh, IS_DUMMY_REL, RangeTblEntry::relkind, RELOPT_BASEREL, 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().

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

◆ set_rel_size()

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

Definition at line 361 of file allpaths.c.

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

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

◆ set_result_pathlist()

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

Definition at line 2600 of file allpaths.c.

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

Referenced by set_rel_size().

2602 {
2603  Relids required_outer;
2604 
2605  /* Mark rel with estimated output rows, width, etc */
2606  set_result_size_estimates(root, rel);
2607 
2608  /*
2609  * We don't support pushing join clauses into the quals of a Result scan,
2610  * but it could still have required parameterization due to LATERAL refs
2611  * in its tlist.
2612  */
2613  required_outer = rel->lateral_relids;
2614 
2615  /* Generate appropriate path */
2616  add_path(rel, create_resultscan_path(root, rel, required_outer));
2617 
2618  /* Select cheapest path (pretty easy in this case...) */
2619  set_cheapest(rel);
2620 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Path * create_resultscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2074
void set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5391
Relids lateral_relids
Definition: pathnodes.h:691
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244

◆ set_subquery_pathlist()

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

Definition at line 2188 of file allpaths.c.

References add_partial_path(), add_path(), Assert, RelOptInfo::baserestrictinfo, bms_is_empty(), RestrictInfo::clause, RelOptInfo::consider_parallel, convert_subquery_pathkeys(), copyObject, create_subqueryscan_path(), Query::distinctClause, fetch_upper_rel(), PlannerInfo::glob, Query::groupClause, Query::groupingSets, has_multiple_baserels(), Query::hasAggs, Query::havingQual, IS_DUMMY_REL, lappend(), RelOptInfo::lateral_relids, lfirst, list_length(), make_tlist_from_pathtarget(), NIL, palloc0(), parse(), PlannerInfo::parse, RelOptInfo::partial_pathlist, Path::pathkeys, RelOptInfo::pathlist, Path::pathtarget, 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(), Query::sortClause, 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().

2190 {
2191  Query *parse = root->parse;
2192  Query *subquery = rte->subquery;
2193  Relids required_outer;
2194  pushdown_safety_info safetyInfo;
2195  double tuple_fraction;
2196  RelOptInfo *sub_final_rel;
2197  ListCell *lc;
2198 
2199  /*
2200  * Must copy the Query so that planning doesn't mess up the RTE contents
2201  * (really really need to fix the planner to not scribble on its input,
2202  * someday ... but see remove_unused_subquery_outputs to start with).
2203  */
2204  subquery = copyObject(subquery);
2205 
2206  /*
2207  * If it's a LATERAL subquery, it might contain some Vars of the current
2208  * query level, requiring it to be treated as parameterized, even though
2209  * we don't support pushing down join quals into subqueries.
2210  */
2211  required_outer = rel->lateral_relids;
2212 
2213  /*
2214  * Zero out result area for subquery_is_pushdown_safe, so that it can set
2215  * flags as needed while recursing. In particular, we need a workspace
2216  * for keeping track of unsafe-to-reference columns. unsafeColumns[i]
2217  * will be set true if we find that output column i of the subquery is
2218  * unsafe to use in a pushed-down qual.
2219  */
2220  memset(&safetyInfo, 0, sizeof(safetyInfo));
2221  safetyInfo.unsafeColumns = (bool *)
2222  palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
2223 
2224  /*
2225  * If the subquery has the "security_barrier" flag, it means the subquery
2226  * originated from a view that must enforce row level security. Then we
2227  * must not push down quals that contain leaky functions. (Ideally this
2228  * would be checked inside subquery_is_pushdown_safe, but since we don't
2229  * currently pass the RTE to that function, we must do it here.)
2230  */
2231  safetyInfo.unsafeLeaky = rte->security_barrier;
2232 
2233  /*
2234  * If there are any restriction clauses that have been attached to the
2235  * subquery relation, consider pushing them down to become WHERE or HAVING
2236  * quals of the subquery itself. This transformation is useful because it
2237  * may allow us to generate a better plan for the subquery than evaluating
2238  * all the subquery output rows and then filtering them.
2239  *
2240  * There are several cases where we cannot push down clauses. Restrictions
2241  * involving the subquery are checked by subquery_is_pushdown_safe().
2242  * Restrictions on individual clauses are checked by
2243  * qual_is_pushdown_safe(). Also, we don't want to push down
2244  * pseudoconstant clauses; better to have the gating node above the
2245  * subquery.
2246  *
2247  * Non-pushed-down clauses will get evaluated as qpquals of the
2248  * SubqueryScan node.
2249  *
2250  * XXX Are there any cases where we want to make a policy decision not to
2251  * push down a pushable qual, because it'd result in a worse plan?
2252  */
2253  if (rel->baserestrictinfo != NIL &&
2254  subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
2255  {
2256  /* OK to consider pushing down individual quals */
2257  List *upperrestrictlist = NIL;
2258  ListCell *l;
2259 
2260  foreach(l, rel->baserestrictinfo)
2261  {
2262  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2263  Node *clause = (Node *) rinfo->clause;
2264 
2265  if (!rinfo->pseudoconstant &&
2266  qual_is_pushdown_safe(subquery, rti, clause, &safetyInfo))
2267  {
2268  /* Push it down */
2269  subquery_push_qual(subquery, rte, rti, clause);
2270  }
2271  else
2272  {
2273  /* Keep it in the upper query */
2274  upperrestrictlist = lappend(upperrestrictlist, rinfo);
2275  }
2276  }
2277  rel->baserestrictinfo = upperrestrictlist;
2278  /* We don't bother recomputing baserestrict_min_security */
2279  }
2280 
2281  pfree(safetyInfo.unsafeColumns);
2282 
2283  /*
2284  * The upper query might not use all the subquery's output columns; if
2285  * not, we can simplify.
2286  */
2287  remove_unused_subquery_outputs(subquery, rel);
2288 
2289  /*
2290  * We can safely pass the outer tuple_fraction down to the subquery if the
2291  * outer level has no joining, aggregation, or sorting to do. Otherwise
2292  * we'd better tell the subquery to plan for full retrieval. (XXX This
2293  * could probably be made more intelligent ...)
2294  */
2295  if (parse->hasAggs ||
2296  parse->groupClause ||
2297  parse->groupingSets ||
2298  parse->havingQual ||
2299  parse->distinctClause ||
2300  parse->sortClause ||
2301  has_multiple_baserels(root))
2302  tuple_fraction = 0.0; /* default case */
2303  else
2304  tuple_fraction = root->tuple_fraction;
2305 
2306  /* plan_params should not be in use in current query level */
2307  Assert(root->plan_params == NIL);
2308 
2309  /* Generate a subroot and Paths for the subquery */
2310  rel->subroot = subquery_planner(root->glob, subquery,
2311  root,
2312  false, tuple_fraction);
2313 
2314  /* Isolate the params needed by this specific subplan */
2315  rel->subplan_params = root->plan_params;
2316  root->plan_params = NIL;
2317 
2318  /*
2319  * It's possible that constraint exclusion proved the subquery empty. If
2320  * so, it's desirable to produce an unadorned dummy path so that we will
2321  * recognize appropriate optimizations at this query level.
2322  */
2323  sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
2324 
2325  if (IS_DUMMY_REL(sub_final_rel))
2326  {
2328  return;
2329  }
2330 
2331  /*
2332  * Mark rel with estimated output rows, width, etc. Note that we have to
2333  * do this before generating outer-query paths, else cost_subqueryscan is
2334  * not happy.
2335  */
2336  set_subquery_size_estimates(root, rel);
2337 
2338  /*
2339  * For each Path that subquery_planner produced, make a SubqueryScanPath
2340  * in the outer query.
2341  */
2342  foreach(lc, sub_final_rel->pathlist)
2343  {
2344  Path *subpath = (Path *) lfirst(lc);
2345  List *pathkeys;
2346 
2347  /* Convert subpath's pathkeys to outer representation */
2348  pathkeys = convert_subquery_pathkeys(root,
2349  rel,
2350  subpath->pathkeys,
2352 
2353  /* Generate outer path using this subpath */
2354  add_path(rel, (Path *)
2355  create_subqueryscan_path(root, rel, subpath,
2356  pathkeys, required_outer));
2357  }
2358 
2359  /* If outer rel allows parallelism, do same for partial paths. */
2360  if (rel->consider_parallel && bms_is_empty(required_outer))
2361  {
2362  /* If consider_parallel is false, there should be no partial paths. */
2363  Assert(sub_final_rel->consider_parallel ||
2364  sub_final_rel->partial_pathlist == NIL);
2365 
2366  /* Same for partial paths. */
2367  foreach(lc, sub_final_rel->partial_pathlist)
2368  {
2369  Path *subpath = (Path *) lfirst(lc);
2370  List *pathkeys;
2371 
2372  /* Convert subpath's pathkeys to outer representation */
2373  pathkeys = convert_subquery_pathkeys(root,
2374  rel,
2375  subpath->pathkeys,
2377 
2378  /* Generate outer path using this subpath */
2379  add_partial_path(rel, (Path *)
2380  create_subqueryscan_path(root, rel, subpath,
2381  pathkeys,
2382  required_outer));
2383  }
2384  }
2385 }
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5149
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1146
Query * parse
Definition: pathnodes.h:179
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1917
List * plan_params
Definition: pathnodes.h:193
List * sortClause
Definition: parsenodes.h:158
List * baserestrictinfo
Definition: pathnodes.h:728
bool hasAggs
Definition: parsenodes.h:125
bool pseudoconstant
Definition: pathnodes.h:1994
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:528
List * partial_pathlist
Definition: pathnodes.h:682
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:639
bool * unsafeColumns
Definition: allpaths.c:56
List * targetList
Definition: parsenodes.h:140
PlannerInfo * subroot
Definition: pathnodes.h:710
Relids lateral_relids
Definition: pathnodes.h:691
double tuple_fraction
Definition: pathnodes.h:336
void pfree(void *pointer)
Definition: mcxt.c:1057
List * distinctClause
Definition: parsenodes.h:156
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1419
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1192
static void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:2129
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:838
PlannerGlobal * glob
Definition: pathnodes.h:181
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel)
Definition: allpaths.c:3686
List * lappend(List *list, void *datum)
Definition: list.c:321
Expr * clause
Definition: pathnodes.h:1986
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3501
void * palloc0(Size size)
Definition: mcxt.c:981
bool security_barrier
Definition: parsenodes.h:1013
List * pathkeys
Definition: pathnodes.h:1159
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
static bool has_multiple_baserels(PlannerInfo *root)
Definition: allpaths.c:2155
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3592
static int list_length(const List *l)
Definition: pg_list.h:169
bool consider_parallel
Definition: pathnodes.h:674
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3235
Query * subquery
Definition: parsenodes.h:1012
List * groupClause
Definition: parsenodes.h:148
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:749
List * pathlist
Definition: pathnodes.h:680
#define copyObject(obj)
Definition: nodes.h:644
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
List * subplan_params
Definition: pathnodes.h:711
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:597
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648
unsigned char bool
Definition: c.h:324

◆ set_tablefunc_pathlist()

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

Definition at line 2480 of file allpaths.c.

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

Referenced by set_rel_pathlist().

2481 {
2482  Relids required_outer;
2483 
2484  /*
2485  * We don't support pushing join clauses into the quals of a tablefunc
2486  * scan, but it could still have required parameterization due to LATERAL
2487  * refs in the function expression.
2488  */
2489  required_outer = rel->lateral_relids;
2490 
2491  /* Generate appropriate path */
2492  add_path(rel, create_tablefuncscan_path(root, rel,
2493  required_outer));
2494 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Relids lateral_relids
Definition: pathnodes.h:691
Path * create_tablefuncscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1971

◆ set_tablesample_rel_pathlist()

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

Definition at line 856 of file allpaths.c.

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

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

◆ set_tablesample_rel_size()

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

Definition at line 816 of file allpaths.c.

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

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

◆ set_values_pathlist()

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

Definition at line 2460 of file allpaths.c.

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

Referenced by set_rel_pathlist().

2461 {
2462  Relids required_outer;
2463 
2464  /*
2465  * We don't support pushing join clauses into the quals of a values scan,
2466  * but it could still have required parameterization due to LATERAL refs
2467  * in the values expressions.
2468  */
2469  required_outer = rel->lateral_relids;
2470 
2471  /* Generate appropriate path */
2472  add_path(rel, create_valuesscan_path(root, rel, required_outer));
2473 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1997
Relids lateral_relids
Definition: pathnodes.h:691

◆ set_worktable_pathlist()

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

Definition at line 2630 of file allpaths.c.

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

2631 {
2632  Path *ctepath;
2633  PlannerInfo *cteroot;
2634  Index levelsup;
2635  Relids required_outer;
2636 
2637  /*
2638  * We need to find the non-recursive term's path, which is in the plan
2639  * level that's processing the recursive UNION, which is one level *below*
2640  * where the CTE comes from.
2641  */
2642  levelsup = rte->ctelevelsup;
2643  if (levelsup == 0) /* shouldn't happen */
2644  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2645  levelsup--;
2646  cteroot = root;
2647  while (levelsup-- > 0)
2648  {
2649  cteroot = cteroot->parent_root;
2650  if (!cteroot) /* shouldn't happen */
2651  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2652  }
2653  ctepath = cteroot->non_recursive_path;
2654  if (!ctepath) /* shouldn't happen */
2655  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
2656 
2657  /* Mark rel with estimated output rows, width, etc */
2658  set_cte_size_estimates(root, rel, ctepath->rows);
2659 
2660  /*
2661  * We don't support pushing join clauses into the quals of a worktable
2662  * scan, but it could still have required parameterization due to LATERAL
2663  * refs in its tlist. (I'm not sure this is actually possible given the
2664  * restrictions on recursive references, but it's easy enough to support.)
2665  */
2666  required_outer = rel->lateral_relids;
2667 
2668  /* Generate appropriate path */
2669  add_path(rel, create_worktablescan_path(root, rel, required_outer));
2670 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
PlannerInfo * parent_root
Definition: pathnodes.h:185
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:5321
Relids lateral_relids
Definition: pathnodes.h:691
#define ERROR
Definition: elog.h:43
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:2100
unsigned int Index
Definition: c.h:482
double rows
Definition: pathnodes.h:1155
struct Path * non_recursive_path
Definition: pathnodes.h:355
Index ctelevelsup
Definition: parsenodes.h:1081
char * ctename
Definition: parsenodes.h:1080
#define elog(elevel,...)
Definition: elog.h:214

◆ standard_join_search()

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

Definition at line 3066 of file allpaths.c.

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

3067 {
3068  int lev;
3069  RelOptInfo *rel;
3070 
3071  /*
3072  * This function cannot be invoked recursively within any one planning
3073  * problem, so join_rel_level[] can't be in use already.
3074  */
3075  Assert(root->join_rel_level == NULL);
3076 
3077  /*
3078  * We employ a simple "dynamic programming" algorithm: we first find all
3079  * ways to build joins of two jointree items, then all ways to build joins
3080  * of three items (from two-item joins and single items), then four-item
3081  * joins, and so on until we have considered all ways to join all the
3082  * items into one rel.
3083  *
3084  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3085  * set root->join_rel_level[1] to represent all the single-jointree-item
3086  * relations.
3087  */
3088  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3089 
3090  root->join_rel_level[1] = initial_rels;
3091 
3092  for (lev = 2; lev <= levels_needed; lev++)
3093  {
3094  ListCell *lc;
3095 
3096  /*
3097  * Determine all possible pairs of relations to be joined at this
3098  * level, and build paths for making each one from every available
3099  * pair of lower-level relations.
3100  */
3101  join_search_one_level(root, lev);
3102 
3103  /*
3104  * Run generate_partitionwise_join_paths() and generate_gather_paths()
3105  * for each just-processed joinrel. We could not do this earlier
3106  * because both regular and partial paths can get added to a
3107  * particular joinrel at multiple times within join_search_one_level.
3108  *
3109  * After that, we're done creating paths for the joinrel, so run
3110  * set_cheapest().
3111  */
3112  foreach(lc, root->join_rel_level[lev])
3113  {
3114  rel = (RelOptInfo *) lfirst(lc);
3115 
3116  /* Create paths for partitionwise joins. */
3118 
3119  /*
3120  * Except for the topmost scan/join rel, consider gathering
3121  * partial paths. We'll do the same for the topmost scan/join rel
3122  * once we know the final targetlist (see grouping_planner).
3123  */
3124  if (lev < levels_needed)
3125  generate_useful_gather_paths(root, rel, false);
3126 
3127  /* Find and save the cheapest paths for this rel */
3128  set_cheapest(rel);
3129 
3130 #ifdef OPTIMIZER_DEBUG
3131  debug_print_rel(root, rel);
3132 #endif
3133  }
3134  }
3135 
3136  /*
3137  * We should have a single rel at the final level.
3138  */
3139  if (root->join_rel_level[levels_needed] == NIL)
3140  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3141  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3142 
3143  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3144 
3145  root->join_rel_level = NULL;
3146 
3147  return rel;
3148 }
#define NIL
Definition: pg_list.h:65
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:3915
#define linitial(l)
Definition: pg_list.h:194
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:2820
#define ERROR
Definition: elog.h:43
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:71
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
void * palloc0(Size size)
Definition: mcxt.c:981
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:189
List ** join_rel_level
Definition: pathnodes.h:256
static int list_length(const List *l)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:214
Definition: pg_list.h:50

◆ subquery_is_pushdown_safe()

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

Definition at line 3235 of file allpaths.c.

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

3237 {
3238  SetOperationStmt *topop;
3239 
3240  /* Check point 1 */
3241  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
3242  return false;
3243 
3244  /* Check point 6 */
3245  if (subquery->groupClause && subquery->groupingSets)
3246  return false;
3247 
3248  /* Check points 3, 4, and 5 */
3249  if (subquery->distinctClause ||
3250  subquery->hasWindowFuncs ||
3251  subquery->hasTargetSRFs)
3252  safetyInfo->unsafeVolatile = true;
3253 
3254  /*
3255  * If we're at a leaf query, check for unsafe expressions in its target
3256  * list, and mark any unsafe ones in unsafeColumns[]. (Non-leaf nodes in
3257  * setop trees have only simple Vars in their tlists, so no need to check
3258  * them.)
3259  */
3260  if (subquery->setOperations == NULL)
3261  check_output_expressions(subquery, safetyInfo);
3262 
3263  /* Are we at top level, or looking at a setop component? */
3264  if (subquery == topquery)
3265  {
3266  /* Top level, so check any component queries */
3267  if (subquery->setOperations != NULL)
3268  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
3269  safetyInfo))
3270  return false;
3271  }
3272  else
3273  {
3274  /* Setop component must not have more components (too weird) */
3275  if (subquery->setOperations != NULL)
3276  return false;
3277  /* Check whether setop component output types match top level */
3278  topop = castNode(SetOperationStmt, topquery->setOperations);
3279  Assert(topop);
3281  topop->colTypes,
3282  safetyInfo);
3283  }
3284  return true;
3285 }
Node * limitOffset
Definition: parsenodes.h:160
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
List * groupingSets
Definition: parsenodes.h:150
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3291
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3426
List * targetList
Definition: parsenodes.h:140
List * distinctClause
Definition: parsenodes.h:156
Node * limitCount
Definition: parsenodes.h:161
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:3358
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:745
bool hasWindowFuncs
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:148

◆ subquery_push_qual()

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

Definition at line 3592 of file allpaths.c.

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

3593 {
3594  if (subquery->setOperations != NULL)
3595  {
3596  /* Recurse to push it separately to each component query */
3597  recurse_push_qual(subquery->setOperations, subquery,
3598  rte, rti, qual);
3599  }
3600  else
3601  {
3602  /*
3603  * We need to replace Vars in the qual (which must refer to outputs of
3604  * the subquery) with copies of the subquery's targetlist expressions.
3605  * Note that at this point, any uplevel Vars in the qual should have
3606  * been replaced with Params, so they need no work.
3607  *
3608  * This step also ensures that when we are pushing into a setop tree,
3609  * each component query gets its own copy of the qual.
3610  */
3611  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
3612  subquery->targetList,
3614  &subquery->hasSubLinks);
3615 
3616  /*
3617  * Now attach the qual to the proper place: normally WHERE, but if the
3618  * subquery uses grouping or aggregation, put it in HAVING (since the
3619  * qual really refers to the group-result rows).
3620  */
3621  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
3622  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
3623  else
3624  subquery->jointree->quals =
3625  make_and_qual(subquery->jointree->quals, qual);
3626 
3627  /*
3628  * We need not change the subquery's hasAggs or hasSubLinks flags,
3629  * since we can't be pushing down any aggregates that weren't there
3630  * before, and we don't push down subselects at all.
3631  */
3632  }
3633 }
FromExpr * jointree
Definition: parsenodes.h:138
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:688
Node * quals
Definition: primnodes.h:1514
List * targetList
Definition: parsenodes.h:140
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:3639
Node * setOperations
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
Node * havingQual
Definition: parsenodes.h:152

◆ targetIsInAllPartitionLists()

static bool targetIsInAllPartitionLists ( TargetEntry tle,
Query query 
)
static

Definition at line 3459 of file allpaths.c.

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

Referenced by check_output_expressions().

3460 {
3461  ListCell *lc;
3462 
3463  foreach(lc, query->windowClause)
3464  {
3465  WindowClause *wc = (WindowClause *) lfirst(lc);
3466 
3468  return false;
3469  }
3470  return true;
3471 }
List * windowClause
Definition: parsenodes.h:154
List * partitionClause
Definition: parsenodes.h:1354
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define lfirst(lc)
Definition: pg_list.h:189

Variable Documentation

◆ enable_geqo

bool enable_geqo = false

Definition at line 62 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ geqo_threshold

int geqo_threshold

Definition at line 63 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

join_search_hook_type join_search_hook = NULL

Definition at line 71 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_parallel_index_scan_size

int min_parallel_index_scan_size

Definition at line 65 of file allpaths.c.

Referenced by compute_parallel_vacuum_workers(), and compute_parallel_worker().

◆ min_parallel_table_scan_size

int min_parallel_table_scan_size

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

Referenced by set_rel_pathlist().