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

2062 {
2063  List *args;
2064  FuncExpr *fexpr;
2065 
2066  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2067  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2068  make_agg_arg(INTERNALOID, InvalidOid));
2069 
2070  fexpr = makeFuncExpr(deserialfn_oid,
2071  INTERNALOID,
2072  args,
2073  InvalidOid,
2074  InvalidOid,
2076  *deserialfnexpr = (Expr *) fexpr;
2077 }
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:520
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2124
#define list_make2(x1, x2)
Definition: pg_list.h:208
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:492
Definition: pg_list.h:51

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

Referenced by build_pertrans_for_aggref().

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

2091 {
2092  List *args;
2093  int i;
2094 
2095  /*
2096  * Build expr tree for final function
2097  */
2098  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2099 
2100  /* finalfn may take additional args, which match agg's input types */
2101  for (i = 0; i < num_finalfn_inputs - 1; i++)
2102  {
2103  args = lappend(args,
2104  make_agg_arg(agg_input_types[i], agg_input_collation));
2105  }
2106 
2107  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2108  agg_result_type,
2109  args,
2110  InvalidOid,
2111  agg_input_collation,
2113  /* finalfn is currently never treated as variadic */
2114 }
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:336
#define list_make1(x1)
Definition: pg_list.h:206

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

Referenced by ExecInitAgg(), and initialize_peragg().

◆ build_aggregate_serialfn_expr()

void build_aggregate_serialfn_expr ( Oid  serialfn_oid,
Expr **  serialfnexpr 
)

Definition at line 2037 of file parse_agg.c.

2039 {
2040  List *args;
2041  FuncExpr *fexpr;
2042 
2043  /* serialfn always takes INTERNAL and returns BYTEA */
2044  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2045 
2046  fexpr = makeFuncExpr(serialfn_oid,
2047  BYTEAOID,
2048  args,
2049  InvalidOid,
2050  InvalidOid,
2052  *serialfnexpr = (Expr *) fexpr;
2053 }

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

Referenced by build_pertrans_for_aggref().

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

1986 {
1987  List *args;
1988  FuncExpr *fexpr;
1989  int i;
1990 
1991  /*
1992  * Build arg list to use in the transfn FuncExpr node.
1993  */
1994  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
1995 
1996  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
1997  {
1998  args = lappend(args,
1999  make_agg_arg(agg_input_types[i], agg_input_collation));
2000  }
2001 
2002  fexpr = makeFuncExpr(transfn_oid,
2003  agg_state_type,
2004  args,
2005  InvalidOid,
2006  agg_input_collation,
2008  fexpr->funcvariadic = agg_variadic;
2009  *transfnexpr = (Expr *) fexpr;
2010 
2011  /*
2012  * Build invtransfn expression if requested, with same args as transfn
2013  */
2014  if (invtransfnexpr != NULL)
2015  {
2016  if (OidIsValid(invtransfn_oid))
2017  {
2018  fexpr = makeFuncExpr(invtransfn_oid,
2019  agg_state_type,
2020  args,
2021  InvalidOid,
2022  agg_input_collation,
2024  fexpr->funcvariadic = agg_variadic;
2025  *invtransfnexpr = (Expr *) fexpr;
2026  }
2027  else
2028  *invtransfnexpr = NULL;
2029  }
2030 }
#define OidIsValid(objectId)
Definition: c.h:710
bool funcvariadic
Definition: primnodes.h:507

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

◆ expand_grouping_sets()

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

Definition at line 1787 of file parse_agg.c.

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

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

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)

Definition at line 1890 of file parse_agg.c.

1891 {
1892  int numArguments = 0;
1893  ListCell *lc;
1894 
1896 
1897  foreach(lc, aggref->aggargtypes)
1898  {
1899  inputTypes[numArguments++] = lfirst_oid(lc);
1900  }
1901 
1902  return numArguments;
1903 }
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition: pg_list.h:171
List * aggargtypes
Definition: primnodes.h:337

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

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

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1062 of file parse_agg.c.

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

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

◆ resolve_aggregate_transtype()

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

Definition at line 1916 of file parse_agg.c.

1920 {
1921  /* resolve actual type of transition state, if polymorphic */
1922  if (IsPolymorphicType(aggtranstype))
1923  {
1924  /* have to fetch the agg's declared input types... */
1925  Oid *declaredArgTypes;
1926  int agg_nargs;
1927 
1928  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1929 
1930  /*
1931  * VARIADIC ANY aggs could have more actual than declared args, but
1932  * such extra args can't affect polymorphic type resolution.
1933  */
1934  Assert(agg_nargs <= numArguments);
1935 
1936  aggtranstype = enforce_generic_type_consistency(inputTypes,
1937  declaredArgTypes,
1938  agg_nargs,
1939  aggtranstype,
1940  false);
1941  pfree(declaredArgTypes);
1942  }
1943  return aggtranstype;
1944 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1677
void pfree(void *pointer)
Definition: mcxt.c:1175
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
unsigned int Oid
Definition: postgres_ext.h:31

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

Referenced by initialize_peragg(), and preprocess_aggref().

◆ transformAggregateCall()

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

Definition at line 102 of file parse_agg.c.

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 }
int16 AttrNumber
Definition: attnum.h:21
int errdetail(const char *fmt,...)
Definition: elog.c:1037
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
List * list_truncate(List *list, int new_size)
Definition: list.c:610
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1551
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:239
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition: parse_agg.c:286
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 * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
void * arg
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
List * aggdistinct
Definition: primnodes.h:341
List * aggdirectargs
Definition: primnodes.h:338
char aggkind
Definition: primnodes.h:346
List * args
Definition: primnodes.h:339
List * aggorder
Definition: primnodes.h:340
int p_next_resno
Definition: parse_node.h:198
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:368

References addTargetToSortList(), Aggref::aggargtypes, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggkind, Aggref::aggorder, arg, generate_unaccent_rules::args, 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(), and transformJsonAggConstructor().

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc g 
)

Definition at line 247 of file parse_agg.c.

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 makeNode(_type_)
Definition: nodes.h:621
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:112
List * args
Definition: primnodes.h:381
ParseExprKind p_expr_kind
Definition: parse_node.h:197

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

◆ transformWindowFuncCall()

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

Definition at line 809 of file parse_agg.c.

811 {
812  const char *err;
813  bool errkind;
814 
815  /*
816  * A window function call can't contain another one (but aggs are OK). XXX
817  * is this required by spec, or just an unimplemented feature?
818  *
819  * Note: we don't need to check the filter expression here, because the
820  * context checks done below and in transformAggregateCall would have
821  * already rejected any window funcs or aggs within the filter.
822  */
823  if (pstate->p_hasWindowFuncs &&
824  contain_windowfuncs((Node *) wfunc->args))
825  ereport(ERROR,
826  (errcode(ERRCODE_WINDOWING_ERROR),
827  errmsg("window function calls cannot be nested"),
828  parser_errposition(pstate,
829  locate_windowfunc((Node *) wfunc->args))));
830 
831  /*
832  * Check to see if the window function is in an invalid place within the
833  * query.
834  *
835  * For brevity we support two schemes for reporting an error here: set
836  * "err" to a custom message, or set "errkind" true if the error context
837  * is sufficiently identified by what ParseExprKindName will return, *and*
838  * what it will return is just a SQL keyword. (Otherwise, use a custom
839  * message to avoid creating translation problems.)
840  */
841  err = NULL;
842  errkind = false;
843  switch (pstate->p_expr_kind)
844  {
845  case EXPR_KIND_NONE:
846  Assert(false); /* can't happen */
847  break;
848  case EXPR_KIND_OTHER:
849  /* Accept window func here; caller must throw error if wanted */
850  break;
851  case EXPR_KIND_JOIN_ON:
853  err = _("window functions are not allowed in JOIN conditions");
854  break;
856  /* can't get here, but just in case, throw an error */
857  errkind = true;
858  break;
860  err = _("window functions are not allowed in functions in FROM");
861  break;
862  case EXPR_KIND_WHERE:
863  errkind = true;
864  break;
865  case EXPR_KIND_POLICY:
866  err = _("window functions are not allowed in policy expressions");
867  break;
868  case EXPR_KIND_HAVING:
869  errkind = true;
870  break;
871  case EXPR_KIND_FILTER:
872  errkind = true;
873  break;
879  err = _("window functions are not allowed in window definitions");
880  break;
882  /* okay */
883  break;
887  errkind = true;
888  break;
890  err = _("window functions are not allowed in MERGE WHEN conditions");
891  break;
892  case EXPR_KIND_GROUP_BY:
893  errkind = true;
894  break;
895  case EXPR_KIND_ORDER_BY:
896  /* okay */
897  break;
899  /* okay */
900  break;
901  case EXPR_KIND_LIMIT:
902  case EXPR_KIND_OFFSET:
903  errkind = true;
904  break;
905  case EXPR_KIND_RETURNING:
906  errkind = true;
907  break;
908  case EXPR_KIND_VALUES:
910  errkind = true;
911  break;
914  err = _("window functions are not allowed in check constraints");
915  break;
918  err = _("window functions are not allowed in DEFAULT expressions");
919  break;
921  err = _("window functions are not allowed in index expressions");
922  break;
924  err = _("window functions are not allowed in statistics expressions");
925  break;
927  err = _("window functions are not allowed in index predicates");
928  break;
930  err = _("window functions are not allowed in transform expressions");
931  break;
933  err = _("window functions are not allowed in EXECUTE parameters");
934  break;
936  err = _("window functions are not allowed in trigger WHEN conditions");
937  break;
939  err = _("window functions are not allowed in partition bound");
940  break;
942  err = _("window functions are not allowed in partition key expressions");
943  break;
945  err = _("window functions are not allowed in CALL arguments");
946  break;
948  err = _("window functions are not allowed in COPY FROM WHERE conditions");
949  break;
951  err = _("window functions are not allowed in column generation expressions");
952  break;
954  errkind = true;
955  break;
956 
957  /*
958  * There is intentionally no default: case here, so that the
959  * compiler will warn if we add a new ParseExprKind without
960  * extending this switch. If we do see an unrecognized value at
961  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
962  * which is sane anyway.
963  */
964  }
965  if (err)
966  ereport(ERROR,
967  (errcode(ERRCODE_WINDOWING_ERROR),
968  errmsg_internal("%s", err),
969  parser_errposition(pstate, wfunc->location)));
970  if (errkind)
971  ereport(ERROR,
972  (errcode(ERRCODE_WINDOWING_ERROR),
973  /* translator: %s is name of a SQL construct, eg GROUP BY */
974  errmsg("window functions are not allowed in %s",
975  ParseExprKindName(pstate->p_expr_kind)),
976  parser_errposition(pstate, wfunc->location)));
977 
978  /*
979  * If the OVER clause just specifies a window name, find that WINDOW
980  * clause (which had better be present). Otherwise, try to match all the
981  * properties of the OVER clause, and make a new entry in the p_windowdefs
982  * list if no luck.
983  */
984  if (windef->name)
985  {
986  Index winref = 0;
987  ListCell *lc;
988 
989  Assert(windef->refname == NULL &&
990  windef->partitionClause == NIL &&
991  windef->orderClause == NIL &&
993 
994  foreach(lc, pstate->p_windowdefs)
995  {
996  WindowDef *refwin = (WindowDef *) lfirst(lc);
997 
998  winref++;
999  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1000  {
1001  wfunc->winref = winref;
1002  break;
1003  }
1004  }
1005  if (lc == NULL) /* didn't find it? */
1006  ereport(ERROR,
1007  (errcode(ERRCODE_UNDEFINED_OBJECT),
1008  errmsg("window \"%s\" does not exist", windef->name),
1009  parser_errposition(pstate, windef->location)));
1010  }
1011  else
1012  {
1013  Index winref = 0;
1014  ListCell *lc;
1015 
1016  foreach(lc, pstate->p_windowdefs)
1017  {
1018  WindowDef *refwin = (WindowDef *) lfirst(lc);
1019 
1020  winref++;
1021  if (refwin->refname && windef->refname &&
1022  strcmp(refwin->refname, windef->refname) == 0)
1023  /* matched on refname */ ;
1024  else if (!refwin->refname && !windef->refname)
1025  /* matched, no refname */ ;
1026  else
1027  continue;
1028  if (equal(refwin->partitionClause, windef->partitionClause) &&
1029  equal(refwin->orderClause, windef->orderClause) &&
1030  refwin->frameOptions == windef->frameOptions &&
1031  equal(refwin->startOffset, windef->startOffset) &&
1032  equal(refwin->endOffset, windef->endOffset))
1033  {
1034  /* found a duplicate window specification */
1035  wfunc->winref = winref;
1036  break;
1037  }
1038  }
1039  if (lc == NULL) /* didn't find it? */
1040  {
1041  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1042  wfunc->winref = list_length(pstate->p_windowdefs);
1043  }
1044  }
1045 
1046  pstate->p_hasWindowFuncs = true;
1047 }
unsigned int Index
Definition: c.h:549
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define _(x)
Definition: elog.c:89
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3070
@ EXPR_KIND_EXECUTE_PARAMETER
Definition: parse_node.h:75
@ EXPR_KIND_DOMAIN_CHECK
Definition: parse_node.h:68
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
@ EXPR_KIND_COLUMN_DEFAULT
Definition: parse_node.h:69
@ EXPR_KIND_DISTINCT_ON
Definition: parse_node.h:61
@ EXPR_KIND_MERGE_WHEN
Definition: parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition: parse_node.h:73
@ EXPR_KIND_INDEX_EXPRESSION
Definition: parse_node.h:71
@ EXPR_KIND_PARTITION_BOUND
Definition: parse_node.h:78
@ EXPR_KIND_FUNCTION_DEFAULT
Definition: parse_node.h:70
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition: parse_node.h:51
@ EXPR_KIND_VALUES
Definition: parse_node.h:65
@ EXPR_KIND_FROM_SUBSELECT
Definition: parse_node.h:44
@ EXPR_KIND_POLICY
Definition: parse_node.h:77
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition: parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition: parse_node.h:79
@ EXPR_KIND_JOIN_USING
Definition: parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition: parse_node.h:72
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_JOIN_ON
Definition: parse_node.h:42
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_ALTER_COL_TRANSFORM
Definition: parse_node.h:74
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_GENERATED_COLUMN
Definition: parse_node.h:82
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:80
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_OTHER
Definition: parse_node.h:41
@ EXPR_KIND_FROM_FUNCTION
Definition: parse_node.h:45
@ EXPR_KIND_TRIGGER_WHEN
Definition: parse_node.h:76
@ EXPR_KIND_FILTER
Definition: parse_node.h:48
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_CHECK_CONSTRAINT
Definition: parse_node.h:67
@ EXPR_KIND_WINDOW_PARTITION
Definition: parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition: parse_node.h:83
@ EXPR_KIND_WINDOW_FRAME_ROWS
Definition: parse_node.h:52
@ EXPR_KIND_WINDOW_ORDER
Definition: parse_node.h:50
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:66
#define FRAMEOPTION_DEFAULTS
Definition: parsenodes.h:562
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:197
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:235
bool p_hasWindowFuncs
Definition: parse_node.h:210
List * p_windowdefs
Definition: parse_node.h:196
List * orderClause
Definition: parsenodes.h:521
List * partitionClause
Definition: parsenodes.h:520
Node * startOffset
Definition: parsenodes.h:523
char * refname
Definition: parsenodes.h:519
Node * endOffset
Definition: parsenodes.h:524
int frameOptions
Definition: parsenodes.h:522
int location
Definition: parsenodes.h:525
char * name
Definition: parsenodes.h:518
List * args
Definition: primnodes.h:399
Index winref
Definition: primnodes.h:401
int location
Definition: primnodes.h:404

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_MERGE_WHEN, 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(), WindowDef::location, WindowFunc::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(), and transformJsonAggConstructor().