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

1957 {
1958  ListCell *lc;
1959 
1960  foreach(lc, aggref->args)
1961  {
1962  HeapTuple typeTuple;
1963  Form_pg_type pt;
1964  TargetEntry *tle = (TargetEntry *) lfirst(lc);
1965  Oid type = exprType((Node *) tle->expr);
1966 
1968  if (!HeapTupleIsValid(typeTuple))
1969  elog(ERROR, "cache lookup failed for type %u", type);
1970 
1971  pt = (Form_pg_type) GETSTRUCT(typeTuple);
1972 
1973  if (!pt->typbyval &&
1974  (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
1975  {
1976  ReleaseSysCache(typeTuple);
1977  return false;
1978  }
1979  ReleaseSysCache(typeTuple);
1980  }
1981  return true;
1982 }
#define OidIsValid(objectId)
Definition: c.h:764
#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:446
Definition: nodes.h:129
Expr * expr
Definition: primnodes.h:1895
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ TYPEOID
Definition: syscache.h:114
const char * type

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

Referenced by preprocess_aggref().

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)

Definition at line 2098 of file parse_agg.c.

2100 {
2101  List *args;
2102  FuncExpr *fexpr;
2103 
2104  /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2105  args = list_make2(make_agg_arg(BYTEAOID, InvalidOid),
2106  make_agg_arg(INTERNALOID, InvalidOid));
2107 
2108  fexpr = makeFuncExpr(deserialfn_oid,
2109  INTERNALOID,
2110  args,
2111  InvalidOid,
2112  InvalidOid,
2114  *deserialfnexpr = (Expr *) fexpr;
2115 }
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition: makefuncs.c:522
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition: parse_agg.c:2162
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define InvalidOid
Definition: postgres_ext.h:36
@ COERCE_EXPLICIT_CALL
Definition: primnodes.h:661
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 2122 of file parse_agg.c.

2129 {
2130  List *args;
2131  int i;
2132 
2133  /*
2134  * Build expr tree for final function
2135  */
2136  args = list_make1(make_agg_arg(agg_state_type, agg_input_collation));
2137 
2138  /* finalfn may take additional args, which match agg's input types */
2139  for (i = 0; i < num_finalfn_inputs - 1; i++)
2140  {
2141  args = lappend(args,
2142  make_agg_arg(agg_input_types[i], agg_input_collation));
2143  }
2144 
2145  *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2146  agg_result_type,
2147  args,
2148  InvalidOid,
2149  agg_input_collation,
2151  /* finalfn is currently never treated as variadic */
2152 }
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 2075 of file parse_agg.c.

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

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

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

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

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

1895 {
1896  int numArguments = 0;
1897  ListCell *lc;
1898 
1899  Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
1900 
1901  foreach(lc, aggref->aggargtypes)
1902  {
1903  inputTypes[numArguments++] = lfirst_oid(lc);
1904  }
1905 
1906  return numArguments;
1907 }
#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_helper(), and preprocess_aggref().

◆ parseCheckAggregates()

void parseCheckAggregates ( ParseState pstate,
Query qry 
)

Definition at line 1066 of file parse_agg.c.

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

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

1924 {
1925  /* resolve actual type of transition state, if polymorphic */
1926  if (IsPolymorphicType(aggtranstype))
1927  {
1928  /* have to fetch the agg's declared input types... */
1929  Oid *declaredArgTypes;
1930  int agg_nargs;
1931 
1932  (void) get_func_signature(aggfuncid, &declaredArgTypes, &agg_nargs);
1933 
1934  /*
1935  * VARIADIC ANY aggs could have more actual than declared args, but
1936  * such extra args can't affect polymorphic type resolution.
1937  */
1938  Assert(agg_nargs <= numArguments);
1939 
1940  aggtranstype = enforce_generic_type_consistency(inputTypes,
1941  declaredArgTypes,
1942  agg_nargs,
1943  aggtranstype,
1944  false);
1945  pfree(declaredArgTypes);
1946  }
1947  return aggtranstype;
1948 }
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1700
void pfree(void *pointer)
Definition: mcxt.c:1456
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:343
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:241
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:452
List * aggdirectargs
Definition: primnodes.h:443
List * aggorder
Definition: primnodes.h:449
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(), and transformJsonAggConstructor().

◆ 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:110
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 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 
1029  /*
1030  * Also see similar de-duplication code in optimize_window_clauses
1031  */
1032  if (equal(refwin->partitionClause, windef->partitionClause) &&
1033  equal(refwin->orderClause, windef->orderClause) &&
1034  refwin->frameOptions == windef->frameOptions &&
1035  equal(refwin->startOffset, windef->startOffset) &&
1036  equal(refwin->endOffset, windef->endOffset))
1037  {
1038  /* found a duplicate window specification */
1039  wfunc->winref = winref;
1040  break;
1041  }
1042  }
1043  if (lc == NULL) /* didn't find it? */
1044  {
1045  pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1046  wfunc->winref = list_length(pstate->p_windowdefs);
1047  }
1048  }
1049 
1050  pstate->p_hasWindowFuncs = true;
1051 }
unsigned int Index
Definition: c.h:603
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
#define _(x)
Definition: elog.c:91
void err(int eval, const char *fmt,...)
Definition: err.c:43
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3064
@ 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:605
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:564
List * partitionClause
Definition: parsenodes.h:563
Node * startOffset
Definition: parsenodes.h:566
char * refname
Definition: parsenodes.h:562
Node * endOffset
Definition: parsenodes.h:567
int frameOptions
Definition: parsenodes.h:565
int location
Definition: parsenodes.h:568
char * name
Definition: parsenodes.h:561
List * args
Definition: primnodes.h:553
Index winref
Definition: primnodes.h:557
int location
Definition: primnodes.h:563

References _, WindowFunc::args, Assert(), contain_windowfuncs(), WindowDef::endOffset, equal(), ereport, err(), 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().