PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/geqo.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.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_mergeappend_paths (PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
 
static Pathget_cheapest_parameterized_child_path (PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
 
static Listaccumulate_append_subpath (List *subpaths, Path *path)
 
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_cte_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 set_dummy_rel_pathlist (RelOptInfo *rel)
 
static bool has_multiple_baserels (PlannerInfo *root)
 
void generate_gather_paths (PlannerInfo *root, RelOptInfo *rel)
 
RelOptInfostandard_join_search (PlannerInfo *root, int levels_needed, List *initial_rels)
 
int compute_parallel_worker (RelOptInfo *rel, BlockNumber heap_pages, BlockNumber index_pages)
 

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

Function Documentation

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

Definition at line 1586 of file allpaths.c.

References IsA, lappend(), list_concat(), list_copy(), AppendPath::subpaths, and MergeAppendPath::subpaths.

Referenced by generate_mergeappend_paths(), and set_append_rel_pathlist().

1587 {
1588  if (IsA(path, AppendPath))
1589  {
1590  AppendPath *apath = (AppendPath *) path;
1591 
1592  /* list_copy is important here to avoid sharing list substructure */
1593  return list_concat(subpaths, list_copy(apath->subpaths));
1594  }
1595  else if (IsA(path, MergeAppendPath))
1596  {
1597  MergeAppendPath *mpath = (MergeAppendPath *) path;
1598 
1599  /* list_copy is important here to avoid sharing list substructure */
1600  return list_concat(subpaths, list_copy(mpath->subpaths));
1601  }
1602  else
1603  return lappend(subpaths, path);
1604 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * subpaths
Definition: relation.h:1119
List * lappend(List *list, void *datum)
Definition: list.c:128
List * subpaths
Definition: relation.h:1137
static void check_output_expressions ( Query subquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 2465 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().

2466 {
2467  ListCell *lc;
2468 
2469  foreach(lc, subquery->targetList)
2470  {
2471  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2472 
2473  if (tle->resjunk)
2474  continue; /* ignore resjunk columns */
2475 
2476  /* We need not check further if output col is already known unsafe */
2477  if (safetyInfo->unsafeColumns[tle->resno])
2478  continue;
2479 
2480  /* Functions returning sets are unsafe (point 1) */
2481  if (subquery->hasTargetSRFs &&
2482  expression_returns_set((Node *) tle->expr))
2483  {
2484  safetyInfo->unsafeColumns[tle->resno] = true;
2485  continue;
2486  }
2487 
2488  /* Volatile functions are unsafe (point 2) */
2489  if (contain_volatile_functions((Node *) tle->expr))
2490  {
2491  safetyInfo->unsafeColumns[tle->resno] = true;
2492  continue;
2493  }
2494 
2495  /* If subquery uses DISTINCT ON, check point 3 */
2496  if (subquery->hasDistinctOn &&
2497  !targetIsInSortList(tle, InvalidOid, subquery->distinctClause))
2498  {
2499  /* non-DISTINCT column, so mark it unsafe */
2500  safetyInfo->unsafeColumns[tle->resno] = true;
2501  continue;
2502  }
2503 
2504  /* If subquery uses window functions, check point 4 */
2505  if (subquery->hasWindowFuncs &&
2506  !targetIsInAllPartitionLists(tle, subquery))
2507  {
2508  /* not present in all PARTITION BY clauses, so mark it unsafe */
2509  safetyInfo->unsafeColumns[tle->resno] = true;
2510  continue;
2511  }
2512  }
2513 }
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:670
Definition: nodes.h:508
bool * unsafeColumns
Definition: allpaths.c:52
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
bool hasDistinctOn
Definition: parsenodes.h:120
List * targetList
Definition: parsenodes.h:131
bool resjunk
Definition: primnodes.h:1337
List * distinctClause
Definition: parsenodes.h:145
static bool targetIsInAllPartitionLists(TargetEntry *tle, Query *query)
Definition: allpaths.c:2566
AttrNumber resno
Definition: primnodes.h:1331
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
bool hasTargetSRFs
Definition: parsenodes.h:118
#define lfirst(lc)
Definition: pg_list.h:106
bool hasWindowFuncs
Definition: parsenodes.h:117
Expr * expr
Definition: primnodes.h:1330
static void compare_tlist_datatypes ( List tlist,
List colTypes,
pushdown_safety_info safetyInfo 
)
static

Definition at line 2533 of file allpaths.c.

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

Referenced by subquery_is_pushdown_safe().

2535 {
2536  ListCell *l;
2537  ListCell *colType = list_head(colTypes);
2538 
2539  foreach(l, tlist)
2540  {
2541  TargetEntry *tle = (TargetEntry *) lfirst(l);
2542 
2543  if (tle->resjunk)
2544  continue; /* ignore resjunk columns */
2545  if (colType == NULL)
2546  elog(ERROR, "wrong number of tlist entries");
2547  if (exprType((Node *) tle->expr) != lfirst_oid(colType))
2548  safetyInfo->unsafeColumns[tle->resno] = true;
2549  colType = lnext(colType);
2550  }
2551  if (colType != NULL)
2552  elog(ERROR, "wrong number of tlist entries");
2553 }
Definition: nodes.h:508
bool * unsafeColumns
Definition: allpaths.c:52
bool resjunk
Definition: primnodes.h:1337
#define ERROR
Definition: elog.h:43
AttrNumber resno
Definition: primnodes.h:1331
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define elog
Definition: elog.h:219
#define lfirst_oid(lc)
Definition: pg_list.h:108
int compute_parallel_worker ( RelOptInfo rel,
BlockNumber  heap_pages,
BlockNumber  index_pages 
)

Definition at line 2887 of file allpaths.c.

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

Referenced by cost_index(), and create_plain_partial_paths().

2889 {
2890  int parallel_workers = 0;
2891  int heap_parallel_workers = 1;
2892  int index_parallel_workers = 1;
2893 
2894  /*
2895  * If the user has set the parallel_workers reloption, use that; otherwise
2896  * select a default number of workers.
2897  */
2898  if (rel->rel_parallel_workers != -1)
2899  parallel_workers = rel->rel_parallel_workers;
2900  else
2901  {
2902  int heap_parallel_threshold;
2903  int index_parallel_threshold;
2904 
2905  /*
2906  * If this relation is too small to be worth a parallel scan, just
2907  * return without doing anything ... unless it's an inheritance child.
2908  * In that case, we want to generate a parallel path here anyway. It
2909  * might not be worthwhile just for this relation, but when combined
2910  * with all of its inheritance siblings it may well pay off.
2911  */
2912  if (heap_pages < (BlockNumber) min_parallel_table_scan_size &&
2913  index_pages < (BlockNumber) min_parallel_index_scan_size &&
2914  rel->reloptkind == RELOPT_BASEREL)
2915  return 0;
2916 
2917  if (heap_pages > 0)
2918  {
2919  /*
2920  * Select the number of workers based on the log of the size of
2921  * the relation. This probably needs to be a good deal more
2922  * sophisticated, but we need something here for now. Note that
2923  * the upper limit of the min_parallel_table_scan_size GUC is
2924  * chosen to prevent overflow here.
2925  */
2926  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
2927  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
2928  {
2929  heap_parallel_workers++;
2930  heap_parallel_threshold *= 3;
2931  if (heap_parallel_threshold > INT_MAX / 3)
2932  break; /* avoid overflow */
2933  }
2934 
2935  parallel_workers = heap_parallel_workers;
2936  }
2937 
2938  if (index_pages > 0)
2939  {
2940  /* same calculation as for heap_pages above */
2941  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
2942  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
2943  {
2944  index_parallel_workers++;
2945  index_parallel_threshold *= 3;
2946  if (index_parallel_threshold > INT_MAX / 3)
2947  break; /* avoid overflow */
2948  }
2949 
2950  if (parallel_workers > 0)
2951  parallel_workers = Min(parallel_workers, index_parallel_workers);
2952  else
2953  parallel_workers = index_parallel_workers;
2954  }
2955  }
2956 
2957  /*
2958  * In no case use more than max_parallel_workers_per_gather workers.
2959  */
2960  parallel_workers = Min(parallel_workers, max_parallel_workers_per_gather);
2961 
2962  return parallel_workers;
2963 }
RelOptKind reloptkind
Definition: relation.h:487
#define Min(x, y)
Definition: c.h:801
uint32 BlockNumber
Definition: block.h:31
int min_parallel_index_scan_size
Definition: allpaths.c:61
int rel_parallel_workers
Definition: relation.h:533
#define Max(x, y)
Definition: c.h:795
int min_parallel_table_scan_size
Definition: allpaths.c:60
int max_parallel_workers_per_gather
Definition: costsize.c:116
static void create_plain_partial_paths ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 678 of file allpaths.c.

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

Referenced by set_plain_rel_pathlist().

679 {
680  int parallel_workers;
681 
682  parallel_workers = compute_parallel_worker(rel, rel->pages, 0);
683 
684  /* If any limit was set to zero, the user doesn't want a parallel scan. */
685  if (parallel_workers <= 0)
686  return;
687 
688  /* Add an unordered partial path based on a parallel sequential scan. */
689  add_partial_path(rel, create_seqscan_path(root, rel, NULL, parallel_workers));
690 }
int compute_parallel_worker(RelOptInfo *rel, BlockNumber heap_pages, BlockNumber index_pages)
Definition: allpaths.c:2887
BlockNumber pages
Definition: relation.h:528
#define NULL
Definition: c.h:226
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:752
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:938
void generate_gather_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 2058 of file allpaths.c.

References add_path(), create_gather_path(), linitial, NIL, NULL, RelOptInfo::partial_pathlist, and RelOptInfo::reltarget.

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

2059 {
2060  Path *cheapest_partial_path;
2061  Path *simple_gather_path;
2062 
2063  /* If there are no partial paths, there's nothing to do here. */
2064  if (rel->partial_pathlist == NIL)
2065  return;
2066 
2067  /*
2068  * The output of Gather is currently always unsorted, so there's only one
2069  * partial path of interest: the cheapest one. That will be the one at
2070  * the front of partial_pathlist because of the way add_partial_path
2071  * works.
2072  *
2073  * Eventually, we should have a Gather Merge operation that can merge
2074  * multiple tuple streams together while preserving their ordering. We
2075  * could usefully generate such a path from each partial path that has
2076  * non-NIL pathkeys.
2077  */
2078  cheapest_partial_path = linitial(rel->partial_pathlist);
2079  simple_gather_path = (Path *)
2080  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
2081  NULL, NULL);
2082  add_path(rel, simple_gather_path);
2083 }
#define NIL
Definition: pg_list.h:69
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1667
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
List * partial_pathlist
Definition: relation.h:506
#define linitial(l)
Definition: pg_list.h:110
#define NULL
Definition: c.h:226
struct PathTarget * reltarget
Definition: relation.h:501
Definition: relation.h:888
static void generate_mergeappend_paths ( PlannerInfo root,
RelOptInfo rel,
List live_childrels,
List all_child_pathkeys 
)
static

Definition at line 1424 of file allpaths.c.

References accumulate_append_subpath(), add_path(), Assert, RelOptInfo::cheapest_total_path, create_merge_append_path(), get_cheapest_path_for_pathkeys(), lfirst, NIL, NULL, Path::param_info, RelOptInfo::pathlist, STARTUP_COST, and TOTAL_COST.

Referenced by set_append_rel_pathlist().

1427 {
1428  ListCell *lcp;
1429 
1430  foreach(lcp, all_child_pathkeys)
1431  {
1432  List *pathkeys = (List *) lfirst(lcp);
1433  List *startup_subpaths = NIL;
1434  List *total_subpaths = NIL;
1435  bool startup_neq_total = false;
1436  ListCell *lcr;
1437 
1438  /* Select the child paths for this ordering... */
1439  foreach(lcr, live_childrels)
1440  {
1441  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1442  Path *cheapest_startup,
1443  *cheapest_total;
1444 
1445  /* Locate the right paths, if they are available. */
1446  cheapest_startup =
1448  pathkeys,
1449  NULL,
1450  STARTUP_COST);
1451  cheapest_total =
1453  pathkeys,
1454  NULL,
1455  TOTAL_COST);
1456 
1457  /*
1458  * If we can't find any paths with the right order just use the
1459  * cheapest-total path; we'll have to sort it later.
1460  */
1461  if (cheapest_startup == NULL || cheapest_total == NULL)
1462  {
1463  cheapest_startup = cheapest_total =
1464  childrel->cheapest_total_path;
1465  /* Assert we do have an unparameterized path for this child */
1466  Assert(cheapest_total->param_info == NULL);
1467  }
1468 
1469  /*
1470  * Notice whether we actually have different paths for the
1471  * "cheapest" and "total" cases; frequently there will be no point
1472  * in two create_merge_append_path() calls.
1473  */
1474  if (cheapest_startup != cheapest_total)
1475  startup_neq_total = true;
1476 
1477  startup_subpaths =
1478  accumulate_append_subpath(startup_subpaths, cheapest_startup);
1479  total_subpaths =
1480  accumulate_append_subpath(total_subpaths, cheapest_total);
1481  }
1482 
1483  /* ... and build the MergeAppend paths */
1484  add_path(rel, (Path *) create_merge_append_path(root,
1485  rel,
1486  startup_subpaths,
1487  pathkeys,
1488  NULL));
1489  if (startup_neq_total)
1490  add_path(rel, (Path *) create_merge_append_path(root,
1491  rel,
1492  total_subpaths,
1493  pathkeys,
1494  NULL));
1495  }
1496 }
#define NIL
Definition: pg_list.h:69
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
ParamPathInfo * param_info
Definition: relation.h:897
struct Path * cheapest_total_path
Definition: relation.h:508
MergeAppendPath * create_merge_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1256
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static List * accumulate_append_subpath(List *subpaths, Path *path)
Definition: allpaths.c:1586
List * pathlist
Definition: relation.h:504
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion)
Definition: pathkeys.c:342
Definition: pg_list.h:45
Definition: relation.h:888
static Path * get_cheapest_parameterized_child_path ( PlannerInfo root,
RelOptInfo rel,
Relids  required_outer 
)
static

Definition at line 1506 of file allpaths.c.

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

Referenced by set_append_rel_pathlist().

1508 {
1509  Path *cheapest;
1510  ListCell *lc;
1511 
1512  /*
1513  * Look up the cheapest existing path with no more than the needed
1514  * parameterization. If it has exactly the needed parameterization, we're
1515  * done.
1516  */
1517  cheapest = get_cheapest_path_for_pathkeys(rel->pathlist,
1518  NIL,
1519  required_outer,
1520  TOTAL_COST);
1521  Assert(cheapest != NULL);
1522  if (bms_equal(PATH_REQ_OUTER(cheapest), required_outer))
1523  return cheapest;
1524 
1525  /*
1526  * Otherwise, we can "reparameterize" an existing path to match the given
1527  * parameterization, which effectively means pushing down additional
1528  * joinquals to be checked within the path's scan. However, some existing
1529  * paths might check the available joinquals already while others don't;
1530  * therefore, it's not clear which existing path will be cheapest after
1531  * reparameterization. We have to go through them all and find out.
1532  */
1533  cheapest = NULL;
1534  foreach(lc, rel->pathlist)
1535  {
1536  Path *path = (Path *) lfirst(lc);
1537 
1538  /* Can't use it if it needs more than requested parameterization */
1539  if (!bms_is_subset(PATH_REQ_OUTER(path), required_outer))
1540  continue;
1541 
1542  /*
1543  * Reparameterization can only increase the path's cost, so if it's
1544  * already more expensive than the current cheapest, forget it.
1545  */
1546  if (cheapest != NULL &&
1547  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
1548  continue;
1549 
1550  /* Reparameterize if needed, then recheck cost */
1551  if (!bms_equal(PATH_REQ_OUTER(path), required_outer))
1552  {
1553  path = reparameterize_path(root, path, required_outer, 1.0);
1554  if (path == NULL)
1555  continue; /* failed to reparameterize this one */
1556  Assert(bms_equal(PATH_REQ_OUTER(path), required_outer));
1557 
1558  if (cheapest != NULL &&
1559  compare_path_costs(cheapest, path, TOTAL_COST) <= 0)
1560  continue;
1561  }
1562 
1563  /* We have a new best path */
1564  cheapest = path;
1565  }
1566 
1567  /* Return the best path, or NULL if we found no suitable candidate */
1568  return cheapest;
1569 }
#define NIL
Definition: pg_list.h:69
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:61
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
#define PATH_REQ_OUTER(path)
Definition: relation.h:914
Path * reparameterize_path(PlannerInfo *root, Path *path, Relids required_outer, double loop_count)
Definition: pathnode.c:3216
List * pathlist
Definition: relation.h:504
Path * get_cheapest_path_for_pathkeys(List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion)
Definition: pathkeys.c:342
Definition: relation.h:888
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:130
static bool has_multiple_baserels ( PlannerInfo root)
static

Definition at line 1639 of file allpaths.c.

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

Referenced by set_subquery_pathlist().

1640 {
1641  int num_base_rels = 0;
1642  Index rti;
1643 
1644  for (rti = 1; rti < root->simple_rel_array_size; rti++)
1645  {
1646  RelOptInfo *brel = root->simple_rel_array[rti];
1647 
1648  if (brel == NULL)
1649  continue;
1650 
1651  /* ignore RTEs that are "other rels" */
1652  if (brel->reloptkind == RELOPT_BASEREL)
1653  if (++num_base_rels > 1)
1654  return true;
1655  }
1656  return false;
1657 }
RelOptKind reloptkind
Definition: relation.h:487
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
int simple_rel_array_size
Definition: relation.h:177
unsigned int Index
Definition: c.h:361
#define NULL
Definition: c.h:226
RelOptInfo* make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 138 of file allpaths.c.

References PlannerInfo::all_baserels, Assert, bms_add_member(), bms_equal(), make_rel_from_joinlist(), NULL, 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, and PlannerInfo::simple_rel_array_size.

Referenced by query_planner().

139 {
140  RelOptInfo *rel;
141  Index rti;
142 
143  /*
144  * Construct the all_baserels Relids set.
145  */
146  root->all_baserels = NULL;
147  for (rti = 1; rti < root->simple_rel_array_size; rti++)
148  {
149  RelOptInfo *brel = root->simple_rel_array[rti];
150 
151  /* there may be empty slots corresponding to non-baserel RTEs */
152  if (brel == NULL)
153  continue;
154 
155  Assert(brel->relid == rti); /* sanity check on array */
156 
157  /* ignore RTEs that are "other rels" */
158  if (brel->reloptkind != RELOPT_BASEREL)
159  continue;
160 
161  root->all_baserels = bms_add_member(root->all_baserels, brel->relid);
162  }
163 
164  /* Mark base rels as to whether we care about fast-start plans */
166 
167  /*
168  * Compute size estimates and consider_parallel flags for each base rel,
169  * then generate access paths.
170  */
171  set_base_rel_sizes(root);
173 
174  /*
175  * Generate access paths for the entire join tree.
176  */
177  rel = make_rel_from_joinlist(root, joinlist);
178 
179  /*
180  * The result should join all and only the query's base rels.
181  */
182  Assert(bms_equal(rel->relids, root->all_baserels));
183 
184  return rel;
185 }
RelOptKind reloptkind
Definition: relation.h:487
static void set_base_rel_sizes(PlannerInfo *root)
Definition: allpaths.c:241
static void set_base_rel_consider_startup(PlannerInfo *root)
Definition: allpaths.c:198
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
Relids all_baserels
Definition: relation.h:193
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:2093
Relids relids
Definition: relation.h:490
int simple_rel_array_size
Definition: relation.h:177
Index relid
Definition: relation.h:518
static void set_base_rel_pathlists(PlannerInfo *root)
Definition: allpaths.c:284
unsigned int Index
Definition: c.h:361
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:130
static RelOptInfo * make_rel_from_joinlist ( PlannerInfo root,
List joinlist 
)
static

Definition at line 2093 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, NULL, and standard_join_search().

Referenced by make_one_rel().

2094 {
2095  int levels_needed;
2096  List *initial_rels;
2097  ListCell *jl;
2098 
2099  /*
2100  * Count the number of child joinlist nodes. This is the depth of the
2101  * dynamic-programming algorithm we must employ to consider all ways of
2102  * joining the child nodes.
2103  */
2104  levels_needed = list_length(joinlist);
2105 
2106  if (levels_needed <= 0)
2107  return NULL; /* nothing to do? */
2108 
2109  /*
2110  * Construct a list of rels corresponding to the child joinlist nodes.
2111  * This may contain both base rels and rels constructed according to
2112  * sub-joinlists.
2113  */
2114  initial_rels = NIL;
2115  foreach(jl, joinlist)
2116  {
2117  Node *jlnode = (Node *) lfirst(jl);
2118  RelOptInfo *thisrel;
2119 
2120  if (IsA(jlnode, RangeTblRef))
2121  {
2122  int varno = ((RangeTblRef *) jlnode)->rtindex;
2123 
2124  thisrel = find_base_rel(root, varno);
2125  }
2126  else if (IsA(jlnode, List))
2127  {
2128  /* Recurse to handle subproblem */
2129  thisrel = make_rel_from_joinlist(root, (List *) jlnode);
2130  }
2131  else
2132  {
2133  elog(ERROR, "unrecognized joinlist node type: %d",
2134  (int) nodeTag(jlnode));
2135  thisrel = NULL; /* keep compiler quiet */
2136  }
2137 
2138  initial_rels = lappend(initial_rels, thisrel);
2139  }
2140 
2141  if (levels_needed == 1)
2142  {
2143  /*
2144  * Single joinlist node, so we're done.
2145  */
2146  return (RelOptInfo *) linitial(initial_rels);
2147  }
2148  else
2149  {
2150  /*
2151  * Consider the different orders in which we could join the rels,
2152  * using a plugin, GEQO, or the regular join search code.
2153  *
2154  * We put the initial_rels list into a PlannerInfo field because
2155  * has_legal_joinclause() needs to look at it (ugly :-().
2156  */
2157  root->initial_rels = initial_rels;
2158 
2159  if (join_search_hook)
2160  return (*join_search_hook) (root, levels_needed, initial_rels);
2161  else if (enable_geqo && levels_needed >= geqo_threshold)
2162  return geqo(root, levels_needed, initial_rels);
2163  else
2164  return standard_join_search(root, levels_needed, initial_rels);
2165  }
2166 }
RelOptInfo * standard_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
Definition: allpaths.c:2198
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Definition: nodes.h:508
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
bool enable_geqo
Definition: allpaths.c:58
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:2093
List * lappend(List *list, void *datum)
Definition: list.c:128
join_search_hook_type join_search_hook
Definition: allpaths.c:67
int geqo_threshold
Definition: allpaths.c:59
RelOptInfo * geqo(PlannerInfo *root, int number_of_rels, List *initial_rels)
Definition: geqo_main.c:67
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define nodeTag(nodeptr)
Definition: nodes.h:513
List * initial_rels
Definition: relation.h:264
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
Definition: pg_list.h:45
static bool qual_is_pushdown_safe ( Query subquery,
Index  rti,
Node qual,
pushdown_safety_info safetyInfo 
)
static

Definition at line 2606 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().

2608 {
2609  bool safe = true;
2610  List *vars;
2611  ListCell *vl;
2612 
2613  /* Refuse subselects (point 1) */
2614  if (contain_subplans(qual))
2615  return false;
2616 
2617  /* Refuse volatile quals if we found they'd be unsafe (point 2) */
2618  if (safetyInfo->unsafeVolatile &&
2620  return false;
2621 
2622  /* Refuse leaky quals if told to (point 3) */
2623  if (safetyInfo->unsafeLeaky &&
2624  contain_leaked_vars(qual))
2625  return false;
2626 
2627  /*
2628  * It would be unsafe to push down window function calls, but at least for
2629  * the moment we could never see any in a qual anyhow. (The same applies
2630  * to aggregates, which we check for in pull_var_clause below.)
2631  */
2633 
2634  /*
2635  * Examine all Vars used in clause; since it's a restriction clause, all
2636  * such Vars must refer to subselect output columns.
2637  */
2639  foreach(vl, vars)
2640  {
2641  Var *var = (Var *) lfirst(vl);
2642 
2643  /*
2644  * XXX Punt if we find any PlaceHolderVars in the restriction clause.
2645  * It's not clear whether a PHV could safely be pushed down, and even
2646  * less clear whether such a situation could arise in any cases of
2647  * practical interest anyway. So for the moment, just refuse to push
2648  * down.
2649  */
2650  if (!IsA(var, Var))
2651  {
2652  safe = false;
2653  break;
2654  }
2655 
2656  Assert(var->varno == rti);
2657  Assert(var->varattno >= 0);
2658 
2659  /* Check point 4 */
2660  if (var->varattno == 0)
2661  {
2662  safe = false;
2663  break;
2664  }
2665 
2666  /* Check point 5 */
2667  if (safetyInfo->unsafeColumns[var->varattno])
2668  {
2669  safe = false;
2670  break;
2671  }
2672  }
2673 
2674  list_free(vars);
2675 
2676  return safe;
2677 }
bool contain_leaked_vars(Node *clause)
Definition: clauses.c:1427
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
AttrNumber varattno
Definition: primnodes.h:146
bool * unsafeColumns
Definition: allpaths.c:52
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
Definition: primnodes.h:141
bool contain_subplans(Node *clause)
Definition: clauses.c:842
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
bool contain_window_function(Node *clause)
Definition: clauses.c:726
Index varno
Definition: primnodes.h:144
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
void list_free(List *list)
Definition: list.c:1133
Definition: regcomp.c:226
Definition: pg_list.h:45
static void recurse_push_qual ( Node setOp,
Query topquery,
RangeTblEntry rte,
Index  rti,
Node qual 
)
static

Definition at line 2730 of file allpaths.c.

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

Referenced by subquery_push_qual().

2732 {
2733  if (IsA(setOp, RangeTblRef))
2734  {
2735  RangeTblRef *rtr = (RangeTblRef *) setOp;
2736  RangeTblEntry *subrte = rt_fetch(rtr->rtindex, topquery->rtable);
2737  Query *subquery = subrte->subquery;
2738 
2739  Assert(subquery != NULL);
2740  subquery_push_qual(subquery, rte, rti, qual);
2741  }
2742  else if (IsA(setOp, SetOperationStmt))
2743  {
2744  SetOperationStmt *op = (SetOperationStmt *) setOp;
2745 
2746  recurse_push_qual(op->larg, topquery, rte, rti, qual);
2747  recurse_push_qual(op->rarg, topquery, rte, rti, qual);
2748  }
2749  else
2750  {
2751  elog(ERROR, "unrecognized node type: %d",
2752  (int) nodeTag(setOp));
2753  }
2754 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * rtable
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:43
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:2683
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:2730
#define nodeTag(nodeptr)
Definition: nodes.h:513
Query * subquery
Definition: parsenodes.h:900
#define elog
Definition: elog.h:219
static bool recurse_pushdown_safe ( Node setOp,
Query topquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 2398 of file allpaths.c.

References Assert, elog, ERROR, IsA, SetOperationStmt::larg, nodeTag, NULL, 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().

2400 {
2401  if (IsA(setOp, RangeTblRef))
2402  {
2403  RangeTblRef *rtr = (RangeTblRef *) setOp;
2404  RangeTblEntry *rte = rt_fetch(rtr->rtindex, topquery->rtable);
2405  Query *subquery = rte->subquery;
2406 
2407  Assert(subquery != NULL);
2408  return subquery_is_pushdown_safe(subquery, topquery, safetyInfo);
2409  }
2410  else if (IsA(setOp, SetOperationStmt))
2411  {
2412  SetOperationStmt *op = (SetOperationStmt *) setOp;
2413 
2414  /* EXCEPT is no good (point 2 for subquery_is_pushdown_safe) */
2415  if (op->op == SETOP_EXCEPT)
2416  return false;
2417  /* Else recurse */
2418  if (!recurse_pushdown_safe(op->larg, topquery, safetyInfo))
2419  return false;
2420  if (!recurse_pushdown_safe(op->rarg, topquery, safetyInfo))
2421  return false;
2422  }
2423  else
2424  {
2425  elog(ERROR, "unrecognized node type: %d",
2426  (int) nodeTag(setOp));
2427  }
2428  return true;
2429 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2398
List * rtable
Definition: parsenodes.h:128
#define ERROR
Definition: elog.h:43
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
SetOperation op
Definition: parsenodes.h:1485
#define nodeTag(nodeptr)
Definition: nodes.h:513
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2346
Query * subquery
Definition: parsenodes.h:900
#define elog
Definition: elog.h:219
static void remove_unused_subquery_outputs ( Query subquery,
RelOptInfo rel 
)
static

Definition at line 2777 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(), NULL, pull_varattnos(), RelOptInfo::relid, RelOptInfo::reltarget, TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, Query::setOperations, and Query::targetList.

Referenced by set_subquery_pathlist().

2778 {
2779  Bitmapset *attrs_used = NULL;
2780  ListCell *lc;
2781 
2782  /*
2783  * Do nothing if subquery has UNION/INTERSECT/EXCEPT: in principle we
2784  * could update all the child SELECTs' tlists, but it seems not worth the
2785  * trouble presently.
2786  */
2787  if (subquery->setOperations)
2788  return;
2789 
2790  /*
2791  * If subquery has regular DISTINCT (not DISTINCT ON), we're wasting our
2792  * time: all its output columns must be used in the distinctClause.
2793  */
2794  if (subquery->distinctClause && !subquery->hasDistinctOn)
2795  return;
2796 
2797  /*
2798  * Collect a bitmap of all the output column numbers used by the upper
2799  * query.
2800  *
2801  * Add all the attributes needed for joins or final output. Note: we must
2802  * look at rel's targetlist, not the attr_needed data, because attr_needed
2803  * isn't computed for inheritance child rels, cf set_append_rel_size().
2804  * (XXX might be worth changing that sometime.)
2805  */
2806  pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
2807 
2808  /* Add all the attributes used by un-pushed-down restriction clauses. */
2809  foreach(lc, rel->baserestrictinfo)
2810  {
2811  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2812 
2813  pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2814  }
2815 
2816  /*
2817  * If there's a whole-row reference to the subquery, we can't remove
2818  * anything.
2819  */
2821  return;
2822 
2823  /*
2824  * Run through the tlist and zap entries we don't need. It's okay to
2825  * modify the tlist items in-place because set_subquery_pathlist made a
2826  * copy of the subquery.
2827  */
2828  foreach(lc, subquery->targetList)
2829  {
2830  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2831  Node *texpr = (Node *) tle->expr;
2832 
2833  /*
2834  * If it has a sortgroupref number, it's used in some sort/group
2835  * clause so we'd better not remove it. Also, don't remove any
2836  * resjunk columns, since their reason for being has nothing to do
2837  * with anybody reading the subquery's output. (It's likely that
2838  * resjunk columns in a sub-SELECT would always have ressortgroupref
2839  * set, but even if they don't, it seems imprudent to remove them.)
2840  */
2841  if (tle->ressortgroupref || tle->resjunk)
2842  continue;
2843 
2844  /*
2845  * If it's used by the upper query, we can't remove it.
2846  */
2848  attrs_used))
2849  continue;
2850 
2851  /*
2852  * If it contains a set-returning function, we can't remove it since
2853  * that could change the number of rows returned by the subquery.
2854  */
2855  if (subquery->hasTargetSRFs &&
2856  expression_returns_set(texpr))
2857  continue;
2858 
2859  /*
2860  * If it contains volatile functions, we daren't remove it for fear
2861  * that the user is expecting their side-effects to happen.
2862  */
2863  if (contain_volatile_functions(texpr))
2864  continue;
2865 
2866  /*
2867  * OK, we don't need it. Replace the expression with a NULL constant.
2868  * Preserve the exposed type of the expression, in case something
2869  * looks at the rowtype of the subquery's result.
2870  */
2871  tle->expr = (Expr *) makeNullConst(exprType(texpr),
2872  exprTypmod(texpr),
2873  exprCollation(texpr));
2874  }
2875 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:274
List * baserestrictinfo
Definition: relation.h:544
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:670
Definition: nodes.h:508
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
bool hasDistinctOn
Definition: parsenodes.h:120
List * targetList
Definition: parsenodes.h:131
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:334
bool resjunk
Definition: primnodes.h:1337
List * distinctClause
Definition: parsenodes.h:145
AttrNumber resno
Definition: primnodes.h:1331
Index relid
Definition: relation.h:518
Expr * clause
Definition: relation.h:1637
List * exprs
Definition: relation.h:824
bool hasTargetSRFs
Definition: parsenodes.h:118
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:748
Node * setOperations
Definition: parsenodes.h:154
Index ressortgroupref
Definition: primnodes.h:1333
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
struct PathTarget * reltarget
Definition: relation.h:501
static void set_append_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 1167 of file allpaths.c.

References accumulate_append_subpath(), add_partial_path(), add_path(), PlannerInfo::append_rel_list, Assert, bms_equal(), RelOptInfo::cheapest_total_path, AppendRelInfo::child_relid, compare_pathkeys(), RelOptInfo::consider_parallel, create_append_path(), generate_mergeappend_paths(), get_cheapest_parameterized_child_path(), IS_DUMMY_REL, lappend(), lfirst, linitial, Max, NIL, NULL, Path::parallel_workers, Path::param_info, AppendRelInfo::parent_relid, RelOptInfo::partial_pathlist, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, RelOptInfo::pathlist, set_rel_pathlist(), PlannerInfo::simple_rel_array, PlannerInfo::simple_rte_array, and subpath().

Referenced by set_rel_pathlist().

1169 {
1170  int parentRTindex = rti;
1171  List *live_childrels = NIL;
1172  List *subpaths = NIL;
1173  bool subpaths_valid = true;
1174  List *partial_subpaths = NIL;
1175  bool partial_subpaths_valid = true;
1176  List *all_child_pathkeys = NIL;
1177  List *all_child_outers = NIL;
1178  ListCell *l;
1179 
1180  /*
1181  * Generate access paths for each member relation, and remember the
1182  * cheapest path for each one. Also, identify all pathkeys (orderings)
1183  * and parameterizations (required_outer sets) available for the member
1184  * relations.
1185  */
1186  foreach(l, root->append_rel_list)
1187  {
1188  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
1189  int childRTindex;
1190  RangeTblEntry *childRTE;
1191  RelOptInfo *childrel;
1192  ListCell *lcp;
1193 
1194  /* append_rel_list contains all append rels; ignore others */
1195  if (appinfo->parent_relid != parentRTindex)
1196  continue;
1197 
1198  /* Re-locate the child RTE and RelOptInfo */
1199  childRTindex = appinfo->child_relid;
1200  childRTE = root->simple_rte_array[childRTindex];
1201  childrel = root->simple_rel_array[childRTindex];
1202 
1203  /*
1204  * If set_append_rel_size() decided the parent appendrel was
1205  * parallel-unsafe at some point after visiting this child rel, we
1206  * need to propagate the unsafety marking down to the child, so that
1207  * we don't generate useless partial paths for it.
1208  */
1209  if (!rel->consider_parallel)
1210  childrel->consider_parallel = false;
1211 
1212  /*
1213  * Compute the child's access paths.
1214  */
1215  set_rel_pathlist(root, childrel, childRTindex, childRTE);
1216 
1217  /*
1218  * If child is dummy, ignore it.
1219  */
1220  if (IS_DUMMY_REL(childrel))
1221  continue;
1222 
1223  /*
1224  * Child is live, so add it to the live_childrels list for use below.
1225  */
1226  live_childrels = lappend(live_childrels, childrel);
1227 
1228  /*
1229  * If child has an unparameterized cheapest-total path, add that to
1230  * the unparameterized Append path we are constructing for the parent.
1231  * If not, there's no workable unparameterized path.
1232  */
1233  if (childrel->cheapest_total_path->param_info == NULL)
1234  subpaths = accumulate_append_subpath(subpaths,
1235  childrel->cheapest_total_path);
1236  else
1237  subpaths_valid = false;
1238 
1239  /* Same idea, but for a partial plan. */
1240  if (childrel->partial_pathlist != NIL)
1241  partial_subpaths = accumulate_append_subpath(partial_subpaths,
1242  linitial(childrel->partial_pathlist));
1243  else
1244  partial_subpaths_valid = false;
1245 
1246  /*
1247  * Collect lists of all the available path orderings and
1248  * parameterizations for all the children. We use these as a
1249  * heuristic to indicate which sort orderings and parameterizations we
1250  * should build Append and MergeAppend paths for.
1251  */
1252  foreach(lcp, childrel->pathlist)
1253  {
1254  Path *childpath = (Path *) lfirst(lcp);
1255  List *childkeys = childpath->pathkeys;
1256  Relids childouter = PATH_REQ_OUTER(childpath);
1257 
1258  /* Unsorted paths don't contribute to pathkey list */
1259  if (childkeys != NIL)
1260  {
1261  ListCell *lpk;
1262  bool found = false;
1263 
1264  /* Have we already seen this ordering? */
1265  foreach(lpk, all_child_pathkeys)
1266  {
1267  List *existing_pathkeys = (List *) lfirst(lpk);
1268 
1269  if (compare_pathkeys(existing_pathkeys,
1270  childkeys) == PATHKEYS_EQUAL)
1271  {
1272  found = true;
1273  break;
1274  }
1275  }
1276  if (!found)
1277  {
1278  /* No, so add it to all_child_pathkeys */
1279  all_child_pathkeys = lappend(all_child_pathkeys,
1280  childkeys);
1281  }
1282  }
1283 
1284  /* Unparameterized paths don't contribute to param-set list */
1285  if (childouter)
1286  {
1287  ListCell *lco;
1288  bool found = false;
1289 
1290  /* Have we already seen this param set? */
1291  foreach(lco, all_child_outers)
1292  {
1293  Relids existing_outers = (Relids) lfirst(lco);
1294 
1295  if (bms_equal(existing_outers, childouter))
1296  {
1297  found = true;
1298  break;
1299  }
1300  }
1301  if (!found)
1302  {
1303  /* No, so add it to all_child_outers */
1304  all_child_outers = lappend(all_child_outers,
1305  childouter);
1306  }
1307  }
1308  }
1309  }
1310 
1311  /*
1312  * If we found unparameterized paths for all children, build an unordered,
1313  * unparameterized Append path for the rel. (Note: this is correct even
1314  * if we have zero or one live subpath due to constraint exclusion.)
1315  */
1316  if (subpaths_valid)
1317  add_path(rel, (Path *) create_append_path(rel, subpaths, NULL, 0));
1318 
1319  /*
1320  * Consider an append of partial unordered, unparameterized partial paths.
1321  */
1322  if (partial_subpaths_valid)
1323  {
1324  AppendPath *appendpath;
1325  ListCell *lc;
1326  int parallel_workers = 0;
1327 
1328  /*
1329  * Decide on the number of workers to request for this append path.
1330  * For now, we just use the maximum value from among the members. It
1331  * might be useful to use a higher number if the Append node were
1332  * smart enough to spread out the workers, but it currently isn't.
1333  */
1334  foreach(lc, partial_subpaths)
1335  {
1336  Path *path = lfirst(lc);
1337 
1338  parallel_workers = Max(parallel_workers, path->parallel_workers);
1339  }
1340  Assert(parallel_workers > 0);
1341 
1342  /* Generate a partial append path. */
1343  appendpath = create_append_path(rel, partial_subpaths, NULL,
1344  parallel_workers);
1345  add_partial_path(rel, (Path *) appendpath);
1346  }
1347 
1348  /*
1349  * Also build unparameterized MergeAppend paths based on the collected
1350  * list of child pathkeys.
1351  */
1352  if (subpaths_valid)
1353  generate_mergeappend_paths(root, rel, live_childrels,
1354  all_child_pathkeys);
1355 
1356  /*
1357  * Build Append paths for each parameterization seen among the child rels.
1358  * (This may look pretty expensive, but in most cases of practical
1359  * interest, the child rels will expose mostly the same parameterizations,
1360  * so that not that many cases actually get considered here.)
1361  *
1362  * The Append node itself cannot enforce quals, so all qual checking must
1363  * be done in the child paths. This means that to have a parameterized
1364  * Append path, we must have the exact same parameterization for each
1365  * child path; otherwise some children might be failing to check the
1366  * moved-down quals. To make them match up, we can try to increase the
1367  * parameterization of lesser-parameterized paths.
1368  */
1369  foreach(l, all_child_outers)
1370  {
1371  Relids required_outer = (Relids) lfirst(l);
1372  ListCell *lcr;
1373 
1374  /* Select the child paths for an Append with this parameterization */
1375  subpaths = NIL;
1376  subpaths_valid = true;
1377  foreach(lcr, live_childrels)
1378  {
1379  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1380  Path *subpath;
1381 
1383  childrel,
1384  required_outer);
1385  if (subpath == NULL)
1386  {
1387  /* failed to make a suitable path for this child */
1388  subpaths_valid = false;
1389  break;
1390  }
1391  subpaths = accumulate_append_subpath(subpaths, subpath);
1392  }
1393 
1394  if (subpaths_valid)
1395  add_path(rel, (Path *)
1396  create_append_path(rel, subpaths, required_outer, 0));
1397  }
1398 }
#define NIL
Definition: pg_list.h:69
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:1506
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers)
Definition: pathnode.c:1202
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
List * partial_pathlist
Definition: relation.h:506
static void generate_mergeappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition: allpaths.c:1424
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:278
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
#define linitial(l)
Definition: pg_list.h:110
#define IS_DUMMY_REL(r)
Definition: relation.h:1126
struct Path * cheapest_total_path
Definition: relation.h:508
Bitmapset * Relids
Definition: relation.h:28
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
List * append_rel_list
Definition: relation.h:249
List * pathkeys
Definition: relation.h:909
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:400
#define Max(x, y)
Definition: c.h:795
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
#define PATH_REQ_OUTER(path)
Definition: relation.h:914
static List * accumulate_append_subpath(List *subpaths, Path *path)
Definition: allpaths.c:1586
bool consider_parallel
Definition: relation.h:498
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:752
List * pathlist
Definition: relation.h:504
Index child_relid
Definition: relation.h:1866
Index parent_relid
Definition: relation.h:1865
Definition: pg_list.h:45
Definition: relation.h:888
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:130
static void set_append_rel_size ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 820 of file allpaths.c.

References add_child_rel_equivalences(), adjust_appendrel_attrs(), PlannerInfo::append_rel_list, Assert, RelOptInfo::attr_widths, RelOptInfo::baserestrict_min_security, RelOptInfo::baserestrictinfo, AppendRelInfo::child_relid, RestrictInfo::clause, RelOptInfo::consider_parallel, contain_vars_of_level(), contain_volatile_functions(), DatumGetBool, eval_const_expressions(), PathTarget::exprs, exprType(), exprTypmod(), find_base_rel(), forboth, get_typavgwidth(), PlannerInfo::glob, RelOptInfo::has_eclass_joins, has_useful_pathkeys(), PlannerInfo::hasPseudoConstantQuals, i, IS_DUMMY_REL, RestrictInfo::is_pushed_down, IsA, RelOptInfo::joininfo, lappend(), lfirst, make_ands_implicit(), make_restrictinfo(), RelOptInfo::max_attr, Min, RelOptInfo::min_attr, NIL, NULL, RestrictInfo::outerjoin_delayed, palloc0(), PlannerGlobal::parallelModeOK, AppendRelInfo::parent_relid, pfree(), relation_excluded_by_constraints(), RelOptInfo::relid, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, rint(), RelOptInfo::rows, RestrictInfo::security_level, RangeTblEntry::securityQuals, 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().

822 {
823  int parentRTindex = rti;
824  bool has_live_children;
825  double parent_rows;
826  double parent_size;
827  double *parent_attrsizes;
828  int nattrs;
829  ListCell *l;
830 
831  /*
832  * Initialize to compute size estimates for whole append relation.
833  *
834  * We handle width estimates by weighting the widths of different child
835  * rels proportionally to their number of rows. This is sensible because
836  * the use of width estimates is mainly to compute the total relation
837  * "footprint" if we have to sort or hash it. To do this, we sum the
838  * total equivalent size (in "double" arithmetic) and then divide by the
839  * total rowcount estimate. This is done separately for the total rel
840  * width and each attribute.
841  *
842  * Note: if you consider changing this logic, beware that child rels could
843  * have zero rows and/or width, if they were excluded by constraints.
844  */
845  has_live_children = false;
846  parent_rows = 0;
847  parent_size = 0;
848  nattrs = rel->max_attr - rel->min_attr + 1;
849  parent_attrsizes = (double *) palloc0(nattrs * sizeof(double));
850 
851  foreach(l, root->append_rel_list)
852  {
853  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
854  int childRTindex;
855  RangeTblEntry *childRTE;
856  RelOptInfo *childrel;
857  List *childquals;
858  Index cq_min_security;
859  bool have_const_false_cq;
860  ListCell *parentvars;
861  ListCell *childvars;
862  ListCell *lc;
863 
864  /* append_rel_list contains all append rels; ignore others */
865  if (appinfo->parent_relid != parentRTindex)
866  continue;
867 
868  childRTindex = appinfo->child_relid;
869  childRTE = root->simple_rte_array[childRTindex];
870 
871  /*
872  * The child rel's RelOptInfo was already created during
873  * add_base_rels_to_query.
874  */
875  childrel = find_base_rel(root, childRTindex);
877 
878  /*
879  * We have to copy the parent's targetlist and quals to the child,
880  * with appropriate substitution of variables. However, only the
881  * baserestrictinfo quals are needed before we can check for
882  * constraint exclusion; so do that first and then check to see if we
883  * can disregard this child.
884  *
885  * The child rel's targetlist might contain non-Var expressions, which
886  * means that substitution into the quals could produce opportunities
887  * for const-simplification, and perhaps even pseudoconstant quals.
888  * Therefore, transform each RestrictInfo separately to see if it
889  * reduces to a constant or pseudoconstant. (We must process them
890  * separately to keep track of the security level of each qual.)
891  */
892  childquals = NIL;
893  cq_min_security = UINT_MAX;
894  have_const_false_cq = false;
895  foreach(lc, rel->baserestrictinfo)
896  {
897  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
898  Node *childqual;
899  ListCell *lc2;
900 
901  Assert(IsA(rinfo, RestrictInfo));
902  childqual = adjust_appendrel_attrs(root,
903  (Node *) rinfo->clause,
904  appinfo);
905  childqual = eval_const_expressions(root, childqual);
906  /* check for flat-out constant */
907  if (childqual && IsA(childqual, Const))
908  {
909  if (((Const *) childqual)->constisnull ||
910  !DatumGetBool(((Const *) childqual)->constvalue))
911  {
912  /* Restriction reduces to constant FALSE or NULL */
913  have_const_false_cq = true;
914  break;
915  }
916  /* Restriction reduces to constant TRUE, so drop it */
917  continue;
918  }
919  /* might have gotten an AND clause, if so flatten it */
920  foreach(lc2, make_ands_implicit((Expr *) childqual))
921  {
922  Node *onecq = (Node *) lfirst(lc2);
923  bool pseudoconstant;
924 
925  /* check for pseudoconstant (no Vars or volatile functions) */
926  pseudoconstant =
927  !contain_vars_of_level(onecq, 0) &&
929  if (pseudoconstant)
930  {
931  /* tell createplan.c to check for gating quals */
932  root->hasPseudoConstantQuals = true;
933  }
934  /* reconstitute RestrictInfo with appropriate properties */
935  childquals = lappend(childquals,
936  make_restrictinfo((Expr *) onecq,
937  rinfo->is_pushed_down,
938  rinfo->outerjoin_delayed,
939  pseudoconstant,
940  rinfo->security_level,
941  NULL, NULL, NULL));
942  /* track minimum security level among child quals */
943  cq_min_security = Min(cq_min_security, rinfo->security_level);
944  }
945  }
946 
947  /*
948  * In addition to the quals inherited from the parent, we might have
949  * securityQuals associated with this particular child node.
950  * (Currently this can only happen in appendrels originating from
951  * UNION ALL; inheritance child tables don't have their own
952  * securityQuals, see expand_inherited_rtentry().) Pull any such
953  * securityQuals up into the baserestrictinfo for the child. This is
954  * similar to process_security_barrier_quals() for the parent rel,
955  * except that we can't make any general deductions from such quals,
956  * since they don't hold for the whole appendrel.
957  */
958  if (childRTE->securityQuals)
959  {
960  Index security_level = 0;
961 
962  foreach(lc, childRTE->securityQuals)
963  {
964  List *qualset = (List *) lfirst(lc);
965  ListCell *lc2;
966 
967  foreach(lc2, qualset)
968  {
969  Expr *qual = (Expr *) lfirst(lc2);
970 
971  /* not likely that we'd see constants here, so no check */
972  childquals = lappend(childquals,
973  make_restrictinfo(qual,
974  true, false, false,
975  security_level,
976  NULL, NULL, NULL));
977  cq_min_security = Min(cq_min_security, security_level);
978  }
979  security_level++;
980  }
981  Assert(security_level <= root->qual_security_level);
982  }
983 
984  /*
985  * OK, we've got all the baserestrictinfo quals for this child.
986  */
987  childrel->baserestrictinfo = childquals;
988  childrel->baserestrict_min_security = cq_min_security;
989 
990  if (have_const_false_cq)
991  {
992  /*
993  * Some restriction clause reduced to constant FALSE or NULL after
994  * substitution, so this child need not be scanned.
995  */
996  set_dummy_rel_pathlist(childrel);
997  continue;
998  }
999 
1000  if (relation_excluded_by_constraints(root, childrel, childRTE))
1001  {
1002  /*
1003  * This child need not be scanned, so we can omit it from the
1004  * appendrel.
1005  */
1006  set_dummy_rel_pathlist(childrel);
1007  continue;
1008  }
1009 
1010  /*
1011  * CE failed, so finish copying/modifying targetlist and join quals.
1012  *
1013  * NB: the resulting childrel->reltarget->exprs may contain arbitrary
1014  * expressions, which otherwise would not occur in a rel's targetlist.
1015  * Code that might be looking at an appendrel child must cope with
1016  * such. (Normally, a rel's targetlist would only include Vars and
1017  * PlaceHolderVars.) XXX we do not bother to update the cost or width
1018  * fields of childrel->reltarget; not clear if that would be useful.
1019  */
1020  childrel->joininfo = (List *)
1022  (Node *) rel->joininfo,
1023  appinfo);
1024  childrel->reltarget->exprs = (List *)
1026  (Node *) rel->reltarget->exprs,
1027  appinfo);
1028 
1029  /*
1030  * We have to make child entries in the EquivalenceClass data
1031  * structures as well. This is needed either if the parent
1032  * participates in some eclass joins (because we will want to consider
1033  * inner-indexscan joins on the individual children) or if the parent
1034  * has useful pathkeys (because we should try to build MergeAppend
1035  * paths that produce those sort orderings).
1036  */
1037  if (rel->has_eclass_joins || has_useful_pathkeys(root, rel))
1038  add_child_rel_equivalences(root, appinfo, rel, childrel);
1039  childrel->has_eclass_joins = rel->has_eclass_joins;
1040 
1041  /*
1042  * Note: we could compute appropriate attr_needed data for the child's
1043  * variables, by transforming the parent's attr_needed through the
1044  * translated_vars mapping. However, currently there's no need
1045  * because attr_needed is only examined for base relations not
1046  * otherrels. So we just leave the child's attr_needed empty.
1047  */
1048 
1049  /*
1050  * If parallelism is allowable for this query in general, see whether
1051  * it's allowable for this childrel in particular. But if we've
1052  * already decided the appendrel is not parallel-safe as a whole,
1053  * there's no point in considering parallelism for this child. For
1054  * consistency, do this before calling set_rel_size() for the child.
1055  */
1056  if (root->glob->parallelModeOK && rel->consider_parallel)
1057  set_rel_consider_parallel(root, childrel, childRTE);
1058 
1059  /*
1060  * Compute the child's size.
1061  */
1062  set_rel_size(root, childrel, childRTindex, childRTE);
1063 
1064  /*
1065  * It is possible that constraint exclusion detected a contradiction
1066  * within a child subquery, even though we didn't prove one above. If
1067  * so, we can skip this child.
1068  */
1069  if (IS_DUMMY_REL(childrel))
1070  continue;
1071 
1072  /* We have at least one live child. */
1073  has_live_children = true;
1074 
1075  /*
1076  * If any live child is not parallel-safe, treat the whole appendrel
1077  * as not parallel-safe. In future we might be able to generate plans
1078  * in which some children are farmed out to workers while others are
1079  * not; but we don't have that today, so it's a waste to consider
1080  * partial paths anywhere in the appendrel unless it's all safe.
1081  * (Child rels visited before this one will be unmarked in
1082  * set_append_rel_pathlist().)
1083  */
1084  if (!childrel->consider_parallel)
1085  rel->consider_parallel = false;
1086 
1087  /*
1088  * Accumulate size information from each live child.
1089  */
1090  Assert(childrel->rows > 0);
1091 
1092  parent_rows += childrel->rows;
1093  parent_size += childrel->reltarget->width * childrel->rows;
1094 
1095  /*
1096  * Accumulate per-column estimates too. We need not do anything for
1097  * PlaceHolderVars in the parent list. If child expression isn't a
1098  * Var, or we didn't record a width estimate for it, we have to fall
1099  * back on a datatype-based estimate.
1100  *
1101  * By construction, child's targetlist is 1-to-1 with parent's.
1102  */
1103  forboth(parentvars, rel->reltarget->exprs,
1104  childvars, childrel->reltarget->exprs)
1105  {
1106  Var *parentvar = (Var *) lfirst(parentvars);
1107  Node *childvar = (Node *) lfirst(childvars);
1108 
1109  if (IsA(parentvar, Var))
1110  {
1111  int pndx = parentvar->varattno - rel->min_attr;
1112  int32 child_width = 0;
1113 
1114  if (IsA(childvar, Var) &&
1115  ((Var *) childvar)->varno == childrel->relid)
1116  {
1117  int cndx = ((Var *) childvar)->varattno - childrel->min_attr;
1118 
1119  child_width = childrel->attr_widths[cndx];
1120  }
1121  if (child_width <= 0)
1122  child_width = get_typavgwidth(exprType(childvar),
1123  exprTypmod(childvar));
1124  Assert(child_width > 0);
1125  parent_attrsizes[pndx] += child_width * childrel->rows;
1126  }
1127  }
1128  }
1129 
1130  if (has_live_children)
1131  {
1132  /*
1133  * Save the finished size estimates.
1134  */
1135  int i;
1136 
1137  Assert(parent_rows > 0);
1138  rel->rows = parent_rows;
1139  rel->reltarget->width = rint(parent_size / parent_rows);
1140  for (i = 0; i < nattrs; i++)
1141  rel->attr_widths[i] = rint(parent_attrsizes[i] / parent_rows);
1142 
1143  /*
1144  * Set "raw tuples" count equal to "rows" for the appendrel; needed
1145  * because some places assume rel->tuples is valid for any baserel.
1146  */
1147  rel->tuples = parent_rows;
1148  }
1149  else
1150  {
1151  /*
1152  * All children were excluded by constraints, so mark the whole
1153  * appendrel dummy. We must do this in this phase so that the rel's
1154  * dummy-ness is visible when we generate paths for other rels.
1155  */
1157  }
1158 
1159  pfree(parent_attrsizes);
1160 }
bool has_eclass_joins
Definition: relation.h:551
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Index security_level
Definition: relation.h:1649
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
RelOptKind reloptkind
Definition: relation.h:487
RestrictInfo * make_restrictinfo(Expr *clause, bool is_pushed_down, bool outerjoin_delayed, bool pseudoconstant, Index security_level, Relids required_relids, Relids outer_relids, Relids nullable_relids)
Definition: restrictinfo.c:57
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:274
List * securityQuals
Definition: parsenodes.h:970
double tuples
Definition: relation.h:529
List * baserestrictinfo
Definition: relation.h:544
#define Min(x, y)
Definition: c.h:801
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1267
Definition: nodes.h:508
AttrNumber varattno
Definition: primnodes.h:146
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2366
Index baserestrict_min_security
Definition: relation.h:547
void add_child_rel_equivalences(PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
Definition: equivclass.c:2068
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:950
Definition: primnodes.h:141
signed int int32
Definition: c.h:253
void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:1616
void pfree(void *pointer)
Definition: mcxt.c:992
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
#define IS_DUMMY_REL(r)
Definition: relation.h:1126
bool parallelModeOK
Definition: relation.h:126
bool outerjoin_delayed
Definition: relation.h:1641
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, AppendRelInfo *appinfo)
Definition: prepunion.c:1734
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:501
List * joininfo
Definition: relation.h:549
PlannerGlobal * glob
Definition: relation.h:154
#define DatumGetBool(X)
Definition: postgres.h:401
double rint(double x)
Definition: rint.c:22
Index relid
Definition: relation.h:518
List * lappend(List *list, void *datum)
Definition: list.c:128
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
Expr * clause
Definition: relation.h:1637
List * exprs
Definition: relation.h:824
void * palloc0(Size size)
Definition: mcxt.c:920
List * append_rel_list
Definition: relation.h:249
unsigned int Index
Definition: c.h:361
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2296
double rows
Definition: relation.h:493
bool hasPseudoConstantQuals
Definition: relation.h:298
bool is_pushed_down
Definition: relation.h:1639
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:369
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
bool consider_parallel
Definition: relation.h:498
int width
Definition: relation.h:827
AttrNumber max_attr
Definition: relation.h:522
int i
bool has_useful_pathkeys(PlannerInfo *root, RelOptInfo *rel)
Definition: pathkeys.c:1531
Index child_relid
Definition: relation.h:1866
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
Index parent_relid
Definition: relation.h:1865
int32 * attr_widths
Definition: relation.h:524
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:501
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:311
AttrNumber min_attr
Definition: relation.h:521
static void set_base_rel_consider_startup ( PlannerInfo root)
static

Definition at line 198 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().

199 {
200  /*
201  * Since parameterized paths can only be used on the inside of a nestloop
202  * join plan, there is usually little value in considering fast-start
203  * plans for them. However, for relations that are on the RHS of a SEMI
204  * or ANTI join, a fast-start plan can be useful because we're only going
205  * to care about fetching one tuple anyway.
206  *
207  * To minimize growth of planning time, we currently restrict this to
208  * cases where the RHS is a single base relation, not a join; there is no
209  * provision for consider_param_startup to get set at all on joinrels.
210  * Also we don't worry about appendrels. costsize.c's costing rules for
211  * nestloop semi/antijoins don't consider such cases either.
212  */
213  ListCell *lc;
214 
215  foreach(lc, root->join_info_list)
216  {
217  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
218  int varno;
219 
220  if ((sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) &&
221  bms_get_singleton_member(sjinfo->syn_righthand, &varno))
222  {
223  RelOptInfo *rel = find_base_rel(root, varno);
224 
225  rel->consider_param_startup = true;
226  }
227  }
228 }
List * join_info_list
Definition: relation.h:247
bool consider_param_startup
Definition: relation.h:497
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:539
Relids syn_righthand
Definition: relation.h:1810
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1811
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
static void set_base_rel_pathlists ( PlannerInfo root)
static

Definition at line 284 of file allpaths.c.

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

285 {
286  Index rti;
287 
288  for (rti = 1; rti < root->simple_rel_array_size; rti++)
289  {
290  RelOptInfo *rel = root->simple_rel_array[rti];
291 
292  /* there may be empty slots corresponding to non-baserel RTEs */
293  if (rel == NULL)
294  continue;
295 
296  Assert(rel->relid == rti); /* sanity check on array */
297 
298  /* ignore RTEs that are "other rels" */
299  if (rel->reloptkind != RELOPT_BASEREL)
300  continue;
301 
302  set_rel_pathlist(root, rel, rti, root->simple_rte_array[rti]);
303  }
304 }
RelOptKind reloptkind
Definition: relation.h:487
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
int simple_rel_array_size
Definition: relation.h:177
Index relid
Definition: relation.h:518
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
unsigned int Index
Definition: c.h:361
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:400
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static void set_base_rel_sizes ( PlannerInfo root)
static

Definition at line 241 of file allpaths.c.

References Assert, PlannerInfo::glob, NULL, 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().

242 {
243  Index rti;
244 
245  for (rti = 1; rti < root->simple_rel_array_size; rti++)
246  {
247  RelOptInfo *rel = root->simple_rel_array[rti];
248  RangeTblEntry *rte;
249 
250  /* there may be empty slots corresponding to non-baserel RTEs */
251  if (rel == NULL)
252  continue;
253 
254  Assert(rel->relid == rti); /* sanity check on array */
255 
256  /* ignore RTEs that are "other rels" */
257  if (rel->reloptkind != RELOPT_BASEREL)
258  continue;
259 
260  rte = root->simple_rte_array[rti];
261 
262  /*
263  * If parallelism is allowable for this query in general, see whether
264  * it's allowable for this rel in particular. We have to do this
265  * before set_rel_size(), because (a) if this rel is an inheritance
266  * parent, set_append_rel_size() will use and perhaps change the rel's
267  * consider_parallel flag, and (b) for some RTE types, set_rel_size()
268  * goes ahead and makes paths immediately.
269  */
270  if (root->glob->parallelModeOK)
271  set_rel_consider_parallel(root, rel, rte);
272 
273  set_rel_size(root, rel, rti, rte);
274  }
275 }
RelOptKind reloptkind
Definition: relation.h:487
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
bool parallelModeOK
Definition: relation.h:126
static void set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:501
PlannerGlobal * glob
Definition: relation.h:154
int simple_rel_array_size
Definition: relation.h:177
Index relid
Definition: relation.h:518
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
unsigned int Index
Definition: c.h:361
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:311
static void set_cte_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 1940 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(), NULL, PlannerInfo::parent_root, PlannerInfo::parse, Plan::plan_rows, set_cte_size_estimates(), and PlannerGlobal::subplans.

Referenced by set_rel_size().

1941 {
1942  Plan *cteplan;
1943  PlannerInfo *cteroot;
1944  Index levelsup;
1945  int ndx;
1946  ListCell *lc;
1947  int plan_id;
1948  Relids required_outer;
1949 
1950  /*
1951  * Find the referenced CTE, and locate the plan previously made for it.
1952  */
1953  levelsup = rte->ctelevelsup;
1954  cteroot = root;
1955  while (levelsup-- > 0)
1956  {
1957  cteroot = cteroot->parent_root;
1958  if (!cteroot) /* shouldn't happen */
1959  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
1960  }
1961 
1962  /*
1963  * Note: cte_plan_ids can be shorter than cteList, if we are still working
1964  * on planning the CTEs (ie, this is a side-reference from another CTE).
1965  * So we mustn't use forboth here.
1966  */
1967  ndx = 0;
1968  foreach(lc, cteroot->parse->cteList)
1969  {
1970  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
1971 
1972  if (strcmp(cte->ctename, rte->ctename) == 0)
1973  break;
1974  ndx++;
1975  }
1976  if (lc == NULL) /* shouldn't happen */
1977  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
1978  if (ndx >= list_length(cteroot->cte_plan_ids))
1979  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
1980  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
1981  Assert(plan_id > 0);
1982  cteplan = (Plan *) list_nth(root->glob->subplans, plan_id - 1);
1983 
1984  /* Mark rel with estimated output rows, width, etc */
1985  set_cte_size_estimates(root, rel, cteplan->plan_rows);
1986 
1987  /*
1988  * We don't support pushing join clauses into the quals of a CTE scan, but
1989  * it could still have required parameterization due to LATERAL refs in
1990  * its tlist.
1991  */
1992  required_outer = rel->lateral_relids;
1993 
1994  /* Generate appropriate path */
1995  add_path(rel, create_ctescan_path(root, rel, required_outer));
1996 }
double plan_rows
Definition: plannodes.h:117
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:4474
Relids lateral_relids
Definition: relation.h:515
#define ERROR
Definition: elog.h:43
void * list_nth(const List *list, int n)
Definition: list.c:410
List * subplans
Definition: relation.h:98
PlannerGlobal * glob
Definition: relation.h:154
struct PlannerInfo * parent_root
Definition: relation.h:158
int list_nth_int(const List *list, int n)
Definition: list.c:421
List * cte_plan_ids
Definition: relation.h:227
unsigned int Index
Definition: c.h:361
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Index ctelevelsup
Definition: parsenodes.h:943
List * cteList
Definition: parsenodes.h:126
char * ctename
Definition: parsenodes.h:942
#define elog
Definition: elog.h:219
Path * create_ctescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1785
void set_dummy_rel_pathlist ( RelOptInfo rel)

Definition at line 1616 of file allpaths.c.

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

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

1617 {
1618  /* Set dummy size estimates --- we leave attr_widths[] as zeroes */
1619  rel->rows = 0;
1620  rel->reltarget->width = 0;
1621 
1622  /* Discard any pre-existing paths; no further need for them */
1623  rel->pathlist = NIL;
1624  rel->partial_pathlist = NIL;
1625 
1626  add_path(rel, (Path *) create_append_path(rel, NIL, NULL, 0));
1627 
1628  /*
1629  * We set the cheapest path immediately, to ensure that IS_DUMMY_REL()
1630  * will recognize the relation as dummy if anyone asks. This is redundant
1631  * when we're called from set_rel_size(), but not when called from
1632  * elsewhere, and doing it twice is harmless anyway.
1633  */
1634  set_cheapest(rel);
1635 }
#define NIL
Definition: pg_list.h:69
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers)
Definition: pathnode.c:1202
List * partial_pathlist
Definition: relation.h:506
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
double rows
Definition: relation.h:493
#define NULL
Definition: c.h:226
int width
Definition: relation.h:827
List * pathlist
Definition: relation.h:504
struct PathTarget * reltarget
Definition: relation.h:501
Definition: relation.h:888
static void set_foreign_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 802 of file allpaths.c.

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

Referenced by set_rel_pathlist().

803 {
804  /* Call the FDW's GetForeignPaths function to generate path(s) */
805  rel->fdwroutine->GetForeignPaths(root, rel, rte->relid);
806 }
struct FdwRoutine * fdwroutine
Definition: relation.h:540
GetForeignPaths_function GetForeignPaths
Definition: fdwapi.h:174
static void set_foreign_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 785 of file allpaths.c.

References clamp_row_est(), RelOptInfo::fdwroutine, FdwRoutine::GetForeignRelSize, RangeTblEntry::relid, RelOptInfo::rows, and set_foreign_size_estimates().

Referenced by set_rel_size().

786 {
787  /* Mark rel with estimated output rows, width, etc */
788  set_foreign_size_estimates(root, rel);
789 
790  /* Let FDW adjust the size estimates, if it can */
791  rel->fdwroutine->GetForeignRelSize(root, rel, rte->relid);
792 
793  /* ... but do not let it set the rows estimate to zero */
794  rel->rows = clamp_row_est(rel->rows);
795 }
struct FdwRoutine * fdwroutine
Definition: relation.h:540
GetForeignRelSize_function GetForeignRelSize
Definition: fdwapi.h:173
double rows
Definition: relation.h:493
void set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4517
double clamp_row_est(double nrows)
Definition: costsize.c:172
static void set_function_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 1849 of file allpaths.c.

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

Referenced by set_rel_pathlist().

1850 {
1851  Relids required_outer;
1852  List *pathkeys = NIL;
1853 
1854  /*
1855  * We don't support pushing join clauses into the quals of a function
1856  * scan, but it could still have required parameterization due to LATERAL
1857  * refs in the function expression.
1858  */
1859  required_outer = rel->lateral_relids;
1860 
1861  /*
1862  * The result is considered unordered unless ORDINALITY was used, in which
1863  * case it is ordered by the ordinal column (the last one). See if we
1864  * care, by checking for uses of that Var in equivalence classes.
1865  */
1866  if (rte->funcordinality)
1867  {
1868  AttrNumber ordattno = rel->max_attr;
1869  Var *var = NULL;
1870  ListCell *lc;
1871 
1872  /*
1873  * Is there a Var for it in rel's targetlist? If not, the query did
1874  * not reference the ordinality column, or at least not in any way
1875  * that would be interesting for sorting.
1876  */
1877  foreach(lc, rel->reltarget->exprs)
1878  {
1879  Var *node = (Var *) lfirst(lc);
1880 
1881  /* checking varno/varlevelsup is just paranoia */
1882  if (IsA(node, Var) &&
1883  node->varattno == ordattno &&
1884  node->varno == rel->relid &&
1885  node->varlevelsup == 0)
1886  {
1887  var = node;
1888  break;
1889  }
1890  }
1891 
1892  /*
1893  * Try to build pathkeys for this Var with int8 sorting. We tell
1894  * build_expression_pathkey not to build any new equivalence class; if
1895  * the Var isn't already mentioned in some EC, it means that nothing
1896  * cares about the ordering.
1897  */
1898  if (var)
1899  pathkeys = build_expression_pathkey(root,
1900  (Expr *) var,
1901  NULL, /* below outer joins */
1903  rel->relids,
1904  false);
1905  }
1906 
1907  /* Generate appropriate path */
1908  add_path(rel, create_functionscan_path(root, rel,
1909  pathkeys, required_outer));
1910 }
#define NIL
Definition: pg_list.h:69
#define Int8LessOperator
Definition: pg_operator.h:181
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
List * build_expression_pathkey(PlannerInfo *root, Expr *expr, Relids nullable_relids, Oid opno, Relids rel, bool create_it)
Definition: pathkeys.c:526
Index varlevelsup
Definition: primnodes.h:151
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
AttrNumber varattno
Definition: primnodes.h:146
bool funcordinality
Definition: parsenodes.h:932
Definition: primnodes.h:141
Path * create_functionscan_path(PlannerInfo *root, RelOptInfo *rel, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1733
Relids lateral_relids
Definition: relation.h:515
Relids relids
Definition: relation.h:490
Index relid
Definition: relation.h:518
Index varno
Definition: primnodes.h:144
List * exprs
Definition: relation.h:824
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
AttrNumber max_attr
Definition: relation.h:522
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:501
int16 AttrNumber
Definition: attnum.h:21
static void set_plain_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 648 of file allpaths.c.

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

Referenced by set_rel_pathlist().

649 {
650  Relids required_outer;
651 
652  /*
653  * We don't support pushing join clauses into the quals of a seqscan, but
654  * it could still have required parameterization due to LATERAL refs in
655  * its tlist.
656  */
657  required_outer = rel->lateral_relids;
658 
659  /* Consider sequential scan */
660  add_path(rel, create_seqscan_path(root, rel, required_outer, 0));
661 
662  /* If appropriate, consider parallel sequential scan */
663  if (rel->consider_parallel && required_outer == NULL)
664  create_plain_partial_paths(root, rel);
665 
666  /* Consider index scans */
667  create_index_paths(root, rel);
668 
669  /* Consider TID scans */
670  create_tidscan_paths(root, rel);
671 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
void create_index_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:232
Relids lateral_relids
Definition: relation.h:515
void create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: tidpath.c:253
#define NULL
Definition: c.h:226
bool consider_parallel
Definition: relation.h:498
static void create_plain_partial_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:678
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:938
static void set_plain_rel_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 484 of file allpaths.c.

References check_index_predicates(), and set_baserel_size_estimates().

Referenced by set_rel_size().

485 {
486  /*
487  * Test any partial indexes of rel for applicability. We must do this
488  * first since partial unique indexes can affect size estimates.
489  */
490  check_index_predicates(root, rel);
491 
492  /* Mark rel with estimated output rows, width, etc */
493  set_baserel_size_estimates(root, rel);
494 }
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:2761
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:3771
static void set_rel_consider_parallel ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 501 of file allpaths.c.

References TableSampleClause::args, Assert, RelOptInfo::baserestrictinfo, RelOptInfo::consider_parallel, PathTarget::exprs, RelOptInfo::fdwroutine, func_parallel(), RangeTblEntry::functions, get_rel_persistence(), PlannerInfo::glob, is_parallel_safe(), FdwRoutine::IsForeignScanParallelSafe, NULL, PlannerGlobal::parallelModeOK, PROPARALLEL_SAFE, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RELPERSISTENCE_TEMP, RelOptInfo::reltarget, RTE_CTE, RTE_FUNCTION, RTE_JOIN, RTE_RELATION, RTE_SUBQUERY, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::tablesample, TableSampleClause::tsmhandler, and RangeTblEntry::values_lists.

Referenced by set_append_rel_size(), and set_base_rel_sizes().

503 {
504  /*
505  * The flag has previously been initialized to false, so we can just
506  * return if it becomes clear that we can't safely set it.
507  */
508  Assert(!rel->consider_parallel);
509 
510  /* Don't call this if parallelism is disallowed for the entire query. */
511  Assert(root->glob->parallelModeOK);
512 
513  /* This should only be called for baserels and appendrel children. */
514  Assert(rel->reloptkind == RELOPT_BASEREL ||
516 
517  /* Assorted checks based on rtekind. */
518  switch (rte->rtekind)
519  {
520  case RTE_RELATION:
521 
522  /*
523  * Currently, parallel workers can't access the leader's temporary
524  * tables. We could possibly relax this if the wrote all of its
525  * local buffers at the start of the query and made no changes
526  * thereafter (maybe we could allow hint bit changes), and if we
527  * taught the workers to read them. Writing a large number of
528  * temporary buffers could be expensive, though, and we don't have
529  * the rest of the necessary infrastructure right now anyway. So
530  * for now, bail out if we see a temporary table.
531  */
533  return;
534 
535  /*
536  * Table sampling can be pushed down to workers if the sample
537  * function and its arguments are safe.
538  */
539  if (rte->tablesample != NULL)
540  {
541  char proparallel = func_parallel(rte->tablesample->tsmhandler);
542 
543  if (proparallel != PROPARALLEL_SAFE)
544  return;
545  if (!is_parallel_safe(root, (Node *) rte->tablesample->args))
546  return;
547  }
548 
549  /*
550  * Ask FDWs whether they can support performing a ForeignScan
551  * within a worker. Most often, the answer will be no. For
552  * example, if the nature of the FDW is such that it opens a TCP
553  * connection with a remote server, each parallel worker would end
554  * up with a separate connection, and these connections might not
555  * be appropriately coordinated between workers and the leader.
556  */
557  if (rte->relkind == RELKIND_FOREIGN_TABLE)
558  {
559  Assert(rel->fdwroutine);
561  return;
562  if (!rel->fdwroutine->IsForeignScanParallelSafe(root, rel, rte))
563  return;
564  }
565 
566  /*
567  * There are additional considerations for appendrels, which we'll
568  * deal with in set_append_rel_size and set_append_rel_pathlist.
569  * For now, just set consider_parallel based on the rel's own
570  * quals and targetlist.
571  */
572  break;
573 
574  case RTE_SUBQUERY:
575 
576  /*
577  * There's no intrinsic problem with scanning a subquery-in-FROM
578  * (as distinct from a SubPlan or InitPlan) in a parallel worker.
579  * If the subquery doesn't happen to have any parallel-safe paths,
580  * then flagging it as consider_parallel won't change anything,
581  * but that's true for plain tables, too. We must set
582  * consider_parallel based on the rel's own quals and targetlist,
583  * so that if a subquery path is parallel-safe but the quals and
584  * projection we're sticking onto it are not, we correctly mark
585  * the SubqueryScanPath as not parallel-safe. (Note that
586  * set_subquery_pathlist() might push some of these quals down
587  * into the subquery itself, but that doesn't change anything.)
588  */
589  break;
590 
591  case RTE_JOIN:
592  /* Shouldn't happen; we're only considering baserels here. */
593  Assert(false);
594  return;
595 
596  case RTE_FUNCTION:
597  /* Check for parallel-restricted functions. */
598  if (!is_parallel_safe(root, (Node *) rte->functions))
599  return;
600  break;
601 
602  case RTE_VALUES:
603  /* Check for parallel-restricted functions. */
604  if (!is_parallel_safe(root, (Node *) rte->values_lists))
605  return;
606  break;
607 
608  case RTE_CTE:
609 
610  /*
611  * CTE tuplestores aren't shared among parallel workers, so we
612  * force all CTE scans to happen in the leader. Also, populating
613  * the CTE would require executing a subplan that's not available
614  * in the worker, might be parallel-restricted, and must get
615  * executed only once.
616  */
617  return;
618  }
619 
620  /*
621  * If there's anything in baserestrictinfo that's parallel-restricted, we
622  * give up on parallelizing access to this relation. We could consider
623  * instead postponing application of the restricted quals until we're
624  * above all the parallelism in the plan tree, but it's not clear that
625  * that would be a win in very many cases, and it might be tricky to make
626  * outer join clauses work correctly. It would likely break equivalence
627  * classes, too.
628  */
629  if (!is_parallel_safe(root, (Node *) rel->baserestrictinfo))
630  return;
631 
632  /*
633  * Likewise, if the relation's outputs are not parallel-safe, give up.
634  * (Usually, they're just Vars, but sometimes they're not.)
635  */
636  if (!is_parallel_safe(root, (Node *) rel->reltarget->exprs))
637  return;
638 
639  /* We have a winner. */
640  rel->consider_parallel = true;
641 }
RelOptKind reloptkind
Definition: relation.h:487
List * baserestrictinfo
Definition: relation.h:544
Definition: nodes.h:508
List * values_lists
Definition: parsenodes.h:937
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1071
IsForeignScanParallelSafe_function IsForeignScanParallelSafe
Definition: fdwapi.h:223
bool parallelModeOK
Definition: relation.h:126
PlannerGlobal * glob
Definition: relation.h:154
struct FdwRoutine * fdwroutine
Definition: relation.h:540
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
#define PROPARALLEL_SAFE
Definition: pg_proc.h:5381
List * exprs
Definition: relation.h:824
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
List * functions
Definition: parsenodes.h:931
char func_parallel(Oid funcid)
Definition: lsyscache.c:1571
bool consider_parallel
Definition: relation.h:498
char get_rel_persistence(Oid relid)
Definition: lsyscache.c:1820
RTEKind rtekind
Definition: parsenodes.h:882
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
struct PathTarget * reltarget
Definition: relation.h:501
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
static void set_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 400 of file allpaths.c.

References elog, ERROR, generate_gather_paths(), RangeTblEntry::inh, IS_DUMMY_REL, NULL, RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, RELOPT_BASEREL, RelOptInfo::reloptkind, RTE_CTE, RTE_FUNCTION, RTE_RELATION, RTE_SUBQUERY, 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_tablesample_rel_pathlist(), set_values_pathlist(), and RangeTblEntry::tablesample.

Referenced by set_append_rel_pathlist(), and set_base_rel_pathlists().

402 {
403  if (IS_DUMMY_REL(rel))
404  {
405  /* We already proved the relation empty, so nothing more to do */
406  }
407  else if (rte->inh)
408  {
409  /* It's an "append relation", process accordingly */
410  set_append_rel_pathlist(root, rel, rti, rte);
411  }
412  else
413  {
414  switch (rel->rtekind)
415  {
416  case RTE_RELATION:
417  if (rte->relkind == RELKIND_FOREIGN_TABLE)
418  {
419  /* Foreign table */
420  set_foreign_pathlist(root, rel, rte);
421  }
422  else if (rte->tablesample != NULL)
423  {
424  /* Sampled relation */
425  set_tablesample_rel_pathlist(root, rel, rte);
426  }
427  else
428  {
429  /* Plain relation */
430  set_plain_rel_pathlist(root, rel, rte);
431  }
432  break;
433  case RTE_SUBQUERY:
434  /* Subquery --- fully handled during set_rel_size */
435  break;
436  case RTE_FUNCTION:
437  /* RangeFunction */
438  set_function_pathlist(root, rel, rte);
439  break;
440  case RTE_VALUES:
441  /* Values list */
442  set_values_pathlist(root, rel, rte);
443  break;
444  case RTE_CTE:
445  /* CTE reference --- fully handled during set_rel_size */
446  break;
447  default:
448  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
449  break;
450  }
451  }
452 
453  /*
454  * If this is a baserel, consider gathering any partial paths we may have
455  * created for it. (If we tried to gather inheritance children, we could
456  * end up with a very large number of gather nodes, each trying to grab
457  * its own pool of workers, so don't do this for otherrels. Instead,
458  * we'll consider gathering partial paths for the parent appendrel.)
459  */
460  if (rel->reloptkind == RELOPT_BASEREL)
461  generate_gather_paths(root, rel);
462 
463  /*
464  * Allow a plugin to editorialize on the set of Paths for this base
465  * relation. It could add new paths (such as CustomPaths) by calling
466  * add_path(), or delete or modify paths added by the core code.
467  */
469  (*set_rel_pathlist_hook) (root, rel, rti, rte);
470 
471  /* Now find the cheapest of the paths for this rel */
472  set_cheapest(rel);
473 
474 #ifdef OPTIMIZER_DEBUG
475  debug_print_rel(root, rel);
476 #endif
477 }
RelOptKind reloptkind
Definition: relation.h:487
set_rel_pathlist_hook_type set_rel_pathlist_hook
Definition: allpaths.c:64
#define ERROR
Definition: elog.h:43
#define IS_DUMMY_REL(r)
Definition: relation.h:1126
static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1167
static void set_foreign_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:802
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:2058
static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:648
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
RTEKind rtekind
Definition: relation.h:520
static void set_tablesample_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:737
#define NULL
Definition: c.h:226
#define elog
Definition: elog.h:219
static void set_function_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:1849
static void set_values_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:1917
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
static void set_rel_size ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 311 of file allpaths.c.

References Assert, elog, ERROR, RangeTblEntry::inh, IS_DUMMY_REL, NULL, relation_excluded_by_constraints(), RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, RELOPT_BASEREL, RelOptInfo::reloptkind, RelOptInfo::rows, RTE_CTE, RTE_FUNCTION, RTE_RELATION, RTE_SUBQUERY, 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_plain_rel_size(), set_subquery_pathlist(), 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().

313 {
314  if (rel->reloptkind == RELOPT_BASEREL &&
315  relation_excluded_by_constraints(root, rel, rte))
316  {
317  /*
318  * We proved we don't need to scan the rel via constraint exclusion,
319  * so set up a single dummy path for it. Here we only check this for
320  * regular baserels; if it's an otherrel, CE was already checked in
321  * set_append_rel_size().
322  *
323  * In this case, we go ahead and set up the relation's path right away
324  * instead of leaving it for set_rel_pathlist to do. This is because
325  * we don't have a convention for marking a rel as dummy except by
326  * assigning a dummy path to it.
327  */
329  }
330  else if (rte->inh)
331  {
332  /* It's an "append relation", process accordingly */
333  set_append_rel_size(root, rel, rti, rte);
334  }
335  else
336  {
337  switch (rel->rtekind)
338  {
339  case RTE_RELATION:
340  if (rte->relkind == RELKIND_FOREIGN_TABLE)
341  {
342  /* Foreign table */
343  set_foreign_size(root, rel, rte);
344  }
345  else if (rte->tablesample != NULL)
346  {
347  /* Sampled relation */
348  set_tablesample_rel_size(root, rel, rte);
349  }
350  else
351  {
352  /* Plain relation */
353  set_plain_rel_size(root, rel, rte);
354  }
355  break;
356  case RTE_SUBQUERY:
357 
358  /*
359  * Subqueries don't support making a choice between
360  * parameterized and unparameterized paths, so just go ahead
361  * and build their paths immediately.
362  */
363  set_subquery_pathlist(root, rel, rti, rte);
364  break;
365  case RTE_FUNCTION:
366  set_function_size_estimates(root, rel);
367  break;
368  case RTE_VALUES:
369  set_values_size_estimates(root, rel);
370  break;
371  case RTE_CTE:
372 
373  /*
374  * CTEs don't support making a choice between parameterized
375  * and unparameterized paths, so just go ahead and build their
376  * paths immediately.
377  */
378  if (rte->self_reference)
379  set_worktable_pathlist(root, rel, rte);
380  else
381  set_cte_pathlist(root, rel, rte);
382  break;
383  default:
384  elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
385  break;
386  }
387  }
388 
389  /*
390  * We insist that all non-dummy rels have a nonzero rowcount estimate.
391  */
392  Assert(rel->rows > 0 || IS_DUMMY_REL(rel));
393 }
RelOptKind reloptkind
Definition: relation.h:487
static void set_cte_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:1940
static void set_foreign_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:785
bool relation_excluded_by_constraints(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: plancat.c:1267
static void set_append_rel_size(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:820
void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:1616
#define ERROR
Definition: elog.h:43
#define IS_DUMMY_REL(r)
Definition: relation.h:1126
static void set_subquery_pathlist(PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
Definition: allpaths.c:1672
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
static void set_tablesample_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:697
bool self_reference
Definition: parsenodes.h:944
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4442
static void set_plain_rel_size(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:484
void set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4404
#define elog
Definition: elog.h:219
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
static void set_worktable_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
Definition: allpaths.c:2006
static void set_subquery_pathlist ( PlannerInfo root,
RelOptInfo rel,
Index  rti,
RangeTblEntry rte 
)
static

Definition at line 1672 of file allpaths.c.

References add_path(), Assert, RelOptInfo::baserestrictinfo, RestrictInfo::clause, 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, NULL, palloc0(), parse(), PlannerInfo::parse, 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().

1674 {
1675  Query *parse = root->parse;
1676  Query *subquery = rte->subquery;
1677  Relids required_outer;
1678  pushdown_safety_info safetyInfo;
1679  double tuple_fraction;
1680  RelOptInfo *sub_final_rel;
1681  ListCell *lc;
1682 
1683  /*
1684  * Must copy the Query so that planning doesn't mess up the RTE contents
1685  * (really really need to fix the planner to not scribble on its input,
1686  * someday ... but see remove_unused_subquery_outputs to start with).
1687  */
1688  subquery = copyObject(subquery);
1689 
1690  /*
1691  * If it's a LATERAL subquery, it might contain some Vars of the current
1692  * query level, requiring it to be treated as parameterized, even though
1693  * we don't support pushing down join quals into subqueries.
1694  */
1695  required_outer = rel->lateral_relids;
1696 
1697  /*
1698  * Zero out result area for subquery_is_pushdown_safe, so that it can set
1699  * flags as needed while recursing. In particular, we need a workspace
1700  * for keeping track of unsafe-to-reference columns. unsafeColumns[i]
1701  * will be set TRUE if we find that output column i of the subquery is
1702  * unsafe to use in a pushed-down qual.
1703  */
1704  memset(&safetyInfo, 0, sizeof(safetyInfo));
1705  safetyInfo.unsafeColumns = (bool *)
1706  palloc0((list_length(subquery->targetList) + 1) * sizeof(bool));
1707 
1708  /*
1709  * If the subquery has the "security_barrier" flag, it means the subquery
1710  * originated from a view that must enforce row level security. Then we
1711  * must not push down quals that contain leaky functions. (Ideally this
1712  * would be checked inside subquery_is_pushdown_safe, but since we don't
1713  * currently pass the RTE to that function, we must do it here.)
1714  */
1715  safetyInfo.unsafeLeaky = rte->security_barrier;
1716 
1717  /*
1718  * If there are any restriction clauses that have been attached to the
1719  * subquery relation, consider pushing them down to become WHERE or HAVING
1720  * quals of the subquery itself. This transformation is useful because it
1721  * may allow us to generate a better plan for the subquery than evaluating
1722  * all the subquery output rows and then filtering them.
1723  *
1724  * There are several cases where we cannot push down clauses. Restrictions
1725  * involving the subquery are checked by subquery_is_pushdown_safe().
1726  * Restrictions on individual clauses are checked by
1727  * qual_is_pushdown_safe(). Also, we don't want to push down
1728  * pseudoconstant clauses; better to have the gating node above the
1729  * subquery.
1730  *
1731  * Non-pushed-down clauses will get evaluated as qpquals of the
1732  * SubqueryScan node.
1733  *
1734  * XXX Are there any cases where we want to make a policy decision not to
1735  * push down a pushable qual, because it'd result in a worse plan?
1736  */
1737  if (rel->baserestrictinfo != NIL &&
1738  subquery_is_pushdown_safe(subquery, subquery, &safetyInfo))
1739  {
1740  /* OK to consider pushing down individual quals */
1741  List *upperrestrictlist = NIL;
1742  ListCell *l;
1743 
1744  foreach(l, rel->baserestrictinfo)
1745  {
1746  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1747  Node *clause = (Node *) rinfo->clause;
1748 
1749  if (!rinfo->pseudoconstant &&
1750  qual_is_pushdown_safe(subquery, rti, clause, &safetyInfo))
1751  {
1752  /* Push it down */
1753  subquery_push_qual(subquery, rte, rti, clause);
1754  }
1755  else
1756  {
1757  /* Keep it in the upper query */
1758  upperrestrictlist = lappend(upperrestrictlist, rinfo);
1759  }
1760  }
1761  rel->baserestrictinfo = upperrestrictlist;
1762  /* We don't bother recomputing baserestrict_min_security */
1763  }
1764 
1765  pfree(safetyInfo.unsafeColumns);
1766 
1767  /*
1768  * The upper query might not use all the subquery's output columns; if
1769  * not, we can simplify.
1770  */
1771  remove_unused_subquery_outputs(subquery, rel);
1772 
1773  /*
1774  * We can safely pass the outer tuple_fraction down to the subquery if the
1775  * outer level has no joining, aggregation, or sorting to do. Otherwise
1776  * we'd better tell the subquery to plan for full retrieval. (XXX This
1777  * could probably be made more intelligent ...)
1778  */
1779  if (parse->hasAggs ||
1780  parse->groupClause ||
1781  parse->groupingSets ||
1782  parse->havingQual ||
1783  parse->distinctClause ||
1784  parse->sortClause ||
1785  has_multiple_baserels(root))
1786  tuple_fraction = 0.0; /* default case */
1787  else
1788  tuple_fraction = root->tuple_fraction;
1789 
1790  /* plan_params should not be in use in current query level */
1791  Assert(root->plan_params == NIL);
1792 
1793  /* Generate a subroot and Paths for the subquery */
1794  rel->subroot = subquery_planner(root->glob, subquery,
1795  root,
1796  false, tuple_fraction);
1797 
1798  /* Isolate the params needed by this specific subplan */
1799  rel->subplan_params = root->plan_params;
1800  root->plan_params = NIL;
1801 
1802  /*
1803  * It's possible that constraint exclusion proved the subquery empty. If
1804  * so, it's desirable to produce an unadorned dummy path so that we will
1805  * recognize appropriate optimizations at this query level.
1806  */
1807  sub_final_rel = fetch_upper_rel(rel->subroot, UPPERREL_FINAL, NULL);
1808 
1809  if (IS_DUMMY_REL(sub_final_rel))
1810  {
1812  return;
1813  }
1814 
1815  /*
1816  * Mark rel with estimated output rows, width, etc. Note that we have to
1817  * do this before generating outer-query paths, else cost_subqueryscan is
1818  * not happy.
1819  */
1820  set_subquery_size_estimates(root, rel);
1821 
1822  /*
1823  * For each Path that subquery_planner produced, make a SubqueryScanPath
1824  * in the outer query.
1825  */
1826  foreach(lc, sub_final_rel->pathlist)
1827  {
1828  Path *subpath = (Path *) lfirst(lc);
1829  List *pathkeys;
1830 
1831  /* Convert subpath's pathkeys to outer representation */
1832  pathkeys = convert_subquery_pathkeys(root,
1833  rel,
1834  subpath->pathkeys,
1836 
1837  /* Generate outer path using this subpath */
1838  add_path(rel, (Path *)
1839  create_subqueryscan_path(root, rel, subpath,
1840  pathkeys, required_outer));
1841  }
1842 }
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4321
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:895
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
SubqueryScanPath * create_subqueryscan_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, Relids required_outer)
Definition: pathnode.c:1705
List * plan_params
Definition: relation.h:166
List * sortClause
Definition: parsenodes.h:147
List * baserestrictinfo
Definition: relation.h:544
bool hasAggs
Definition: parsenodes.h:116
bool pseudoconstant
Definition: relation.h:1645
List * groupingSets
Definition: parsenodes.h:139
Definition: nodes.h:508
List * make_tlist_from_pathtarget(PathTarget *target)
Definition: tlist.c:595
bool * unsafeColumns
Definition: allpaths.c:52
char bool
Definition: c.h:199
List * targetList
Definition: parsenodes.h:131
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
PlannerInfo * subroot
Definition: relation.h:531
Relids lateral_relids
Definition: relation.h:515
double tuple_fraction
Definition: relation.h:286
void set_dummy_rel_pathlist(RelOptInfo *rel)
Definition: allpaths.c:1616
void pfree(void *pointer)
Definition: mcxt.c:992
List * distinctClause
Definition: parsenodes.h:145
#define IS_DUMMY_REL(r)
Definition: relation.h:1126
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
List * convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
Definition: pathkeys.c:580
PlannerGlobal * glob
Definition: relation.h:154
static void remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel)
Definition: allpaths.c:2777
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1637
static bool qual_is_pushdown_safe(Query *subquery, Index rti, Node *qual, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2606
void * palloc0(Size size)
Definition: mcxt.c:920
bool security_barrier
Definition: parsenodes.h:901
List * pathkeys
Definition: relation.h:909
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
static bool has_multiple_baserels(PlannerInfo *root)
Definition: allpaths.c:1639
static void subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:2683
static int list_length(const List *l)
Definition: pg_list.h:89
static bool subquery_is_pushdown_safe(Query *subquery, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2346
Query * subquery
Definition: parsenodes.h:900
List * groupClause
Definition: parsenodes.h:137
List * pathlist
Definition: relation.h:504
Node * havingQual
Definition: parsenodes.h:141
Definition: pg_list.h:45
List * subplan_params
Definition: relation.h:532
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:450
Definition: relation.h:888
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
static void set_tablesample_rel_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 737 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().

738 {
739  Relids required_outer;
740  Path *path;
741 
742  /*
743  * We don't support pushing join clauses into the quals of a samplescan,
744  * but it could still have required parameterization due to LATERAL refs
745  * in its tlist or TABLESAMPLE arguments.
746  */
747  required_outer = rel->lateral_relids;
748 
749  /* Consider sampled scan */
750  path = create_samplescan_path(root, rel, required_outer);
751 
752  /*
753  * If the sampling method does not support repeatable scans, we must avoid
754  * plans that would scan the rel multiple times. Ideally, we'd simply
755  * avoid putting the rel on the inside of a nestloop join; but adding such
756  * a consideration to the planner seems like a great deal of complication
757  * to support an uncommon usage of second-rate sampling methods. Instead,
758  * if there is a risk that the query might perform an unsafe join, just
759  * wrap the SampleScan in a Materialize node. We can check for joins by
760  * counting the membership of all_baserels (note that this correctly
761  * counts inheritance trees as single rels). If we're inside a subquery,
762  * we can't easily check whether a join might occur in the outer query, so
763  * just assume one is possible.
764  *
765  * GetTsmRoutine is relatively expensive compared to the other tests here,
766  * so check repeatable_across_scans last, even though that's a bit odd.
767  */
768  if ((root->query_level > 1 ||
771  {
772  path = (Path *) create_material_path(rel, path);
773  }
774 
775  add_path(rel, path);
776 
777  /* For the moment, at least, there are no other paths to consider */
778 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
MaterialPath * create_material_path(RelOptInfo *rel, Path *subpath)
Definition: pathnode.c:1385
Relids lateral_relids
Definition: relation.h:515
Relids all_baserels
Definition: relation.h:193
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:604
Path * create_samplescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:963
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
bool repeatable_across_scans
Definition: tsmapi.h:64
Index query_level
Definition: relation.h:156
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
Definition: relation.h:888
static void set_tablesample_rel_size ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 697 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().

698 {
699  TableSampleClause *tsc = rte->tablesample;
700  TsmRoutine *tsm;
701  BlockNumber pages;
702  double tuples;
703 
704  /*
705  * Test any partial indexes of rel for applicability. We must do this
706  * first since partial unique indexes can affect size estimates.
707  */
708  check_index_predicates(root, rel);
709 
710  /*
711  * Call the sampling method's estimation function to estimate the number
712  * of pages it will read and the number of tuples it will return. (Note:
713  * we assume the function returns sane values.)
714  */
715  tsm = GetTsmRoutine(tsc->tsmhandler);
716  tsm->SampleScanGetSampleSize(root, rel, tsc->args,
717  &pages, &tuples);
718 
719  /*
720  * For the moment, because we will only consider a SampleScan path for the
721  * rel, it's okay to just overwrite the pages and tuples estimates for the
722  * whole relation. If we ever consider multiple path types for sampled
723  * rels, we'll need more complication.
724  */
725  rel->pages = pages;
726  rel->tuples = tuples;
727 
728  /* Mark rel with estimated output rows, width, etc */
729  set_baserel_size_estimates(root, rel);
730 }
double tuples
Definition: relation.h:529
uint32 BlockNumber
Definition: block.h:31
void check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
Definition: indxpath.c:2761
SampleScanGetSampleSize_function SampleScanGetSampleSize
Definition: tsmapi.h:67
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:3771
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: relation.h:528
struct TableSampleClause * tablesample
Definition: parsenodes.h:895
static void set_values_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 1917 of file allpaths.c.

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

Referenced by set_rel_pathlist().

1918 {
1919  Relids required_outer;
1920 
1921  /*
1922  * We don't support pushing join clauses into the quals of a values scan,
1923  * but it could still have required parameterization due to LATERAL refs
1924  * in the values expressions.
1925  */
1926  required_outer = rel->lateral_relids;
1927 
1928  /* Generate appropriate path */
1929  add_path(rel, create_valuesscan_path(root, rel, required_outer));
1930 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
Path * create_valuesscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1759
Relids lateral_relids
Definition: relation.h:515
static void set_worktable_pathlist ( PlannerInfo root,
RelOptInfo rel,
RangeTblEntry rte 
)
static

Definition at line 2006 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().

2007 {
2008  Path *ctepath;
2009  PlannerInfo *cteroot;
2010  Index levelsup;
2011  Relids required_outer;
2012 
2013  /*
2014  * We need to find the non-recursive term's path, which is in the plan
2015  * level that's processing the recursive UNION, which is one level *below*
2016  * where the CTE comes from.
2017  */
2018  levelsup = rte->ctelevelsup;
2019  if (levelsup == 0) /* shouldn't happen */
2020  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2021  levelsup--;
2022  cteroot = root;
2023  while (levelsup-- > 0)
2024  {
2025  cteroot = cteroot->parent_root;
2026  if (!cteroot) /* shouldn't happen */
2027  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
2028  }
2029  ctepath = cteroot->non_recursive_path;
2030  if (!ctepath) /* shouldn't happen */
2031  elog(ERROR, "could not find path for CTE \"%s\"", rte->ctename);
2032 
2033  /* Mark rel with estimated output rows, width, etc */
2034  set_cte_size_estimates(root, rel, ctepath->rows);
2035 
2036  /*
2037  * We don't support pushing join clauses into the quals of a worktable
2038  * scan, but it could still have required parameterization due to LATERAL
2039  * refs in its tlist. (I'm not sure this is actually possible given the
2040  * restrictions on recursive references, but it's easy enough to support.)
2041  */
2042  required_outer = rel->lateral_relids;
2043 
2044  /* Generate appropriate path */
2045  add_path(rel, create_worktablescan_path(root, rel, required_outer));
2046 }
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
void set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
Definition: costsize.c:4474
Relids lateral_relids
Definition: relation.h:515
#define ERROR
Definition: elog.h:43
Path * create_worktablescan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: pathnode.c:1810
struct PlannerInfo * parent_root
Definition: relation.h:158
unsigned int Index
Definition: c.h:361
double rows
Definition: relation.h:905
struct Path * non_recursive_path
Definition: relation.h:304
Index ctelevelsup
Definition: parsenodes.h:943
char * ctename
Definition: parsenodes.h:942
#define elog
Definition: elog.h:219
Definition: relation.h:888
RelOptInfo* standard_join_search ( PlannerInfo root,
int  levels_needed,
List initial_rels 
)

Definition at line 2198 of file allpaths.c.

References Assert, elog, ERROR, generate_gather_paths(), PlannerInfo::join_rel_level, join_search_one_level(), lfirst, linitial, list_length(), NIL, NULL, palloc0(), and set_cheapest().

Referenced by make_rel_from_joinlist().

2199 {
2200  int lev;
2201  RelOptInfo *rel;
2202 
2203  /*
2204  * This function cannot be invoked recursively within any one planning
2205  * problem, so join_rel_level[] can't be in use already.
2206  */
2207  Assert(root->join_rel_level == NULL);
2208 
2209  /*
2210  * We employ a simple "dynamic programming" algorithm: we first find all
2211  * ways to build joins of two jointree items, then all ways to build joins
2212  * of three items (from two-item joins and single items), then four-item
2213  * joins, and so on until we have considered all ways to join all the
2214  * items into one rel.
2215  *
2216  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
2217  * set root->join_rel_level[1] to represent all the single-jointree-item
2218  * relations.
2219  */
2220  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
2221 
2222  root->join_rel_level[1] = initial_rels;
2223 
2224  for (lev = 2; lev <= levels_needed; lev++)
2225  {
2226  ListCell *lc;
2227 
2228  /*
2229  * Determine all possible pairs of relations to be joined at this
2230  * level, and build paths for making each one from every available
2231  * pair of lower-level relations.
2232  */
2233  join_search_one_level(root, lev);
2234 
2235  /*
2236  * Run generate_gather_paths() for each just-processed joinrel. We
2237  * could not do this earlier because both regular and partial paths
2238  * can get added to a particular joinrel at multiple times within
2239  * join_search_one_level. After that, we're done creating paths for
2240  * the joinrel, so run set_cheapest().
2241  */
2242  foreach(lc, root->join_rel_level[lev])
2243  {
2244  rel = (RelOptInfo *) lfirst(lc);
2245 
2246  /* Create GatherPaths for any useful partial paths for rel */
2247  generate_gather_paths(root, rel);
2248 
2249  /* Find and save the cheapest paths for this rel */
2250  set_cheapest(rel);
2251 
2252 #ifdef OPTIMIZER_DEBUG
2253  debug_print_rel(root, rel);
2254 #endif
2255  }
2256  }
2257 
2258  /*
2259  * We should have a single rel at the final level.
2260  */
2261  if (root->join_rel_level[levels_needed] == NIL)
2262  elog(ERROR, "failed to build any %d-way joins", levels_needed);
2263  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
2264 
2265  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
2266 
2267  root->join_rel_level = NULL;
2268 
2269  return rel;
2270 }
#define NIL
Definition: pg_list.h:69
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:2058
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:51
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
void * palloc0(Size size)
Definition: mcxt.c:920
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
List ** join_rel_level
Definition: relation.h:222
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
static bool subquery_is_pushdown_safe ( Query subquery,
Query topquery,
pushdown_safety_info safetyInfo 
)
static

Definition at line 2346 of file allpaths.c.

References Assert, check_output_expressions(), SetOperationStmt::colTypes, compare_tlist_datatypes(), Query::distinctClause, Query::hasTargetSRFs, Query::hasWindowFuncs, IsA, Query::limitCount, Query::limitOffset, NULL, recurse_pushdown_safe(), Query::setOperations, Query::targetList, and pushdown_safety_info::unsafeVolatile.

Referenced by recurse_pushdown_safe(), and set_subquery_pathlist().

2348 {
2349  SetOperationStmt *topop;
2350 
2351  /* Check point 1 */
2352  if (subquery->limitOffset != NULL || subquery->limitCount != NULL)
2353  return false;
2354 
2355  /* Check points 3, 4, and 5 */
2356  if (subquery->distinctClause ||
2357  subquery->hasWindowFuncs ||
2358  subquery->hasTargetSRFs)
2359  safetyInfo->unsafeVolatile = true;
2360 
2361  /*
2362  * If we're at a leaf query, check for unsafe expressions in its target
2363  * list, and mark any unsafe ones in unsafeColumns[]. (Non-leaf nodes in
2364  * setop trees have only simple Vars in their tlists, so no need to check
2365  * them.)
2366  */
2367  if (subquery->setOperations == NULL)
2368  check_output_expressions(subquery, safetyInfo);
2369 
2370  /* Are we at top level, or looking at a setop component? */
2371  if (subquery == topquery)
2372  {
2373  /* Top level, so check any component queries */
2374  if (subquery->setOperations != NULL)
2375  if (!recurse_pushdown_safe(subquery->setOperations, topquery,
2376  safetyInfo))
2377  return false;
2378  }
2379  else
2380  {
2381  /* Setop component must not have more components (too weird) */
2382  if (subquery->setOperations != NULL)
2383  return false;
2384  /* Check whether setop component output types match top level */
2385  topop = (SetOperationStmt *) topquery->setOperations;
2386  Assert(topop && IsA(topop, SetOperationStmt));
2388  topop->colTypes,
2389  safetyInfo);
2390  }
2391  return true;
2392 }
Node * limitOffset
Definition: parsenodes.h:149
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
static bool recurse_pushdown_safe(Node *setOp, Query *topquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2398
static void compare_tlist_datatypes(List *tlist, List *colTypes, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2533
List * targetList
Definition: parsenodes.h:131
List * distinctClause
Definition: parsenodes.h:145
Node * limitCount
Definition: parsenodes.h:150
static void check_output_expressions(Query *subquery, pushdown_safety_info *safetyInfo)
Definition: allpaths.c:2465
bool hasTargetSRFs
Definition: parsenodes.h:118
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
bool hasWindowFuncs
Definition: parsenodes.h:117
Node * setOperations
Definition: parsenodes.h:154
static void subquery_push_qual ( Query subquery,
RangeTblEntry rte,
Index  rti,
Node qual 
)
static

Definition at line 2683 of file allpaths.c.

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

Referenced by recurse_push_qual(), and set_subquery_pathlist().

2684 {
2685  if (subquery->setOperations != NULL)
2686  {
2687  /* Recurse to push it separately to each component query */
2688  recurse_push_qual(subquery->setOperations, subquery,
2689  rte, rti, qual);
2690  }
2691  else
2692  {
2693  /*
2694  * We need to replace Vars in the qual (which must refer to outputs of
2695  * the subquery) with copies of the subquery's targetlist expressions.
2696  * Note that at this point, any uplevel Vars in the qual should have
2697  * been replaced with Params, so they need no work.
2698  *
2699  * This step also ensures that when we are pushing into a setop tree,
2700  * each component query gets its own copy of the qual.
2701  */
2702  qual = ReplaceVarsFromTargetList(qual, rti, 0, rte,
2703  subquery->targetList,
2705  &subquery->hasSubLinks);
2706 
2707  /*
2708  * Now attach the qual to the proper place: normally WHERE, but if the
2709  * subquery uses grouping or aggregation, put it in HAVING (since the
2710  * qual really refers to the group-result rows).
2711  */
2712  if (subquery->hasAggs || subquery->groupClause || subquery->groupingSets || subquery->havingQual)
2713  subquery->havingQual = make_and_qual(subquery->havingQual, qual);
2714  else
2715  subquery->jointree->quals =
2716  make_and_qual(subquery->jointree->quals, qual);
2717 
2718  /*
2719  * We need not change the subquery's hasAggs or hasSubLinks flags,
2720  * since we can't be pushing down any aggregates that weren't there
2721  * before, and we don't push down subselects at all.
2722  */
2723  }
2724 }
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: clauses.c:347
FromExpr * jointree
Definition: parsenodes.h:129
bool hasAggs
Definition: parsenodes.h:116
List * groupingSets
Definition: parsenodes.h:139
Node * quals
Definition: primnodes.h:1434
List * targetList
Definition: parsenodes.h:131
Node * ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks)
#define NULL
Definition: c.h:226
static void recurse_push_qual(Node *setOp, Query *topquery, RangeTblEntry *rte, Index rti, Node *qual)
Definition: allpaths.c:2730
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
bool hasSubLinks
Definition: parsenodes.h:119
Node * havingQual
Definition: parsenodes.h:141
static bool targetIsInAllPartitionLists ( TargetEntry tle,
Query query 
)
static

Definition at line 2566 of file allpaths.c.

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

Referenced by check_output_expressions().

2567 {
2568  ListCell *lc;
2569 
2570  foreach(lc, query->windowClause)
2571  {
2572  WindowClause *wc = (WindowClause *) lfirst(lc);
2573 
2575  return false;
2576  }
2577  return true;
2578 }
List * windowClause
Definition: parsenodes.h:143
List * partitionClause
Definition: parsenodes.h:1195
#define InvalidOid
Definition: postgres_ext.h:36
bool targetIsInSortList(TargetEntry *tle, Oid sortop, List *sortList)
#define lfirst(lc)
Definition: pg_list.h:106

Variable Documentation

bool enable_geqo = false

Definition at line 58 of file allpaths.c.

Referenced by make_rel_from_joinlist().

int geqo_threshold

Definition at line 59 of file allpaths.c.

Referenced by make_rel_from_joinlist().

join_search_hook_type join_search_hook = NULL

Definition at line 67 of file allpaths.c.

Referenced by make_rel_from_joinlist().

int min_parallel_index_scan_size

Definition at line 61 of file allpaths.c.

Referenced by compute_parallel_worker().

int min_parallel_table_scan_size

Definition at line 60 of file allpaths.c.

Referenced by compute_parallel_worker().

set_rel_pathlist_hook_type set_rel_pathlist_hook = NULL

Definition at line 64 of file allpaths.c.

Referenced by set_rel_pathlist().