PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_agg.h File Reference
Include dependency graph for parse_agg.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

void transformAggregateCall (ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
 
NodetransformGroupingFunc (ParseState *pstate, GroupingFunc *g)
 
void transformWindowFuncCall (ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
 
void parseCheckAggregates (ParseState *pstate, Query *qry)
 
Listexpand_grouping_sets (List *groupingSets, int limit)
 
int get_aggregate_argtypes (Aggref *aggref, Oid *inputTypes)
 
Oid resolve_aggregate_transtype (Oid aggfuncid, Oid aggtranstype, Oid *inputTypes, int numArguments)
 
void build_aggregate_transfn_expr (Oid *agg_input_types, int agg_num_inputs, int agg_num_direct_inputs, bool agg_variadic, Oid agg_state_type, Oid agg_input_collation, Oid transfn_oid, Oid invtransfn_oid, Expr **transfnexpr, Expr **invtransfnexpr)
 
void build_aggregate_combinefn_expr (Oid agg_state_type, Oid agg_input_collation, Oid combinefn_oid, Expr **combinefnexpr)
 
void build_aggregate_serialfn_expr (Oid serialfn_oid, Expr **serialfnexpr)
 
void build_aggregate_deserialfn_expr (Oid deserialfn_oid, Expr **deserialfnexpr)
 
void build_aggregate_finalfn_expr (Oid *agg_input_types, int num_finalfn_inputs, Oid agg_state_type, Oid agg_result_type, Oid agg_input_collation, Oid finalfn_oid, Expr **finalfnexpr)
 

Function Documentation

void build_aggregate_combinefn_expr ( Oid  agg_state_type,
Oid  agg_input_collation,
Oid  combinefn_oid,
Expr **  combinefnexpr 
)

Definition at line 1928 of file parse_agg.c.

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, InvalidOid, list_make2, make_agg_arg(), and makeFuncExpr().

Referenced by build_pertrans_for_aggref().

1932 {
1933  Node *argp;
1934  List *args;
1935  FuncExpr *fexpr;
1936 
1937  /* combinefn takes two arguments of the aggregate state type */
1938  argp = make_agg_arg(agg_state_type, agg_input_collation);
1939 
1940  args = list_make2(argp, argp);
1941 
1942  fexpr = makeFuncExpr(combinefn_oid,
1943  agg_state_type,
1944  args,
1945  InvalidOid,
1946  agg_input_collation,
1948  /* combinefn is currently never treated as variadic */
1949  *combinefnexpr = (Expr *) fexpr;
1950 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2044
Definition: nodes.h:506
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:45
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:516
void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 1980 of file parse_agg.c.

References generate_unaccent_rules::args, BYTEAOID, COERCE_EXPLICIT_CALL, INTERNALOID, InvalidOid, list_make2, make_agg_arg(), and makeFuncExpr().

Referenced by build_pertrans_for_aggref().

1982 {
1983  List *args;
1984  FuncExpr *fexpr;
1985 
1986  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
1989 
1990  fexpr = makeFuncExpr(deserialfn_oid,
1991  INTERNALOID,
1992  args,
1993  InvalidOid,
1994  InvalidOid,
1996  *deserialfnexpr = (Expr *) fexpr;
1997 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2044
#define InvalidOid
Definition: postgres_ext.h:36
#define INTERNALOID
Definition: pg_type.h:694
#define BYTEAOID
Definition: pg_type.h:292
Definition: pg_list.h:45
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:516
void build_aggregate_finalfn_expr ( Oid agg_input_types,
int  num_finalfn_inputs,
Oid  agg_state_type,
Oid  agg_result_type,
Oid  agg_input_collation,
Oid  finalfn_oid,
Expr **  finalfnexpr 
)

Definition at line 2004 of file parse_agg.c.

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, i, InvalidOid, lappend(), list_make1, make_agg_arg(), and makeFuncExpr().

Referenced by ExecInitAgg(), and initialize_peragg().

2011 {
2012  List *args;
2013  int i;
2014 
2015  /*
2016  * Build expr tree for final function
2017  */
2018  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2019 
2020  /* finalfn may take additional args, which match agg's input types */
2021  for (i = 0; i < num_finalfn_inputs - 1; i++)
2022  {
2023  args = lappend(args,
2024  make_agg_arg(agg_input_types[i], agg_input_collation));
2025  }
2026 
2027  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2028  agg_result_type,
2029  args,
2030  InvalidOid,
2031  agg_input_collation,
2033  /* finalfn is currently never treated as variadic */
2034 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2044
#define list_make1(x1)
Definition: pg_list.h:133
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:45
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:516
void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 1957 of file parse_agg.c.

References generate_unaccent_rules::args, BYTEAOID, COERCE_EXPLICIT_CALL, INTERNALOID, InvalidOid, list_make1, make_agg_arg(), and makeFuncExpr().

Referenced by build_pertrans_for_aggref().

1959 {
1960  List *args;
1961  FuncExpr *fexpr;
1962 
1963  /* serialfn always takes INTERNAL and returns BYTEA */
1965 
1966  fexpr = makeFuncExpr(serialfn_oid,
1967  BYTEAOID,
1968  args,
1969  InvalidOid,
1970  InvalidOid,
1972  *serialfnexpr = (Expr *) fexpr;
1973 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2044
#define list_make1(x1)
Definition: pg_list.h:133
#define InvalidOid
Definition: postgres_ext.h:36
#define INTERNALOID
Definition: pg_type.h:694
#define BYTEAOID
Definition: pg_type.h:292
Definition: pg_list.h:45
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:516
void build_aggregate_transfn_expr ( Oid agg_input_types,
int  agg_num_inputs,
int  agg_num_direct_inputs,
bool  agg_variadic,
Oid  agg_state_type,
Oid  agg_input_collation,
Oid  transfn_oid,
Oid  invtransfn_oid,
Expr **  transfnexpr,
Expr **  invtransfnexpr 
)

Definition at line 1867 of file parse_agg.c.

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, FuncExpr::funcvariadic, i, InvalidOid, lappend(), list_make1, make_agg_arg(), makeFuncExpr(), NULL, and OidIsValid.

Referenced by build_pertrans_for_aggref(), and initialize_peragg().

1877 {
1878  List *args;
1879  FuncExpr *fexpr;
1880  int i;
1881 
1882  /*
1883  * Build arg list to use in the transfn FuncExpr node.
1884  */
1885  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1886 
1887  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1888  {
1889  args = lappend(args,
1890  make_agg_arg(agg_input_types[i], agg_input_collation));
1891  }
1892 
1893  fexpr = makeFuncExpr(transfn_oid,
1894  agg_state_type,
1895  args,
1896  InvalidOid,
1897  agg_input_collation,
1899  fexpr->funcvariadic = agg_variadic;
1900  *transfnexpr = (Expr *) fexpr;
1901 
1902  /*
1903  * Build invtransfn expression if requested, with same args as transfn
1904  */
1905  if (invtransfnexpr != NULL)
1906  {
1907  if (OidIsValid(invtransfn_oid))
1908  {
1909  fexpr = makeFuncExpr(invtransfn_oid,
1910  agg_state_type,
1911  args,
1912  InvalidOid,
1913  agg_input_collation,
1915  fexpr->funcvariadic = agg_variadic;
1916  *invtransfnexpr = (Expr *) fexpr;
1917  }
1918  else
1919  *invtransfnexpr = NULL;
1920  }
1921 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2044
#define OidIsValid(objectId)
Definition: c.h:538
#define list_make1(x1)
Definition: pg_list.h:133
List * lappend(List *list, void *datum)
Definition: list.c:128
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
int i
Definition: pg_list.h:45
bool funcvariadic
Definition: primnodes.h:451
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:516
List* expand_grouping_sets ( List groupingSets,
int  limit 
)

Definition at line 1687 of file parse_agg.c.

References Assert, buf, cmp_list_len_asc(), expand_groupingset_node(), for_each_cell, lappend(), lfirst, linitial, list_head(), list_length(), list_union_int(), lnext, NIL, palloc(), pfree(), qsort, and result.

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1688 {
1689  List *expanded_groups = NIL;
1690  List *result = NIL;
1691  double numsets = 1;
1692  ListCell *lc;
1693 
1694  if (groupingSets == NIL)
1695  return NIL;
1696 
1697  foreach(lc, groupingSets)
1698  {
1699  List *current_result = NIL;
1700  GroupingSet *gs = lfirst(lc);
1701 
1702  current_result = expand_groupingset_node(gs);
1703 
1704  Assert(current_result != NIL);
1705 
1706  numsets *= list_length(current_result);
1707 
1708  if (limit >= 0 && numsets > limit)
1709  return NIL;
1710 
1711  expanded_groups = lappend(expanded_groups, current_result);
1712  }
1713 
1714  /*
1715  * Do cartesian product between sublists of expanded_groups. While at it,
1716  * remove any duplicate elements from individual grouping sets (we must
1717  * NOT change the number of sets though)
1718  */
1719 
1720  foreach(lc, (List *) linitial(expanded_groups))
1721  {
1722  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1723  }
1724 
1725  for_each_cell(lc, lnext(list_head(expanded_groups)))
1726  {
1727  List *p = lfirst(lc);
1728  List *new_result = NIL;
1729  ListCell *lc2;
1730 
1731  foreach(lc2, result)
1732  {
1733  List *q = lfirst(lc2);
1734  ListCell *lc3;
1735 
1736  foreach(lc3, p)
1737  {
1738  new_result = lappend(new_result,
1739  list_union_int(q, (List *) lfirst(lc3)));
1740  }
1741  }
1742  result = new_result;
1743  }
1744 
1745  if (list_length(result) > 1)
1746  {
1747  int result_len = list_length(result);
1748  List **buf = palloc(sizeof(List *) * result_len);
1749  List **ptr = buf;
1750 
1751  foreach(lc, result)
1752  {
1753  *ptr++ = lfirst(lc);
1754  }
1755 
1756  qsort(buf, result_len, sizeof(List *), cmp_list_len_asc);
1757 
1758  result = NIL;
1759  ptr = buf;
1760 
1761  while (result_len-- > 0)
1762  result = lappend(result, *ptr++);
1763 
1764  pfree(buf);
1765  }
1766 
1767  return result;
1768 }
static int cmp_list_len_asc(const void *a, const void *b)
Definition: parse_agg.c:1671
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1618
void pfree(void *pointer)
Definition: mcxt.c:950
#define linitial(l)
Definition: pg_list.h:110
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1566
static char * buf
Definition: pg_test_fsync.c:65
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:744
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
#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 for_each_cell(cell, initcell)
Definition: pg_list.h:163
void * palloc(Size size)
Definition: mcxt.c:849
#define qsort(a, b, c, d)
Definition: port.h:440
Definition: pg_list.h:45
int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1786 of file parse_agg.c.

References Aggref::aggargtypes, Assert, FUNC_MAX_ARGS, lfirst_oid, and list_length().

Referenced by ExecInitAgg(), get_agg_clause_costs_walker(), and get_agg_expr().

1787 {
1788  int numArguments = 0;
1789  ListCell *lc;
1790 
1792 
1793  foreach(lc, aggref->aggargtypes)
1794  {
1795  inputTypes[numArguments++] = lfirst_oid(lc);
1796  }
1797 
1798  return numArguments;
1799 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:299
#define Assert(condition)
Definition: c.h:675
static int list_length(const List *l)
Definition: pg_list.h:89
#define lfirst_oid(lc)
Definition: pg_list.h:108
void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 977 of file parse_agg.c.

References Assert, check_ungrouped_columns(), CurrentMemoryContext, ereport, errcode(), errmsg(), ERROR, expand_grouping_sets(), TargetEntry::expr, exprLocation(), finalize_grouping_exprs(), flatten_join_alias_vars(), for_each_cell, get_sortgroupclause_tle(), Query::groupClause, Query::groupingSets, PlannerInfo::hasJoinRTEs, Query::havingQual, IsA, lappend(), lcons(), lfirst, linitial, list_head(), list_intersection_int(), list_length(), list_member_int(), lnext, locate_agg_of_level(), makeNode, NIL, NULL, ParseState::p_hasAggs, ParseState::p_rtable, PlannerInfo::parse, parser_errposition(), PlannerInfo::planner_cxt, TargetEntry::ressortgroupref, RTE_CTE, RTE_JOIN, RangeTblEntry::rtekind, RangeTblEntry::self_reference, and Query::targetList.

Referenced by transformDeleteStmt(), transformSelectStmt(), and transformSetOperationStmt().

978 {
979  List *gset_common = NIL;
980  List *groupClauses = NIL;
981  List *groupClauseCommonVars = NIL;
982  bool have_non_var_grouping;
983  List *func_grouped_rels = NIL;
984  ListCell *l;
985  bool hasJoinRTEs;
986  bool hasSelfRefRTEs;
987  PlannerInfo *root = NULL;
988  Node *clause;
989 
990  /* This should only be called if we found aggregates or grouping */
991  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
992 
993  /*
994  * If we have grouping sets, expand them and find the intersection of all
995  * sets.
996  */
997  if (qry->groupingSets)
998  {
999  /*
1000  * The limit of 4096 is arbitrary and exists simply to avoid resource
1001  * issues from pathological constructs.
1002  */
1003  List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
1004 
1005  if (!gsets)
1006  ereport(ERROR,
1007  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1008  errmsg("too many grouping sets present (maximum 4096)"),
1009  parser_errposition(pstate,
1010  qry->groupClause
1011  ? exprLocation((Node *) qry->groupClause)
1012  : exprLocation((Node *) qry->groupingSets))));
1013 
1014  /*
1015  * The intersection will often be empty, so help things along by
1016  * seeding the intersect with the smallest set.
1017  */
1018  gset_common = linitial(gsets);
1019 
1020  if (gset_common)
1021  {
1022  for_each_cell(l, lnext(list_head(gsets)))
1023  {
1024  gset_common = list_intersection_int(gset_common, lfirst(l));
1025  if (!gset_common)
1026  break;
1027  }
1028  }
1029 
1030  /*
1031  * If there was only one grouping set in the expansion, AND if the
1032  * groupClause is non-empty (meaning that the grouping set is not
1033  * empty either), then we can ditch the grouping set and pretend we
1034  * just had a normal GROUP BY.
1035  */
1036  if (list_length(gsets) == 1 && qry->groupClause)
1037  qry->groupingSets = NIL;
1038  }
1039 
1040  /*
1041  * Scan the range table to see if there are JOIN or self-reference CTE
1042  * entries. We'll need this info below.
1043  */
1044  hasJoinRTEs = hasSelfRefRTEs = false;
1045  foreach(l, pstate->p_rtable)
1046  {
1047  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1048 
1049  if (rte->rtekind == RTE_JOIN)
1050  hasJoinRTEs = true;
1051  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1052  hasSelfRefRTEs = true;
1053  }
1054 
1055  /*
1056  * Build a list of the acceptable GROUP BY expressions for use by
1057  * check_ungrouped_columns().
1058  *
1059  * We get the TLE, not just the expr, because GROUPING wants to know the
1060  * sortgroupref.
1061  */
1062  foreach(l, qry->groupClause)
1063  {
1064  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1065  TargetEntry *expr;
1066 
1067  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1068  if (expr == NULL)
1069  continue; /* probably cannot happen */
1070 
1071  groupClauses = lcons(expr, groupClauses);
1072  }
1073 
1074  /*
1075  * If there are join alias vars involved, we have to flatten them to the
1076  * underlying vars, so that aliased and unaliased vars will be correctly
1077  * taken as equal. We can skip the expense of doing this if no rangetable
1078  * entries are RTE_JOIN kind. We use the planner's flatten_join_alias_vars
1079  * routine to do the flattening; it wants a PlannerInfo root node, which
1080  * fortunately can be mostly dummy.
1081  */
1082  if (hasJoinRTEs)
1083  {
1084  root = makeNode(PlannerInfo);
1085  root->parse = qry;
1087  root->hasJoinRTEs = true;
1088 
1089  groupClauses = (List *) flatten_join_alias_vars(root,
1090  (Node *) groupClauses);
1091  }
1092 
1093  /*
1094  * Detect whether any of the grouping expressions aren't simple Vars; if
1095  * they're all Vars then we don't have to work so hard in the recursive
1096  * scans. (Note we have to flatten aliases before this.)
1097  *
1098  * Track Vars that are included in all grouping sets separately in
1099  * groupClauseCommonVars, since these are the only ones we can use to
1100  * check for functional dependencies.
1101  */
1102  have_non_var_grouping = false;
1103  foreach(l, groupClauses)
1104  {
1105  TargetEntry *tle = lfirst(l);
1106 
1107  if (!IsA(tle->expr, Var))
1108  {
1109  have_non_var_grouping = true;
1110  }
1111  else if (!qry->groupingSets ||
1112  list_member_int(gset_common, tle->ressortgroupref))
1113  {
1114  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1115  }
1116  }
1117 
1118  /*
1119  * Check the targetlist and HAVING clause for ungrouped variables.
1120  *
1121  * Note: because we check resjunk tlist elements as well as regular ones,
1122  * this will also find ungrouped variables that came from ORDER BY and
1123  * WINDOW clauses. For that matter, it's also going to examine the
1124  * grouping expressions themselves --- but they'll all pass the test ...
1125  *
1126  * We also finalize GROUPING expressions, but for that we need to traverse
1127  * the original (unflattened) clause in order to modify nodes.
1128  */
1129  clause = (Node *) qry->targetList;
1130  finalize_grouping_exprs(clause, pstate, qry,
1131  groupClauses, root,
1132  have_non_var_grouping);
1133  if (hasJoinRTEs)
1134  clause = flatten_join_alias_vars(root, clause);
1135  check_ungrouped_columns(clause, pstate, qry,
1136  groupClauses, groupClauseCommonVars,
1137  have_non_var_grouping,
1138  &func_grouped_rels);
1139 
1140  clause = (Node *) qry->havingQual;
1141  finalize_grouping_exprs(clause, pstate, qry,
1142  groupClauses, root,
1143  have_non_var_grouping);
1144  if (hasJoinRTEs)
1145  clause = flatten_join_alias_vars(root, clause);
1146  check_ungrouped_columns(clause, pstate, qry,
1147  groupClauses, groupClauseCommonVars,
1148  have_non_var_grouping,
1149  &func_grouped_rels);
1150 
1151  /*
1152  * Per spec, aggregates can't appear in a recursive term.
1153  */
1154  if (pstate->p_hasAggs && hasSelfRefRTEs)
1155  ereport(ERROR,
1156  (errcode(ERRCODE_INVALID_RECURSION),
1157  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1158  parser_errposition(pstate,
1159  locate_agg_of_level((Node *) qry, 0))));
1160 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Query * parse
Definition: relation.h:154
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
bool hasJoinRTEs
Definition: relation.h:298
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:826
List * groupingSets
Definition: parsenodes.h:139
Definition: nodes.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
bool p_hasAggs
Definition: parse_node.h:192
Definition: primnodes.h:163
List * targetList
Definition: parsenodes.h:131
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseVars, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1184
#define linitial(l)
Definition: pg_list.h:110
#define ERROR
Definition: elog.h:43
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, PlannerInfo *root, bool have_non_var_grouping)
Definition: parse_agg.c:1392
bool list_member_int(const List *list, int datum)
Definition: list.c:485
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
Node * flatten_join_alias_vars(PlannerInfo *root, Node *node)
Definition: var.c:670
bool self_reference
Definition: parsenodes.h:983
List * lcons(void *datum, List *list)
Definition: list.c:259
#define makeNode(_type_)
Definition: nodes.h:554
#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
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
#define for_each_cell(cell, initcell)
Definition: pg_list.h:163
List * expand_grouping_sets(List *groupingSets, int limit)
Definition: parse_agg.c:1687
RTEKind rtekind
Definition: parsenodes.h:916
List * groupClause
Definition: parsenodes.h:137
int errmsg(const char *fmt,...)
Definition: elog.c:797
Index ressortgroupref
Definition: primnodes.h:1355
MemoryContext planner_cxt
Definition: relation.h:286
Node * havingQual
Definition: parsenodes.h:141
Definition: pg_list.h:45
List * p_rtable
Definition: parse_node.h:168
Oid resolve_aggregate_transtype ( Oid  aggfuncid,
Oid  aggtranstype,
Oid inputTypes,
int  numArguments 
)

Definition at line 1812 of file parse_agg.c.

References Assert, enforce_generic_type_consistency(), get_func_signature(), IsPolymorphicType, and pfree().

Referenced by get_agg_clause_costs_walker(), and initialize_peragg().

1816 {
1817  /* resolve actual type of transition state, if polymorphic */
1818  if (IsPolymorphicType(aggtranstype))
1819  {
1820  /* have to fetch the agg's declared input types... */
1821  Oid *declaredArgTypes;
1822  int agg_nargs;
1823 
1824  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1825 
1826  /*
1827  * VARIADIC ANY aggs could have more actual than declared args, but
1828  * such extra args can't affect polymorphic type resolution.
1829  */
1830  Assert(agg_nargs <= numArguments);
1831 
1832  aggtranstype = enforce_generic_type_consistency(inputTypes,
1833  declaredArgTypes,
1834  agg_nargs,
1835  aggtranstype,
1836  false);
1837  pfree(declaredArgTypes);
1838  }
1839  return aggtranstype;
1840 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1468
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:950
#define IsPolymorphicType(typid)
Definition: pg_type.h:741
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
#define Assert(condition)
Definition: c.h:675
void transformAggregateCall ( ParseState pstate,
Aggref agg,
List args,
List aggorder,
bool  agg_distinct 
)

Definition at line 103 of file parse_agg.c.

References addTargetToSortList(), Aggref::aggargtypes, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggkind, AGGKIND_IS_ORDERED_SET, Aggref::aggorder, arg, Aggref::args, Assert, check_agglevels_and_constraints(), ereport, errcode(), errdetail(), errmsg(), ERROR, EXPR_KIND_ORDER_BY, exprLocation(), exprType(), forboth, format_type_be(), get_sortgroupclause_expr(), lappend(), lappend_oid(), lfirst, list_copy_tail(), list_length(), list_truncate(), makeTargetEntry(), NIL, NULL, OidIsValid, ParseState::p_next_resno, parser_errposition(), SortGroupClause::sortop, transformDistinctClause(), and transformSortClause().

Referenced by ParseFuncOrColumn().

105 {
106  List *argtypes = NIL;
107  List *tlist = NIL;
108  List *torder = NIL;
109  List *tdistinct = NIL;
110  AttrNumber attno = 1;
111  int save_next_resno;
112  ListCell *lc;
113 
114  /*
115  * Before separating the args into direct and aggregated args, make a list
116  * of their data type OIDs for use later.
117  */
118  foreach(lc, args)
119  {
120  Expr *arg = (Expr *) lfirst(lc);
121 
122  argtypes = lappend_oid(argtypes, exprType((Node *) arg));
123  }
124  agg->aggargtypes = argtypes;
125 
127  {
128  /*
129  * For an ordered-set agg, the args list includes direct args and
130  * aggregated args; we must split them apart.
131  */
132  int numDirectArgs = list_length(args) - list_length(aggorder);
133  List *aargs;
134  ListCell *lc2;
135 
136  Assert(numDirectArgs >= 0);
137 
138  aargs = list_copy_tail(args, numDirectArgs);
139  agg->aggdirectargs = list_truncate(args, numDirectArgs);
140 
141  /*
142  * Build a tlist from the aggregated args, and make a sortlist entry
143  * for each one. Note that the expressions in the SortBy nodes are
144  * ignored (they are the raw versions of the transformed args); we are
145  * just looking at the sort information in the SortBy nodes.
146  */
147  forboth(lc, aargs, lc2, aggorder)
148  {
149  Expr *arg = (Expr *) lfirst(lc);
150  SortBy *sortby = (SortBy *) lfirst(lc2);
151  TargetEntry *tle;
152 
153  /* We don't bother to assign column names to the entries */
154  tle = makeTargetEntry(arg, attno++, NULL, false);
155  tlist = lappend(tlist, tle);
156 
157  torder = addTargetToSortList(pstate, tle,
158  torder, tlist, sortby);
159  }
160 
161  /* Never any DISTINCT in an ordered-set agg */
162  Assert(!agg_distinct);
163  }
164  else
165  {
166  /* Regular aggregate, so it has no direct args */
167  agg->aggdirectargs = NIL;
168 
169  /*
170  * Transform the plain list of Exprs into a targetlist.
171  */
172  foreach(lc, args)
173  {
174  Expr *arg = (Expr *) lfirst(lc);
175  TargetEntry *tle;
176 
177  /* We don't bother to assign column names to the entries */
178  tle = makeTargetEntry(arg, attno++, NULL, false);
179  tlist = lappend(tlist, tle);
180  }
181 
182  /*
183  * If we have an ORDER BY, transform it. This will add columns to the
184  * tlist if they appear in ORDER BY but weren't already in the arg
185  * list. They will be marked resjunk = true so we can tell them apart
186  * from regular aggregate arguments later.
187  *
188  * We need to mess with p_next_resno since it will be used to number
189  * any new targetlist entries.
190  */
191  save_next_resno = pstate->p_next_resno;
192  pstate->p_next_resno = attno;
193 
194  torder = transformSortClause(pstate,
195  aggorder,
196  &tlist,
198  true /* force SQL99 rules */ );
199 
200  /*
201  * If we have DISTINCT, transform that to produce a distinctList.
202  */
203  if (agg_distinct)
204  {
205  tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
206 
207  /*
208  * Remove this check if executor support for hashed distinct for
209  * aggregates is ever added.
210  */
211  foreach(lc, tdistinct)
212  {
213  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
214 
215  if (!OidIsValid(sortcl->sortop))
216  {
217  Node *expr = get_sortgroupclause_expr(sortcl, tlist);
218 
219  ereport(ERROR,
220  (errcode(ERRCODE_UNDEFINED_FUNCTION),
221  errmsg("could not identify an ordering operator for type %s",
222  format_type_be(exprType(expr))),
223  errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
224  parser_errposition(pstate, exprLocation(expr))));
225  }
226  }
227  }
228 
229  pstate->p_next_resno = save_next_resno;
230  }
231 
232  /* Update the Aggref with the transformation results */
233  agg->args = tlist;
234  agg->aggorder = torder;
235  agg->aggdistinct = tdistinct;
236 
237  check_agglevels_and_constraints(pstate, (Node *) agg);
238 }
List * aggdistinct
Definition: primnodes.h:303
#define NIL
Definition: pg_list.h:69
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1204
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:382
Definition: nodes.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
List * args
Definition: primnodes.h:301
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:287
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
#define AGGKIND_IS_ORDERED_SET(kind)
Definition: pg_aggregate.h:129
List * aggargtypes
Definition: primnodes.h:299
#define ERROR
Definition: elog.h:43
List * aggorder
Definition: primnodes.h:302
int errdetail(const char *fmt,...)
Definition: elog.c:873
int p_next_resno
Definition: parse_node.h:183
List * aggdirectargs
Definition: primnodes.h:300
#define ereport(elevel, rest)
Definition: elog.h:122
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
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
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * arg
char aggkind
Definition: primnodes.h:308
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc g 
)

Definition at line 248 of file parse_agg.c.

References generate_unaccent_rules::args, GroupingFunc::args, check_agglevels_and_constraints(), ereport, errcode(), errmsg(), ERROR, lappend(), lfirst, list_length(), GroupingFunc::location, makeNode, NIL, ParseState::p_expr_kind, parser_errposition(), result, and transformExpr().

Referenced by transformExprRecurse().

249 {
250  ListCell *lc;
251  List *args = p->args;
252  List *result_list = NIL;
254 
255  if (list_length(args) > 31)
256  ereport(ERROR,
257  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
258  errmsg("GROUPING must have fewer than 32 arguments"),
259  parser_errposition(pstate, p->location)));
260 
261  foreach(lc, args)
262  {
263  Node *current_result;
264 
265  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
266 
267  /* acceptability of expressions is checked later */
268 
269  result_list = lappend(result_list, current_result);
270  }
271 
272  result->args = result_list;
273  result->location = p->location;
274 
275  check_agglevels_and_constraints(pstate, (Node *) result);
276 
277  return (Node *) result;
278 }
#define NIL
Definition: pg_list.h:69
List * args
Definition: primnodes.h:341
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:287
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
ParseExprKind p_expr_kind
Definition: parse_node.h:182
#define makeNode(_type_)
Definition: nodes.h:554
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45
void transformWindowFuncCall ( ParseState pstate,
WindowFunc wfunc,
WindowDef windef 
)

Definition at line 746 of file parse_agg.c.

References _, WindowFunc::args, Assert, contain_windowfuncs(), WindowDef::endOffset, equal(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, EXPR_KIND_ALTER_COL_TRANSFORM, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_DISTINCT_ON, EXPR_KIND_DOMAIN_CHECK, EXPR_KIND_EXECUTE_PARAMETER, EXPR_KIND_FILTER, EXPR_KIND_FROM_FUNCTION, EXPR_KIND_FROM_SUBSELECT, EXPR_KIND_FUNCTION_DEFAULT, EXPR_KIND_GROUP_BY, EXPR_KIND_HAVING, EXPR_KIND_INDEX_EXPRESSION, EXPR_KIND_INDEX_PREDICATE, EXPR_KIND_INSERT_TARGET, EXPR_KIND_JOIN_ON, EXPR_KIND_JOIN_USING, EXPR_KIND_LIMIT, EXPR_KIND_NONE, EXPR_KIND_OFFSET, EXPR_KIND_ORDER_BY, EXPR_KIND_OTHER, EXPR_KIND_PARTITION_EXPRESSION, EXPR_KIND_POLICY, EXPR_KIND_RETURNING, EXPR_KIND_SELECT_TARGET, EXPR_KIND_TRIGGER_WHEN, EXPR_KIND_UPDATE_SOURCE, EXPR_KIND_UPDATE_TARGET, EXPR_KIND_VALUES, EXPR_KIND_VALUES_SINGLE, EXPR_KIND_WHERE, EXPR_KIND_WINDOW_FRAME_RANGE, EXPR_KIND_WINDOW_FRAME_ROWS, EXPR_KIND_WINDOW_ORDER, EXPR_KIND_WINDOW_PARTITION, FRAMEOPTION_DEFAULTS, WindowDef::frameOptions, lappend(), lfirst, list_length(), locate_windowfunc(), WindowFunc::location, WindowDef::location, WindowDef::name, NIL, NULL, WindowDef::orderClause, ParseState::p_expr_kind, ParseState::p_hasWindowFuncs, ParseState::p_windowdefs, ParseExprKindName(), parser_errposition(), WindowDef::partitionClause, WindowDef::refname, WindowDef::startOffset, and WindowFunc::winref.

Referenced by ParseFuncOrColumn().

748 {
749  const char *err;
750  bool errkind;
751 
752  /*
753  * A window function call can't contain another one (but aggs are OK). XXX
754  * is this required by spec, or just an unimplemented feature?
755  *
756  * Note: we don't need to check the filter expression here, because the
757  * context checks done below and in transformAggregateCall would have
758  * already rejected any window funcs or aggs within the filter.
759  */
760  if (pstate->p_hasWindowFuncs &&
761  contain_windowfuncs((Node *) wfunc->args))
762  ereport(ERROR,
763  (errcode(ERRCODE_WINDOWING_ERROR),
764  errmsg("window function calls cannot be nested"),
765  parser_errposition(pstate,
766  locate_windowfunc((Node *) wfunc->args))));
767 
768  /*
769  * Check to see if the window function is in an invalid place within the
770  * query.
771  *
772  * For brevity we support two schemes for reporting an error here: set
773  * "err" to a custom message, or set "errkind" true if the error context
774  * is sufficiently identified by what ParseExprKindName will return, *and*
775  * what it will return is just a SQL keyword. (Otherwise, use a custom
776  * message to avoid creating translation problems.)
777  */
778  err = NULL;
779  errkind = false;
780  switch (pstate->p_expr_kind)
781  {
782  case EXPR_KIND_NONE:
783  Assert(false); /* can't happen */
784  break;
785  case EXPR_KIND_OTHER:
786  /* Accept window func here; caller must throw error if wanted */
787  break;
788  case EXPR_KIND_JOIN_ON:
790  err = _("window functions are not allowed in JOIN conditions");
791  break;
793  /* can't get here, but just in case, throw an error */
794  errkind = true;
795  break;
797  err = _("window functions are not allowed in functions in FROM");
798  break;
799  case EXPR_KIND_WHERE:
800  errkind = true;
801  break;
802  case EXPR_KIND_POLICY:
803  err = _("window functions are not allowed in policy expressions");
804  break;
805  case EXPR_KIND_HAVING:
806  errkind = true;
807  break;
808  case EXPR_KIND_FILTER:
809  errkind = true;
810  break;
815  err = _("window functions are not allowed in window definitions");
816  break;
818  /* okay */
819  break;
823  errkind = true;
824  break;
825  case EXPR_KIND_GROUP_BY:
826  errkind = true;
827  break;
828  case EXPR_KIND_ORDER_BY:
829  /* okay */
830  break;
832  /* okay */
833  break;
834  case EXPR_KIND_LIMIT:
835  case EXPR_KIND_OFFSET:
836  errkind = true;
837  break;
838  case EXPR_KIND_RETURNING:
839  errkind = true;
840  break;
841  case EXPR_KIND_VALUES:
843  errkind = true;
844  break;
847  err = _("window functions are not allowed in check constraints");
848  break;
851  err = _("window functions are not allowed in DEFAULT expressions");
852  break;
854  err = _("window functions are not allowed in index expressions");
855  break;
857  err = _("window functions are not allowed in index predicates");
858  break;
860  err = _("window functions are not allowed in transform expressions");
861  break;
863  err = _("window functions are not allowed in EXECUTE parameters");
864  break;
866  err = _("window functions are not allowed in trigger WHEN conditions");
867  break;
869  err = _("window functions are not allowed in partition key expression");
870  break;
871 
872  /*
873  * There is intentionally no default: case here, so that the
874  * compiler will warn if we add a new ParseExprKind without
875  * extending this switch. If we do see an unrecognized value at
876  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
877  * which is sane anyway.
878  */
879  }
880  if (err)
881  ereport(ERROR,
882  (errcode(ERRCODE_WINDOWING_ERROR),
883  errmsg_internal("%s", err),
884  parser_errposition(pstate, wfunc->location)));
885  if (errkind)
886  ereport(ERROR,
887  (errcode(ERRCODE_WINDOWING_ERROR),
888  /* translator: %s is name of a SQL construct, eg GROUP BY */
889  errmsg("window functions are not allowed in %s",
890  ParseExprKindName(pstate->p_expr_kind)),
891  parser_errposition(pstate, wfunc->location)));
892 
893  /*
894  * If the OVER clause just specifies a window name, find that WINDOW
895  * clause (which had better be present). Otherwise, try to match all the
896  * properties of the OVER clause, and make a new entry in the p_windowdefs
897  * list if no luck.
898  */
899  if (windef->name)
900  {
901  Index winref = 0;
902  ListCell *lc;
903 
904  Assert(windef->refname == NULL &&
905  windef->partitionClause == NIL &&
906  windef->orderClause == NIL &&
908 
909  foreach(lc, pstate->p_windowdefs)
910  {
911  WindowDef *refwin = (WindowDef *) lfirst(lc);
912 
913  winref++;
914  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
915  {
916  wfunc->winref = winref;
917  break;
918  }
919  }
920  if (lc == NULL) /* didn't find it? */
921  ereport(ERROR,
922  (errcode(ERRCODE_UNDEFINED_OBJECT),
923  errmsg("window \"%s\" does not exist", windef->name),
924  parser_errposition(pstate, windef->location)));
925  }
926  else
927  {
928  Index winref = 0;
929  ListCell *lc;
930 
931  foreach(lc, pstate->p_windowdefs)
932  {
933  WindowDef *refwin = (WindowDef *) lfirst(lc);
934 
935  winref++;
936  if (refwin->refname && windef->refname &&
937  strcmp(refwin->refname, windef->refname) == 0)
938  /* matched on refname */ ;
939  else if (!refwin->refname && !windef->refname)
940  /* matched, no refname */ ;
941  else
942  continue;
943  if (equal(refwin->partitionClause, windef->partitionClause) &&
944  equal(refwin->orderClause, windef->orderClause) &&
945  refwin->frameOptions == windef->frameOptions &&
946  equal(refwin->startOffset, windef->startOffset) &&
947  equal(refwin->endOffset, windef->endOffset))
948  {
949  /* found a duplicate window specification */
950  wfunc->winref = winref;
951  break;
952  }
953  }
954  if (lc == NULL) /* didn't find it? */
955  {
956  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
957  wfunc->winref = list_length(pstate->p_windowdefs);
958  }
959  }
960 
961  pstate->p_hasWindowFuncs = true;
962 }
List * partitionClause
Definition: parsenodes.h:480
#define NIL
Definition: pg_list.h:69
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:516
List * args
Definition: primnodes.h:359
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2946
int frameOptions
Definition: parsenodes.h:482
char * name
Definition: parsenodes.h:478
Definition: nodes.h:506
int errcode(int sqlerrcode)
Definition: elog.c:575
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
Index winref
Definition: primnodes.h:361
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3352
bool p_hasWindowFuncs
Definition: parse_node.h:193
Node * startOffset
Definition: parsenodes.h:483
#define ERROR
Definition: elog.h:43
int location
Definition: parsenodes.h:485
List * p_windowdefs
Definition: parse_node.h:181
Node * endOffset
Definition: parsenodes.h:484
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
List * orderClause
Definition: parsenodes.h:481
unsigned int Index
Definition: c.h:365
ParseExprKind p_expr_kind
Definition: parse_node.h:182
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int location
Definition: primnodes.h:364
#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
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:109
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * refname
Definition: parsenodes.h:479
#define _(x)
Definition: elog.c:84
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197