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 *p)
 
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)
 
bool agg_args_support_sendreceive (Aggref *aggref)
 
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

◆ agg_args_support_sendreceive()

bool agg_args_support_sendreceive ( Aggref aggref)

Definition at line 1957 of file parse_agg.c.

1958 {
1959  ListCell *lc;
1960 
1961  foreach(lc, aggref->args)
1962  {
1963  HeapTuple typeTuple;
1964  Form_pg_type pt;
1965  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1966  Oid type = exprType((Node *) tle->expr);
1967 
1969  if (!HeapTupleIsValid(typeTuple))
1970  elog(ERROR, "cache lookup failed for type %u", type);
1971 
1972  pt = (Form_pg_type) GETSTRUCT(typeTuple);
1973 
1974  if (!pt->typbyval &&
1975  (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
1976  {
1977  ReleaseSysCache(typeTuple);
1978  return false;
1979  }
1980  ReleaseSysCache(typeTuple);
1981  }
1982  return true;
1983 }
#define OidIsValid(objectId)
Definition: c.h:759
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:43
#define lfirst(lc)
Definition: pg_list.h:172
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
List * args
Definition: primnodes.h:443
Definition: nodes.h:129
Expr * expr
Definition: primnodes.h:1722
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:865
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:817
@ TYPEOID
Definition: syscache.h:114

References Aggref::args, elog(), ERROR, TargetEntry::expr, exprType(), GETSTRUCT, HeapTupleIsValid, lfirst, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), SearchSysCache1(), generate_unaccent_rules::type, and TYPEOID.

Referenced by preprocess_aggref().

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 2099 of file parse_agg.c.

2101 {
2102  List *args;
2103  FuncExpr *fexpr;
2104 
2105  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2106  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2107  make_agg_arg(INTERNALOID, InvalidOid));
2108 
2109  fexpr = makeFuncExpr(deserialfn_oid,
2110  INTERNALOID,
2111  args,
2112  InvalidOid,
2113  InvalidOid,
2115  *deserialfnexpr = (Expr *) fexpr;
2116 }
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:521
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2163
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:658
Definition: pg_list.h:54

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

2130 {
2131  List *args;
2132  int i;
2133 
2134  /*
2135  * Build expr tree for final function
2136  */
2137  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2138 
2139  /* finalfn may take additional args, which match agg's input types */
2140  for (i = 0; i < num_finalfn_inputs - 1; i++)
2141  {
2142  args = lappend(args,
2143  make_agg_arg(agg_input_types[i], agg_input_collation));
2144  }
2145 
2146  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2147  agg_result_type,
2148  args,
2149  InvalidOid,
2150  agg_input_collation,
2152  /* finalfn is currently never treated as variadic */
2153 }
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
#define list_make1(x1)
Definition: pg_list.h:212

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

2078 {
2079  List *args;
2080  FuncExpr *fexpr;
2081 
2082  /* serialfn always takes INTERNAL and returns BYTEA */
2083  args = list_make1(make_agg_arg(INTERNALOID, InvalidOid));
2084 
2085  fexpr = makeFuncExpr(serialfn_oid,
2086  BYTEAOID,
2087  args,
2088  InvalidOid,
2089  InvalidOid,
2091  *serialfnexpr = (Expr *) fexpr;
2092 }

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

2025 {
2026  List *args;
2027  FuncExpr *fexpr;
2028  int i;
2029 
2030  /*
2031  * Build arg list to use in the transfn FuncExpr node.
2032  */
2033  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2034 
2035  for (i = agg_num_direct_inputs; i < agg_num_inputs; i++)
2036  {
2037  args = lappend(args,
2038  make_agg_arg(agg_input_types[i], agg_input_collation));
2039  }
2040 
2041  fexpr = makeFuncExpr(transfn_oid,
2042  agg_state_type,
2043  args,
2044  InvalidOid,
2045  agg_input_collation,
2047  fexpr->funcvariadic = agg_variadic;
2048  *transfnexpr = (Expr *) fexpr;
2049 
2050  /*
2051  * Build invtransfn expression if requested, with same args as transfn
2052  */
2053  if (invtransfnexpr != NULL)
2054  {
2055  if (OidIsValid(invtransfn_oid))
2056  {
2057  fexpr = makeFuncExpr(invtransfn_oid,
2058  agg_state_type,
2059  args,
2060  InvalidOid,
2061  agg_input_collation,
2063  fexpr->funcvariadic = agg_variadic;
2064  *invtransfnexpr = (Expr *) fexpr;
2065  }
2066  else
2067  *invtransfnexpr = NULL;
2068  }
2069 }

References generate_unaccent_rules::args, COERCE_EXPLICIT_CALL, 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 1792 of file parse_agg.c.

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

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

1896 {
1897  int numArguments = 0;
1898  ListCell *lc;
1899 
1900  Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
1901 
1902  foreach(lc, aggref->aggargtypes)
1903  {
1904  inputTypes[numArguments++] = lfirst_oid(lc);
1905  }
1906 
1907  return numArguments;
1908 }
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition: pg_list.h:174

References Assert(), FUNC_MAX_ARGS, lfirst_oid, and list_length().

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

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1067 of file parse_agg.c.

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

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

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

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

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

References addTargetToSortList(), Aggref::aggdirectargs, Aggref::aggdistinct, 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().

◆ transformGroupingFunc()

Node* transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)

Definition at line 248 of file parse_agg.c.

249 {
250  ListCell *lc;
251  List *args = p->args;
252  List *result_list = NIL;
254 
255  if (list_length(args) > 31)
256  ereport(ERROR,
257  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
258  errmsg("GROUPING must have fewer than 32 arguments"),
259  parser_errposition(pstate, p->location)));
260 
261  foreach(lc, args)
262  {
263  Node *current_result;
264 
265  current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
266 
267  /* acceptability of expressions is checked later */
268 
269  result_list = lappend(result_list, current_result);
270  }
271 
272  result->args = result_list;
273  result->location = p->location;
274 
275  check_agglevels_and_constraints(pstate, (Node *) result);
276 
277  return (Node *) result;
278 }
#define makeNode(_type_)
Definition: nodes.h:176
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:92
ParseExprKind p_expr_kind
Definition: parse_node.h:210

References generate_unaccent_rules::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 810 of file parse_agg.c.

812 {
813  const char *err;
814  bool errkind;
815 
816  /*
817  * A window function call can't contain another one (but aggs are OK). XXX
818  * is this required by spec, or just an unimplemented feature?
819  *
820  * Note: we don't need to check the filter expression here, because the
821  * context checks done below and in transformAggregateCall would have
822  * already rejected any window funcs or aggs within the filter.
823  */
824  if (pstate->p_hasWindowFuncs &&
825  contain_windowfuncs((Node *) wfunc->args))
826  ereport(ERROR,
827  (errcode(ERRCODE_WINDOWING_ERROR),
828  errmsg("window function calls cannot be nested"),
829  parser_errposition(pstate,
830  locate_windowfunc((Node *) wfunc->args))));
831 
832  /*
833  * Check to see if the window function is in an invalid place within the
834  * query.
835  *
836  * For brevity we support two schemes for reporting an error here: set
837  * "err" to a custom message, or set "errkind" true if the error context
838  * is sufficiently identified by what ParseExprKindName will return, *and*
839  * what it will return is just a SQL keyword. (Otherwise, use a custom
840  * message to avoid creating translation problems.)
841  */
842  err = NULL;
843  errkind = false;
844  switch (pstate->p_expr_kind)
845  {
846  case EXPR_KIND_NONE:
847  Assert(false); /* can't happen */
848  break;
849  case EXPR_KIND_OTHER:
850  /* Accept window func here; caller must throw error if wanted */
851  break;
852  case EXPR_KIND_JOIN_ON:
854  err = _("window functions are not allowed in JOIN conditions");
855  break;
857  /* can't get here, but just in case, throw an error */
858  errkind = true;
859  break;
861  err = _("window functions are not allowed in functions in FROM");
862  break;
863  case EXPR_KIND_WHERE:
864  errkind = true;
865  break;
866  case EXPR_KIND_POLICY:
867  err = _("window functions are not allowed in policy expressions");
868  break;
869  case EXPR_KIND_HAVING:
870  errkind = true;
871  break;
872  case EXPR_KIND_FILTER:
873  errkind = true;
874  break;
880  err = _("window functions are not allowed in window definitions");
881  break;
883  /* okay */
884  break;
888  errkind = true;
889  break;
891  err = _("window functions are not allowed in MERGE WHEN conditions");
892  break;
893  case EXPR_KIND_GROUP_BY:
894  errkind = true;
895  break;
896  case EXPR_KIND_ORDER_BY:
897  /* okay */
898  break;
900  /* okay */
901  break;
902  case EXPR_KIND_LIMIT:
903  case EXPR_KIND_OFFSET:
904  errkind = true;
905  break;
906  case EXPR_KIND_RETURNING:
907  errkind = true;
908  break;
909  case EXPR_KIND_VALUES:
911  errkind = true;
912  break;
915  err = _("window functions are not allowed in check constraints");
916  break;
919  err = _("window functions are not allowed in DEFAULT expressions");
920  break;
922  err = _("window functions are not allowed in index expressions");
923  break;
925  err = _("window functions are not allowed in statistics expressions");
926  break;
928  err = _("window functions are not allowed in index predicates");
929  break;
931  err = _("window functions are not allowed in transform expressions");
932  break;
934  err = _("window functions are not allowed in EXECUTE parameters");
935  break;
937  err = _("window functions are not allowed in trigger WHEN conditions");
938  break;
940  err = _("window functions are not allowed in partition bound");
941  break;
943  err = _("window functions are not allowed in partition key expressions");
944  break;
946  err = _("window functions are not allowed in CALL arguments");
947  break;
949  err = _("window functions are not allowed in COPY FROM WHERE conditions");
950  break;
952  err = _("window functions are not allowed in column generation expressions");
953  break;
955  errkind = true;
956  break;
957 
958  /*
959  * There is intentionally no default: case here, so that the
960  * compiler will warn if we add a new ParseExprKind without
961  * extending this switch. If we do see an unrecognized value at
962  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
963  * which is sane anyway.
964  */
965  }
966  if (err)
967  ereport(ERROR,
968  (errcode(ERRCODE_WINDOWING_ERROR),
969  errmsg_internal("%s", err),
970  parser_errposition(pstate, wfunc->location)));
971  if (errkind)
972  ereport(ERROR,
973  (errcode(ERRCODE_WINDOWING_ERROR),
974  /* translator: %s is name of a SQL construct, eg GROUP BY */
975  errmsg("window functions are not allowed in %s",
976  ParseExprKindName(pstate->p_expr_kind)),
977  parser_errposition(pstate, wfunc->location)));
978 
979  /*
980  * If the OVER clause just specifies a window name, find that WINDOW
981  * clause (which had better be present). Otherwise, try to match all the
982  * properties of the OVER clause, and make a new entry in the p_windowdefs
983  * list if no luck.
984  */
985  if (windef->name)
986  {
987  Index winref = 0;
988  ListCell *lc;
989 
990  Assert(windef->refname == NULL &&
991  windef->partitionClause == NIL &&
992  windef->orderClause == NIL &&
994 
995  foreach(lc, pstate->p_windowdefs)
996  {
997  WindowDef *refwin = (WindowDef *) lfirst(lc);
998 
999  winref++;
1000  if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1001  {
1002  wfunc->winref = winref;
1003  break;
1004  }
1005  }
1006  if (lc == NULL) /* didn't find it? */
1007  ereport(ERROR,
1008  (errcode(ERRCODE_UNDEFINED_OBJECT),
1009  errmsg("window \"%s\" does not exist", windef->name),
1010  parser_errposition(pstate, windef->location)));
1011  }
1012  else
1013  {
1014  Index winref = 0;
1015  ListCell *lc;
1016 
1017  foreach(lc, pstate->p_windowdefs)
1018  {
1019  WindowDef *refwin = (WindowDef *) lfirst(lc);
1020 
1021  winref++;
1022  if (refwin->refname && windef->refname &&
1023  strcmp(refwin->refname, windef->refname) == 0)
1024  /* matched on refname */ ;
1025  else if (!refwin->refname && !windef->refname)
1026  /* matched, no refname */ ;
1027  else
1028  continue;
1029 
1030  /*
1031  * Also see similar de-duplication code in optimize_window_clauses
1032  */
1033  if (equal(refwin->partitionClause, windef->partitionClause) &&
1034  equal(refwin->orderClause, windef->orderClause) &&
1035  refwin->frameOptions == windef->frameOptions &&
1036  equal(refwin->startOffset, windef->startOffset) &&
1037  equal(refwin->endOffset, windef->endOffset))
1038  {
1039  /* found a duplicate window specification */
1040  wfunc->winref = winref;
1041  break;
1042  }
1043  }
1044  if (lc == NULL) /* didn't find it? */
1045  {
1046  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1047  wfunc->winref = list_length(pstate->p_windowdefs);
1048  }
1049  }
1050 
1051  pstate->p_hasWindowFuncs = true;
1052 }
unsigned int Index
Definition: c.h:598
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
#define _(x)
Definition: elog.c:91
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:2951
@ 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:606
bool contain_windowfuncs(Node *node)
Definition: rewriteManip.c:215
int locate_windowfunc(Node *node)
Definition: rewriteManip.c:253
bool p_hasWindowFuncs
Definition: parse_node.h:223
List * p_windowdefs
Definition: parse_node.h:209
List * orderClause
Definition: parsenodes.h:565
List * partitionClause
Definition: parsenodes.h:564
Node * startOffset
Definition: parsenodes.h:567
char * refname
Definition: parsenodes.h:563
Node * endOffset
Definition: parsenodes.h:568
int frameOptions
Definition: parsenodes.h:566
int location
Definition: parsenodes.h:569
char * name
Definition: parsenodes.h:562
List * args
Definition: primnodes.h:550
Index winref
Definition: primnodes.h:554
int location
Definition: primnodes.h:560

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