PostgreSQL Source Code  git master
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

◆ build_aggregate_combinefn_expr()

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

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

1965 {
1966  Node *argp;
1967  List *args;
1968  FuncExpr *fexpr;
1969 
1970  /* combinefn takes two arguments of the aggregate state type */
1971  argp = make_agg_arg(agg_state_type, agg_input_collation);
1972 
1973  args = list_make2(argp, argp);
1974 
1975  fexpr = makeFuncExpr(combinefn_oid,
1976  agg_state_type,
1977  args,
1978  InvalidOid,
1979  agg_input_collation,
1981  /* combinefn is currently never treated as variadic */
1982  *combinefnexpr = (Expr *) fexpr;
1983 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2077
Definition: nodes.h:525
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

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

2015 {
2016  List *args;
2017  FuncExpr *fexpr;
2018 
2019  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2020  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2021  make_agg_arg(INTERNALOID, InvalidOid));
2022 
2023  fexpr = makeFuncExpr(deserialfn_oid,
2024  INTERNALOID,
2025  args,
2026  InvalidOid,
2027  InvalidOid,
2029  *deserialfnexpr = (Expr *) fexpr;
2030 }
#define list_make2(x1, x2)
Definition: pg_list.h:229
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2077
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ build_aggregate_finalfn_expr()

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

2044 {
2045  List *args;
2046  int i;
2047 
2048  /*
2049  * Build expr tree for final function
2050  */
2051  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2052 
2053  /* finalfn may take additional args, which match agg's input types */
2054  for (i = 0; i < num_finalfn_inputs - 1; i++)
2055  {
2056  args = lappend(args,
2057  make_agg_arg(agg_input_types[i], agg_input_collation));
2058  }
2059 
2060  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2061  agg_result_type,
2062  args,
2063  InvalidOid,
2064  agg_input_collation,
2066  /* finalfn is currently never treated as variadic */
2067 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2077
#define list_make1(x1)
Definition: pg_list.h:227
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 1990 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref().

1992 {
1993  List *args;
1994  FuncExpr *fexpr;
1995 
1996  /* serialfn always takes INTERNAL and returns BYTEA */
1997  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
1998 
1999  fexpr = makeFuncExpr(serialfn_oid,
2000  BYTEAOID,
2001  args,
2002  InvalidOid,
2003  InvalidOid,
2005  *serialfnexpr = (Expr *) fexpr;
2006 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2077
#define list_make1(x1)
Definition: pg_list.h:227
#define InvalidOid
Definition: postgres_ext.h:36
Definition: pg_list.h:50
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ build_aggregate_transfn_expr()

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 1900 of file parse_agg.c.

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

Referenced by build_pertrans_for_aggref(), and initialize_peragg().

1910 {
1911  List *args;
1912  FuncExpr *fexpr;
1913  int i;
1914 
1915  /*
1916  * Build arg list to use in the transfn FuncExpr node.
1917  */
1918  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1919 
1920  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1921  {
1922  args = lappend(args,
1923  make_agg_arg(agg_input_types[i], agg_input_collation));
1924  }
1925 
1926  fexpr = makeFuncExpr(transfn_oid,
1927  agg_state_type,
1928  args,
1929  InvalidOid,
1930  agg_input_collation,
1932  fexpr->funcvariadic = agg_variadic;
1933  *transfnexpr = (Expr *) fexpr;
1934 
1935  /*
1936  * Build invtransfn expression if requested, with same args as transfn
1937  */
1938  if (invtransfnexpr != NULL)
1939  {
1940  if (OidIsValid(invtransfn_oid))
1941  {
1942  fexpr = makeFuncExpr(invtransfn_oid,
1943  agg_state_type,
1944  args,
1945  InvalidOid,
1946  agg_input_collation,
1948  fexpr->funcvariadic = agg_variadic;
1949  *invtransfnexpr = (Expr *) fexpr;
1950  }
1951  else
1952  *invtransfnexpr = NULL;
1953  }
1954 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2077
#define OidIsValid(objectId)
Definition: c.h:639
#define list_make1(x1)
Definition: pg_list.h:227
List * lappend(List *list, void *datum)
Definition: list.c:322
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:458
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:517

◆ expand_grouping_sets()

List* expand_grouping_sets ( List groupingSets,
int  limit 
)

Definition at line 1739 of file parse_agg.c.

References Assert, cmp_list_len_asc(), expand_groupingset_node(), for_each_cell, lappend(), lfirst, linitial, list_length(), list_second_cell(), list_sort(), list_union_int(), and NIL.

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1740 {
1741  List *expanded_groups = NIL;
1742  List *result = NIL;
1743  double numsets = 1;
1744  ListCell *lc;
1745 
1746  if (groupingSets == NIL)
1747  return NIL;
1748 
1749  foreach(lc, groupingSets)
1750  {
1751  List *current_result = NIL;
1752  GroupingSet *gs = lfirst(lc);
1753 
1754  current_result = expand_groupingset_node(gs);
1755 
1756  Assert(current_result != NIL);
1757 
1758  numsets *= list_length(current_result);
1759 
1760  if (limit >= 0 && numsets > limit)
1761  return NIL;
1762 
1763  expanded_groups = lappend(expanded_groups, current_result);
1764  }
1765 
1766  /*
1767  * Do cartesian product between sublists of expanded_groups. While at it,
1768  * remove any duplicate elements from individual grouping sets (we must
1769  * NOT change the number of sets though)
1770  */
1771 
1772  foreach(lc, (List *) linitial(expanded_groups))
1773  {
1774  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1775  }
1776 
1777  for_each_cell(lc, expanded_groups, list_second_cell(expanded_groups))
1778  {
1779  List *p = lfirst(lc);
1780  List *new_result = NIL;
1781  ListCell *lc2;
1782 
1783  foreach(lc2, result)
1784  {
1785  List *q = lfirst(lc2);
1786  ListCell *lc3;
1787 
1788  foreach(lc3, p)
1789  {
1790  new_result = lappend(new_result,
1791  list_union_int(q, (List *) lfirst(lc3)));
1792  }
1793  }
1794  result = new_result;
1795  }
1796 
1797  /* Now sort the lists by length */
1798  list_sort(result, cmp_list_len_asc);
1799 
1800  return result;
1801 }
#define NIL
Definition: pg_list.h:65
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
#define linitial(l)
Definition: pg_list.h:195
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1621
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:963
List * lappend(List *list, void *datum)
Definition: list.c:322
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1723
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1482
Definition: pg_list.h:50

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

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

1820 {
1821  int numArguments = 0;
1822  ListCell *lc;
1823 
1825 
1826  foreach(lc, aggref->aggargtypes)
1827  {
1828  inputTypes[numArguments++] = lfirst_oid(lc);
1829  }
1830 
1831  return numArguments;
1832 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:303
#define Assert(condition)
Definition: c.h:733
static int list_length(const List *l)
Definition: pg_list.h:169
#define lfirst_oid(lc)
Definition: pg_list.h:192

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1042 of file parse_agg.c.

References Assert, check_ungrouped_columns(), 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, Query::havingQual, IsA, lappend(), lfirst, linitial, list_intersection_int(), list_length(), list_member_int(), list_second_cell(), locate_agg_of_level(), NIL, ParseState::p_hasAggs, ParseState::p_rtable, parser_errposition(), TargetEntry::ressortgroupref, RTE_CTE, RTE_JOIN, RangeTblEntry::rtekind, RangeTblEntry::self_reference, and Query::targetList.

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

1043 {
1044  List *gset_common = NIL;
1045  List *groupClauses = NIL;
1046  List *groupClauseCommonVars = NIL;
1047  bool have_non_var_grouping;
1048  List *func_grouped_rels = NIL;
1049  ListCell *l;
1050  bool hasJoinRTEs;
1051  bool hasSelfRefRTEs;
1052  Node *clause;
1053 
1054  /* This should only be called if we found aggregates or grouping */
1055  Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1056 
1057  /*
1058  * If we have grouping sets, expand them and find the intersection of all
1059  * sets.
1060  */
1061  if (qry->groupingSets)
1062  {
1063  /*
1064  * The limit of 4096 is arbitrary and exists simply to avoid resource
1065  * issues from pathological constructs.
1066  */
1067  List *gsets = expand_grouping_sets(qry->groupingSets, 4096);
1068 
1069  if (!gsets)
1070  ereport(ERROR,
1071  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
1072  errmsg("too many grouping sets present (maximum 4096)"),
1073  parser_errposition(pstate,
1074  qry->groupClause
1075  ? exprLocation((Node *) qry->groupClause)
1076  : exprLocation((Node *) qry->groupingSets))));
1077 
1078  /*
1079  * The intersection will often be empty, so help things along by
1080  * seeding the intersect with the smallest set.
1081  */
1082  gset_common = linitial(gsets);
1083 
1084  if (gset_common)
1085  {
1086  for_each_cell(l, gsets, list_second_cell(gsets))
1087  {
1088  gset_common = list_intersection_int(gset_common, lfirst(l));
1089  if (!gset_common)
1090  break;
1091  }
1092  }
1093 
1094  /*
1095  * If there was only one grouping set in the expansion, AND if the
1096  * groupClause is non-empty (meaning that the grouping set is not
1097  * empty either), then we can ditch the grouping set and pretend we
1098  * just had a normal GROUP BY.
1099  */
1100  if (list_length(gsets) == 1 && qry->groupClause)
1101  qry->groupingSets = NIL;
1102  }
1103 
1104  /*
1105  * Scan the range table to see if there are JOIN or self-reference CTE
1106  * entries. We'll need this info below.
1107  */
1108  hasJoinRTEs = hasSelfRefRTEs = false;
1109  foreach(l, pstate->p_rtable)
1110  {
1111  RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
1112 
1113  if (rte->rtekind == RTE_JOIN)
1114  hasJoinRTEs = true;
1115  else if (rte->rtekind == RTE_CTE && rte->self_reference)
1116  hasSelfRefRTEs = true;
1117  }
1118 
1119  /*
1120  * Build a list of the acceptable GROUP BY expressions for use by
1121  * check_ungrouped_columns().
1122  *
1123  * We get the TLE, not just the expr, because GROUPING wants to know the
1124  * sortgroupref.
1125  */
1126  foreach(l, qry->groupClause)
1127  {
1128  SortGroupClause *grpcl = (SortGroupClause *) lfirst(l);
1129  TargetEntry *expr;
1130 
1131  expr = get_sortgroupclause_tle(grpcl, qry->targetList);
1132  if (expr == NULL)
1133  continue; /* probably cannot happen */
1134 
1135  groupClauses = lappend(groupClauses, expr);
1136  }
1137 
1138  /*
1139  * If there are join alias vars involved, we have to flatten them to the
1140  * underlying vars, so that aliased and unaliased vars will be correctly
1141  * taken as equal. We can skip the expense of doing this if no rangetable
1142  * entries are RTE_JOIN kind.
1143  */
1144  if (hasJoinRTEs)
1145  groupClauses = (List *) flatten_join_alias_vars(qry,
1146  (Node *) groupClauses);
1147 
1148  /*
1149  * Detect whether any of the grouping expressions aren't simple Vars; if
1150  * they're all Vars then we don't have to work so hard in the recursive
1151  * scans. (Note we have to flatten aliases before this.)
1152  *
1153  * Track Vars that are included in all grouping sets separately in
1154  * groupClauseCommonVars, since these are the only ones we can use to
1155  * check for functional dependencies.
1156  */
1157  have_non_var_grouping = false;
1158  foreach(l, groupClauses)
1159  {
1160  TargetEntry *tle = lfirst(l);
1161 
1162  if (!IsA(tle->expr, Var))
1163  {
1164  have_non_var_grouping = true;
1165  }
1166  else if (!qry->groupingSets ||
1167  list_member_int(gset_common, tle->ressortgroupref))
1168  {
1169  groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1170  }
1171  }
1172 
1173  /*
1174  * Check the targetlist and HAVING clause for ungrouped variables.
1175  *
1176  * Note: because we check resjunk tlist elements as well as regular ones,
1177  * this will also find ungrouped variables that came from ORDER BY and
1178  * WINDOW clauses. For that matter, it's also going to examine the
1179  * grouping expressions themselves --- but they'll all pass the test ...
1180  *
1181  * We also finalize GROUPING expressions, but for that we need to traverse
1182  * the original (unflattened) clause in order to modify nodes.
1183  */
1184  clause = (Node *) qry->targetList;
1185  finalize_grouping_exprs(clause, pstate, qry,
1186  groupClauses, hasJoinRTEs,
1187  have_non_var_grouping);
1188  if (hasJoinRTEs)
1189  clause = flatten_join_alias_vars(qry, clause);
1190  check_ungrouped_columns(clause, pstate, qry,
1191  groupClauses, groupClauseCommonVars,
1192  have_non_var_grouping,
1193  &func_grouped_rels);
1194 
1195  clause = (Node *) qry->havingQual;
1196  finalize_grouping_exprs(clause, pstate, qry,
1197  groupClauses, hasJoinRTEs,
1198  have_non_var_grouping);
1199  if (hasJoinRTEs)
1200  clause = flatten_join_alias_vars(qry, clause);
1201  check_ungrouped_columns(clause, pstate, qry,
1202  groupClauses, groupClauseCommonVars,
1203  have_non_var_grouping,
1204  &func_grouped_rels);
1205 
1206  /*
1207  * Per spec, aggregates can't appear in a recursive term.
1208  */
1209  if (pstate->p_hasAggs && hasSelfRefRTEs)
1210  ereport(ERROR,
1211  (errcode(ERRCODE_INVALID_RECURSION),
1212  errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1213  parser_errposition(pstate,
1214  locate_agg_of_level((Node *) qry, 0))));
1215 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:389
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1191
List * list_intersection_int(const List *list1, const List *list2)
Definition: list.c:1045
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:390
List * groupingSets
Definition: parsenodes.h:150
Definition: nodes.h:525
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
Definition: parse_agg.c:1447
int errcode(int sqlerrcode)
Definition: elog.c:608
bool p_hasAggs
Definition: parse_node.h:203
Definition: primnodes.h:167
List * targetList
Definition: parsenodes.h:140
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
bool list_member_int(const List *list, int datum)
Definition: list.c:655
static ListCell * list_second_cell(const List *l)
Definition: pg_list.h:139
static void check_ungrouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, bool have_non_var_grouping, List **func_grouped_rels)
Definition: parse_agg.c:1239
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
int locate_agg_of_level(Node *node, int levelsup)
Definition: rewriteManip.c:131
bool self_reference
Definition: parsenodes.h:1058
Node * flatten_join_alias_vars(Query *query, Node *node)
Definition: var.c:670
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
List * expand_grouping_sets(List *groupingSets, int limit)
Definition: parse_agg.c:1739
RTEKind rtekind
Definition: parsenodes.h:974
List * groupClause
Definition: parsenodes.h:148
int errmsg(const char *fmt,...)
Definition: elog.c:822
Index ressortgroupref
Definition: primnodes.h:1396
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
List * p_rtable
Definition: parse_node.h:177

◆ resolve_aggregate_transtype()

Oid resolve_aggregate_transtype ( Oid  aggfuncid,
Oid  aggtranstype,
Oid inputTypes,
int  numArguments 
)

Definition at line 1845 of file parse_agg.c.

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

Referenced by get_agg_clause_costs_walker(), and initialize_peragg().

1849 {
1850  /* resolve actual type of transition state, if polymorphic */
1851  if (IsPolymorphicType(aggtranstype))
1852  {
1853  /* have to fetch the agg's declared input types... */
1854  Oid *declaredArgTypes;
1855  int agg_nargs;
1856 
1857  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1858 
1859  /*
1860  * VARIADIC ANY aggs could have more actual than declared args, but
1861  * such extra args can't affect polymorphic type resolution.
1862  */
1863  Assert(agg_nargs <= numArguments);
1864 
1865  aggtranstype = enforce_generic_type_consistency(inputTypes,
1866  declaredArgTypes,
1867  agg_nargs,
1868  aggtranstype,
1869  false);
1870  pfree(declaredArgTypes);
1871  }
1872  return aggtranstype;
1873 }
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1498
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1056
#define Assert(condition)
Definition: c.h:733

◆ transformAggregateCall()

void transformAggregateCall ( ParseState pstate,
Aggref agg,
List args,
List aggorder,
bool  agg_distinct 
)

Definition at line 102 of file parse_agg.c.

References addTargetToSortList(), Aggref::aggargtypes, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggkind, 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, OidIsValid, ParseState::p_next_resno, parser_errposition(), SortGroupClause::sortop, transformDistinctClause(), and transformSortClause().

Referenced by ParseFuncOrColumn().

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

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc g 
)

Definition at line 247 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(), and transformExpr().

Referenced by transformExprRecurse().

248 {
249  ListCell *lc;
250  List *args = p->args;
251  List *result_list = NIL;
253 
254  if (list_length(args) > 31)
255  ereport(ERROR,
256  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
257  errmsg("GROUPING must have fewer than 32 arguments"),
258  parser_errposition(pstate, p->location)));
259 
260  foreach(lc, args)
261  {
262  Node *current_result;
263 
264  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
265 
266  /* acceptability of expressions is checked later */
267 
268  result_list = lappend(result_list, current_result);
269  }
270 
271  result->args = result_list;
272  result->location = p->location;
273 
274  check_agglevels_and_constraints(pstate, (Node *) result);
275 
276  return (Node *) result;
277 }
#define NIL
Definition: pg_list.h:65
List * args
Definition: primnodes.h:345
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:144
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
ParseExprKind p_expr_kind
Definition: parse_node.h:191
#define makeNode(_type_)
Definition: nodes.h:573
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
Definition: pg_list.h:50

◆ transformWindowFuncCall()

void transformWindowFuncCall ( ParseState pstate,
WindowFunc wfunc,
WindowDef windef 
)

Definition at line 798 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_CALL_ARGUMENT, EXPR_KIND_CHECK_CONSTRAINT, EXPR_KIND_COLUMN_DEFAULT, EXPR_KIND_COPY_WHERE, 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_GENERATED_COLUMN, 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_BOUND, 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_GROUPS, 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, 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().

800 {
801  const char *err;
802  bool errkind;
803 
804  /*
805  * A window function call can't contain another one (but aggs are OK). XXX
806  * is this required by spec, or just an unimplemented feature?
807  *
808  * Note: we don't need to check the filter expression here, because the
809  * context checks done below and in transformAggregateCall would have
810  * already rejected any window funcs or aggs within the filter.
811  */
812  if (pstate->p_hasWindowFuncs &&
813  contain_windowfuncs((Node *) wfunc->args))
814  ereport(ERROR,
815  (errcode(ERRCODE_WINDOWING_ERROR),
816  errmsg("window function calls cannot be nested"),
817  parser_errposition(pstate,
818  locate_windowfunc((Node *) wfunc->args))));
819 
820  /*
821  * Check to see if the window function is in an invalid place within the
822  * query.
823  *
824  * For brevity we support two schemes for reporting an error here: set
825  * "err" to a custom message, or set "errkind" true if the error context
826  * is sufficiently identified by what ParseExprKindName will return, *and*
827  * what it will return is just a SQL keyword. (Otherwise, use a custom
828  * message to avoid creating translation problems.)
829  */
830  err = NULL;
831  errkind = false;
832  switch (pstate->p_expr_kind)
833  {
834  case EXPR_KIND_NONE:
835  Assert(false); /* can't happen */
836  break;
837  case EXPR_KIND_OTHER:
838  /* Accept window func here; caller must throw error if wanted */
839  break;
840  case EXPR_KIND_JOIN_ON:
842  err = _("window functions are not allowed in JOIN conditions");
843  break;
845  /* can't get here, but just in case, throw an error */
846  errkind = true;
847  break;
849  err = _("window functions are not allowed in functions in FROM");
850  break;
851  case EXPR_KIND_WHERE:
852  errkind = true;
853  break;
854  case EXPR_KIND_POLICY:
855  err = _("window functions are not allowed in policy expressions");
856  break;
857  case EXPR_KIND_HAVING:
858  errkind = true;
859  break;
860  case EXPR_KIND_FILTER:
861  errkind = true;
862  break;
868  err = _("window functions are not allowed in window definitions");
869  break;
871  /* okay */
872  break;
876  errkind = true;
877  break;
878  case EXPR_KIND_GROUP_BY:
879  errkind = true;
880  break;
881  case EXPR_KIND_ORDER_BY:
882  /* okay */
883  break;
885  /* okay */
886  break;
887  case EXPR_KIND_LIMIT:
888  case EXPR_KIND_OFFSET:
889  errkind = true;
890  break;
891  case EXPR_KIND_RETURNING:
892  errkind = true;
893  break;
894  case EXPR_KIND_VALUES:
896  errkind = true;
897  break;
900  err = _("window functions are not allowed in check constraints");
901  break;
904  err = _("window functions are not allowed in DEFAULT expressions");
905  break;
907  err = _("window functions are not allowed in index expressions");
908  break;
910  err = _("window functions are not allowed in index predicates");
911  break;
913  err = _("window functions are not allowed in transform expressions");
914  break;
916  err = _("window functions are not allowed in EXECUTE parameters");
917  break;
919  err = _("window functions are not allowed in trigger WHEN conditions");
920  break;
922  err = _("window functions are not allowed in partition bound");
923  break;
925  err = _("window functions are not allowed in partition key expressions");
926  break;
928  err = _("window functions are not allowed in CALL arguments");
929  break;
931  err = _("window functions are not allowed in COPY FROM WHERE conditions");
932  break;
934  err = _("window functions are not allowed in column generation expressions");
935  break;
936 
937  /*
938  * There is intentionally no default: case here, so that the
939  * compiler will warn if we add a new ParseExprKind without
940  * extending this switch. If we do see an unrecognized value at
941  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
942  * which is sane anyway.
943  */
944  }
945  if (err)
946  ereport(ERROR,
947  (errcode(ERRCODE_WINDOWING_ERROR),
948  errmsg_internal("%s", err),
949  parser_errposition(pstate, wfunc->location)));
950  if (errkind)
951  ereport(ERROR,
952  (errcode(ERRCODE_WINDOWING_ERROR),
953  /* translator: %s is name of a SQL construct, eg GROUP BY */
954  errmsg("window functions are not allowed in %s",
955  ParseExprKindName(pstate->p_expr_kind)),
956  parser_errposition(pstate, wfunc->location)));
957 
958  /*
959  * If the OVER clause just specifies a window name, find that WINDOW
960  * clause (which had better be present). Otherwise, try to match all the
961  * properties of the OVER clause, and make a new entry in the p_windowdefs
962  * list if no luck.
963  */
964  if (windef->name)
965  {
966  Index winref = 0;
967  ListCell *lc;
968 
969  Assert(windef->refname == NULL &&
970  windef->partitionClause == NIL &&
971  windef->orderClause == NIL &&
973 
974  foreach(lc, pstate->p_windowdefs)
975  {
976  WindowDef *refwin = (WindowDef *) lfirst(lc);
977 
978  winref++;
979  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
980  {
981  wfunc->winref = winref;
982  break;
983  }
984  }
985  if (lc == NULL) /* didn't find it? */
986  ereport(ERROR,
987  (errcode(ERRCODE_UNDEFINED_OBJECT),
988  errmsg("window \"%s\" does not exist", windef->name),
989  parser_errposition(pstate, windef->location)));
990  }
991  else
992  {
993  Index winref = 0;
994  ListCell *lc;
995 
996  foreach(lc, pstate->p_windowdefs)
997  {
998  WindowDef *refwin = (WindowDef *) lfirst(lc);
999 
1000  winref++;
1001  if (refwin->refname && windef->refname &&
1002  strcmp(refwin->refname, windef->refname) == 0)
1003  /* matched on refname */ ;
1004  else if (!refwin->refname && !windef->refname)
1005  /* matched, no refname */ ;
1006  else
1007  continue;
1008  if (equal(refwin->partitionClause, windef->partitionClause) &&
1009  equal(refwin->orderClause, windef->orderClause) &&
1010  refwin->frameOptions == windef->frameOptions &&
1011  equal(refwin->startOffset, windef->startOffset) &&
1012  equal(refwin->endOffset, windef->endOffset))
1013  {
1014  /* found a duplicate window specification */
1015  wfunc->winref = winref;
1016  break;
1017  }
1018  }
1019  if (lc == NULL) /* didn't find it? */
1020  {
1021  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1022  wfunc->winref = list_length(pstate->p_windowdefs);
1023  }
1024  }
1025 
1026  pstate->p_hasWindowFuncs = true;
1027 }
List * partitionClause
Definition: parsenodes.h:489
#define NIL
Definition: pg_list.h:65
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:531
List * args
Definition: primnodes.h:363
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3009
int frameOptions
Definition: parsenodes.h:491
char * name
Definition: parsenodes.h:487
Definition: nodes.h:525
int errcode(int sqlerrcode)
Definition: elog.c:608
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
Index winref
Definition: primnodes.h:365
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3481
bool p_hasWindowFuncs
Definition: parse_node.h:204
Node * startOffset
Definition: parsenodes.h:492
#define ERROR
Definition: elog.h:43
int location
Definition: parsenodes.h:494
List * p_windowdefs
Definition: parse_node.h:190
Node * endOffset
Definition: parsenodes.h:493
#define ereport(elevel, rest)
Definition: elog.h:141
List * lappend(List *list, void *datum)
Definition: list.c:322
List * orderClause
Definition: parsenodes.h:490
unsigned int Index
Definition: c.h:476
ParseExprKind p_expr_kind
Definition: parse_node.h:191
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
int location
Definition: primnodes.h:368
#define Assert(condition)
Definition: c.h:733
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * refname
Definition: parsenodes.h:488
#define _(x)
Definition: elog.c:87
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197