PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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)
extern

Definition at line 2184 of file parse_agg.c.

2185{
2186 ListCell *lc;
2187
2188 foreach(lc, aggref->args)
2189 {
2193 Oid type = exprType((Node *) tle->expr);
2194
2195 /*
2196 * RECORD is a special case: it has typsend/typreceive functions, but
2197 * record_recv only works if passed the correct typmod to identify the
2198 * specific anonymous record type. array_agg_deserialize cannot do
2199 * that, so we have to disclaim support for the case.
2200 */
2201 if (type == RECORDOID)
2202 return false;
2203
2206 elog(ERROR, "cache lookup failed for type %u", type);
2207
2209
2210 if (!pt->typbyval &&
2211 (!OidIsValid(pt->typsend) || !OidIsValid(pt->typreceive)))
2212 {
2214 return false;
2215 }
2217 }
2218 return true;
2219}
#define OidIsValid(objectId)
Definition c.h:858
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
#define lfirst(lc)
Definition pg_list.h:172
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
unsigned int Oid
static int fb(int x)
List * args
Definition primnodes.h:488
Definition nodes.h:135
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
const char * type

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

Referenced by preprocess_aggref().

◆ build_aggregate_deserialfn_expr()

void build_aggregate_deserialfn_expr ( Oid  deserialfn_oid,
Expr **  deserialfnexpr 
)
extern

Definition at line 2335 of file parse_agg.c.

2337{
2338 List *args;
2339 FuncExpr *fexpr;
2340
2341 /* deserialfn always takes BYTEA, INTERNAL and returns INTERNAL */
2344
2345 fexpr = makeFuncExpr(deserialfn_oid,
2347 args,
2348 InvalidOid,
2349 InvalidOid,
2351 *deserialfnexpr = (Expr *) fexpr;
2352}
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition makefuncs.c:594
static Node * make_agg_arg(Oid argtype, Oid argcollation)
Definition parse_agg.c:2399
#define list_make2(x1, x2)
Definition pg_list.h:246
#define InvalidOid
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
Definition pg_list.h:54

References COERCE_EXPLICIT_CALL, fb(), 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 
)
extern

Definition at line 2359 of file parse_agg.c.

2366{
2367 List *args;
2368 int i;
2369
2370 /*
2371 * Build expr tree for final function
2372 */
2374
2375 /* finalfn may take additional args, which match agg's input types */
2376 for (i = 0; i < num_finalfn_inputs - 1; i++)
2377 {
2378 args = lappend(args,
2380 }
2381
2382 *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
2384 args,
2385 InvalidOid,
2388 /* finalfn is currently never treated as variadic */
2389}
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
#define list_make1(x1)
Definition pg_list.h:244

References COERCE_EXPLICIT_CALL, fb(), 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 
)
extern

Definition at line 2312 of file parse_agg.c.

2314{
2315 List *args;
2316 FuncExpr *fexpr;
2317
2318 /* serialfn always takes INTERNAL and returns BYTEA */
2320
2321 fexpr = makeFuncExpr(serialfn_oid,
2322 BYTEAOID,
2323 args,
2324 InvalidOid,
2325 InvalidOid,
2327 *serialfnexpr = (Expr *) fexpr;
2328}

References COERCE_EXPLICIT_CALL, fb(), 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 
)
extern

Definition at line 2251 of file parse_agg.c.

2261{
2262 List *args;
2263 FuncExpr *fexpr;
2264 int i;
2265
2266 /*
2267 * Build arg list to use in the transfn FuncExpr node.
2268 */
2270
2272 {
2273 args = lappend(args,
2275 }
2276
2277 fexpr = makeFuncExpr(transfn_oid,
2279 args,
2280 InvalidOid,
2283 fexpr->funcvariadic = agg_variadic;
2284 *transfnexpr = (Expr *) fexpr;
2285
2286 /*
2287 * Build invtransfn expression if requested, with same args as transfn
2288 */
2289 if (invtransfnexpr != NULL)
2290 {
2291 if (OidIsValid(invtransfn_oid))
2292 {
2293 fexpr = makeFuncExpr(invtransfn_oid,
2295 args,
2296 InvalidOid,
2299 fexpr->funcvariadic = agg_variadic;
2300 *invtransfnexpr = (Expr *) fexpr;
2301 }
2302 else
2304 }
2305}

References COERCE_EXPLICIT_CALL, fb(), 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 
)
extern

Definition at line 2019 of file parse_agg.c.

2020{
2022 List *result = NIL;
2023 double numsets = 1;
2024 ListCell *lc;
2025
2026 if (groupingSets == NIL)
2027 return NIL;
2028
2029 foreach(lc, groupingSets)
2030 {
2032 GroupingSet *gs = lfirst(lc);
2033
2035
2037
2038 numsets *= list_length(current_result);
2039
2040 if (limit >= 0 && numsets > limit)
2041 return NIL;
2042
2044 }
2045
2046 /*
2047 * Do cartesian product between sublists of expanded_groups. While at it,
2048 * remove any duplicate elements from individual grouping sets (we must
2049 * NOT change the number of sets though)
2050 */
2051
2052 foreach(lc, (List *) linitial(expanded_groups))
2053 {
2055 }
2056
2058 {
2059 List *p = lfirst(lc);
2060 List *new_result = NIL;
2061 ListCell *lc2;
2062
2063 foreach(lc2, result)
2064 {
2065 List *q = lfirst(lc2);
2066 ListCell *lc3;
2067
2068 foreach(lc3, p)
2069 {
2071 list_union_int(q, (List *) lfirst(lc3)));
2072 }
2073 }
2075 }
2076
2077 /* Now sort the lists by length and deduplicate if necessary */
2078 if (!groupDistinct || list_length(result) < 2)
2080 else
2081 {
2082 ListCell *cell;
2083 List *prev;
2084
2085 /* Sort each groupset individually */
2086 foreach(cell, result)
2088
2089 /* Now sort the list of groupsets by length and contents */
2091
2092 /* Finally, remove duplicates */
2093 prev = linitial(result);
2094 for_each_from(cell, result, 1)
2095 {
2096 if (equal(lfirst(cell), prev))
2098 else
2099 prev = lfirst(cell);
2100 }
2101 }
2102
2103 return result;
2104}
#define Assert(condition)
Definition c.h:943
uint32 result
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
int list_int_cmp(const ListCell *p1, const ListCell *p2)
Definition list.c:1691
List * list_union_int(const List *list1, const List *list2)
Definition list.c:1113
static int cmp_list_len_asc(const ListCell *a, const ListCell *b)
Definition parse_agg.c:1975
static int cmp_list_len_contents_asc(const ListCell *a, const ListCell *b)
Definition parse_agg.c:1985
static List * expand_groupingset_node(GroupingSet *gs)
Definition parse_agg.c:1873
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:423
#define for_each_from(cell, lst, N)
Definition pg_list.h:446
#define linitial(l)
Definition pg_list.h:178

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

Referenced by parseCheckAggregates(), query_is_distinct_for(), and subquery_planner().

◆ get_aggregate_argtypes()

int get_aggregate_argtypes ( Aggref aggref,
Oid inputTypes 
)
extern

Definition at line 2122 of file parse_agg.c.

2123{
2124 int numArguments = 0;
2125 ListCell *lc;
2126
2127 Assert(list_length(aggref->aggargtypes) <= FUNC_MAX_ARGS);
2128
2129 foreach(lc, aggref->aggargtypes)
2130 {
2131 inputTypes[numArguments++] = lfirst_oid(lc);
2132 }
2133
2134 return numArguments;
2135}
#define FUNC_MAX_ARGS
#define lfirst_oid(lc)
Definition pg_list.h:174

References Assert, fb(), 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 
)
extern

Definition at line 1160 of file parse_agg.c.

1161{
1162 List *gset_common = NIL;
1163 List *groupClauses = NIL;
1164 List *groupClauseCommonVars = NIL;
1165 bool have_non_var_grouping;
1166 List *func_grouped_rels = NIL;
1167 ListCell *l;
1168 bool hasJoinRTEs;
1169 bool hasSelfRefRTEs;
1170 Node *clause;
1171
1172 /* This should only be called if we found aggregates or grouping */
1173 Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets);
1174
1175 /*
1176 * If we have grouping sets, expand them and find the intersection of all
1177 * sets.
1178 */
1179 if (qry->groupingSets)
1180 {
1181 /*
1182 * The limit of 4096 is arbitrary and exists simply to avoid resource
1183 * issues from pathological constructs.
1184 */
1185 List *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096);
1186
1187 if (!gsets)
1188 ereport(ERROR,
1190 errmsg("too many grouping sets present (maximum 4096)"),
1191 parser_errposition(pstate,
1192 qry->groupClause
1193 ? exprLocation((Node *) qry->groupClause)
1194 : exprLocation((Node *) qry->groupingSets))));
1195
1196 /*
1197 * The intersection will often be empty, so help things along by
1198 * seeding the intersect with the smallest set.
1199 */
1200 gset_common = linitial(gsets);
1201
1202 if (gset_common)
1203 {
1204 for_each_from(l, gsets, 1)
1205 {
1206 gset_common = list_intersection_int(gset_common, lfirst(l));
1207 if (!gset_common)
1208 break;
1209 }
1210 }
1211
1212 /*
1213 * If there was only one grouping set in the expansion, AND if the
1214 * groupClause is non-empty (meaning that the grouping set is not
1215 * empty either), then we can ditch the grouping set and pretend we
1216 * just had a normal GROUP BY.
1217 */
1218 if (list_length(gsets) == 1 && qry->groupClause)
1219 qry->groupingSets = NIL;
1220 }
1221
1222 /*
1223 * Scan the range table to see if there are JOIN or self-reference CTE
1224 * entries. We'll need this info below.
1225 */
1226 hasJoinRTEs = hasSelfRefRTEs = false;
1227 foreach(l, pstate->p_rtable)
1228 {
1230
1231 if (rte->rtekind == RTE_JOIN)
1232 hasJoinRTEs = true;
1233 else if (rte->rtekind == RTE_CTE && rte->self_reference)
1234 hasSelfRefRTEs = true;
1235 }
1236
1237 /*
1238 * Build a list of the acceptable GROUP BY expressions to save in the
1239 * RTE_GROUP RTE, and for use by substitute_grouped_columns().
1240 *
1241 * We get the TLE, not just the expr, because GROUPING wants to know the
1242 * sortgroupref.
1243 */
1244 foreach(l, qry->groupClause)
1245 {
1247 TargetEntry *expr;
1248
1250 if (expr == NULL)
1251 continue; /* probably cannot happen */
1252
1253 groupClauses = lappend(groupClauses, expr);
1254 }
1255
1256 /*
1257 * If there are any acceptable GROUP BY expressions, build an RTE and
1258 * nsitem for the result of the grouping step. (It's important to do this
1259 * before flattening join alias vars in groupClauses, because the RTE
1260 * should preserve any alias vars that were in the input.)
1261 */
1262 if (groupClauses)
1263 {
1264 pstate->p_grouping_nsitem =
1265 addRangeTableEntryForGroup(pstate, groupClauses);
1266
1267 /* Set qry->rtable again in case it was previously NIL */
1268 qry->rtable = pstate->p_rtable;
1269 /* Mark the Query as having RTE_GROUP RTE */
1270 qry->hasGroupRTE = true;
1271 }
1272
1273 /*
1274 * If there are join alias vars involved, we have to flatten them to the
1275 * underlying vars, so that aliased and unaliased vars will be correctly
1276 * taken as equal. We can skip the expense of doing this if no rangetable
1277 * entries are RTE_JOIN kind.
1278 */
1279 if (hasJoinRTEs)
1280 groupClauses = (List *)
1281 flatten_join_alias_for_parser(qry, (Node *) groupClauses, 0);
1282
1283 /*
1284 * Detect whether any of the grouping expressions aren't simple Vars; if
1285 * they're all Vars then we don't have to work so hard in the recursive
1286 * scans. (Note we have to flatten aliases before this.)
1287 *
1288 * Track Vars that are included in all grouping sets separately in
1289 * groupClauseCommonVars, since these are the only ones we can use to
1290 * check for functional dependencies.
1291 */
1292 have_non_var_grouping = false;
1293 foreach(l, groupClauses)
1294 {
1295 TargetEntry *tle = lfirst(l);
1296
1297 if (!IsA(tle->expr, Var))
1298 {
1299 have_non_var_grouping = true;
1300 }
1301 else if (!qry->groupingSets ||
1302 list_member_int(gset_common, tle->ressortgroupref))
1303 {
1304 groupClauseCommonVars = lappend(groupClauseCommonVars, tle->expr);
1305 }
1306 }
1307
1308 /*
1309 * Replace grouped variables in the targetlist and HAVING clause with Vars
1310 * that reference the RTE_GROUP RTE. Emit an error message if we find any
1311 * ungrouped variables.
1312 *
1313 * Note: because we check resjunk tlist elements as well as regular ones,
1314 * this will also find ungrouped variables that came from ORDER BY and
1315 * WINDOW clauses. For that matter, it's also going to examine the
1316 * grouping expressions themselves --- but they'll all pass the test ...
1317 *
1318 * We also finalize GROUPING expressions, but for that we need to traverse
1319 * the original (unflattened) clause in order to modify nodes.
1320 */
1321 clause = (Node *) qry->targetList;
1322 finalize_grouping_exprs(clause, pstate, qry,
1323 groupClauses, hasJoinRTEs,
1324 have_non_var_grouping);
1325 if (hasJoinRTEs)
1326 clause = flatten_join_alias_for_parser(qry, clause, 0);
1327 qry->targetList = (List *)
1328 substitute_grouped_columns(clause, pstate, qry,
1329 groupClauses, groupClauseCommonVars,
1330 gset_common,
1331 have_non_var_grouping,
1332 &func_grouped_rels);
1333
1334 clause = (Node *) qry->havingQual;
1335 finalize_grouping_exprs(clause, pstate, qry,
1336 groupClauses, hasJoinRTEs,
1337 have_non_var_grouping);
1338 if (hasJoinRTEs)
1339 clause = flatten_join_alias_for_parser(qry, clause, 0);
1340 qry->havingQual =
1341 substitute_grouped_columns(clause, pstate, qry,
1342 groupClauses, groupClauseCommonVars,
1343 gset_common,
1344 have_non_var_grouping,
1345 &func_grouped_rels);
1346
1347 /*
1348 * Per spec, aggregates can't appear in a recursive term.
1349 */
1350 if (pstate->p_hasAggs && hasSelfRefRTEs)
1351 ereport(ERROR,
1353 errmsg("aggregate functions are not allowed in a recursive query's recursive term"),
1354 parser_errposition(pstate,
1355 locate_agg_of_level((Node *) qry, 0))));
1356}
int errcode(int sqlerrcode)
Definition elog.c:874
#define ereport(elevel,...)
Definition elog.h:152
List * list_intersection_int(const List *list1, const List *list2)
Definition list.c:1200
bool list_member_int(const List *list, int datum)
Definition list.c:702
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1392
#define IsA(nodeptr, _type_)
Definition nodes.h:164
static char * errmsg
static void finalize_grouping_exprs(Node *node, ParseState *pstate, Query *qry, List *groupClauses, bool hasJoinRTEs, bool have_non_var_grouping)
Definition parse_agg.c:1634
List * expand_grouping_sets(List *groupingSets, bool groupDistinct, int limit)
Definition parse_agg.c:2019
static Node * substitute_grouped_columns(Node *node, ParseState *pstate, Query *qry, List *groupClauses, List *groupClauseCommonVars, List *gset_common, bool have_non_var_grouping, List **func_grouped_rels)
Definition parse_agg.c:1371
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
ParseNamespaceItem * addRangeTableEntryForGroup(ParseState *pstate, List *groupClauses)
@ RTE_JOIN
@ RTE_CTE
int locate_agg_of_level(Node *node, int levelsup)
ParseNamespaceItem * p_grouping_nsitem
Definition parse_node.h:230
List * p_rtable
Definition parse_node.h:215
bool p_hasAggs
Definition parse_node.h:246
bool groupDistinct
Definition parsenodes.h:220
List * groupClause
Definition parsenodes.h:219
Node * havingQual
Definition parsenodes.h:225
List * rtable
Definition parsenodes.h:178
List * targetList
Definition parsenodes.h:201
List * groupingSets
Definition parsenodes.h:223
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition tlist.c:376
Node * flatten_join_alias_for_parser(Query *query, Node *node, int sublevels_up)
Definition var.c:819

References addRangeTableEntryForGroup(), Assert, ereport, errcode(), errmsg, ERROR, expand_grouping_sets(), exprLocation(), fb(), finalize_grouping_exprs(), flatten_join_alias_for_parser(), 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_grouping_nsitem, ParseState::p_hasAggs, ParseState::p_rtable, parser_errposition(), Query::rtable, RTE_CTE, RTE_JOIN, substitute_grouped_columns(), and Query::targetList.

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

◆ resolve_aggregate_transtype()

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

Definition at line 2148 of file parse_agg.c.

2152{
2153 /* resolve actual type of transition state, if polymorphic */
2154 if (IsPolymorphicType(aggtranstype))
2155 {
2156 /* have to fetch the agg's declared input types... */
2158 int agg_nargs;
2159
2161
2162 /*
2163 * VARIADIC ANY aggs could have more actual than declared args, but
2164 * such extra args can't affect polymorphic type resolution.
2165 */
2166 Assert(agg_nargs <= numArguments);
2167
2170 agg_nargs,
2171 aggtranstype,
2172 false);
2174 }
2175 return aggtranstype;
2176}
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition lsyscache.c:1916
void pfree(void *pointer)
Definition mcxt.c:1616
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(), fb(), 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 
)
extern

Definition at line 113 of file parse_agg.c.

115{
116 List *argtypes = NIL;
117 List *tlist = NIL;
118 List *torder = NIL;
119 List *tdistinct = NIL;
120 AttrNumber attno = 1;
121 int save_next_resno;
122 ListCell *lc;
123
124 if (AGGKIND_IS_ORDERED_SET(agg->aggkind))
125 {
126 /*
127 * For an ordered-set agg, the args list includes direct args and
128 * aggregated args; we must split them apart.
129 */
130 int numDirectArgs = list_length(args) - list_length(aggorder);
131 List *aargs;
132 ListCell *lc2;
133
134 Assert(numDirectArgs >= 0);
135
137 agg->aggdirectargs = list_truncate(args, numDirectArgs);
138
139 /*
140 * Build a tlist from the aggregated args, and make a sortlist entry
141 * for each one. Note that the expressions in the SortBy nodes are
142 * ignored (they are the raw versions of the transformed args); we are
143 * just looking at the sort information in the SortBy nodes.
144 */
145 forboth(lc, aargs, lc2, aggorder)
146 {
147 Expr *arg = (Expr *) lfirst(lc);
148 SortBy *sortby = (SortBy *) lfirst(lc2);
150
151 /* We don't bother to assign column names to the entries */
152 tle = makeTargetEntry(arg, attno++, NULL, false);
153 tlist = lappend(tlist, tle);
154
156 torder, tlist, sortby);
157 }
158
159 /* Never any DISTINCT in an ordered-set agg */
160 Assert(!agg_distinct);
161 }
162 else
163 {
164 /* Regular aggregate, so it has no direct args */
165 agg->aggdirectargs = NIL;
166
167 /*
168 * Transform the plain list of Exprs into a targetlist.
169 */
170 foreach(lc, args)
171 {
172 Expr *arg = (Expr *) lfirst(lc);
174
175 /* We don't bother to assign column names to the entries */
176 tle = makeTargetEntry(arg, attno++, NULL, false);
177 tlist = lappend(tlist, tle);
178 }
179
180 /*
181 * If we have an ORDER BY, transform it. This will add columns to the
182 * tlist if they appear in ORDER BY but weren't already in the arg
183 * list. They will be marked resjunk = true so we can tell them apart
184 * from regular aggregate arguments later.
185 *
186 * We need to mess with p_next_resno since it will be used to number
187 * any new targetlist entries.
188 */
190 pstate->p_next_resno = attno;
191
193 aggorder,
194 &tlist,
196 true /* force SQL99 rules */ );
197
198 /*
199 * If we have DISTINCT, transform that to produce a distinctList.
200 */
201 if (agg_distinct)
202 {
203 tdistinct = transformDistinctClause(pstate, &tlist, torder, true);
204
205 /*
206 * Remove this check if executor support for hashed distinct for
207 * aggregates is ever added.
208 */
209 foreach(lc, tdistinct)
210 {
212
213 if (!OidIsValid(sortcl->sortop))
214 {
215 Node *expr = get_sortgroupclause_expr(sortcl, tlist);
216
219 errmsg("could not identify an ordering operator for type %s",
220 format_type_be(exprType(expr))),
221 errdetail("Aggregates with DISTINCT must be able to sort their inputs."),
222 parser_errposition(pstate, exprLocation(expr))));
223 }
224 }
225 }
226
228 }
229
230 /* Update the Aggref with the transformation results */
231 agg->args = tlist;
232 agg->aggorder = torder;
233 agg->aggdistinct = tdistinct;
234
235 /*
236 * Now build the aggargtypes list with the type OIDs of the direct and
237 * aggregated args, ignoring any resjunk entries that might have been
238 * added by ORDER BY/DISTINCT processing. We can't do this earlier
239 * because said processing can modify some args' data types, in particular
240 * by resolving previously-unresolved "unknown" literals.
241 */
242 foreach(lc, agg->aggdirectargs)
243 {
244 Expr *arg = (Expr *) lfirst(lc);
245
246 argtypes = lappend_oid(argtypes, exprType((Node *) arg));
247 }
248 foreach(lc, tlist)
249 {
251
252 if (tle->resjunk)
253 continue; /* ignore junk */
254 argtypes = lappend_oid(argtypes, exprType((Node *) tle->expr));
255 }
256 agg->aggargtypes = argtypes;
257
259}
int16 AttrNumber
Definition attnum.h:21
Datum arg
Definition elog.c:1322
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * format_type_be(Oid type_oid)
List * list_copy_tail(const List *oldlist, int nskip)
Definition list.c:1613
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
List * list_truncate(List *list, int new_size)
Definition list.c:631
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition makefuncs.c:289
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr)
Definition parse_agg.c:308
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
List * addTargetToSortList(ParseState *pstate, TargetEntry *tle, List *sortlist, List *targetlist, SortBy *sortby)
@ EXPR_KIND_ORDER_BY
Definition parse_node.h:61
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:550
int p_next_resno
Definition parse_node.h:233
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition tlist.c:388

References addTargetToSortList(), arg, Assert, check_agglevels_and_constraints(), ereport, errcode(), errdetail(), errmsg, ERROR, EXPR_KIND_ORDER_BY, exprLocation(), exprType(), fb(), 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(), transformDistinctClause(), and transformSortClause().

Referenced by ParseFuncOrColumn(), and transformJsonAggConstructor().

◆ transformGroupingFunc()

Node * transformGroupingFunc ( ParseState pstate,
GroupingFunc p 
)
extern

Definition at line 269 of file parse_agg.c.

270{
271 ListCell *lc;
272 List *args = p->args;
275
276 if (list_length(args) > 31)
279 errmsg("GROUPING must have fewer than 32 arguments"),
280 parser_errposition(pstate, p->location)));
281
282 foreach(lc, args)
283 {
285
286 current_result = transformExpr(pstate, (Node *) lfirst(lc), pstate->p_expr_kind);
287
288 /* acceptability of expressions is checked later */
289
291 }
292
293 result->args = result_list;
294 result->location = p->location;
295
297
298 return (Node *) result;
299}
#define makeNode(_type_)
Definition nodes.h:161
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition parse_expr.c:121
ParseLoc location
Definition primnodes.h:574
ParseExprKind p_expr_kind
Definition parse_node.h:232

References check_agglevels_and_constraints(), ereport, errcode(), errmsg, ERROR, fb(), lappend(), lfirst, list_length(), GroupingFunc::location, makeNode, NIL, ParseState::p_expr_kind, parser_errposition(), result, and transformExpr().

Referenced by transformExprRecurse().

◆ transformWindowFuncCall()

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

Definition at line 894 of file parse_agg.c.

896{
897 const char *err;
898 bool errkind;
899
900 /*
901 * A window function call can't contain another one (but aggs are OK). XXX
902 * is this required by spec, or just an unimplemented feature?
903 *
904 * Note: we don't need to check the filter expression here, because the
905 * context checks done below and in transformAggregateCall would have
906 * already rejected any window funcs or aggs within the filter.
907 */
908 if (pstate->p_hasWindowFuncs &&
909 contain_windowfuncs((Node *) wfunc->args))
912 errmsg("window function calls cannot be nested"),
913 parser_errposition(pstate,
914 locate_windowfunc((Node *) wfunc->args))));
915
916 /*
917 * Check to see if the window function is in an invalid place within the
918 * query.
919 *
920 * For brevity we support two schemes for reporting an error here: set
921 * "err" to a custom message, or set "errkind" true if the error context
922 * is sufficiently identified by what ParseExprKindName will return, *and*
923 * what it will return is just a SQL keyword. (Otherwise, use a custom
924 * message to avoid creating translation problems.)
925 */
926 err = NULL;
927 errkind = false;
928 switch (pstate->p_expr_kind)
929 {
930 case EXPR_KIND_NONE:
931 Assert(false); /* can't happen */
932 break;
933 case EXPR_KIND_OTHER:
934 /* Accept window func here; caller must throw error if wanted */
935 break;
938 err = _("window functions are not allowed in JOIN conditions");
939 break;
941 /* can't get here, but just in case, throw an error */
942 errkind = true;
943 break;
945 err = _("window functions are not allowed in functions in FROM");
946 break;
947 case EXPR_KIND_WHERE:
948 errkind = true;
949 break;
950 case EXPR_KIND_POLICY:
951 err = _("window functions are not allowed in policy expressions");
952 break;
953 case EXPR_KIND_HAVING:
954 errkind = true;
955 break;
956 case EXPR_KIND_FILTER:
957 errkind = true;
958 break;
964 err = _("window functions are not allowed in window definitions");
965 break;
967 /* okay */
968 break;
972 errkind = true;
973 break;
975 err = _("window functions are not allowed in MERGE WHEN conditions");
976 break;
978 errkind = true;
979 break;
981 /* okay */
982 break;
984 /* okay */
985 break;
986 case EXPR_KIND_LIMIT:
987 case EXPR_KIND_OFFSET:
988 errkind = true;
989 break;
992 errkind = true;
993 break;
994 case EXPR_KIND_VALUES:
996 errkind = true;
997 break;
1000 err = _("window functions are not allowed in check constraints");
1001 break;
1004 err = _("window functions are not allowed in DEFAULT expressions");
1005 break;
1007 err = _("window functions are not allowed in index expressions");
1008 break;
1010 err = _("window functions are not allowed in statistics expressions");
1011 break;
1013 err = _("window functions are not allowed in index predicates");
1014 break;
1016 err = _("window functions are not allowed in transform expressions");
1017 break;
1019 err = _("window functions are not allowed in EXECUTE parameters");
1020 break;
1022 err = _("window functions are not allowed in trigger WHEN conditions");
1023 break;
1025 err = _("window functions are not allowed in partition bound");
1026 break;
1028 err = _("window functions are not allowed in partition key expressions");
1029 break;
1031 err = _("window functions are not allowed in CALL arguments");
1032 break;
1034 err = _("window functions are not allowed in COPY FROM WHERE conditions");
1035 break;
1037 err = _("window functions are not allowed in column generation expressions");
1038 break;
1040 errkind = true;
1041 break;
1043 err = _("window functions are not allowed in property definition expressions");
1044 break;
1046 err = _("window functions are not allowed in FOR PORTION OF expressions");
1047 break;
1048
1049 /*
1050 * There is intentionally no default: case here, so that the
1051 * compiler will warn if we add a new ParseExprKind without
1052 * extending this switch. If we do see an unrecognized value at
1053 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
1054 * which is sane anyway.
1055 */
1056 }
1057 if (err)
1058 ereport(ERROR,
1060 errmsg_internal("%s", err),
1061 parser_errposition(pstate, wfunc->location)));
1062 if (errkind)
1063 ereport(ERROR,
1065 /* translator: %s is name of a SQL construct, eg GROUP BY */
1066 errmsg("window functions are not allowed in %s",
1068 parser_errposition(pstate, wfunc->location)));
1069
1070 /*
1071 * If the OVER clause just specifies a window name, find that WINDOW
1072 * clause (which had better be present). Otherwise, try to match all the
1073 * properties of the OVER clause, and make a new entry in the p_windowdefs
1074 * list if no luck.
1075 */
1076 if (windef->name)
1077 {
1078 Index winref = 0;
1079 ListCell *lc;
1080
1081 Assert(windef->refname == NULL &&
1082 windef->partitionClause == NIL &&
1083 windef->orderClause == NIL &&
1084 windef->frameOptions == FRAMEOPTION_DEFAULTS);
1085
1086 foreach(lc, pstate->p_windowdefs)
1087 {
1089
1090 winref++;
1091 if (refwin->name && strcmp(refwin->name, windef->name) == 0)
1092 {
1093 wfunc->winref = winref;
1094 break;
1095 }
1096 }
1097 if (lc == NULL) /* didn't find it? */
1098 ereport(ERROR,
1100 errmsg("window \"%s\" does not exist", windef->name),
1101 parser_errposition(pstate, windef->location)));
1102 }
1103 else
1104 {
1105 Index winref = 0;
1106 ListCell *lc;
1107
1108 foreach(lc, pstate->p_windowdefs)
1109 {
1111
1112 winref++;
1113 if (refwin->refname && windef->refname &&
1114 strcmp(refwin->refname, windef->refname) == 0)
1115 /* matched on refname */ ;
1116 else if (!refwin->refname && !windef->refname)
1117 /* matched, no refname */ ;
1118 else
1119 continue;
1120
1121 /*
1122 * Also see similar de-duplication code in optimize_window_clauses
1123 */
1124 if (equal(refwin->partitionClause, windef->partitionClause) &&
1125 equal(refwin->orderClause, windef->orderClause) &&
1126 refwin->frameOptions == windef->frameOptions &&
1127 equal(refwin->startOffset, windef->startOffset) &&
1128 equal(refwin->endOffset, windef->endOffset))
1129 {
1130 /* found a duplicate window specification */
1131 wfunc->winref = winref;
1132 break;
1133 }
1134 }
1135 if (lc == NULL) /* didn't find it? */
1136 {
1137 pstate->p_windowdefs = lappend(pstate->p_windowdefs, windef);
1138 wfunc->winref = list_length(pstate->p_windowdefs);
1139 }
1140 }
1141
1142 pstate->p_hasWindowFuncs = true;
1143}
unsigned int Index
Definition c.h:698
#define _(x)
Definition elog.c:95
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
void err(int eval, const char *fmt,...)
Definition err.c:43
const char * ParseExprKindName(ParseExprKind exprKind)
@ EXPR_KIND_EXECUTE_PARAMETER
Definition parse_node.h:77
@ EXPR_KIND_DOMAIN_CHECK
Definition parse_node.h:70
@ EXPR_KIND_COPY_WHERE
Definition parse_node.h:83
@ EXPR_KIND_COLUMN_DEFAULT
Definition parse_node.h:71
@ EXPR_KIND_DISTINCT_ON
Definition parse_node.h:62
@ EXPR_KIND_MERGE_WHEN
Definition parse_node.h:58
@ EXPR_KIND_STATS_EXPRESSION
Definition parse_node.h:75
@ EXPR_KIND_INDEX_EXPRESSION
Definition parse_node.h:73
@ EXPR_KIND_MERGE_RETURNING
Definition parse_node.h:66
@ EXPR_KIND_PROPGRAPH_PROPERTY
Definition parse_node.h:86
@ EXPR_KIND_PARTITION_BOUND
Definition parse_node.h:80
@ EXPR_KIND_FUNCTION_DEFAULT
Definition parse_node.h:72
@ EXPR_KIND_WINDOW_FRAME_RANGE
Definition parse_node.h:51
@ EXPR_KIND_VALUES
Definition parse_node.h:67
@ EXPR_KIND_FROM_SUBSELECT
Definition parse_node.h:44
@ EXPR_KIND_POLICY
Definition parse_node.h:79
@ EXPR_KIND_WINDOW_FRAME_GROUPS
Definition parse_node.h:53
@ EXPR_KIND_PARTITION_EXPRESSION
Definition parse_node.h:81
@ EXPR_KIND_JOIN_USING
Definition parse_node.h:43
@ EXPR_KIND_INDEX_PREDICATE
Definition parse_node.h:74
@ EXPR_KIND_OFFSET
Definition parse_node.h:64
@ 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:76
@ EXPR_KIND_LIMIT
Definition parse_node.h:63
@ 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:65
@ EXPR_KIND_GENERATED_COLUMN
Definition parse_node.h:84
@ EXPR_KIND_NONE
Definition parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition parse_node.h:82
@ EXPR_KIND_GROUP_BY
Definition parse_node.h:60
@ EXPR_KIND_FOR_PORTION
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:78
@ 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:69
@ EXPR_KIND_WINDOW_PARTITION
Definition parse_node.h:49
@ EXPR_KIND_CYCLE_MARK
Definition parse_node.h:85
@ 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:68
#define FRAMEOPTION_DEFAULTS
Definition parsenodes.h:639
bool contain_windowfuncs(Node *node)
int locate_windowfunc(Node *node)
bool p_hasWindowFuncs
Definition parse_node.h:247
List * p_windowdefs
Definition parse_node.h:231
List * args
Definition primnodes.h:606
Index winref
Definition primnodes.h:612
ParseLoc location
Definition primnodes.h:620

References _, WindowFunc::args, Assert, contain_windowfuncs(), 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_FOR_PORTION, 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_RETURNING, 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_PROPGRAPH_PROPERTY, 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, fb(), FRAMEOPTION_DEFAULTS, lappend(), lfirst, list_length(), locate_windowfunc(), WindowFunc::location, NIL, ParseState::p_expr_kind, ParseState::p_hasWindowFuncs, ParseState::p_windowdefs, ParseExprKindName(), parser_errposition(), and WindowFunc::winref.

Referenced by ParseFuncOrColumn(), and transformJsonAggConstructor().