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 1772 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(), result, 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().

1773 {
1774  Node *result;
1776 
1777  context.root = root;
1778  context.appinfo = appinfo;
1779 
1780  /*
1781  * Must be prepared to start with a Query or a bare expression tree.
1782  */
1783  if (node && IsA(node, Query))
1784  {
1785  Query *newnode;
1786 
1787  newnode = query_tree_mutator((Query *) node,
1789  (void *) &context,
1791  if (newnode->resultRelation == appinfo->parent_relid)
1792  {
1793  newnode->resultRelation = appinfo->child_relid;
1794  /* Fix tlist resnos too, if it's inherited UPDATE */
1795  if (newnode->commandType == CMD_UPDATE)
1796  newnode->targetList =
1798  appinfo);
1799  }
1800  result = (Node *) newnode;
1801  }
1802  else
1803  result = adjust_appendrel_attrs_mutator(node, &context);
1804 
1805  return result;
1806 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
int resultRelation
Definition: parsenodes.h:113
Definition: nodes.h:504
return result
Definition: formatting.c:1618
static List * adjust_inherited_tlist(List *tlist, AppendRelInfo *context)
Definition: prepunion.c:2051
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:1809
Index child_relid
Definition: relation.h:1908
Index parent_relid
Definition: relation.h:1907
Query * query_tree_mutator(Query *query, Node *(*mutator)(), void *context, int flags)
Definition: nodeFuncs.c:3077
Node* adjust_appendrel_attrs_multilevel ( PlannerInfo root,
Node node,
RelOptInfo child_rel 
)

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

2141 {
2142  AppendRelInfo *appinfo = find_childrel_appendrelinfo(root, child_rel);
2143  RelOptInfo *parent_rel = find_base_rel(root, appinfo->parent_relid);
2144 
2145  /* If parent is also a child, first recurse to apply its translations */
2146  if (parent_rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
2147  node = adjust_appendrel_attrs_multilevel(root, node, parent_rel);
2148  else
2149  Assert(parent_rel->reloptkind == RELOPT_BASEREL);
2150  /* Now translate for this child */
2151  return adjust_appendrel_attrs(root, node, appinfo);
2152 }
RelOptKind reloptkind
Definition: relation.h:491
AppendRelInfo * find_childrel_appendrelinfo(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:946
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, AppendRelInfo *appinfo)
Definition: prepunion.c:1772
#define Assert(condition)
Definition: c.h:675
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *child_rel)
Definition: prepunion.c:2139
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:223
Index parent_relid
Definition: relation.h:1907
static Node * adjust_appendrel_attrs_mutator ( Node node,
adjust_appendrel_attrs_context context 
)
static

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

1811 {
1812  AppendRelInfo *appinfo = context->appinfo;
1813 
1814  if (node == NULL)
1815  return NULL;
1816  if (IsA(node, Var))
1817  {
1818  Var *var = (Var *) copyObject(node);
1819 
1820  if (var->varlevelsup == 0 &&
1821  var->varno == appinfo->parent_relid)
1822  {
1823  var->varno = appinfo->child_relid;
1824  var->varnoold = appinfo->child_relid;
1825  if (var->varattno > 0)
1826  {
1827  Node *newnode;
1828 
1829  if (var->varattno > list_length(appinfo->translated_vars))
1830  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
1831  var->varattno, get_rel_name(appinfo->parent_reloid));
1832  newnode = copyObject(list_nth(appinfo->translated_vars,
1833  var->varattno - 1));
1834  if (newnode == NULL)
1835  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
1836  var->varattno, get_rel_name(appinfo->parent_reloid));
1837  return newnode;
1838  }
1839  else if (var->varattno == 0)
1840  {
1841  /*
1842  * Whole-row Var: if we are dealing with named rowtypes, we
1843  * can use a whole-row Var for the child table plus a coercion
1844  * step to convert the tuple layout to the parent's rowtype.
1845  * Otherwise we have to generate a RowExpr.
1846  */
1847  if (OidIsValid(appinfo->child_reltype))
1848  {
1849  Assert(var->vartype == appinfo->parent_reltype);
1850  if (appinfo->parent_reltype != appinfo->child_reltype)
1851  {
1853 
1854  r->arg = (Expr *) var;
1855  r->resulttype = appinfo->parent_reltype;
1857  r->location = -1;
1858  /* Make sure the Var node has the right type ID, too */
1859  var->vartype = appinfo->child_reltype;
1860  return (Node *) r;
1861  }
1862  }
1863  else
1864  {
1865  /*
1866  * Build a RowExpr containing the translated variables.
1867  *
1868  * In practice var->vartype will always be RECORDOID here,
1869  * so we need to come up with some suitable column names.
1870  * We use the parent RTE's column names.
1871  *
1872  * Note: we can't get here for inheritance cases, so there
1873  * is no need to worry that translated_vars might contain
1874  * some dummy NULLs.
1875  */
1876  RowExpr *rowexpr;
1877  List *fields;
1878  RangeTblEntry *rte;
1879 
1880  rte = rt_fetch(appinfo->parent_relid,
1881  context->root->parse->rtable);
1882  fields = (List *) copyObject(appinfo->translated_vars);
1883  rowexpr = makeNode(RowExpr);
1884  rowexpr->args = fields;
1885  rowexpr->row_typeid = var->vartype;
1886  rowexpr->row_format = COERCE_IMPLICIT_CAST;
1887  rowexpr->colnames = copyObject(rte->eref->colnames);
1888  rowexpr->location = -1;
1889 
1890  return (Node *) rowexpr;
1891  }
1892  }
1893  /* system attributes don't need any other translation */
1894  }
1895  return (Node *) var;
1896  }
1897  if (IsA(node, CurrentOfExpr))
1898  {
1899  CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1900 
1901  if (cexpr->cvarno == appinfo->parent_relid)
1902  cexpr->cvarno = appinfo->child_relid;
1903  return (Node *) cexpr;
1904  }
1905  if (IsA(node, RangeTblRef))
1906  {
1907  RangeTblRef *rtr = (RangeTblRef *) copyObject(node);
1908 
1909  if (rtr->rtindex == appinfo->parent_relid)
1910  rtr->rtindex = appinfo->child_relid;
1911  return (Node *) rtr;
1912  }
1913  if (IsA(node, JoinExpr))
1914  {
1915  /* Copy the JoinExpr node with correct mutation of subnodes */
1916  JoinExpr *j;
1917 
1918  j = (JoinExpr *) expression_tree_mutator(node,
1920  (void *) context);
1921  /* now fix JoinExpr's rtindex (probably never happens) */
1922  if (j->rtindex == appinfo->parent_relid)
1923  j->rtindex = appinfo->child_relid;
1924  return (Node *) j;
1925  }
1926  if (IsA(node, PlaceHolderVar))
1927  {
1928  /* Copy the PlaceHolderVar node with correct mutation of subnodes */
1929  PlaceHolderVar *phv;
1930 
1931  phv = (PlaceHolderVar *) expression_tree_mutator(node,
1933  (void *) context);
1934  /* now fix PlaceHolderVar's relid sets */
1935  if (phv->phlevelsup == 0)
1936  phv->phrels = adjust_relid_set(phv->phrels,
1937  appinfo->parent_relid,
1938  appinfo->child_relid);
1939  return (Node *) phv;
1940  }
1941  /* Shouldn't need to handle planner auxiliary nodes here */
1942  Assert(!IsA(node, SpecialJoinInfo));
1943  Assert(!IsA(node, AppendRelInfo));
1944  Assert(!IsA(node, PlaceHolderInfo));
1945  Assert(!IsA(node, MinMaxAggInfo));
1946 
1947  /*
1948  * We have to process RestrictInfo nodes specially. (Note: although
1949  * set_append_rel_pathlist will hide RestrictInfos in the parent's
1950  * baserestrictinfo list from us, it doesn't hide those in joininfo.)
1951  */
1952  if (IsA(node, RestrictInfo))
1953  {
1954  RestrictInfo *oldinfo = (RestrictInfo *) node;
1955  RestrictInfo *newinfo = makeNode(RestrictInfo);
1956 
1957  /* Copy all flat-copiable fields */
1958  memcpy(newinfo, oldinfo, sizeof(RestrictInfo));
1959 
1960  /* Recursively fix the clause itself */
1961  newinfo->clause = (Expr *)
1962  adjust_appendrel_attrs_mutator((Node *) oldinfo->clause, context);
1963 
1964  /* and the modified version, if an OR clause */
1965  newinfo->orclause = (Expr *)
1966  adjust_appendrel_attrs_mutator((Node *) oldinfo->orclause, context);
1967 
1968  /* adjust relid sets too */
1969  newinfo->clause_relids = adjust_relid_set(oldinfo->clause_relids,
1970  appinfo->parent_relid,
1971  appinfo->child_relid);
1972  newinfo->required_relids = adjust_relid_set(oldinfo->required_relids,
1973  appinfo->parent_relid,
1974  appinfo->child_relid);
1975  newinfo->outer_relids = adjust_relid_set(oldinfo->outer_relids,
1976  appinfo->parent_relid,
1977  appinfo->child_relid);
1978  newinfo->nullable_relids = adjust_relid_set(oldinfo->nullable_relids,
1979  appinfo->parent_relid,
1980  appinfo->child_relid);
1981  newinfo->left_relids = adjust_relid_set(oldinfo->left_relids,
1982  appinfo->parent_relid,
1983  appinfo->child_relid);
1984  newinfo->right_relids = adjust_relid_set(oldinfo->right_relids,
1985  appinfo->parent_relid,
1986  appinfo->child_relid);
1987 
1988  /*
1989  * Reset cached derivative fields, since these might need to have
1990  * different values when considering the child relation. Note we
1991  * don't reset left_ec/right_ec: each child variable is implicitly
1992  * equivalent to its parent, so still a member of the same EC if any.
1993  */
1994  newinfo->eval_cost.startup = -1;
1995  newinfo->norm_selec = -1;
1996  newinfo->outer_selec = -1;
1997  newinfo->left_em = NULL;
1998  newinfo->right_em = NULL;
1999  newinfo->scansel_cache = NIL;
2000  newinfo->left_bucketsize = -1;
2001  newinfo->right_bucketsize = -1;
2002 
2003  return (Node *) newinfo;
2004  }
2005 
2006  /*
2007  * NOTE: we do not need to recurse into sublinks, because they should
2008  * already have been converted to subplans before we see them.
2009  */
2010  Assert(!IsA(node, SubLink));
2011  Assert(!IsA(node, Query));
2012 
2014  (void *) context);
2015 }
QualCost eval_cost
Definition: relation.h:1716
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:984
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
Query * parse
Definition: relation.h:154
Index varlevelsup
Definition: primnodes.h:173
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2420
Relids required_relids
Definition: relation.h:1697
List * colnames
Definition: primnodes.h:43
Expr * orclause
Definition: relation.h:1710
Relids clause_relids
Definition: relation.h:1694
Definition: nodes.h:504
Relids left_relids
Definition: relation.h:1706
AttrNumber varattno
Definition: primnodes.h:168
static Relids adjust_relid_set(Relids relids, Index oldrelid, Index newrelid)
Definition: prepunion.c:2021
Definition: primnodes.h:163
#define OidIsValid(objectId)
Definition: c.h:538
List * translated_vars
Definition: relation.h:1935
Oid parent_reltype
Definition: relation.h:1916
Cost startup
Definition: relation.h:45
Relids outer_relids
Definition: relation.h:1700
Selectivity norm_selec
Definition: relation.h:1717
void * copyObject(const void *from)
Definition: copyfuncs.c:4619
Index varnoold
Definition: primnodes.h:176
List * rtable
Definition: parsenodes.h:128
Relids phrels
Definition: relation.h:1783
#define ERROR
Definition: elog.h:43
List * colnames
Definition: primnodes.h:997
Oid vartype
Definition: primnodes.h:170
EquivalenceMember * left_em
Definition: relation.h:1729
int location
Definition: primnodes.h:998
void * list_nth(const List *list, int n)
Definition: list.c:410
Selectivity outer_selec
Definition: relation.h:1720
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
EquivalenceMember * right_em
Definition: relation.h:1730
Expr * clause
Definition: relation.h:1679
Index varno
Definition: primnodes.h:166
Relids nullable_relids
Definition: relation.h:1703
CoercionForm convertformat
Definition: primnodes.h:860
Selectivity left_bucketsize
Definition: relation.h:1740
#define makeNode(_type_)
Definition: nodes.h:552
Relids right_relids
Definition: relation.h:1707
static Node * adjust_appendrel_attrs_mutator(Node *node, adjust_appendrel_attrs_context *context)
Definition: prepunion.c:1809
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
Oid row_typeid
Definition: primnodes.h:985
static int list_length(const List *l)
Definition: pg_list.h:89
Oid child_reltype
Definition: relation.h:1917
Index phlevelsup
Definition: relation.h:1785
Selectivity right_bucketsize
Definition: relation.h:1741
#define elog
Definition: elog.h:219
Index child_relid
Definition: relation.h:1908
Alias * eref
Definition: parsenodes.h:1000
Oid parent_reloid
Definition: relation.h:1942
Index parent_relid
Definition: relation.h:1907
CoercionForm row_format
Definition: primnodes.h:996
int rtindex
Definition: primnodes.h:1440
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
List * scansel_cache
Definition: relation.h:1731
static List * adjust_inherited_tlist ( List tlist,
AppendRelInfo context 
)
static

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

2052 {
2053  bool changed_it = false;
2054  ListCell *tl;
2055  List *new_tlist;
2056  bool more;
2057  int attrno;
2058 
2059  /* This should only happen for an inheritance case, not UNION ALL */
2060  Assert(OidIsValid(context->parent_reloid));
2061 
2062  /* Scan tlist and update resnos to match attnums of child rel */
2063  foreach(tl, tlist)
2064  {
2065  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2066  Var *childvar;
2067 
2068  if (tle->resjunk)
2069  continue; /* ignore junk items */
2070 
2071  /* Look up the translation of this column: it must be a Var */
2072  if (tle->resno <= 0 ||
2073  tle->resno > list_length(context->translated_vars))
2074  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
2075  tle->resno, get_rel_name(context->parent_reloid));
2076  childvar = (Var *) list_nth(context->translated_vars, tle->resno - 1);
2077  if (childvar == NULL || !IsA(childvar, Var))
2078  elog(ERROR, "attribute %d of relation \"%s\" does not exist",
2079  tle->resno, get_rel_name(context->parent_reloid));
2080 
2081  if (tle->resno != childvar->varattno)
2082  {
2083  tle->resno = childvar->varattno;
2084  changed_it = true;
2085  }
2086  }
2087 
2088  /*
2089  * If we changed anything, re-sort the tlist by resno, and make sure
2090  * resjunk entries have resnos above the last real resno. The sort
2091  * algorithm is a bit stupid, but for such a seldom-taken path, small is
2092  * probably better than fast.
2093  */
2094  if (!changed_it)
2095  return tlist;
2096 
2097  new_tlist = NIL;
2098  more = true;
2099  for (attrno = 1; more; attrno++)
2100  {
2101  more = false;
2102  foreach(tl, tlist)
2103  {
2104  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2105 
2106  if (tle->resjunk)
2107  continue; /* ignore junk items */
2108 
2109  if (tle->resno == attrno)
2110  new_tlist = lappend(new_tlist, tle);
2111  else if (tle->resno > attrno)
2112  more = true;
2113  }
2114  }
2115 
2116  foreach(tl, tlist)
2117  {
2118  TargetEntry *tle = (TargetEntry *) lfirst(tl);
2119 
2120  if (!tle->resjunk)
2121  continue; /* here, ignore non-junk items */
2122 
2123  tle->resno = attrno;
2124  new_tlist = lappend(new_tlist, tle);
2125  attrno++;
2126  }
2127 
2128  return new_tlist;
2129 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
#define OidIsValid(objectId)
Definition: c.h:538
List * translated_vars
Definition: relation.h:1935
bool resjunk
Definition: primnodes.h:1359
#define ERROR
Definition: elog.h:43
void * list_nth(const List *list, int n)
Definition: list.c:410
AttrNumber resno
Definition: primnodes.h:1353
List * lappend(List *list, void *datum)
Definition: list.c:128
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:1942
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 2021 of file prepunion.c.

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

Referenced by adjust_appendrel_attrs_mutator().

2022 {
2023  if (bms_is_member(oldrelid, relids))
2024  {
2025  /* Ensure we have a modifiable copy */
2026  relids = bms_copy(relids);
2027  /* Remove old, add new */
2028  relids = bms_del_member(relids, oldrelid);
2029  relids = bms_add_member(relids, newrelid);
2030  }
2031  return relids;
2032 }
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:1998
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:918
int errcode(int sqlerrcode)
Definition: elog.c:575
bool grouping_is_hashable(List *groupClause)
Definition: tlist.c:538
double tuple_fraction
Definition: relation.h:290
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: relation.h:929
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:1836
#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:1607
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:930
#define NULL
Definition: c.h:229
double rows
Definition: relation.h:928
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
size_t Size
Definition: c.h:356
static int list_length(const List *l)
Definition: pg_list.h:89
#define MAXALIGN(LEN)
Definition: c.h:588
bool enable_hashagg
Definition: costsize.c:124
int width
Definition: relation.h:850
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool grouping_is_sortable(List *groupClause)
Definition: tlist.c:518
Definition: relation.h:911
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, PartitionedChildRelInfo::child_rels, AppendRelInfo::child_reltype, copyObject(), find_all_inheritors(), get_plan_rowmark(), has_subclass(), heap_close, heap_open(), RangeTblEntry::inh, RangeTblEntry::insertedCols, PlanRowMark::isParent, lappend(), lappend_int(), lfirst_oid, list_concat(), list_length(), make_inh_translation_list(), makeNode, PlanRowMark::markType, NIL, NoLock, NULL, AppendRelInfo::parent_relid, PartitionedChildRelInfo::parent_relid, AppendRelInfo::parent_reloid, AppendRelInfo::parent_reltype, parse(), PlannerInfo::parse, PlannerInfo::pcinfo_list, PlanRowMark::prti, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_PARTITIONED_TABLE, 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  bool need_append;
1368  PartitionedChildRelInfo *pcinfo;
1369  List *partitioned_child_rels = NIL;
1370 
1371  /* Does RT entry allow inheritance? */
1372  if (!rte->inh)
1373  return;
1374  /* Ignore any already-expanded UNION ALL nodes */
1375  if (rte->rtekind != RTE_RELATION)
1376  {
1377  Assert(rte->rtekind == RTE_SUBQUERY);
1378  return;
1379  }
1380  /* Fast path for common case of childless table */
1381  parentOID = rte->relid;
1382  if (!has_subclass(parentOID))
1383  {
1384  /* Clear flag before returning */
1385  rte->inh = false;
1386  return;
1387  }
1388 
1389  /*
1390  * The rewriter should already have obtained an appropriate lock on each
1391  * relation named in the query. However, for each child relation we add
1392  * to the query, we must obtain an appropriate lock, because this will be
1393  * the first use of those relations in the parse/rewrite/plan pipeline.
1394  *
1395  * If the parent relation is the query's result relation, then we need
1396  * RowExclusiveLock. Otherwise, if it's accessed FOR UPDATE/SHARE, we
1397  * need RowShareLock; otherwise AccessShareLock. We can't just grab
1398  * AccessShareLock because then the executor would be trying to upgrade
1399  * the lock, leading to possible deadlocks. (This code should match the
1400  * parser and rewriter.)
1401  */
1402  oldrc = get_plan_rowmark(root->rowMarks, rti);
1403  if (rti == parse->resultRelation)
1404  lockmode = RowExclusiveLock;
1405  else if (oldrc && RowMarkRequiresRowShareLock(oldrc->markType))
1406  lockmode = RowShareLock;
1407  else
1408  lockmode = AccessShareLock;
1409 
1410  /* Scan for all members of inheritance set, acquire needed locks */
1411  inhOIDs = find_all_inheritors(parentOID, lockmode, NULL);
1412 
1413  /*
1414  * Check that there's at least one descendant, else treat as no-child
1415  * case. This could happen despite above has_subclass() check, if table
1416  * once had a child but no longer does.
1417  */
1418  if (list_length(inhOIDs) < 2)
1419  {
1420  /* Clear flag before returning */
1421  rte->inh = false;
1422  return;
1423  }
1424 
1425  /*
1426  * If parent relation is selected FOR UPDATE/SHARE, we need to mark its
1427  * PlanRowMark as isParent = true, and generate a new PlanRowMark for each
1428  * child.
1429  */
1430  if (oldrc)
1431  oldrc->isParent = true;
1432 
1433  /*
1434  * Must open the parent relation to examine its tupdesc. We need not lock
1435  * it; we assume the rewriter already did.
1436  */
1437  oldrelation = heap_open(parentOID, NoLock);
1438 
1439  /* Scan the inheritance set and expand it */
1440  appinfos = NIL;
1441  need_append = false;
1442  foreach(l, inhOIDs)
1443  {
1444  Oid childOID = lfirst_oid(l);
1445  Relation newrelation;
1446  RangeTblEntry *childrte;
1447  Index childRTindex;
1448  AppendRelInfo *appinfo;
1449 
1450  /* Open rel if needed; we already have required locks */
1451  if (childOID != parentOID)
1452  newrelation = heap_open(childOID, NoLock);
1453  else
1454  newrelation = oldrelation;
1455 
1456  /*
1457  * It is possible that the parent table has children that are temp
1458  * tables of other backends. We cannot safely access such tables
1459  * (because of buffering issues), and the best thing to do seems to be
1460  * to silently ignore them.
1461  */
1462  if (childOID != parentOID && RELATION_IS_OTHER_TEMP(newrelation))
1463  {
1464  heap_close(newrelation, lockmode);
1465  continue;
1466  }
1467 
1468  /*
1469  * Build an RTE for the child, and attach to query's rangetable list.
1470  * We copy most fields of the parent's RTE, but replace relation OID
1471  * and relkind, and set inh = false. Also, set requiredPerms to zero
1472  * since all required permissions checks are done on the original RTE.
1473  * Likewise, set the child's securityQuals to empty, because we only
1474  * want to apply the parent's RLS conditions regardless of what RLS
1475  * properties individual children may have. (This is an intentional
1476  * choice to make inherited RLS work like regular permissions checks.)
1477  * The parent securityQuals will be propagated to children along with
1478  * other base restriction clauses, so we don't need to do it here.
1479  */
1480  childrte = copyObject(rte);
1481  childrte->relid = childOID;
1482  childrte->relkind = newrelation->rd_rel->relkind;
1483  childrte->inh = false;
1484  childrte->requiredPerms = 0;
1485  childrte->securityQuals = NIL;
1486  parse->rtable = lappend(parse->rtable, childrte);
1487  childRTindex = list_length(parse->rtable);
1488 
1489  /*
1490  * Build an AppendRelInfo for this parent and child, unless the child
1491  * is a partitioned table.
1492  */
1493  if (childrte->relkind != RELKIND_PARTITIONED_TABLE)
1494  {
1495  need_append = true;
1496  appinfo = makeNode(AppendRelInfo);
1497  appinfo->parent_relid = rti;
1498  appinfo->child_relid = childRTindex;
1499  appinfo->parent_reltype = oldrelation->rd_rel->reltype;
1500  appinfo->child_reltype = newrelation->rd_rel->reltype;
1501  make_inh_translation_list(oldrelation, newrelation, childRTindex,
1502  &appinfo->translated_vars);
1503  appinfo->parent_reloid = parentOID;
1504  appinfos = lappend(appinfos, appinfo);
1505 
1506  /*
1507  * Translate the column permissions bitmaps to the child's attnums
1508  * (we have to build the translated_vars list before we can do
1509  * this). But if this is the parent table, leave copyObject's
1510  * result alone.
1511  *
1512  * Note: we need to do this even though the executor won't run any
1513  * permissions checks on the child RTE. The
1514  * insertedCols/updatedCols bitmaps may be examined for
1515  * trigger-firing purposes.
1516  */
1517  if (childOID != parentOID)
1518  {
1520  appinfo->translated_vars);
1522  appinfo->translated_vars);
1523  childrte->updatedCols = translate_col_privs(rte->updatedCols,
1524  appinfo->translated_vars);
1525  }
1526  }
1527  else
1528  partitioned_child_rels = lappend_int(partitioned_child_rels,
1529  childRTindex);
1530 
1531  /*
1532  * Build a PlanRowMark if parent is marked FOR UPDATE/SHARE.
1533  */
1534  if (oldrc)
1535  {
1536  PlanRowMark *newrc = makeNode(PlanRowMark);
1537 
1538  newrc->rti = childRTindex;
1539  newrc->prti = rti;
1540  newrc->rowmarkId = oldrc->rowmarkId;
1541  /* Reselect rowmark type, because relkind might not match parent */
1542  newrc->markType = select_rowmark_type(childrte, oldrc->strength);
1543  newrc->allMarkTypes = (1 << newrc->markType);
1544  newrc->strength = oldrc->strength;
1545  newrc->waitPolicy = oldrc->waitPolicy;
1546 
1547  /*
1548  * We mark RowMarks for partitioned child tables as parent RowMarks
1549  * so that the executor ignores them (except their existence means
1550  * that the child tables be locked using appropriate mode).
1551  */
1552  newrc->isParent = (childrte->relkind == RELKIND_PARTITIONED_TABLE);
1553 
1554  /* Include child's rowmark type in parent's allMarkTypes */
1555  oldrc->allMarkTypes |= newrc->allMarkTypes;
1556 
1557  root->rowMarks = lappend(root->rowMarks, newrc);
1558  }
1559 
1560  /* Close child relations, but keep locks */
1561  if (childOID != parentOID)
1562  heap_close(newrelation, NoLock);
1563  }
1564 
1565  heap_close(oldrelation, NoLock);
1566 
1567  /*
1568  * If all the children were temp tables or a partitioned parent did not
1569  * have any leaf partitions, pretend it's a non-inheritance situation; we
1570  * don't need Append node in that case. The duplicate RTE we added for
1571  * the parent table is harmless, so we don't bother to get rid of it;
1572  * ditto for the useless PlanRowMark node.
1573  */
1574  if (!need_append)
1575  {
1576  /* Clear flag before returning */
1577  rte->inh = false;
1578  return;
1579  }
1580 
1581  /*
1582  * We keep a list of objects in root, each of which maps a partitioned
1583  * parent RT index to the list of RT indexes of its partitioned child
1584  * tables. When creating an Append or a ModifyTable path for the parent,
1585  * we copy the child RT index list verbatim to the path so that it could
1586  * be carried over to the executor so that the latter could identify
1587  * the partitioned child tables.
1588  */
1589  if (partitioned_child_rels != NIL)
1590  {
1592 
1594  pcinfo->parent_relid = rti;
1595  pcinfo->child_rels = partitioned_child_rels;
1596  root->pcinfo_list = lappend(root->pcinfo_list, pcinfo);
1597  }
1598 
1599  /* Otherwise, OK to add to root->append_rel_list */
1600  root->append_rel_list = list_concat(root->append_rel_list, appinfos);
1601 }
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:255
Query * parse
Definition: relation.h:154
RowMarkType markType
Definition: plannodes.h:981
int LOCKMODE
Definition: lockdefs.h:26
RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength)
Definition: planner.c:2263
List * securityQuals
Definition: parsenodes.h:1009
int resultRelation
Definition: parsenodes.h:113
#define AccessShareLock
Definition: lockdefs.h:36
Index prti
Definition: plannodes.h:979
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:1718
AclMode requiredPerms
Definition: parsenodes.h:1004
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
Index rowmarkId
Definition: plannodes.h:980
LockWaitPolicy waitPolicy
Definition: plannodes.h:984
List * translated_vars
Definition: relation.h:1935
#define RowMarkRequiresRowShareLock(marktype)
Definition: plannodes.h:934
Oid parent_reltype
Definition: relation.h:1916
void * copyObject(const void *from)
Definition: copyfuncs.c:4619
Bitmapset * selectedCols
Definition: parsenodes.h:1006
bool has_subclass(Oid relationId)
Definition: pg_inherits.c:242
List * rtable
Definition: parsenodes.h:128
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
int allMarkTypes
Definition: plannodes.h:982
List * lappend_int(List *list, int datum)
Definition: list.c:146
List * lappend(List *list, void *datum)
Definition: list.c:128
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define RowShareLock
Definition: lockdefs.h:37
List * append_rel_list
Definition: relation.h:251
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1287
unsigned int Index
Definition: c.h:365
Bitmapset * updatedCols
Definition: parsenodes.h:1008
Index rti
Definition: plannodes.h:978
#define makeNode(_type_)
Definition: nodes.h:552
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
List * pcinfo_list
Definition: relation.h:253
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:534
LockClauseStrength strength
Definition: plannodes.h:983
static int list_length(const List *l)
Definition: pg_list.h:89
Oid child_reltype
Definition: relation.h:1917
static void make_inh_translation_list(Relation oldrelation, Relation newrelation, Index newvarno, List **translated_vars)
Definition: prepunion.c:1611
RTEKind rtekind
Definition: parsenodes.h:916
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:158
Bitmapset * insertedCols
Definition: parsenodes.h:1007
PlanRowMark * get_plan_rowmark(List *rowmarks, Index rtindex)
Definition: preptlist.c:401
bool isParent
Definition: plannodes.h:985
Index child_relid
Definition: relation.h:1908
Oid parent_reloid
Definition: relation.h:1942
Index parent_relid
Definition: relation.h:1907
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:649
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:154
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:365
#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:1077
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:504
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1354
signed int int32
Definition: c.h:256
void pfree(void *pointer)
Definition: mcxt.c:950
bool resjunk
Definition: primnodes.h:1359
char * flag(int b)
Definition: test-ctype.c:33
AttrNumber resno
Definition: primnodes.h:1353
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:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1352
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:849
Index ressortgroupref
Definition: primnodes.h:1355
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, NIL);
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:918
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:2946
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:865
static List * generate_setop_grouplist(SetOperationStmt *op, List *targetlist)
Definition: prepunion.c:1275
#define Min(x, y)
Definition: c.h:806
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers, List *partitioned_rels)
Definition: pathnode.c:1203
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:290
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
#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:1533
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2486
#define NULL
Definition: c.h:229
double rows
Definition: relation.h:928
static int list_length(const List *l)
Definition: pg_list.h:89
SetOperation op
Definition: parsenodes.h:1524
SetOpCmd
Definition: nodes.h:766
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Definition: relation.h:911
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:307
#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:3008
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
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:1533
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
struct Path * non_recursive_path
Definition: relation.h:308
SetOperation op
Definition: parsenodes.h:1524
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
Definition: relation.h:911
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:1141
void * copyObject(const void *from)
Definition: copyfuncs.c:4619
bool resjunk
Definition: primnodes.h:1359
AttrNumber resno
Definition: primnodes.h:1353
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:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1355
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:555
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:1077
#define INT4OID
Definition: pg_type.h:316
Definition: nodes.h:504
unsigned int Oid
Definition: postgres_ext.h:31
char * resname
Definition: primnodes.h:1354
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:256
bool resjunk
Definition: primnodes.h:1359
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:1353
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:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1352
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:745
#define Int32GetDatum(X)
Definition: postgres.h:485
Index ressortgroupref
Definition: primnodes.h:1355
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(), NIL, 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, NIL);
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 }
#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:918
static List * recurse_union_children(Node *setOp, PlannerInfo *root, SetOperationStmt *top_union, List *refnames_tlist, List **tlist_list)
Definition: prepunion.c:775
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
AppendPath * create_append_path(RelOptInfo *rel, List *subpaths, Relids required_outer, int parallel_workers, List *partitioned_rels)
Definition: pathnode.c:1203
double tuple_fraction
Definition: relation.h:290
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
List * colCollations
Definition: parsenodes.h:1533
#define NULL
Definition: c.h:229
double rows
Definition: relation.h:928
Definition: pg_list.h:45
Definition: relation.h:911
static void make_inh_translation_list ( Relation  oldrelation,
Relation  newrelation,
Index  newvarno,
List **  translated_vars 
)
static

Definition at line 1611 of file prepunion.c.

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

Referenced by expand_inherited_rtentry().

1614 {
1615  List *vars = NIL;
1616  TupleDesc old_tupdesc = RelationGetDescr(oldrelation);
1617  TupleDesc new_tupdesc = RelationGetDescr(newrelation);
1618  int oldnatts = old_tupdesc->natts;
1619  int newnatts = new_tupdesc->natts;
1620  int old_attno;
1621 
1622  for (old_attno = 0; old_attno < oldnatts; old_attno++)
1623  {
1624  Form_pg_attribute att;
1625  char *attname;
1626  Oid atttypid;
1627  int32 atttypmod;
1628  Oid attcollation;
1629  int new_attno;
1630 
1631  att = old_tupdesc->attrs[old_attno];
1632  if (att->attisdropped)
1633  {
1634  /* Just put NULL into this list entry */
1635  vars = lappend(vars, NULL);
1636  continue;
1637  }
1638  attname = NameStr(att->attname);
1639  atttypid = att->atttypid;
1640  atttypmod = att->atttypmod;
1641  attcollation = att->attcollation;
1642 
1643  /*
1644  * When we are generating the "translation list" for the parent table
1645  * of an inheritance set, no need to search for matches.
1646  */
1647  if (oldrelation == newrelation)
1648  {
1649  vars = lappend(vars, makeVar(newvarno,
1650  (AttrNumber) (old_attno + 1),
1651  atttypid,
1652  atttypmod,
1653  attcollation,
1654  0));
1655  continue;
1656  }
1657 
1658  /*
1659  * Otherwise we have to search for the matching column by name.
1660  * There's no guarantee it'll have the same column position, because
1661  * of cases like ALTER TABLE ADD COLUMN and multiple inheritance.
1662  * However, in simple cases it will be the same column number, so try
1663  * that before we go groveling through all the columns.
1664  *
1665  * Note: the test for (att = ...) != NULL cannot fail, it's just a
1666  * notational device to include the assignment into the if-clause.
1667  */
1668  if (old_attno < newnatts &&
1669  (att = new_tupdesc->attrs[old_attno]) != NULL &&
1670  !att->attisdropped && att->attinhcount != 0 &&
1671  strcmp(attname, NameStr(att->attname)) == 0)
1672  new_attno = old_attno;
1673  else
1674  {
1675  for (new_attno = 0; new_attno < newnatts; new_attno++)
1676  {
1677  att = new_tupdesc->attrs[new_attno];
1678  if (!att->attisdropped && att->attinhcount != 0 &&
1679  strcmp(attname, NameStr(att->attname)) == 0)
1680  break;
1681  }
1682  if (new_attno >= newnatts)
1683  elog(ERROR, "could not find inherited attribute \"%s\" of relation \"%s\"",
1684  attname, RelationGetRelationName(newrelation));
1685  }
1686 
1687  /* Found it, check type and collation match */
1688  if (atttypid != att->atttypid || atttypmod != att->atttypmod)
1689  elog(ERROR, "attribute \"%s\" of relation \"%s\" does not match parent's type",
1690  attname, RelationGetRelationName(newrelation));
1691  if (attcollation != att->attcollation)
1692  elog(ERROR, "attribute \"%s\" of relation \"%s\" does not match parent's collation",
1693  attname, RelationGetRelationName(newrelation));
1694 
1695  vars = lappend(vars, makeVar(newvarno,
1696  (AttrNumber) (new_attno + 1),
1697  atttypid,
1698  atttypmod,
1699  attcollation,
1700  0));
1701  }
1702 
1703  *translated_vars = vars;
1704 }
#define NIL
Definition: pg_list.h:69
#define RelationGetDescr(relation)
Definition: rel.h:429
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:256
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
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:229
#define NameStr(name)
Definition: c.h:499
#define elog
Definition: elog.h:219
Definition: regcomp.c:224
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:918
List * make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist)
Definition: pathkeys.c:865
UpperUniquePath * create_upper_unique_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, int numCols, double numGroups)
Definition: pathnode.c:2588
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:895
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:2640
#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:2486
List * pathkeys
Definition: relation.h:932
#define NULL
Definition: c.h:229
double rows
Definition: relation.h:928
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
Definition: relation.h:911
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:555
Query * parse
Definition: relation.h:154
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:573
Definition: nodes.h:504
List * fromlist
Definition: primnodes.h:1455
create_upper_paths_hook_type create_upper_paths_hook
Definition: planner.c:68
bool hasRecursion
Definition: relation.h:304
Node * quals
Definition: primnodes.h:1456
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:895
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:187
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
List * colCollations
Definition: parsenodes.h:1533
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:62
Node * setOperations
Definition: parsenodes.h:154
Query * subquery
Definition: parsenodes.h:934
List * groupClause
Definition: parsenodes.h:137
Node * havingQual
Definition: parsenodes.h:141
List * processed_tlist
Definition: relation.h:280
Definition: pg_list.h:45
Definition: relation.h:911
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
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:2343
void set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4474
#define NIL
Definition: pg_list.h:69
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset)
Definition: selfuncs.c:3277
#define IsA(nodeptr, _type_)
Definition: nodes.h:555
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:1769
List * plan_params
Definition: relation.h:168
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:536
double tuple_fraction
Definition: relation.h:290
List * distinctClause
Definition: parsenodes.h:145
#define ERROR
Definition: elog.h:43
RelOptInfo * parent
Definition: relation.h:917
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:895
PlannerGlobal * glob
Definition: relation.h:156
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:187
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:91
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
SetOperation op
Definition: parsenodes.h:1524
#define nodeTag(nodeptr)
Definition: nodes.h:509
Query * subquery
Definition: parsenodes.h:934
List * groupClause
Definition: parsenodes.h:137
bool hasHavingQual
Definition: relation.h:301
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:280
Definition: pg_list.h:45
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:455
Definition: relation.h:911
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5229
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, recurse_set_operations(), and result.

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:555
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:2946
List * list_concat(List *list1, List *list2)
Definition: list.c:321
return result
Definition: formatting.c:1618
#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:1533
#define NULL
Definition: c.h:229
SetOperation op
Definition: parsenodes.h:1524
Definition: pg_list.h:45
static Bitmapset * translate_col_privs ( const Bitmapset parent_privs,
List translated_vars 
)
static

Definition at line 1718 of file prepunion.c.

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

Referenced by expand_inherited_rtentry().

1720 {
1721  Bitmapset *child_privs = NULL;
1722  bool whole_row;
1723  int attno;
1724  ListCell *lc;
1725 
1726  /* System attributes have the same numbers in all tables */
1727  for (attno = FirstLowInvalidHeapAttributeNumber + 1; attno < 0; attno++)
1728  {
1730  parent_privs))
1731  child_privs = bms_add_member(child_privs,
1733  }
1734 
1735  /* Check if parent has whole-row reference */
1737  parent_privs);
1738 
1739  /* And now translate the regular user attributes, using the vars list */
1740  attno = InvalidAttrNumber;
1741  foreach(lc, translated_vars)
1742  {
1743  Var *var = castNode(Var, lfirst(lc));
1744 
1745  attno++;
1746  if (var == NULL) /* ignore dropped columns */
1747  continue;
1748  if (whole_row ||
1750  parent_privs))
1751  child_privs = bms_add_member(child_privs,
1753  }
1754 
1755  return child_privs;
1756 }
#define castNode(_type_, nodeptr)
Definition: nodes.h:573
AttrNumber varattno
Definition: primnodes.h:168
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
Definition: primnodes.h:163
#define NULL
Definition: c.h:229
#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