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, bool groupDistinct, 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_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_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

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

2052 {
2053  List *args;
2054  FuncExpr *fexpr;
2055 
2056  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2057  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2058  make_agg_arg(INTERNALOID, InvalidOid));
2059 
2060  fexpr = makeFuncExpr(deserialfn_oid,
2061  INTERNALOID,
2062  args,
2063  InvalidOid,
2064  InvalidOid,
2066  *deserialfnexpr = (Expr *) fexpr;
2067 }
#define list_make2(x1, x2)
Definition: pg_list.h:208
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2114
#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:519

◆ 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 2074 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().

2081 {
2082  List *args;
2083  int i;
2084 
2085  /*
2086  * Build expr tree for final function
2087  */
2088  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2089 
2090  /* finalfn may take additional args, which match agg's input types */
2091  for (i = 0; i < num_finalfn_inputs - 1; i++)
2092  {
2093  args = lappend(args,
2094  make_agg_arg(agg_input_types[i], agg_input_collation));
2095  }
2096 
2097  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2098  agg_result_type,
2099  args,
2100  InvalidOid,
2101  agg_input_collation,
2103  /* finalfn is currently never treated as variadic */
2104 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2114
#define list_make1(x1)
Definition: pg_list.h:206
List * lappend(List *list, void *datum)
Definition: list.c:336
#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:519

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

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

2029 {
2030  List *args;
2031  FuncExpr *fexpr;
2032 
2033  /* serialfn always takes INTERNAL and returns BYTEA */
2034  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2035 
2036  fexpr = makeFuncExpr(serialfn_oid,
2037  BYTEAOID,
2038  args,
2039  InvalidOid,
2040  InvalidOid,
2042  *serialfnexpr = (Expr *) fexpr;
2043 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2114
#define list_make1(x1)
Definition: pg_list.h:206
#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:519

◆ 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 1966 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().

1976 {
1977  List *args;
1978  FuncExpr *fexpr;
1979  int i;
1980 
1981  /*
1982  * Build arg list to use in the transfn FuncExpr node.
1983  */
1984  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1985 
1986  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1987  {
1988  args = lappend(args,
1989  make_agg_arg(agg_input_types[i], agg_input_collation));
1990  }
1991 
1992  fexpr = makeFuncExpr(transfn_oid,
1993  agg_state_type,
1994  args,
1995  InvalidOid,
1996  agg_input_collation,
1998  fexpr->funcvariadic = agg_variadic;
1999  *transfnexpr = (Expr *) fexpr;
2000 
2001  /*
2002  * Build invtransfn expression if requested, with same args as transfn
2003  */
2004  if (invtransfnexpr != NULL)
2005  {
2006  if (OidIsValid(invtransfn_oid))
2007  {
2008  fexpr = makeFuncExpr(invtransfn_oid,
2009  agg_state_type,
2010  args,
2011  InvalidOid,
2012  agg_input_collation,
2014  fexpr->funcvariadic = agg_variadic;
2015  *invtransfnexpr = (Expr *) fexpr;
2016  }
2017  else
2018  *invtransfnexpr = NULL;
2019  }
2020 }
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2114
#define OidIsValid(objectId)
Definition: c.h:710
#define list_make1(x1)
Definition: pg_list.h:206
List * lappend(List *list, void *datum)
Definition: list.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int i
Definition: pg_list.h:50
bool funcvariadic
Definition: primnodes.h:498
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:519

◆ expand_grouping_sets()

List* expand_grouping_sets ( List groupingSets,
bool  groupDistinct,
int  limit 
)

Definition at line 1777 of file parse_agg.c.

References Assert, cmp_list_len_asc(), cmp_list_len_contents_asc(), equal(), expand_groupingset_node(), for_each_from, foreach_delete_current, lappend(), lfirst, linitial, list_int_cmp(), list_length(), list_sort(), list_union_int(), and NIL.

Referenced by parseCheckAggregates(), and preprocess_grouping_sets().

1778 {
1779  List *expanded_groups = NIL;
1780  List *result = NIL;
1781  double numsets = 1;
1782  ListCell *lc;
1783 
1784  if (groupingSets == NIL)
1785  return NIL;
1786 
1787  foreach(lc, groupingSets)
1788  {
1789  List *current_result = NIL;
1790  GroupingSet *gs = lfirst(lc);
1791 
1792  current_result = expand_groupingset_node(gs);
1793 
1794  Assert(current_result != NIL);
1795 
1796  numsets *= list_length(current_result);
1797 
1798  if (limit >= 0 && numsets > limit)
1799  return NIL;
1800 
1801  expanded_groups = lappend(expanded_groups, current_result);
1802  }
1803 
1804  /*
1805  * Do cartesian product between sublists of expanded_groups. While at it,
1806  * remove any duplicate elements from individual grouping sets (we must
1807  * NOT change the number of sets though)
1808  */
1809 
1810  foreach(lc, (List *) linitial(expanded_groups))
1811  {
1812  result = lappend(result, list_union_int(NIL, (List *) lfirst(lc)));
1813  }
1814 
1815  for_each_from(lc, expanded_groups, 1)
1816  {
1817  List *p = lfirst(lc);
1818  List *new_result = NIL;
1819  ListCell *lc2;
1820 
1821  foreach(lc2, result)
1822  {
1823  List *q = lfirst(lc2);
1824  ListCell *lc3;
1825 
1826  foreach(lc3, p)
1827  {
1828  new_result = lappend(new_result,
1829  list_union_int(q, (List *) lfirst(lc3)));
1830  }
1831  }
1832  result = new_result;
1833  }
1834 
1835  /* Now sort the lists by length and deduplicate if necessary */
1836  if (!groupDistinct || list_length(result) < 2)
1837  list_sort(result, cmp_list_len_asc);
1838  else
1839  {
1840  ListCell *cell;
1841  List *prev;
1842 
1843  /* Sort each groupset individually */
1844  foreach(cell, result)
1845  list_sort(lfirst(cell), list_int_cmp);
1846 
1847  /* Now sort the list of groupsets by length and contents */
1849 
1850  /* Finally, remove duplicates */
1851  prev = linitial(result);
1852  for_each_from(cell, result, 1)
1853  {
1854  if (equal(lfirst(cell), prev))
1855  result = foreach_delete_current(result, cell);
1856  else
1857  prev = lfirst(cell);
1858  }
1859  }
1860 
1861  return result;
1862 }
#define NIL
Definition: pg_list.h:65
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3149
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define linitial(l)
Definition: pg_list.h:174
static List * expand_groupingset_node(GroupingSet *gs)
Definition: parse_agg.c:1631
List * list_union_int(const List *list1, const List *list2)
Definition: list.c:977
List * lappend(List *list, void *datum)
Definition: list.c:336
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
static int cmp_list_len_contents_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1743
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition: parse_agg.c:1733
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1496
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition: list.c:1513
Definition: pg_list.h:50

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1880 of file parse_agg.c.

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

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

1881 {
1882  int numArguments = 0;
1883  ListCell *lc;
1884 
1886 
1887  foreach(lc, aggref->aggargtypes)
1888  {
1889  inputTypes[numArguments++] = lfirst_oid(lc);
1890  }
1891 
1892  return numArguments;
1893 }
#define FUNC_MAX_ARGS
List * aggargtypes
Definition: primnodes.h:328
#define Assert(condition)
Definition: c.h:804
static int list_length(const List *l)
Definition: pg_list.h:149
#define lfirst_oid(lc)
Definition: pg_list.h:171

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1052 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_from, get_sortgroupclause_tle(), Query::groupClause, Query::groupDistinct, Query::groupingSets, Query::havingQual, IsA, lappend(), lfirst, linitial, list_intersection_int(), list_length(), list_member_int(), 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(), transformPLAssignStmt(), transformSelectStmt(), and transformSetOperationStmt().

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

◆ resolve_aggregate_transtype()

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

Definition at line 1906 of file parse_agg.c.

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

Referenced by initialize_peragg(), and preprocess_aggref().

1910 {
1911  /* resolve actual type of transition state, if polymorphic */
1912  if (IsPolymorphicType(aggtranstype))
1913  {
1914  /* have to fetch the agg's declared input types... */
1915  Oid *declaredArgTypes;
1916  int agg_nargs;
1917 
1918  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1919 
1920  /*
1921  * VARIADIC ANY aggs could have more actual than declared args, but
1922  * such extra args can't affect polymorphic type resolution.
1923  */
1924  Assert(agg_nargs <= numArguments);
1925 
1926  aggtranstype = enforce_generic_type_consistency(inputTypes,
1927  declaredArgTypes,
1928  agg_nargs,
1929  aggtranstype,
1930  false);
1931  pfree(declaredArgTypes);
1932  }
1933  return aggtranstype;
1934 }
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:1667
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:1169
#define Assert(condition)
Definition: c.h:804

◆ 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:332
#define NIL
Definition: pg_list.h:65
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1250
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:600
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:368
Definition: nodes.h:536
int errcode(int sqlerrcode)
Definition: elog.c:698
List * args
Definition: primnodes.h:330
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
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:1437
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
List * aggargtypes
Definition: primnodes.h:328
#define ERROR
Definition: elog.h:46
List * aggorder
Definition: primnodes.h:331
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int p_next_resno
Definition: parse_node.h:197
List * aggdirectargs
Definition: primnodes.h:329
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * arg
char aggkind
Definition: primnodes.h:337
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:372
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
Definition: nodes.h:536
int errcode(int sqlerrcode)
Definition: elog.c:698
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
ParseExprKind p_expr_kind
Definition: parse_node.h:196
#define ereport(elevel,...)
Definition: elog.h:157
#define makeNode(_type_)
Definition: nodes.h:584
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: pg_list.h:50

◆ transformWindowFuncCall()

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

Definition at line 802 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_CYCLE_MARK, 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_STATS_EXPRESSION, 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().

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