PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
prepunion.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "catalog/pg_inherits_fn.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/tlist.h"
#include "parser/parse_coerce.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/selfuncs.h"
Include dependency graph for prepunion.c:

Go to the source code of this file.

Data Structures

struct  adjust_appendrel_attrs_context
 

Functions

static Pathrecurse_set_operations (Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, double *pNumGroups)
 
static Pathgenerate_recursion_path (SetOperationStmt *setOp, PlannerInfo *root, List *refnames_tlist, List **pTargetList)
 
static Pathgenerate_union_path (SetOperationStmt *op, PlannerInfo *root, List *refnames_tlist, List **pTargetList, double *pNumGroups)
 
static Pathgenerate_nonunion_path (SetOperationStmt *op, PlannerInfo *root, List *refnames_tlist, List **pTargetList, double *pNumGroups)
 
static Listrecurse_union_children (Node *setOp, PlannerInfo *root, SetOperationStmt *top_union, List *refnames_tlist, List **tlist_list)
 
static Pathmake_union_unique (SetOperationStmt *op, Path *path, List *tlist, PlannerInfo *root)
 
static bool choose_hashed_setop (PlannerInfo *root, List *groupClauses, Path *input_path, double dNumGroups, double dNumOutputRows, const char *construct)
 
static Listgenerate_setop_tlist (List *colTypes, List *colCollations, int flag, Index varno, bool hack_constants, List *input_tlist, List *refnames_tlist)
 
static Listgenerate_append_tlist (List *colTypes, List *colCollations, bool flag, List *input_tlists, List *refnames_tlist)
 
static Listgenerate_setop_grouplist (SetOperationStmt *op, List *targetlist)
 
static void expand_inherited_rtentry (PlannerInfo *root, RangeTblEntry *rte, Index rti)
 
static void make_inh_translation_list (Relation oldrelation, Relation newrelation, Index newvarno, List **translated_vars)
 
static Bitmapsettranslate_col_privs (const Bitmapset *parent_privs, List *translated_vars)
 
static Nodeadjust_appendrel_attrs_mutator (Node *node, adjust_appendrel_attrs_context *context)
 
static Relids adjust_relid_set (Relids relids, Index oldrelid, Index newrelid)
 
static Listadjust_inherited_tlist (List *tlist, AppendRelInfo *context)
 
RelOptInfoplan_set_operations (PlannerInfo *root)
 
void expand_inherited_tables (PlannerInfo *root)
 
Nodeadjust_appendrel_attrs (PlannerInfo *root, Node *node, AppendRelInfo *appinfo)
 
Nodeadjust_appendrel_attrs_multilevel (PlannerInfo *root, Node *node, RelOptInfo *child_rel)
 

Function Documentation

Node* adjust_appendrel_attrs ( PlannerInfo root,
Node node,
AppendRelInfo appinfo 
)

Definition at line 1733 of file prepunion.c.

References adjust_appendrel_attrs_mutator(), adjust_inherited_tlist(), adjust_appendrel_attrs_context::appinfo, AppendRelInfo::child_relid, CMD_UPDATE, Query::commandType, IsA, AppendRelInfo::parent_relid, QTW_IGNORE_RC_SUBQUERIES, query_tree_mutator(), Query::resultRelation, adjust_appendrel_attrs_context::root, and Query::targetList.

Referenced by add_child_rel_equivalences(), adjust_appendrel_attrs_multilevel(), inheritance_planner(), and set_append_rel_size().

1734 {
1735  Node *result;
1737 
1738  context.root = root;
1739  context.appinfo = appinfo;
1740 
1741  /*
1742  * Must be prepared to start with a Query or a bare expression tree.
1743  */
1744  if (node && IsA(node, Query))
1745  {
1746  Query *newnode;
1747 
1748  newnode = query_tree_mutator((Query *) node,
1750  (void *) &context,
1752  if (newnode->resultRelation == appinfo->parent_relid)
1753  {
1754  newnode->resultRelation = appinfo->child_relid;
1755  /* Fix tlist resnos too, if it's inherited UPDATE */
1756  if (newnode->commandType == CMD_UPDATE)
1757  newnode->targetList =
1759  appinfo);
1760  }
1761  result = (Node *) newnode;
1762  }
1763  else
1764  result = adjust_appendrel_attrs_mutator(node, &context);
1765 
1766  return result;
1767 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int resultRelation
Definition: parsenodes.h:113
Definition: nodes.h:508
static List * adjust_inherited_tlist(List *tlist, AppendRelInfo *context)
Definition: prepunion.c:2012
List * targetList
Definition: parsenodes.h:131
#define QTW_IGNORE_RC_SUBQUERIES
Definition: nodeFuncs.h:22
CmdType commandType
Definition: parsenodes.h:103
static Node * adjust_appendrel_attrs_mutator(Node *node, adjust_appendrel_attrs_context *context)
Definition: prepunion.c:1770
Index child_relid
Definition: relation.h:1866
Index parent_relid
Definition: relation.h:1865
Query * query_tree_mutator(Query *query, Node *(*mutator)(), void *context, int flags)
Definition: nodeFuncs.c:3040
Node* adjust_appendrel_attrs_multilevel ( PlannerInfo root,
Node node,
RelOptInfo child_rel 
)

Definition at line 2100 of file prepunion.c.

References adjust_appendrel_attrs(), adjust_appendrel_attrs_multilevel(), Assert, find_base_rel(), find_childrel_appendrelinfo(), AppendRelInfo::parent_relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, and RelOptInfo::reloptkind.

Referenced by adjust_appendrel_attrs_multilevel(), and generate_join_implied_equalities_broken().

2102 {
2103  AppendRelInfo *appinfo = find_childrel_appendrelinfo(root, child_rel);
2104  RelOptInfo *parent_rel = find_base_rel(root, appinfo->parent_relid);
2105 
2106  /* If parent is also a child, first recurse to apply its translations */
2107  if (parent_rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
2108  node = adjust_appendrel_attrs_multilevel(root, node, parent_rel);
2109  else
2110  Assert(parent_rel->reloptkind == RELOPT_BASEREL);
2111  /* Now translate for this child */
2112  return adjust_appendrel_attrs(root, node, appinfo);
2113 }
RelOptKind reloptkind
Definition: relation.h:487
AppendRelInfo * find_childrel_appendrelinfo(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:921
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, AppendRelInfo *appinfo)
Definition: prepunion.c:1733
#define Assert(condition)
Definition: c.h:671
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *child_rel)
Definition: prepunion.c:2100
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
Index parent_relid
Definition: relation.h:1865
static Node * adjust_appendrel_attrs_mutator ( Node node,
adjust_appendrel_attrs_context context 
)
static

Definition at line 1770 of file prepunion.c.

References adjust_relid_set(), adjust_appendrel_attrs_context::appinfo, ConvertRowtypeExpr::arg, RowExpr::args, Assert, AppendRelInfo::child_relid, AppendRelInfo::child_reltype, RestrictInfo::clause, RestrictInfo::clause_relids, COERCE_IMPLICIT_CAST, Alias::colnames, RowExpr::colnames, ConvertRowtypeExpr::convertformat, copyObject(), CurrentOfExpr::cvarno, elog, RangeTblEntry::eref, ERROR, RestrictInfo::eval_cost, expression_tree_mutator(), get_rel_name(), IsA, RestrictInfo::left_bucketsize, RestrictInfo::left_em, RestrictInfo::left_relids, list_length(), list_nth(), ConvertRowtypeExpr::location, RowExpr::location, makeNode, NIL, RestrictInfo::norm_selec, NULL, RestrictInfo::nullable_relids, OidIsValid, RestrictInfo::orclause, RestrictInfo::outer_relids, RestrictInfo::outer_selec, AppendRelInfo::parent_relid, AppendRelInfo::parent_reloid, AppendRelInfo::parent_reltype, PlannerInfo::parse, PlaceHolderVar::phlevelsup, PlaceHolderVar::phrels, RestrictInfo::required_relids, ConvertRowtypeExpr::resulttype, RestrictInfo::right_bucketsize, RestrictInfo::right_em, RestrictInfo::right_relids, adjust_appendrel_attrs_context::root, RowExpr::row_format, RowExpr::row_typeid, rt_fetch, Query::rtable, RangeTblRef::rtindex, JoinExpr::rtindex, RestrictInfo::scansel_cache, QualCost::startup, AppendRelInfo::translated_vars, Var::varattno, Var::varlevelsup, Var::varno, Var::varnoold, and Var::vartype.

Referenced by adjust_appendrel_attrs().

1772 {
1773  AppendRelInfo *appinfo = context->appinfo;
1774 
1775  if (node == NULL)
1776  return NULL;
1777  if (IsA(node, Var))
1778  {
1779  Var *var = (Var *) copyObject(node);
1780 
1781  if (var->varlevelsup == 0 &&
1782  var->varno == appinfo->parent_relid)
1783  {
1784  var->varno = appinfo->child_relid;
1785  var->varnoold = appinfo->child_relid;
1786  if (var->varattno > 0)
1787  {
1788  Node *newnode;
1789 
1790  if (var->varattno > list_length(appinfo->translated_vars))
1791  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
1792  var->varattno, get_rel_name(appinfo->parent_reloid));
1793  newnode = copyObject(list_nth(appinfo->translated_vars,
1794  var->varattno - 1));
1795  if (newnode == NULL)
1796  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
1797  var->varattno, get_rel_name(appinfo->parent_reloid));
1798  return newnode;
1799  }
1800  else if (var->varattno == 0)
1801  {
1802  /*
1803  * Whole-row Var: if we are dealing with named rowtypes, we
1804  * can use a whole-row Var for the child table plus a coercion
1805  * step to convert the tuple layout to the parent's rowtype.
1806  * Otherwise we have to generate a RowExpr.
1807  */
1808  if (OidIsValid(appinfo->child_reltype))
1809  {
1810  Assert(var->vartype == appinfo->parent_reltype);
1811  if (appinfo->parent_reltype != appinfo->child_reltype)
1812  {
1814 
1815  r->arg = (Expr *) var;
1816  r->resulttype = appinfo->parent_reltype;
1818  r->location = -1;
1819  /* Make sure the Var node has the right type ID, too */
1820  var->vartype = appinfo->child_reltype;
1821  return (Node *) r;
1822  }
1823  }
1824  else
1825  {
1826  /*
1827  * Build a RowExpr containing the translated variables.
1828  *
1829  * In practice var->vartype will always be RECORDOID here,
1830  * so we need to come up with some suitable column names.
1831  * We use the parent RTE's column names.
1832  *
1833  * Note: we can't get here for inheritance cases, so there
1834  * is no need to worry that translated_vars might contain
1835  * some dummy NULLs.
1836  */
1837  RowExpr *rowexpr;
1838  List *fields;
1839  RangeTblEntry *rte;
1840 
1841  rte = rt_fetch(appinfo->parent_relid,
1842  context->root->parse->rtable);
1843  fields = (List *) copyObject(appinfo->translated_vars);
1844  rowexpr = makeNode(RowExpr);
1845  rowexpr->args = fields;
1846  rowexpr->row_typeid = var->vartype;
1847  rowexpr->row_format = COERCE_IMPLICIT_CAST;
1848  rowexpr->colnames = copyObject(rte->eref->colnames);
1849  rowexpr->location = -1;
1850 
1851  return (Node *) rowexpr;
1852  }
1853  }
1854  /* system attributes don't need any other translation */
1855  }
1856  return (Node *) var;
1857  }
1858  if (IsA(node, CurrentOfExpr))
1859  {
1860  CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1861 
1862  if (cexpr->cvarno == appinfo->parent_relid)
1863  cexpr->cvarno = appinfo->child_relid;
1864  return (Node *) cexpr;
1865  }
1866  if (IsA(node, RangeTblRef))
1867  {
1868  RangeTblRef *rtr = (RangeTblRef *) copyObject(node);
1869 
1870  if (rtr->rtindex == appinfo->parent_relid)
1871  rtr->rtindex = appinfo->child_relid;
1872  return (Node *) rtr;
1873  }
1874  if (IsA(node, JoinExpr))
1875  {
1876  /* Copy the JoinExpr node with correct mutation of subnodes */
1877  JoinExpr *j;
1878 
1879  j = (JoinExpr *) expression_tree_mutator(node,
1881  (void *) context);
1882  /* now fix JoinExpr's rtindex (probably never happens) */
1883  if (j->rtindex == appinfo->parent_relid)
1884  j->rtindex = appinfo->child_relid;
1885  return (Node *) j;
1886  }
1887  if (IsA(node, PlaceHolderVar))
1888  {
1889  /* Copy the PlaceHolderVar node with correct mutation of subnodes */
1890  PlaceHolderVar *phv;
1891 
1892  phv = (PlaceHolderVar *) expression_tree_mutator(node,
1894  (void *) context);
1895  /* now fix PlaceHolderVar's relid sets */
1896  if (phv->phlevelsup == 0)
1897  phv->phrels = adjust_relid_set(phv->phrels,
1898  appinfo->parent_relid,
1899  appinfo->child_relid);
1900  return (Node *) phv;
1901  }
1902  /* Shouldn't need to handle planner auxiliary nodes here */
1903  Assert(!IsA(node, SpecialJoinInfo));
1904  Assert(!IsA(node, AppendRelInfo));
1905  Assert(!IsA(node, PlaceHolderInfo));
1906  Assert(!IsA(node, MinMaxAggInfo));
1907 
1908  /*
1909  * We have to process RestrictInfo nodes specially. (Note: although
1910  * set_append_rel_pathlist will hide RestrictInfos in the parent's
1911  * baserestrictinfo list from us, it doesn't hide those in joininfo.)
1912  */
1913  if (IsA(node, RestrictInfo))
1914  {
1915  RestrictInfo *oldinfo = (RestrictInfo *) node;
1916  RestrictInfo *newinfo = makeNode(RestrictInfo);
1917 
1918  /* Copy all flat-copiable fields */
1919  memcpy(newinfo, oldinfo, sizeof(RestrictInfo));
1920 
1921  /* Recursively fix the clause itself */
1922  newinfo->clause = (Expr *)
1923  adjust_appendrel_attrs_mutator((Node *) oldinfo->clause, context);
1924 
1925  /* and the modified version, if an OR clause */
1926  newinfo->orclause = (Expr *)
1927  adjust_appendrel_attrs_mutator((Node *) oldinfo->orclause, context);
1928 
1929  /* adjust relid sets too */
1930  newinfo->clause_relids = adjust_relid_set(oldinfo->clause_relids,
1931  appinfo->parent_relid,
1932  appinfo->child_relid);
1933  newinfo->required_relids = adjust_relid_set(oldinfo->required_relids,
1934  appinfo->parent_relid,
1935  appinfo->child_relid);
1936  newinfo->outer_relids = adjust_relid_set(oldinfo->outer_relids,
1937  appinfo->parent_relid,
1938  appinfo->child_relid);
1939  newinfo->nullable_relids = adjust_relid_set(oldinfo->nullable_relids,
1940  appinfo->parent_relid,
1941  appinfo->child_relid);
1942  newinfo->left_relids = adjust_relid_set(oldinfo->left_relids,
1943  appinfo->parent_relid,
1944  appinfo->child_relid);
1945  newinfo->right_relids = adjust_relid_set(oldinfo->right_relids,
1946  appinfo->parent_relid,
1947  appinfo->child_relid);
1948 
1949  /*
1950  * Reset cached derivative fields, since these might need to have
1951  * different values when considering the child relation. Note we
1952  * don't reset left_ec/right_ec: each child variable is implicitly
1953  * equivalent to its parent, so still a member of the same EC if any.
1954  */
1955  newinfo->eval_cost.startup = -1;
1956  newinfo->norm_selec = -1;
1957  newinfo->outer_selec = -1;
1958  newinfo->left_em = NULL;
1959  newinfo->right_em = NULL;
1960  newinfo->scansel_cache = NIL;
1961  newinfo->left_bucketsize = -1;
1962  newinfo->right_bucketsize = -1;
1963 
1964  return (Node *) newinfo;
1965  }
1966 
1967  /*
1968  * NOTE: we do not need to recurse into sublinks, because they should
1969  * already have been converted to subplans before we see them.
1970  */
1971  Assert(!IsA(node, SubLink));
1972  Assert(!IsA(node, Query));
1973 
1975  (void *) context);
1976 }
QualCost eval_cost
Definition: relation.h:1674
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:962
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Query * parse
Definition: relation.h:152
Index varlevelsup
Definition: primnodes.h:151
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2397
Relids required_relids
Definition: relation.h:1655
List * colnames
Definition: primnodes.h:42
Expr * orclause
Definition: relation.h:1668
Relids clause_relids
Definition: relation.h:1652
Definition: nodes.h:508
Relids left_relids
Definition: relation.h:1664
AttrNumber varattno
Definition: primnodes.h:146
static Relids adjust_relid_set(Relids relids, Index oldrelid, Index newrelid)
Definition: prepunion.c:1982
Definition: primnodes.h:141
#define OidIsValid(objectId)
Definition: c.h:534
List * translated_vars
Definition: relation.h:1893
Oid parent_reltype
Definition: relation.h:1874
Cost startup
Definition: relation.h:45
Relids outer_relids
Definition: relation.h:1658
Selectivity norm_selec
Definition: relation.h:1675
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
Index varnoold
Definition: primnodes.h:154
List * rtable
Definition: parsenodes.h:128
Relids phrels
Definition: relation.h:1741
#define ERROR
Definition: elog.h:43
List * colnames
Definition: primnodes.h:975
Oid vartype
Definition: primnodes.h:148
EquivalenceMember * left_em
Definition: relation.h:1687
int location
Definition: primnodes.h:976
void * list_nth(const List *list, int n)
Definition: list.c:410
Selectivity outer_selec
Definition: relation.h:1678
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
EquivalenceMember * right_em
Definition: relation.h:1688
Expr * clause
Definition: relation.h:1637
Index varno
Definition: primnodes.h:144
Relids nullable_relids
Definition: relation.h:1661
CoercionForm convertformat
Definition: primnodes.h:838
Selectivity left_bucketsize
Definition: relation.h:1698
#define makeNode(_type_)
Definition: nodes.h:556
Relids right_relids
Definition: relation.h:1665
static Node * adjust_appendrel_attrs_mutator(Node *node, adjust_appendrel_attrs_context *context)
Definition: prepunion.c:1770
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
Oid row_typeid
Definition: primnodes.h:963
static int list_length(const List *l)
Definition: pg_list.h:89
Oid child_reltype
Definition: relation.h:1875
Index phlevelsup
Definition: relation.h:1743
Selectivity right_bucketsize
Definition: relation.h:1699
#define elog
Definition: elog.h:219
Index child_relid
Definition: relation.h:1866
Alias * eref
Definition: parsenodes.h:961
Oid parent_reloid
Definition: relation.h:1900
Index parent_relid
Definition: relation.h:1865
CoercionForm row_format
Definition: primnodes.h:974
int rtindex
Definition: primnodes.h:1418
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
List * scansel_cache
Definition: relation.h:1689
static List * adjust_inherited_tlist ( List tlist,
AppendRelInfo context 
)
static

Definition at line 2012 of file prepunion.c.

References Assert, elog, ERROR, get_rel_name(), IsA, lappend(), lfirst, list_length(), list_nth(), NIL, NULL, OidIsValid, AppendRelInfo::parent_reloid, TargetEntry::resjunk, TargetEntry::resno, AppendRelInfo::translated_vars, and Var::varattno.

Referenced by adjust_appendrel_attrs().

2013 {
2014  bool changed_it = false;
2015  ListCell *tl;
2016  List *new_tlist;
2017  bool more;
2018  int attrno;
2019 
2020  /* This should only happen for an inheritance case, not UNION ALL */
2021  Assert(OidIsValid(context->parent_reloid));
2022 
2023  /* Scan tlist and update resnos to match attnums of child rel */
2024  foreach(tl, tlist)
2025  {
2026  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2027  Var *childvar;
2028 
2029  if (tle->resjunk)
2030  continue; /* ignore junk items */
2031 
2032  /* Look up the translation of this column: it must be a Var */
2033  if (tle->resno <= 0 ||
2034  tle->resno > list_length(context->translated_vars))
2035  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
2036  tle->resno, get_rel_name(context->parent_reloid));
2037  childvar = (Var *) list_nth(context->translated_vars, tle->resno - 1);
2038  if (childvar == NULL || !IsA(childvar, Var))
2039  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
2040  tle->resno, get_rel_name(context->parent_reloid));
2041 
2042  if (tle->resno != childvar->varattno)
2043  {
2044  tle->resno = childvar->varattno;
2045  changed_it = true;
2046  }
2047  }
2048 
2049  /*
2050  * If we changed anything, re-sort the tlist by resno, and make sure
2051  * resjunk entries have resnos above the last real resno. The sort
2052  * algorithm is a bit stupid, but for such a seldom-taken path, small is
2053  * probably better than fast.
2054  */
2055  if (!changed_it)
2056  return tlist;
2057 
2058  new_tlist = NIL;
2059  more = true;
2060  for (attrno = 1; more; attrno++)
2061  {
2062  more = false;
2063  foreach(tl, tlist)
2064  {
2065  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2066 
2067  if (tle->resjunk)
2068  continue; /* ignore junk items */
2069 
2070  if (tle->resno == attrno)
2071  new_tlist = lappend(new_tlist, tle);
2072  else if (tle->resno > attrno)
2073  more = true;
2074  }
2075  }
2076 
2077  foreach(tl, tlist)
2078  {
2079  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2080 
2081  if (!tle->resjunk)
2082  continue; /* here, ignore non-junk items */
2083 
2084  tle->resno = attrno;
2085  new_tlist = lappend(new_tlist, tle);
2086  attrno++;
2087  }
2088 
2089  return new_tlist;
2090 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
AttrNumber varattno
Definition: primnodes.h:146
Definition: primnodes.h:141
#define OidIsValid(objectId)
Definition: c.h:534
List * translated_vars
Definition: relation.h:1893
bool resjunk
Definition: primnodes.h:1337
#define ERROR
Definition: elog.h:43
void * list_nth(const List *list, int n)
Definition: list.c:410
AttrNumber resno
Definition: primnodes.h:1331
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define elog
Definition: elog.h:219
Oid parent_reloid
Definition: relation.h:1900
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
static Relids adjust_relid_set ( Relids  relids,
Index  oldrelid,
Index  newrelid 
)
static

Definition at line 1982 of file prepunion.c.

References bms_add_member(), bms_copy(), bms_del_member(), and bms_is_member().

Referenced by adjust_appendrel_attrs_mutator().

1983 {
1984  if (bms_is_member(oldrelid, relids))
1985  {
1986  /* Ensure we have a modifiable copy */
1987  relids = bms_copy(relids);
1988  /* Remove old, add new */
1989  relids = bms_del_member(relids, oldrelid);
1990  relids = bms_add_member(relids, newrelid);
1991  }
1992  return relids;
1993 }
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:110
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:705
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
static bool choose_hashed_setop ( PlannerInfo root,
List groupClauses,
Path input_path,
double  dNumGroups,
double  dNumOutputRows,
const char *  construct 
)
static

Definition at line 899 of file prepunion.c.

References AGG_HASHED, compare_fractional_path_costs(), cost_agg(), cost_group(), cost_sort(), enable_hashagg, ereport, errcode(), errdetail(), errmsg(), ERROR, grouping_is_hashable(), grouping_is_sortable(), list_length(), MAXALIGN, NIL, NULL, Path::pathtarget, Path::rows, SizeofMinimalTupleHeader, Path::startup_cost, Path::total_cost, PlannerInfo::tuple_fraction, PathTarget::width, and work_mem.

Referenced by generate_nonunion_path(), and make_union_unique().

903 {
904  int numGroupCols = list_length(groupClauses);
905  bool can_sort;
906  bool can_hash;
907  Size hashentrysize;
908  Path hashed_p;
909  Path sorted_p;
910  double tuple_fraction;
911 
912  /* Check whether the operators support sorting or hashing */
913  can_sort = grouping_is_sortable(groupClauses);
914  can_hash = grouping_is_hashable(groupClauses);
915  if (can_hash && can_sort)
916  {
917  /* we have a meaningful choice to make, continue ... */
918  }
919  else if (can_hash)
920  return true;
921  else if (can_sort)
922  return false;
923  else
924  ereport(ERROR,
925  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
926  /* translator: %s is UNION, INTERSECT, or EXCEPT */
927  errmsg("could not implement %s", construct),
928  errdetail("Some of the datatypes only support hashing, while others only support sorting.")));
929 
930  /* Prefer sorting when enable_hashagg is off */
931  if (!enable_hashagg)
932  return false;
933 
934  /*
935  * Don't do it if it doesn't look like the hashtable will fit into
936  * work_mem.
937  */
938  hashentrysize = MAXALIGN(input_path->pathtarget->width) + MAXALIGN(SizeofMinimalTupleHeader);
939 
940  if (hashentrysize * dNumGroups > work_mem * 1024L)
941  return false;
942 
943  /*
944  * See if the estimated cost is no more than doing it the other way.
945  *
946  * We need to consider input_plan + hashagg versus input_plan + sort +
947  * group. Note that the actual result plan might involve a SetOp or
948  * Unique node, not Agg or Group, but the cost estimates for Agg and Group
949  * should be close enough for our purposes here.
950  *
951  * These path variables are dummies that just hold cost fields; we don't
952  * make actual Paths for these steps.
953  */
954  cost_agg(&hashed_p, root, AGG_HASHED, NULL,
955  numGroupCols, dNumGroups,
956  input_path->startup_cost, input_path->total_cost,
957  input_path->rows);
958 
959  /*
960  * Now for the sorted case. Note that the input is *always* unsorted,
961  * since it was made by appending unrelated sub-relations together.
962  */
963  sorted_p.startup_cost = input_path->startup_cost;
964  sorted_p.total_cost = input_path->total_cost;
965  /* XXX cost_sort doesn't actually look at pathkeys, so just pass NIL */
966  cost_sort(&sorted_p, root, NIL, sorted_p.total_cost,
967  input_path->rows, input_path->pathtarget->width,
968  0.0, work_mem, -1.0);
969  cost_group(&sorted_p, root, numGroupCols, dNumGroups,
970  sorted_p.startup_cost, sorted_p.total_cost,
971  input_path->rows);
972 
973  /*
974  * Now make the decision using the top-level tuple fraction. First we
975  * have to convert an absolute count (LIMIT) into fractional form.
976  */
977  tuple_fraction = root->tuple_fraction;
978  if (tuple_fraction >= 1.0)
979  tuple_fraction /= dNumOutputRows;
980 
981  if (compare_fractional_path_costs(&hashed_p, &sorted_p,
982  tuple_fraction) < 0)
983  {
984  /* Hashed is cheaper, so use it */
985  return true;
986  }
987  return false;
988 }
void cost_group(Path *path, PlannerInfo *root, int numGroupCols, double numGroups, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
Definition: costsize.c:1853
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:895
int errcode(int sqlerrcode)
Definition: elog.c:575
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
double tuple_fraction
Definition: relation.h:286
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: relation.h:906
int errdetail(const char *fmt,...)
Definition: elog.c:873
void cost_agg(Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
Definition: costsize.c:1691
#define ereport(elevel, rest)
Definition: elog.h:122
#define SizeofMinimalTupleHeader
Definition: htup_details.h:650
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1462
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:907
#define NULL
Definition: c.h:226
double rows
Definition: relation.h:905
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
size_t Size
Definition: c.h:353
static int list_length(const List *l)
Definition: pg_list.h:89
#define MAXALIGN(LEN)
Definition: c.h:584
bool enable_hashagg
Definition: costsize.c:124
int width
Definition: relation.h:827
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
Definition: relation.h:888
static void expand_inherited_rtentry ( PlannerInfo root,
RangeTblEntry rte,
Index  rti 
)
static

Definition at line 1357 of file prepunion.c.

References AccessShareLock, PlanRowMark::allMarkTypes, PlannerInfo::append_rel_list, Assert, AppendRelInfo::child_relid, AppendRelInfo::child_reltype, copyObject(), find_all_inheritors(), get_plan_rowmark(), has_subclass(), heap_close, heap_open(), RangeTblEntry::inh, RangeTblEntry::insertedCols, PlanRowMark::isParent, lappend(), lfirst_oid, list_concat(), list_length(), make_inh_translation_list(), makeNode, PlanRowMark::markType, NIL, NoLock, NULL, AppendRelInfo::parent_relid, AppendRelInfo::parent_reloid, AppendRelInfo::parent_reltype, parse(), PlannerInfo::parse, PlanRowMark::prti, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::requiredPerms, Query::resultRelation, RowExclusiveLock, PlanRowMark::rowmarkId, RowMarkRequiresRowShareLock, PlannerInfo::rowMarks, RowShareLock, Query::rtable, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, PlanRowMark::rti, RangeTblEntry::securityQuals, select_rowmark_type(), RangeTblEntry::selectedCols, PlanRowMark::strength, translate_col_privs(), AppendRelInfo::translated_vars, RangeTblEntry::updatedCols, and PlanRowMark::waitPolicy.

Referenced by expand_inherited_tables().

1358 {
1359  Query *parse = root->parse;
1360  Oid parentOID;
1361  PlanRowMark *oldrc;
1362  Relation oldrelation;
1363  LOCKMODE lockmode;
1364  List *inhOIDs;
1365  List *appinfos;
1366  ListCell *l;
1367 
1368  /* Does RT entry allow inheritance? */
1369  if (!rte->inh)
1370  return;
1371  /* Ignore any already-expanded UNION ALL nodes */
1372  if (rte->rtekind != RTE_RELATION)
1373  {
1374  Assert(rte->rtekind == RTE_SUBQUERY);
1375  return;
1376  }
1377  /* Fast path for common case of childless table */
1378  parentOID = rte->relid;
1379  if (!has_subclass(parentOID))
1380  {
1381  /* Clear flag before returning */
1382  rte->inh = false;
1383  return;
1384  }
1385 
1386  /*
1387  * The rewriter should already have obtained an appropriate lock on each
1388  * relation named in the query. However, for each child relation we add
1389  * to the query, we must obtain an appropriate lock, because this will be
1390  * the first use of those relations in the parse/rewrite/plan pipeline.
1391  *
1392  * If the parent relation is the query's result relation, then we need
1393  * RowExclusiveLock. Otherwise, if it's accessed FOR UPDATE/SHARE, we
1394  * need RowShareLock; otherwise AccessShareLock. We can't just grab
1395  * AccessShareLock because then the executor would be trying to upgrade
1396  * the lock, leading to possible deadlocks. (This code should match the
1397  * parser and rewriter.)
1398  */
1399  oldrc = get_plan_rowmark(root->rowMarks, rti);
1400  if (rti == parse->resultRelation)
1401  lockmode = RowExclusiveLock;
1402  else if (oldrc && RowMarkRequiresRowShareLock(oldrc->markType))
1403  lockmode = RowShareLock;
1404  else
1405  lockmode = AccessShareLock;
1406 
1407  /* Scan for all members of inheritance set, acquire needed locks */
1408  inhOIDs = find_all_inheritors(parentOID, lockmode, NULL);
1409 
1410  /*
1411  * Check that there's at least one descendant, else treat as no-child
1412  * case. This could happen despite above has_subclass() check, if table
1413  * once had a child but no longer does.
1414  */
1415  if (list_length(inhOIDs) < 2)
1416  {
1417  /* Clear flag before returning */
1418  rte->inh = false;
1419  return;
1420  }
1421 
1422  /*
1423  * If parent relation is selected FOR UPDATE/SHARE, we need to mark its
1424  * PlanRowMark as isParent = true, and generate a new PlanRowMark for each
1425  * child.
1426  */
1427  if (oldrc)
1428  oldrc->isParent = true;
1429 
1430  /*
1431  * Must open the parent relation to examine its tupdesc. We need not lock
1432  * it; we assume the rewriter already did.
1433  */
1434  oldrelation = heap_open(parentOID, NoLock);
1435 
1436  /* Scan the inheritance set and expand it */
1437  appinfos = NIL;
1438  foreach(l, inhOIDs)
1439  {
1440  Oid childOID = lfirst_oid(l);
1441  Relation newrelation;
1442  RangeTblEntry *childrte;
1443  Index childRTindex;
1444  AppendRelInfo *appinfo;
1445 
1446  /* Open rel if needed; we already have required locks */
1447  if (childOID != parentOID)
1448  newrelation = heap_open(childOID, NoLock);
1449  else
1450  newrelation = oldrelation;
1451 
1452  /*
1453  * It is possible that the parent table has children that are temp
1454  * tables of other backends. We cannot safely access such tables
1455  * (because of buffering issues), and the best thing to do seems to be
1456  * to silently ignore them.
1457  */
1458  if (childOID != parentOID && RELATION_IS_OTHER_TEMP(newrelation))
1459  {
1460  heap_close(newrelation, lockmode);
1461  continue;
1462  }
1463 
1464  /*
1465  * Build an RTE for the child, and attach to query's rangetable list.
1466  * We copy most fields of the parent's RTE, but replace relation OID
1467  * and relkind, and set inh = false. Also, set requiredPerms to zero
1468  * since all required permissions checks are done on the original RTE.
1469  * Likewise, set the child's securityQuals to empty, because we only
1470  * want to apply the parent's RLS conditions regardless of what RLS
1471  * properties individual children may have. (This is an intentional
1472  * choice to make inherited RLS work like regular permissions checks.)
1473  * The parent securityQuals will be propagated to children along with
1474  * other base restriction clauses, so we don't need to do it here.
1475  */
1476  childrte = copyObject(rte);
1477  childrte->relid = childOID;
1478  childrte->relkind = newrelation->rd_rel->relkind;
1479  childrte->inh = false;
1480  childrte->requiredPerms = 0;
1481  childrte->securityQuals = NIL;
1482  parse->rtable = lappend(parse->rtable, childrte);
1483  childRTindex = list_length(parse->rtable);
1484 
1485  /*
1486  * Build an AppendRelInfo for this parent and child.
1487  */
1488  appinfo = makeNode(AppendRelInfo);
1489  appinfo->parent_relid = rti;
1490  appinfo->child_relid = childRTindex;
1491  appinfo->parent_reltype = oldrelation->rd_rel->reltype;
1492  appinfo->child_reltype = newrelation->rd_rel->reltype;
1493  make_inh_translation_list(oldrelation, newrelation, childRTindex,
1494  &appinfo->translated_vars);
1495  appinfo->parent_reloid = parentOID;
1496  appinfos = lappend(appinfos, appinfo);
1497 
1498  /*
1499  * Translate the column permissions bitmaps to the child's attnums (we
1500  * have to build the translated_vars list before we can do this). But
1501  * if this is the parent table, leave copyObject's result alone.
1502  *
1503  * Note: we need to do this even though the executor won't run any
1504  * permissions checks on the child RTE. The insertedCols/updatedCols
1505  * bitmaps may be examined for trigger-firing purposes.
1506  */
1507  if (childOID != parentOID)
1508  {
1510  appinfo->translated_vars);
1512  appinfo->translated_vars);
1513  childrte->updatedCols = translate_col_privs(rte->updatedCols,
1514  appinfo->translated_vars);
1515  }
1516 
1517  /*
1518  * Build a PlanRowMark if parent is marked FOR UPDATE/SHARE.
1519  */
1520  if (oldrc)
1521  {
1522  PlanRowMark *newrc = makeNode(PlanRowMark);
1523 
1524  newrc->rti = childRTindex;
1525  newrc->prti = rti;
1526  newrc->rowmarkId = oldrc->rowmarkId;
1527  /* Reselect rowmark type, because relkind might not match parent */
1528  newrc->markType = select_rowmark_type(childrte, oldrc->strength);
1529  newrc->allMarkTypes = (1 << newrc->markType);
1530  newrc->strength = oldrc->strength;
1531  newrc->waitPolicy = oldrc->waitPolicy;
1532  newrc->isParent = false;
1533 
1534  /* Include child's rowmark type in parent's allMarkTypes */
1535  oldrc->allMarkTypes |= newrc->allMarkTypes;
1536 
1537  root->rowMarks = lappend(root->rowMarks, newrc);
1538  }
1539 
1540  /* Close child relations, but keep locks */
1541  if (childOID != parentOID)
1542  heap_close(newrelation, NoLock);
1543  }
1544 
1545  heap_close(oldrelation, NoLock);
1546 
1547  /*
1548  * If all the children were temp tables, pretend it's a non-inheritance
1549  * situation. The duplicate RTE we added for the parent table is
1550  * harmless, so we don't bother to get rid of it; ditto for the useless
1551  * PlanRowMark node.
1552  */
1553  if (list_length(appinfos) < 2)
1554  {
1555  /* Clear flag before returning */
1556  rte->inh = false;
1557  return;
1558  }
1559 
1560  /* Otherwise, OK to add to root->append_rel_list */
1561  root->append_rel_list = list_concat(root->append_rel_list, appinfos);
1562 }
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:251
Query * parse
Definition: relation.h:152
RowMarkType markType
Definition: plannodes.h:943
int LOCKMODE
Definition: lockdefs.h:26
RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
Definition: planner.c:2216
List * securityQuals
Definition: parsenodes.h:970
int resultRelation
Definition: parsenodes.h:113
#define AccessShareLock
Definition: lockdefs.h:36
Index prti
Definition: plannodes.h:941
List * list_concat(List *list1, List *list2)
Definition: list.c:321
static Bitmapset * translate_col_privs(const Bitmapset *parent_privs, List *translated_vars)
Definition: prepunion.c:1679
AclMode requiredPerms
Definition: parsenodes.h:965
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:942
LockWaitPolicy waitPolicy
Definition: plannodes.h:946
List * translated_vars
Definition: relation.h:1893
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:897
Oid parent_reltype
Definition: relation.h:1874
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
Bitmapset * selectedCols
Definition: parsenodes.h:967
bool has_subclass(Oid relationId)
Definition: pg_inherits.c:243
List * rtable
Definition: parsenodes.h:128
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int allMarkTypes
Definition: plannodes.h:944
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RowShareLock
Definition: lockdefs.h:37
List * append_rel_list
Definition: relation.h:249
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:362
Bitmapset * updatedCols
Definition: parsenodes.h:969
Index rti
Definition: plannodes.h:940
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:530
LockClauseStrength strength
Definition: plannodes.h:945
static int list_length(const List *l)
Definition: pg_list.h:89
Oid child_reltype
Definition: relation.h:1875
static void make_inh_translation_list(Relation oldrelation, Relation newrelation, Index newvarno, List **translated_vars)
Definition: prepunion.c:1572
RTEKind rtekind
Definition: parsenodes.h:882
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:159
Bitmapset * insertedCols
Definition: parsenodes.h:968
PlanRowMark * get_plan_rowmark(List *rowmarks, Index rtindex)
Definition: preptlist.c:401
bool isParent
Definition: plannodes.h:947
Index child_relid
Definition: relation.h:1866
Oid parent_reloid
Definition: relation.h:1900
Index parent_relid
Definition: relation.h:1865
Definition: pg_list.h:45
#define lfirst_oid(lc)
Definition: pg_list.h:108
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
void expand_inherited_tables ( PlannerInfo root)

Definition at line 1318 of file prepunion.c.

References expand_inherited_rtentry(), lfirst, list_head(), list_length(), lnext, PlannerInfo::parse, and Query::rtable.

Referenced by subquery_planner().

1319 {
1320  Index nrtes;
1321  Index rti;
1322  ListCell *rl;
1323 
1324  /*
1325  * expand_inherited_rtentry may add RTEs to parse->rtable; there is no
1326  * need to scan them since they can't have inh=true. So just scan as far
1327  * as the original end of the rtable list.
1328  */
1329  nrtes = list_length(root->parse->rtable);
1330  rl = list_head(root->parse->rtable);
1331  for (rti = 1; rti <= nrtes; rti++)
1332  {
1333  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rl);
1334 
1335  expand_inherited_rtentry(root, rte, rti);
1336  rl = lnext(rl);
1337  }
1338 }
Query * parse
Definition: relation.h:152
List * rtable
Definition: parsenodes.h:128
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
static void expand_inherited_rtentry(PlannerInfo *root, RangeTblEntry *rte, Index rti)
Definition: prepunion.c:1357
unsigned int Index
Definition: c.h:362
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
static List * generate_append_tlist ( List colTypes,
List colCollations,
bool  flag,
List input_tlists,
List refnames_tlist 
)
static

Definition at line 1147 of file prepunion.c.

References Assert, TargetEntry::expr, exprType(), exprTypmod(), forthree, INT4OID, InvalidOid, lappend(), lfirst, lfirst_oid, list_head(), list_length(), lnext, makeTargetEntry(), makeVar(), NIL, NULL, palloc(), pfree(), pstrdup(), TargetEntry::resjunk, TargetEntry::resname, TargetEntry::resno, and TargetEntry::ressortgroupref.

Referenced by generate_nonunion_path(), generate_recursion_path(), and generate_union_path().

1151 {
1152  List *tlist = NIL;
1153  int resno = 1;
1154  ListCell *curColType;
1155  ListCell *curColCollation;
1156  ListCell *ref_tl_item;
1157  int colindex;
1158  TargetEntry *tle;
1159  Node *expr;
1160  ListCell *tlistl;
1161  int32 *colTypmods;
1162 
1163  /*
1164  * First extract typmods to use.
1165  *
1166  * If the inputs all agree on type and typmod of a particular column, use
1167  * that typmod; else use -1.
1168  */
1169  colTypmods = (int32 *) palloc(list_length(colTypes) * sizeof(int32));
1170 
1171  foreach(tlistl, input_tlists)
1172  {
1173  List *subtlist = (List *) lfirst(tlistl);
1174  ListCell *subtlistl;
1175 
1176  curColType = list_head(colTypes);
1177  colindex = 0;
1178  foreach(subtlistl, subtlist)
1179  {
1180  TargetEntry *subtle = (TargetEntry *) lfirst(subtlistl);
1181 
1182  if (subtle->resjunk)
1183  continue;
1184  Assert(curColType != NULL);
1185  if (exprType((Node *) subtle->expr) == lfirst_oid(curColType))
1186  {
1187  /* If first subplan, copy the typmod; else compare */
1188  int32 subtypmod = exprTypmod((Node *) subtle->expr);
1189 
1190  if (tlistl == list_head(input_tlists))
1191  colTypmods[colindex] = subtypmod;
1192  else if (subtypmod != colTypmods[colindex])
1193  colTypmods[colindex] = -1;
1194  }
1195  else
1196  {
1197  /* types disagree, so force typmod to -1 */
1198  colTypmods[colindex] = -1;
1199  }
1200  curColType = lnext(curColType);
1201  colindex++;
1202  }
1203  Assert(curColType == NULL);
1204  }
1205 
1206  /*
1207  * Now we can build the tlist for the Append.
1208  */
1209  colindex = 0;
1210  forthree(curColType, colTypes, curColCollation, colCollations,
1211  ref_tl_item, refnames_tlist)
1212  {
1213  Oid colType = lfirst_oid(curColType);
1214  int32 colTypmod = colTypmods[colindex++];
1215  Oid colColl = lfirst_oid(curColCollation);
1216  TargetEntry *reftle = (TargetEntry *) lfirst(ref_tl_item);
1217 
1218  Assert(reftle->resno == resno);
1219  Assert(!reftle->resjunk);
1220  expr = (Node *) makeVar(0,
1221  resno,
1222  colType,
1223  colTypmod,
1224  colColl,
1225  0);
1226  tle = makeTargetEntry((Expr *) expr,
1227  (AttrNumber) resno++,
1228  pstrdup(reftle->resname),
1229  false);
1230 
1231  /*
1232  * By convention, all non-resjunk columns in a setop tree have
1233  * ressortgroupref equal to their resno. In some cases the ref isn't
1234  * needed, but this is a cleaner way than modifying the tlist later.
1235  */
1236  tle->ressortgroupref = tle->resno;
1237 
1238  tlist = lappend(tlist, tle);
1239  }
1240 
1241  if (flag)
1242  {
1243  /* Add a resjunk flag column */
1244  /* flag value is shown as copied up from subplan */
1245  expr = (Node *) makeVar(0,
1246  resno,
1247  INT4OID,
1248  -1,
1249  InvalidOid,
1250  0);
1251  tle = makeTargetEntry((Expr *) expr,
1252  (AttrNumber) resno++,
1253  pstrdup("flag"),
1254  true);
1255  tlist = lappend(tlist, tle);
1256  }
1257 
1258  pfree(colTypmods);
1259 
1260  return tlist;
1261 }
#define NIL
Definition: pg_list.h:69
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:273
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:183
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:508
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1332
signed int int32
Definition: c.h:253
void pfree(void *pointer)
Definition: mcxt.c:992
bool resjunk
Definition: primnodes.h:1337
char * flag(int b)
Definition: test-ctype.c:33
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
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
void * palloc(Size size)
Definition: mcxt.c:891
Index ressortgroupref
Definition: primnodes.h:1333
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define lfirst_oid(lc)
Definition: pg_list.h:108
static Path * generate_nonunion_path ( SetOperationStmt op,
PlannerInfo root,
List refnames_tlist,
List **  pTargetList,
double *  pNumGroups 
)
static

Definition at line 599 of file prepunion.c.

References SetOperationStmt::all, choose_hashed_setop(), SetOperationStmt::colCollations, SetOperationStmt::colTypes, create_append_path(), create_pathtarget, create_setop_path(), create_sort_path(), elog, ERROR, fetch_upper_rel(), generate_append_tlist(), generate_setop_grouplist(), SetOperationStmt::larg, list_length(), list_make2, make_pathkeys_for_sortclauses(), Min, NIL, NULL, SetOperationStmt::op, Path::pathtarget, SetOperationStmt::rarg, recurse_set_operations(), Path::rows, SETOP_EXCEPT, SETOP_HASHED, SETOP_INTERSECT, SETOP_SORTED, SETOPCMD_EXCEPT, SETOPCMD_EXCEPT_ALL, SETOPCMD_INTERSECT, SETOPCMD_INTERSECT_ALL, PlannerInfo::tuple_fraction, and UPPERREL_SETOP.

Referenced by recurse_set_operations().

603 {
604  RelOptInfo *result_rel = fetch_upper_rel(root, UPPERREL_SETOP, NULL);
605  double save_fraction = root->tuple_fraction;
606  Path *lpath,
607  *rpath,
608  *path;
609  List *lpath_tlist,
610  *rpath_tlist,
611  *tlist_list,
612  *tlist,
613  *groupList,
614  *pathlist;
615  double dLeftGroups,
616  dRightGroups,
617  dNumGroups,
618  dNumOutputRows;
619  bool use_hash;
620  SetOpCmd cmd;
621  int firstFlag;
622 
623  /*
624  * Tell children to fetch all tuples.
625  */
626  root->tuple_fraction = 0.0;
627 
628  /* Recurse on children, ensuring their outputs are marked */
629  lpath = recurse_set_operations(op->larg, root,
630  op->colTypes, op->colCollations,
631  false, 0,
632  refnames_tlist,
633  &lpath_tlist,
634  &dLeftGroups);
635  rpath = recurse_set_operations(op->rarg, root,
636  op->colTypes, op->colCollations,
637  false, 1,
638  refnames_tlist,
639  &rpath_tlist,
640  &dRightGroups);
641 
642  /* Undo effects of forcing tuple_fraction to 0 */
643  root->tuple_fraction = save_fraction;
644 
645  /*
646  * For EXCEPT, we must put the left input first. For INTERSECT, either
647  * order should give the same results, and we prefer to put the smaller
648  * input first in order to minimize the size of the hash table in the
649  * hashing case. "Smaller" means the one with the fewer groups.
650  */
651  if (op->op == SETOP_EXCEPT || dLeftGroups <= dRightGroups)
652  {
653  pathlist = list_make2(lpath, rpath);
654  tlist_list = list_make2(lpath_tlist, rpath_tlist);
655  firstFlag = 0;
656  }
657  else
658  {
659  pathlist = list_make2(rpath, lpath);
660  tlist_list = list_make2(rpath_tlist, lpath_tlist);
661  firstFlag = 1;
662  }
663 
664  /*
665  * Generate tlist for Append plan node.
666  *
667  * The tlist for an Append plan isn't important as far as the Append is
668  * concerned, but we must make it look real anyway for the benefit of the
669  * next plan level up. In fact, it has to be real enough that the flag
670  * column is shown as a variable not a constant, else setrefs.c will get
671  * confused.
672  */
673  tlist = generate_append_tlist(op->colTypes, op->colCollations, true,
674  tlist_list, refnames_tlist);
675 
676  *pTargetList = tlist;
677 
678  /*
679  * Append the child results together.
680  */
681  path = (Path *) create_append_path(result_rel, pathlist, NULL, 0);
682 
683  /* We have to manually jam the right tlist into the path; ick */
684  path->pathtarget = create_pathtarget(root, tlist);
685 
686  /* Identify the grouping semantics */
687  groupList = generate_setop_grouplist(op, tlist);
688 
689  /* punt if nothing to group on (can this happen?) */
690  if (groupList == NIL)
691  return path;
692 
693  /*
694  * Estimate number of distinct groups that we'll need hashtable entries
695  * for; this is the size of the left-hand input for EXCEPT, or the smaller
696  * input for INTERSECT. Also estimate the number of eventual output rows.
697  * In non-ALL cases, we estimate each group produces one output row; in
698  * ALL cases use the relevant relation size. These are worst-case
699  * estimates, of course, but we need to be conservative.
700  */
701  if (op->op == SETOP_EXCEPT)
702  {
703  dNumGroups = dLeftGroups;
704  dNumOutputRows = op->all ? lpath->rows : dNumGroups;
705  }
706  else
707  {
708  dNumGroups = Min(dLeftGroups, dRightGroups);
709  dNumOutputRows = op->all ? Min(lpath->rows, rpath->rows) : dNumGroups;
710  }
711 
712  /*
713  * Decide whether to hash or sort, and add a sort node if needed.
714  */
715  use_hash = choose_hashed_setop(root, groupList, path,
716  dNumGroups, dNumOutputRows,
717  (op->op == SETOP_INTERSECT) ? "INTERSECT" : "EXCEPT");
718 
719  if (!use_hash)
720  path = (Path *) create_sort_path(root,
721  result_rel,
722  path,
724  groupList,
725  tlist),
726  -1.0);
727 
728  /*
729  * Finally, add a SetOp path node to generate the correct output.
730  */
731  switch (op->op)
732  {
733  case SETOP_INTERSECT:
735  break;
736  case SETOP_EXCEPT:
738  break;
739  default:
740  elog(ERROR, "unrecognized set op: %d", (int) op->op);
741  cmd = SETOPCMD_INTERSECT; /* keep compiler quiet */
742  break;
743  }
744  path = (Path *) create_setop_path(root,
745  result_rel,
746  path,
747  cmd,
748  use_hash ? SETOP_HASHED : SETOP_SORTED,
749  groupList,
750  list_length(op->colTypes) + 1,
751  use_hash ? firstFlag : -1,
752  dNumGroups,
753  dNumOutputRows);
754 
755  if (pNumGroups)
756  *pNumGroups = dNumGroups;
757 
758  return path;
759 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
#define NIL
Definition: pg_list.h:69
static List * generate_append_tlist(List *colTypes, List *colCollations, bool flag, List *input_tlists, List *refnames_tlist)
Definition: prepunion.c:1147
PathTarget * pathtarget
Definition: relation.h:895
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers)
Definition: pathnode.c:1202
SetOpPath * create_setop_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, SetOpCmd cmd, SetOpStrategy strategy, List *distinctList, AttrNumber flagColIdx, int firstFlag, double numGroups, double outputRows)
Definition: pathnode.c:2856
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:838
static List * generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
Definition: prepunion.c:1275
#define Min(x, y)
Definition: c.h:802
static bool choose_hashed_setop(PlannerInfo *root, List *groupClauses, Path *input_path, double dNumGroups, double dNumOutputRows, const char *construct)
Definition: prepunion.c:899
double tuple_fraction
Definition: relation.h:286
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
static Path * recurse_set_operations(Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:248
List * colCollations
Definition: parsenodes.h:1494
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2396
#define NULL
Definition: c.h:226
double rows
Definition: relation.h:905
static int list_length(const List *l)
Definition: pg_list.h:89
SetOperation op
Definition: parsenodes.h:1485
SetOpCmd
Definition: nodes.h:770
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Definition: relation.h:888
static Path * generate_recursion_path ( SetOperationStmt setOp,
PlannerInfo root,
List refnames_tlist,
List **  pTargetList 
)
static

Definition at line 417 of file prepunion.c.

References SetOperationStmt::all, Assert, SetOperationStmt::colCollations, SetOperationStmt::colTypes, create_pathtarget, create_recursiveunion_path(), elog, ereport, errcode(), errdetail(), errmsg(), ERROR, fetch_upper_rel(), generate_append_tlist(), generate_setop_grouplist(), grouping_is_hashable(), SetOperationStmt::larg, list_make2, NIL, PlannerInfo::non_recursive_path, NULL, SetOperationStmt::op, SetOperationStmt::rarg, recurse_set_operations(), Path::rows, SETOP_UNION, UPPERREL_SETOP, and PlannerInfo::wt_param_id.

Referenced by plan_set_operations().

420 {
421  RelOptInfo *result_rel = fetch_upper_rel(root, UPPERREL_SETOP, NULL);
422  Path *path;
423  Path *lpath;
424  Path *rpath;
425  List *lpath_tlist;
426  List *rpath_tlist;
427  List *tlist;
428  List *groupList;
429  double dNumGroups;
430 
431  /* Parser should have rejected other cases */
432  if (setOp->op != SETOP_UNION)
433  elog(ERROR, "only UNION queries can be recursive");
434  /* Worktable ID should be assigned */
435  Assert(root->wt_param_id >= 0);
436 
437  /*
438  * Unlike a regular UNION node, process the left and right inputs
439  * separately without any intention of combining them into one Append.
440  */
441  lpath = recurse_set_operations(setOp->larg, root,
442  setOp->colTypes, setOp->colCollations,
443  false, -1,
444  refnames_tlist,
445  &lpath_tlist,
446  NULL);
447  /* The right path will want to look at the left one ... */
448  root->non_recursive_path = lpath;
449  rpath = recurse_set_operations(setOp->rarg, root,
450  setOp->colTypes, setOp->colCollations,
451  false, -1,
452  refnames_tlist,
453  &rpath_tlist,
454  NULL);
455  root->non_recursive_path = NULL;
456 
457  /*
458  * Generate tlist for RecursiveUnion path node --- same as in Append cases
459  */
460  tlist = generate_append_tlist(setOp->colTypes, setOp->colCollations, false,
461  list_make2(lpath_tlist, rpath_tlist),
462  refnames_tlist);
463 
464  *pTargetList = tlist;
465 
466  /*
467  * If UNION, identify the grouping operators
468  */
469  if (setOp->all)
470  {
471  groupList = NIL;
472  dNumGroups = 0;
473  }
474  else
475  {
476  /* Identify the grouping semantics */
477  groupList = generate_setop_grouplist(setOp, tlist);
478 
479  /* We only support hashing here */
480  if (!grouping_is_hashable(groupList))
481  ereport(ERROR,
482  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
483  errmsg("could not implement recursive UNION"),
484  errdetail("All column datatypes must be hashable.")));
485 
486  /*
487  * For the moment, take the number of distinct groups as equal to the
488  * total input size, ie, the worst case.
489  */
490  dNumGroups = lpath->rows + rpath->rows * 10;
491  }
492 
493  /*
494  * And make the path node.
495  */
496  path = (Path *) create_recursiveunion_path(root,
497  result_rel,
498  lpath,
499  rpath,
500  create_pathtarget(root, tlist),
501  groupList,
502  root->wt_param_id,
503  dNumGroups);
504 
505  return path;
506 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
#define NIL
Definition: pg_list.h:69
static List * generate_append_tlist(List *colTypes, List *colCollations, bool flag, List *input_tlists, List *refnames_tlist)
Definition: prepunion.c:1147
static List * generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
Definition: prepunion.c:1275
int errcode(int sqlerrcode)
Definition: elog.c:575
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
int wt_param_id
Definition: relation.h:303
#define ERROR
Definition: elog.h:43
RecursiveUnionPath * create_recursiveunion_path(PlannerInfo *root, RelOptInfo *rel, Path *leftpath, Path *rightpath, PathTarget *target, List *distinctList, int wtParam, double numGroups)
Definition: pathnode.c:2918
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
#define ereport(elevel, rest)
Definition: elog.h:122
static Path * recurse_set_operations(Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:248
List * colCollations
Definition: parsenodes.h:1494
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
struct Path * non_recursive_path
Definition: relation.h:304
SetOperation op
Definition: parsenodes.h:1485
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Definition: relation.h:888
static List * generate_setop_grouplist ( SetOperationStmt op,
List targetlist 
)
static

Definition at line 1275 of file prepunion.c.

References Assert, copyObject(), SetOperationStmt::groupClauses, lfirst, list_head(), lnext, NULL, TargetEntry::resjunk, TargetEntry::resno, TargetEntry::ressortgroupref, and SortGroupClause::tleSortGroupRef.

Referenced by generate_nonunion_path(), generate_recursion_path(), and make_union_unique().

1276 {
1277  List *grouplist = (List *) copyObject(op->groupClauses);
1278  ListCell *lg;
1279  ListCell *lt;
1280 
1281  lg = list_head(grouplist);
1282  foreach(lt, targetlist)
1283  {
1284  TargetEntry *tle = (TargetEntry *) lfirst(lt);
1285  SortGroupClause *sgc;
1286 
1287  if (tle->resjunk)
1288  {
1289  /* resjunk columns should not have sortgrouprefs */
1290  Assert(tle->ressortgroupref == 0);
1291  continue; /* ignore resjunk columns */
1292  }
1293 
1294  /* non-resjunk columns should have sortgroupref = resno */
1295  Assert(tle->ressortgroupref == tle->resno);
1296 
1297  /* non-resjunk columns should have grouping clauses */
1298  Assert(lg != NULL);
1299  sgc = (SortGroupClause *) lfirst(lg);
1300  lg = lnext(lg);
1301  Assert(sgc->tleSortGroupRef == 0);
1302 
1303  sgc->tleSortGroupRef = tle->ressortgroupref;
1304  }
1305  Assert(lg == NULL);
1306  return grouplist;
1307 }
Index tleSortGroupRef
Definition: parsenodes.h:1102
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
bool resjunk
Definition: primnodes.h:1337
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 Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1333
Definition: pg_list.h:45
static List * generate_setop_tlist ( List colTypes,
List colCollations,
int  flag,
Index  varno,
bool  hack_constants,
List input_tlist,
List refnames_tlist 
)
static

Definition at line 1002 of file prepunion.c.

References Assert, COERCE_IMPLICIT_CAST, coerce_to_common_type(), TargetEntry::expr, exprCollation(), exprType(), exprTypmod(), forthree, Int32GetDatum, INT4OID, InvalidOid, IsA, lappend(), lfirst, lfirst_oid, list_head(), lnext, makeConst(), makeRelabelType(), makeTargetEntry(), makeVar(), NIL, NULL, pstrdup(), TargetEntry::resjunk, TargetEntry::resname, TargetEntry::resno, and TargetEntry::ressortgroupref.

Referenced by recurse_set_operations().

1008 {
1009  List *tlist = NIL;
1010  int resno = 1;
1011  ListCell *ctlc,
1012  *cclc,
1013  *itlc,
1014  *rtlc;
1015  TargetEntry *tle;
1016  Node *expr;
1017 
1018  /* there's no forfour() so we must chase one list manually */
1019  rtlc = list_head(refnames_tlist);
1020  forthree(ctlc, colTypes, cclc, colCollations, itlc, input_tlist)
1021  {
1022  Oid colType = lfirst_oid(ctlc);
1023  Oid colColl = lfirst_oid(cclc);
1024  TargetEntry *inputtle = (TargetEntry *) lfirst(itlc);
1025  TargetEntry *reftle = (TargetEntry *) lfirst(rtlc);
1026 
1027  rtlc = lnext(rtlc);
1028 
1029  Assert(inputtle->resno == resno);
1030  Assert(reftle->resno == resno);
1031  Assert(!inputtle->resjunk);
1032  Assert(!reftle->resjunk);
1033 
1034  /*
1035  * Generate columns referencing input columns and having appropriate
1036  * data types and column names. Insert datatype coercions where
1037  * necessary.
1038  *
1039  * HACK: constants in the input's targetlist are copied up as-is
1040  * rather than being referenced as subquery outputs. This is mainly
1041  * to ensure that when we try to coerce them to the output column's
1042  * datatype, the right things happen for UNKNOWN constants. But do
1043  * this only at the first level of subquery-scan plans; we don't want
1044  * phony constants appearing in the output tlists of upper-level
1045  * nodes!
1046  */
1047  if (hack_constants && inputtle->expr && IsA(inputtle->expr, Const))
1048  expr = (Node *) inputtle->expr;
1049  else
1050  expr = (Node *) makeVar(varno,
1051  inputtle->resno,
1052  exprType((Node *) inputtle->expr),
1053  exprTypmod((Node *) inputtle->expr),
1054  exprCollation((Node *) inputtle->expr),
1055  0);
1056 
1057  if (exprType(expr) != colType)
1058  {
1059  /*
1060  * Note: it's not really cool to be applying coerce_to_common_type
1061  * here; one notable point is that assign_expr_collations never
1062  * gets run on any generated nodes. For the moment that's not a
1063  * problem because we force the correct exposed collation below.
1064  * It would likely be best to make the parser generate the correct
1065  * output tlist for every set-op to begin with, though.
1066  */
1067  expr = coerce_to_common_type(NULL, /* no UNKNOWNs here */
1068  expr,
1069  colType,
1070  "UNION/INTERSECT/EXCEPT");
1071  }
1072 
1073  /*
1074  * Ensure the tlist entry's exposed collation matches the set-op. This
1075  * is necessary because plan_set_operations() reports the result
1076  * ordering as a list of SortGroupClauses, which don't carry collation
1077  * themselves but just refer to tlist entries. If we don't show the
1078  * right collation then planner.c might do the wrong thing in
1079  * higher-level queries.
1080  *
1081  * Note we use RelabelType, not CollateExpr, since this expression
1082  * will reach the executor without any further processing.
1083  */
1084  if (exprCollation(expr) != colColl)
1085  {
1086  expr = (Node *) makeRelabelType((Expr *) expr,
1087  exprType(expr),
1088  exprTypmod(expr),
1089  colColl,
1091  }
1092 
1093  tle = makeTargetEntry((Expr *) expr,
1094  (AttrNumber) resno++,
1095  pstrdup(reftle->resname),
1096  false);
1097 
1098  /*
1099  * By convention, all non-resjunk columns in a setop tree have
1100  * ressortgroupref equal to their resno. In some cases the ref isn't
1101  * needed, but this is a cleaner way than modifying the tlist later.
1102  */
1103  tle->ressortgroupref = tle->resno;
1104 
1105  tlist = lappend(tlist, tle);
1106  }
1107 
1108  if (flag >= 0)
1109  {
1110  /* Add a resjunk flag column */
1111  /* flag value is the given constant */
1112  expr = (Node *) makeConst(INT4OID,
1113  -1,
1114  InvalidOid,
1115  sizeof(int32),
1117  false,
1118  true);
1119  tle = makeTargetEntry((Expr *) expr,
1120  (AttrNumber) resno++,
1121  pstrdup("flag"),
1122  true);
1123  tlist = lappend(tlist, tle);
1124  }
1125 
1126  return tlist;
1127 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:273
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:183
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:508
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1332
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:296
signed int int32
Definition: c.h:253
bool resjunk
Definition: primnodes.h:1337
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition: makefuncs.c:399
char * flag(int b)
Definition: test-ctype.c:33
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
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#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:745
#define Int32GetDatum(X)
Definition: postgres.h:487
Index ressortgroupref
Definition: primnodes.h:1333
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
#define lfirst_oid(lc)
Definition: pg_list.h:108
static Path * generate_union_path ( SetOperationStmt op,
PlannerInfo root,
List refnames_tlist,
List **  pTargetList,
double *  pNumGroups 
)
static

Definition at line 512 of file prepunion.c.

References SetOperationStmt::all, SetOperationStmt::colCollations, SetOperationStmt::colTypes, create_append_path(), create_pathtarget, fetch_upper_rel(), generate_append_tlist(), SetOperationStmt::larg, list_concat(), make_union_unique(), NULL, Path::pathtarget, SetOperationStmt::rarg, recurse_union_children(), Path::rows, PlannerInfo::tuple_fraction, and UPPERREL_SETOP.

Referenced by recurse_set_operations().

516 {
517  RelOptInfo *result_rel = fetch_upper_rel(root, UPPERREL_SETOP, NULL);
518  double save_fraction = root->tuple_fraction;
519  List *pathlist;
520  List *child_tlists1;
521  List *child_tlists2;
522  List *tlist_list;
523  List *tlist;
524  Path *path;
525 
526  /*
527  * If plain UNION, tell children to fetch all tuples.
528  *
529  * Note: in UNION ALL, we pass the top-level tuple_fraction unmodified to
530  * each arm of the UNION ALL. One could make a case for reducing the
531  * tuple fraction for later arms (discounting by the expected size of the
532  * earlier arms' results) but it seems not worth the trouble. The normal
533  * case where tuple_fraction isn't already zero is a LIMIT at top level,
534  * and passing it down as-is is usually enough to get the desired result
535  * of preferring fast-start plans.
536  */
537  if (!op->all)
538  root->tuple_fraction = 0.0;
539 
540  /*
541  * If any of my children are identical UNION nodes (same op, all-flag, and
542  * colTypes) then they can be merged into this node so that we generate
543  * only one Append and unique-ification for the lot. Recurse to find such
544  * nodes and compute their children's paths.
545  */
546  pathlist = list_concat(recurse_union_children(op->larg, root,
547  op, refnames_tlist,
548  &child_tlists1),
549  recurse_union_children(op->rarg, root,
550  op, refnames_tlist,
551  &child_tlists2));
552  tlist_list = list_concat(child_tlists1, child_tlists2);
553 
554  /*
555  * Generate tlist for Append plan node.
556  *
557  * The tlist for an Append plan isn't important as far as the Append is
558  * concerned, but we must make it look real anyway for the benefit of the
559  * next plan level up.
560  */
561  tlist = generate_append_tlist(op->colTypes, op->colCollations, false,
562  tlist_list, refnames_tlist);
563 
564  *pTargetList = tlist;
565 
566  /*
567  * Append the child results together.
568  */
569  path = (Path *) create_append_path(result_rel, pathlist, NULL, 0);
570 
571  /* We have to manually jam the right tlist into the path; ick */
572  path->pathtarget = create_pathtarget(root, tlist);
573 
574  /*
575  * For UNION ALL, we just need the Append path. For UNION, need to add
576  * node(s) to remove duplicates.
577  */
578  if (!op->all)
579  path = make_union_unique(op, path, tlist, root);
580 
581  /*
582  * Estimate number of groups if caller wants it. For now we just assume
583  * the output is unique --- this is certainly true for the UNION case, and
584  * we want worst-case estimates anyway.
585  */
586  if (pNumGroups)
587  *pNumGroups = path->rows;
588 
589  /* Undo effects of possibly forcing tuple_fraction to 0 */
590  root->tuple_fraction = save_fraction;
591 
592  return path;
593 }
static List * generate_append_tlist(List *colTypes, List *colCollations, bool flag, List *input_tlists, List *refnames_tlist)
Definition: prepunion.c:1147
PathTarget * pathtarget
Definition: relation.h:895
static List * recurse_union_children(Node *setOp, PlannerInfo *root, SetOperationStmt *top_union, List *refnames_tlist, List **tlist_list)
Definition: prepunion.c:775
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers)
Definition: pathnode.c:1202
static Path * make_union_unique(SetOperationStmt *op, Path *path, List *tlist, PlannerInfo *root)
Definition: prepunion.c:832
List * list_concat(List *list1, List *list2)
Definition: list.c:321
double tuple_fraction
Definition: relation.h:286
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
List * colCollations
Definition: parsenodes.h:1494
#define NULL
Definition: c.h:226
double rows
Definition: relation.h:905
Definition: pg_list.h:45
Definition: relation.h:888
static void make_inh_translation_list ( Relation  oldrelation,
Relation  newrelation,
Index  newvarno,
List **  translated_vars 
)
static

Definition at line 1572 of file prepunion.c.

References tupleDesc::attrs, elog, ERROR, lappend(), makeVar(), NameStr, tupleDesc::natts, NIL, NULL, RelationGetDescr, and RelationGetRelationName.

Referenced by expand_inherited_rtentry().

1575 {
1576  List *vars = NIL;
1577  TupleDesc old_tupdesc = RelationGetDescr(oldrelation);
1578  TupleDesc new_tupdesc = RelationGetDescr(newrelation);
1579  int oldnatts = old_tupdesc->natts;
1580  int newnatts = new_tupdesc->natts;
1581  int old_attno;
1582 
1583  for (old_attno = 0; old_attno < oldnatts; old_attno++)
1584  {
1585  Form_pg_attribute att;
1586  char *attname;
1587  Oid atttypid;
1588  int32 atttypmod;
1589  Oid attcollation;
1590  int new_attno;
1591 
1592  att = old_tupdesc->attrs[old_attno];
1593  if (att->attisdropped)
1594  {
1595  /* Just put NULL into this list entry */
1596  vars = lappend(vars, NULL);
1597  continue;
1598  }
1599  attname = NameStr(att->attname);
1600  atttypid = att->atttypid;
1601  atttypmod = att->atttypmod;
1602  attcollation = att->attcollation;
1603 
1604  /*
1605  * When we are generating the "translation list" for the parent table
1606  * of an inheritance set, no need to search for matches.
1607  */
1608  if (oldrelation == newrelation)
1609  {
1610  vars = lappend(vars, makeVar(newvarno,
1611  (AttrNumber) (old_attno + 1),
1612  atttypid,
1613  atttypmod,
1614  attcollation,
1615  0));
1616  continue;
1617  }
1618 
1619  /*
1620  * Otherwise we have to search for the matching column by name.
1621  * There's no guarantee it'll have the same column position, because
1622  * of cases like ALTER TABLE ADD COLUMN and multiple inheritance.
1623  * However, in simple cases it will be the same column number, so try
1624  * that before we go groveling through all the columns.
1625  *
1626  * Note: the test for (att = ...) != NULL cannot fail, it's just a
1627  * notational device to include the assignment into the if-clause.
1628  */
1629  if (old_attno < newnatts &&
1630  (att = new_tupdesc->attrs[old_attno]) != NULL &&
1631  !att->attisdropped && att->attinhcount != 0 &&
1632  strcmp(attname, NameStr(att->attname)) == 0)
1633  new_attno = old_attno;
1634  else
1635  {
1636  for (new_attno = 0; new_attno < newnatts; new_attno++)
1637  {
1638  att = new_tupdesc->attrs[new_attno];
1639  if (!att->attisdropped && att->attinhcount != 0 &&
1640  strcmp(attname, NameStr(att->attname)) == 0)
1641  break;
1642  }
1643  if (new_attno >= newnatts)
1644  elog(ERROR, "could not find inherited attribute \"%s\" of relation \"%s\"",
1645  attname, RelationGetRelationName(newrelation));
1646  }
1647 
1648  /* Found it, check type and collation match */
1649  if (atttypid != att->atttypid || atttypmod != att->atttypmod)
1650  elog(ERROR, "attribute \"%s\" of relation \"%s\" does not match parent's type",
1651  attname, RelationGetRelationName(newrelation));
1652  if (attcollation != att->attcollation)
1653  elog(ERROR, "attribute \"%s\" of relation \"%s\" does not match parent's collation",
1654  attname, RelationGetRelationName(newrelation));
1655 
1656  vars = lappend(vars, makeVar(newvarno,
1657  (AttrNumber) (new_attno + 1),
1658  atttypid,
1659  atttypmod,
1660  attcollation,
1661  0));
1662  }
1663 
1664  *translated_vars = vars;
1665 }
#define NIL
Definition: pg_list.h:69
#define RelationGetDescr(relation)
Definition: rel.h:425
Form_pg_attribute * attrs
Definition: tupdesc.h:74
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:73
signed int int32
Definition: c.h:253
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:433
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:67
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:226
#define NameStr(name)
Definition: c.h:495
#define elog
Definition: elog.h:219
Definition: regcomp.c:226
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
static Path * make_union_unique ( SetOperationStmt op,
Path path,
List tlist,
PlannerInfo root 
)
static

Definition at line 832 of file prepunion.c.

References AGG_HASHED, AGGSPLIT_SIMPLE, choose_hashed_setop(), create_agg_path(), create_pathtarget, create_sort_path(), create_upper_unique_path(), fetch_upper_rel(), generate_setop_grouplist(), list_length(), make_pathkeys_for_sortclauses(), NIL, NULL, Path::pathkeys, Path::pathtarget, Path::rows, and UPPERREL_SETOP.

Referenced by generate_union_path().

834 {
835  RelOptInfo *result_rel = fetch_upper_rel(root, UPPERREL_SETOP, NULL);
836  List *groupList;
837  double dNumGroups;
838 
839  /* Identify the grouping semantics */
840  groupList = generate_setop_grouplist(op, tlist);
841 
842  /* punt if nothing to group on (can this happen?) */
843  if (groupList == NIL)
844  return path;
845 
846  /*
847  * XXX for the moment, take the number of distinct groups as equal to the
848  * total input size, ie, the worst case. This is too conservative, but we
849  * don't want to risk having the hashtable overrun memory; also, it's not
850  * clear how to get a decent estimate of the true size. One should note
851  * as well the propensity of novices to write UNION rather than UNION ALL
852  * even when they don't expect any duplicates...
853  */
854  dNumGroups = path->rows;
855 
856  /* Decide whether to hash or sort */
857  if (choose_hashed_setop(root, groupList, path,
858  dNumGroups, dNumGroups,
859  "UNION"))
860  {
861  /* Hashed aggregate plan --- no sort needed */
862  path = (Path *) create_agg_path(root,
863  result_rel,
864  path,
865  create_pathtarget(root, tlist),
866  AGG_HASHED,
868  groupList,
869  NIL,
870  NULL,
871  dNumGroups);
872  }
873  else
874  {
875  /* Sort and Unique */
876  path = (Path *) create_sort_path(root,
877  result_rel,
878  path,
880  groupList,
881  tlist),
882  -1.0);
883  /* We have to manually jam the right tlist into the path; ick */
884  path->pathtarget = create_pathtarget(root, tlist);
885  path = (Path *) create_upper_unique_path(root,
886  result_rel,
887  path,
888  list_length(path->pathkeys),
889  dNumGroups);
890  }
891 
892  return path;
893 }
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:895
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:838
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:2498
static List * generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
Definition: prepunion.c:1275
static bool choose_hashed_setop(PlannerInfo *root, List *groupClauses, Path *input_path, double dNumGroups, double dNumOutputRows, const char *construct)
Definition: prepunion.c:899
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
AggPath * create_agg_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, AggStrategy aggstrategy, AggSplit aggsplit, List *groupClause, List *qual, const AggClauseCosts *aggcosts, double numGroups)
Definition: pathnode.c:2550
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2396
List * pathkeys
Definition: relation.h:909
#define NULL
Definition: c.h:226
double rows
Definition: relation.h:905
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
Definition: relation.h:888
RelOptInfo* plan_set_operations ( PlannerInfo root)

Definition at line 129 of file prepunion.c.

References add_path(), Assert, castNode, SetOperationStmt::colCollations, SetOperationStmt::colTypes, create_upper_paths_hook, Query::distinctClause, fetch_upper_rel(), FromExpr::fromlist, generate_recursion_path(), Query::groupClause, PlannerInfo::hasRecursion, Query::havingQual, IsA, Query::jointree, SetOperationStmt::larg, NIL, NULL, parse(), PlannerInfo::parse, PlannerInfo::processed_tlist, FromExpr::quals, recurse_set_operations(), set_cheapest(), Query::setOperations, setup_simple_rel_arrays(), PlannerInfo::simple_rte_array, RangeTblEntry::subquery, Query::targetList, UPPERREL_SETOP, and Query::windowClause.

Referenced by grouping_planner().

130 {
131  Query *parse = root->parse;
133  Node *node;
134  RangeTblEntry *leftmostRTE;
135  Query *leftmostQuery;
136  RelOptInfo *setop_rel;
137  Path *path;
138  List *top_tlist;
139 
140  Assert(topop);
141 
142  /* check for unsupported stuff */
143  Assert(parse->jointree->fromlist == NIL);
144  Assert(parse->jointree->quals == NULL);
145  Assert(parse->groupClause == NIL);
146  Assert(parse->havingQual == NULL);
147  Assert(parse->windowClause == NIL);
148  Assert(parse->distinctClause == NIL);
149 
150  /*
151  * We'll need to build RelOptInfos for each of the leaf subqueries, which
152  * are RTE_SUBQUERY rangetable entries in this Query. Prepare the index
153  * arrays for that.
154  */
156 
157  /*
158  * Find the leftmost component Query. We need to use its column names for
159  * all generated tlists (else SELECT INTO won't work right).
160  */
161  node = topop->larg;
162  while (node && IsA(node, SetOperationStmt))
163  node = ((SetOperationStmt *) node)->larg;
164  Assert(node && IsA(node, RangeTblRef));
165  leftmostRTE = root->simple_rte_array[((RangeTblRef *) node)->rtindex];
166  leftmostQuery = leftmostRTE->subquery;
167  Assert(leftmostQuery != NULL);
168 
169  /*
170  * We return our results in the (SETOP, NULL) upperrel. For the moment,
171  * this is also the parent rel of all Paths in the setop tree; we may well
172  * change that in future.
173  */
174  setop_rel = fetch_upper_rel(root, UPPERREL_SETOP, NULL);
175 
176  /*
177  * We don't currently worry about setting setop_rel's consider_parallel
178  * flag, nor about allowing FDWs to contribute paths to it.
179  */
180 
181  /*
182  * If the topmost node is a recursive union, it needs special processing.
183  */
184  if (root->hasRecursion)
185  {
186  path = generate_recursion_path(topop, root,
187  leftmostQuery->targetList,
188  &top_tlist);
189  }
190  else
191  {
192  /*
193  * Recurse on setOperations tree to generate paths for set ops. The
194  * final output path should have just the column types shown as the
195  * output from the top-level node, plus possibly resjunk working
196  * columns (we can rely on upper-level nodes to deal with that).
197  */
198  path = recurse_set_operations((Node *) topop, root,
199  topop->colTypes, topop->colCollations,
200  true, -1,
201  leftmostQuery->targetList,
202  &top_tlist,
203  NULL);
204  }
205 
206  /* Must return the built tlist into root->processed_tlist. */
207  root->processed_tlist = top_tlist;
208 
209  /* Add only the final path to the SETOP upperrel. */
210  add_path(setop_rel, path);
211 
212  /* Let extensions possibly add some more paths */
214  (*create_upper_paths_hook) (root, UPPERREL_SETOP,
215  NULL, setop_rel);
216 
217  /* Select cheapest path */
218  set_cheapest(setop_rel);
219 
220  return setop_rel;
221 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
FromExpr * jointree
Definition: parsenodes.h:129
static Path * generate_recursion_path(SetOperationStmt *setOp, PlannerInfo *root, List *refnames_tlist, List **pTargetList)
Definition: prepunion.c:417
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Definition: nodes.h:508
List * fromlist
Definition: primnodes.h:1433
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:68
bool hasRecursion
Definition: relation.h:300
Node * quals
Definition: primnodes.h:1434
List * windowClause
Definition: parsenodes.h:143
List * targetList
Definition: parsenodes.h:131
List * distinctClause
Definition: parsenodes.h:145
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
static Path * recurse_set_operations(Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:248
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
List * colCollations
Definition: parsenodes.h:1494
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:59
Node * setOperations
Definition: parsenodes.h:154
Query * subquery
Definition: parsenodes.h:900
List * groupClause
Definition: parsenodes.h:137
Node * havingQual
Definition: parsenodes.h:141
List * processed_tlist
Definition: relation.h:276
Definition: pg_list.h:45
Definition: relation.h:888
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
static Path * recurse_set_operations ( Node setOp,
PlannerInfo root,
List colTypes,
List colCollations,
bool  junkOK,
int  flag,
List refnames_tlist,
List **  pTargetList,
double *  pNumGroups 
)
static

Definition at line 248 of file prepunion.c.

References apply_projection_to_path(), Assert, build_simple_rel(), create_pathtarget, create_subqueryscan_path(), Query::distinctClause, elog, ERROR, estimate_num_groups(), fetch_upper_rel(), generate_nonunion_path(), generate_setop_tlist(), generate_union_path(), get_cheapest_fractional_path(), get_tlist_exprs(), PlannerInfo::glob, Query::groupClause, Query::groupingSets, Query::hasAggs, PlannerInfo::hasHavingQual, IsA, NIL, nodeTag, NULL, SetOperationStmt::op, Path::parent, PlannerInfo::plan_params, PlannerInfo::processed_tlist, RELOPT_BASEREL, Path::rows, RangeTblRef::rtindex, set_subquery_size_estimates(), SETOP_UNION, PlannerInfo::simple_rte_array, subpath(), RangeTblEntry::subquery, subquery_planner(), RelOptInfo::subroot, tlist_same_collations(), tlist_same_datatypes(), PlannerInfo::tuple_fraction, and UPPERREL_FINAL.

Referenced by generate_nonunion_path(), generate_recursion_path(), plan_set_operations(), and recurse_union_children().

254 {
255  if (IsA(setOp, RangeTblRef))
256  {
257  RangeTblRef *rtr = (RangeTblRef *) setOp;
258  RangeTblEntry *rte = root->simple_rte_array[rtr->rtindex];
259  Query *subquery = rte->subquery;
260  RelOptInfo *rel;
261  PlannerInfo *subroot;
262  RelOptInfo *final_rel;
263  Path *subpath;
264  Path *path;
265  List *tlist;
266 
267  Assert(subquery != NULL);
268 
269  /*
270  * We need to build a RelOptInfo for each leaf subquery. This isn't
271  * used for much here, but it carries the subroot data structures
272  * forward to setrefs.c processing.
273  */
274  rel = build_simple_rel(root, rtr->rtindex, RELOPT_BASEREL);
275 
276  /* plan_params should not be in use in current query level */
277  Assert(root->plan_params == NIL);
278 
279  /* Generate a subroot and Paths for the subquery */
280  subroot = rel->subroot = subquery_planner(root->glob, subquery,
281  root,
282  false,
283  root->tuple_fraction);
284 
285  /*
286  * It should not be possible for the primitive query to contain any
287  * cross-references to other primitive queries in the setop tree.
288  */
289  if (root->plan_params)
290  elog(ERROR, "unexpected outer reference in set operation subquery");
291 
292  /*
293  * Mark rel with estimated output rows, width, etc. Note that we have
294  * to do this before generating outer-query paths, else
295  * cost_subqueryscan is not happy.
296  */
297  set_subquery_size_estimates(root, rel);
298 
299  /*
300  * For the moment, we consider only a single Path for the subquery.
301  * This should change soon (make it look more like
302  * set_subquery_pathlist).
303  */
304  final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
305  subpath = get_cheapest_fractional_path(final_rel,
306  root->tuple_fraction);
307 
308  /*
309  * Stick a SubqueryScanPath atop that.
310  *
311  * We don't bother to determine the subquery's output ordering since
312  * it won't be reflected in the set-op result anyhow; so just label
313  * the SubqueryScanPath with nil pathkeys. (XXX that should change
314  * soon too, likely.)
315  */
316  path = (Path *) create_subqueryscan_path(root, rel, subpath,
317  NIL, NULL);
318 
319  /*
320  * Figure out the appropriate target list, and update the
321  * SubqueryScanPath with the PathTarget form of that.
322  */
323  tlist = generate_setop_tlist(colTypes, colCollations,
324  flag,
325  rtr->rtindex,
326  true,
327  subroot->processed_tlist,
328  refnames_tlist);
329 
330  path = apply_projection_to_path(root, rel, path,
331  create_pathtarget(root, tlist));
332 
333  /* Return the fully-fledged tlist to caller, too */
334  *pTargetList = tlist;
335 
336  /*
337  * Estimate number of groups if caller wants it. If the subquery used
338  * grouping or aggregation, its output is probably mostly unique
339  * anyway; otherwise do statistical estimation.
340  */
341  if (pNumGroups)
342  {
343  if (subquery->groupClause || subquery->groupingSets ||
344  subquery->distinctClause ||
345  subroot->hasHavingQual || subquery->hasAggs)
346  *pNumGroups = subpath->rows;
347  else
348  *pNumGroups = estimate_num_groups(subroot,
349  get_tlist_exprs(subroot->processed_tlist, false),
350  subpath->rows,
351  NULL);
352  }
353 
354  return (Path *) path;
355  }
356  else if (IsA(setOp, SetOperationStmt))
357  {
358  SetOperationStmt *op = (SetOperationStmt *) setOp;
359  Path *path;
360 
361  /* UNIONs are much different from INTERSECT/EXCEPT */
362  if (op->op == SETOP_UNION)
363  path = generate_union_path(op, root,
364  refnames_tlist,
365  pTargetList,
366  pNumGroups);
367  else
368  path = generate_nonunion_path(op, root,
369  refnames_tlist,
370  pTargetList,
371  pNumGroups);
372 
373  /*
374  * If necessary, add a Result node to project the caller-requested
375  * output columns.
376  *
377  * XXX you don't really want to know about this: setrefs.c will apply
378  * fix_upper_expr() to the Result node's tlist. This would fail if the
379  * Vars generated by generate_setop_tlist() were not exactly equal()
380  * to the corresponding tlist entries of the subplan. However, since
381  * the subplan was generated by generate_union_plan() or
382  * generate_nonunion_plan(), and hence its tlist was generated by
383  * generate_append_tlist(), this will work. We just tell
384  * generate_setop_tlist() to use varno 0.
385  */
386  if (flag >= 0 ||
387  !tlist_same_datatypes(*pTargetList, colTypes, junkOK) ||
388  !tlist_same_collations(*pTargetList, colCollations, junkOK))
389  {
390  *pTargetList = generate_setop_tlist(colTypes, colCollations,
391  flag,
392  0,
393  false,
394  *pTargetList,
395  refnames_tlist);
396  path = apply_projection_to_path(root,
397  path->parent,
398  path,
399  create_pathtarget(root,
400  *pTargetList));
401  }
402  return path;
403  }
404  else
405  {
406  elog(ERROR, "unrecognized node type: %d",
407  (int) nodeTag(setOp));
408  *pTargetList = NIL;
409  return NULL; /* keep compiler quiet */
410  }
411 }
Path * apply_projection_to_path(PlannerInfo *root, RelOptInfo *rel, Path *path, PathTarget *target)
Definition: pathnode.c:2253
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4314
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3272
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
bool tlist_same_datatypes(List *tlist, List *colTypes, bool junkOK)
Definition: tlist.c:251
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
static Path * generate_union_path(SetOperationStmt *op, PlannerInfo *root, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:512
bool hasAggs
Definition: parsenodes.h:116
static Path * generate_nonunion_path(SetOperationStmt *op, PlannerInfo *root, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:599
List * groupingSets
Definition: parsenodes.h:139
PlannerInfo * subroot
Definition: relation.h:531
double tuple_fraction
Definition: relation.h:286
List * distinctClause
Definition: parsenodes.h:145
#define ERROR
Definition: elog.h:43
RelOptInfo * parent
Definition: relation.h:894
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
PlannerGlobal * glob
Definition: relation.h:154
char * flag(int b)
Definition: test-ctype.c:33
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
List * get_tlist_exprs(List *tlist, bool includeJunk)
Definition: tlist.c:166
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
Definition: relnode.c:88
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
SetOperation op
Definition: parsenodes.h:1485
#define nodeTag(nodeptr)
Definition: nodes.h:513
Query * subquery
Definition: parsenodes.h:900
List * groupClause
Definition: parsenodes.h:137
bool hasHavingQual
Definition: relation.h:297
bool tlist_same_collations(List *tlist, List *colCollations, bool junkOK)
Definition: tlist.c:285
#define elog
Definition: elog.h:219
List * processed_tlist
Definition: relation.h:276
Definition: pg_list.h:45
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
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5058
static List * generate_setop_tlist(List *colTypes, List *colCollations, int flag, Index varno, bool hack_constants, List *input_tlist, List *refnames_tlist)
Definition: prepunion.c:1002
static List * recurse_union_children ( Node setOp,
PlannerInfo root,
SetOperationStmt top_union,
List refnames_tlist,
List **  tlist_list 
)
static

Definition at line 775 of file prepunion.c.

References SetOperationStmt::all, SetOperationStmt::colCollations, SetOperationStmt::colTypes, equal(), IsA, SetOperationStmt::larg, list_concat(), list_make1, NULL, SetOperationStmt::op, SetOperationStmt::rarg, and recurse_set_operations().

Referenced by generate_union_path().

779 {
780  List *result;
781  List *child_tlist;
782 
783  if (IsA(setOp, SetOperationStmt))
784  {
785  SetOperationStmt *op = (SetOperationStmt *) setOp;
786 
787  if (op->op == top_union->op &&
788  (op->all == top_union->all || op->all) &&
789  equal(op->colTypes, top_union->colTypes))
790  {
791  /* Same UNION, so fold children into parent's subpath list */
792  List *child_tlists1;
793  List *child_tlists2;
794 
795  result = list_concat(recurse_union_children(op->larg, root,
796  top_union,
797  refnames_tlist,
798  &child_tlists1),
799  recurse_union_children(op->rarg, root,
800  top_union,
801  refnames_tlist,
802  &child_tlists2));
803  *tlist_list = list_concat(child_tlists1, child_tlists2);
804  return result;
805  }
806  }
807 
808  /*
809  * Not same, so plan this child separately.
810  *
811  * Note we disallow any resjunk columns in child results. This is
812  * necessary since the Append node that implements the union won't do any
813  * projection, and upper levels will get confused if some of our output
814  * tuples have junk and some don't. This case only arises when we have an
815  * EXCEPT or INTERSECT as child, else there won't be resjunk anyway.
816  */
817  result = list_make1(recurse_set_operations(setOp, root,
818  top_union->colTypes,
819  top_union->colCollations,
820  false, -1,
821  refnames_tlist,
822  &child_tlist,
823  NULL));
824  *tlist_list = list_make1(child_tlist);
825  return result;
826 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
static List * recurse_union_children(Node *setOp, PlannerInfo *root, SetOperationStmt *top_union, List *refnames_tlist, List **tlist_list)
Definition: prepunion.c:775
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2870
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define list_make1(x1)
Definition: pg_list.h:133
static Path * recurse_set_operations(Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, double *pNumGroups)
Definition: prepunion.c:248
List * colCollations
Definition: parsenodes.h:1494
#define NULL
Definition: c.h:226
SetOperation op
Definition: parsenodes.h:1485
Definition: pg_list.h:45
static Bitmapset * translate_col_privs ( const Bitmapset parent_privs,
List translated_vars 
)
static

Definition at line 1679 of file prepunion.c.

References bms_add_member(), bms_is_member(), castNode, FirstLowInvalidHeapAttributeNumber, InvalidAttrNumber, lfirst, NULL, and Var::varattno.

Referenced by expand_inherited_rtentry().

1681 {
1682  Bitmapset *child_privs = NULL;
1683  bool whole_row;
1684  int attno;
1685  ListCell *lc;
1686 
1687  /* System attributes have the same numbers in all tables */
1688  for (attno = FirstLowInvalidHeapAttributeNumber + 1; attno < 0; attno++)
1689  {
1691  parent_privs))
1692  child_privs = bms_add_member(child_privs,
1694  }
1695 
1696  /* Check if parent has whole-row reference */
1698  parent_privs);
1699 
1700  /* And now translate the regular user attributes, using the vars list */
1701  attno = InvalidAttrNumber;
1702  foreach(lc, translated_vars)
1703  {
1704  Var *var = castNode(Var, lfirst(lc));
1705 
1706  attno++;
1707  if (var == NULL) /* ignore dropped columns */
1708  continue;
1709  if (whole_row ||
1711  parent_privs))
1712  child_privs = bms_add_member(child_privs,
1714  }
1715 
1716  return child_privs;
1717 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
AttrNumber varattno
Definition: primnodes.h:146
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
Definition: primnodes.h:141
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
#define InvalidAttrNumber
Definition: attnum.h:23
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419