]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_agg.c
When a GUC string variable is not set, print the empty string (in SHOW etc.),
[postgresql] / src / backend / parser / parse_agg.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_agg.c
4  *        handle aggregates in parser
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_agg.c,v 1.72 2006/07/14 14:52:21 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "nodes/makefuncs.h"
18 #include "optimizer/clauses.h"
19 #include "optimizer/tlist.h"
20 #include "optimizer/var.h"
21 #include "parser/parse_agg.h"
22 #include "parser/parsetree.h"
23 #include "rewrite/rewriteManip.h"
24 #include "utils/lsyscache.h"
25
26
27 typedef struct
28 {
29         ParseState *pstate;
30         List       *groupClauses;
31         bool            have_non_var_grouping;
32         int                     sublevels_up;
33 } check_ungrouped_columns_context;
34
35 static void check_ungrouped_columns(Node *node, ParseState *pstate,
36                                                 List *groupClauses, bool have_non_var_grouping);
37 static bool check_ungrouped_columns_walker(Node *node,
38                                                            check_ungrouped_columns_context *context);
39
40
41 /*
42  * transformAggregateCall -
43  *              Finish initial transformation of an aggregate call
44  *
45  * parse_func.c has recognized the function as an aggregate, and has set
46  * up all the fields of the Aggref except agglevelsup.  Here we must
47  * determine which query level the aggregate actually belongs to, set
48  * agglevelsup accordingly, and mark p_hasAggs true in the corresponding
49  * pstate level.
50  */
51 void
52 transformAggregateCall(ParseState *pstate, Aggref *agg)
53 {
54         int                     min_varlevel;
55
56         /*
57          * The aggregate's level is the same as the level of the lowest-level
58          * variable or aggregate in its argument; or if it contains no variables
59          * at all, we presume it to be local.
60          */
61         min_varlevel = find_minimum_var_level((Node *) agg->target);
62
63         /*
64          * An aggregate can't directly contain another aggregate call of the same
65          * level (though outer aggs are okay).  We can skip this check if we
66          * didn't find any local vars or aggs.
67          */
68         if (min_varlevel == 0)
69         {
70                 if (checkExprHasAggs((Node *) agg->target))
71                         ereport(ERROR,
72                                         (errcode(ERRCODE_GROUPING_ERROR),
73                                          errmsg("aggregate function calls may not be nested")));
74         }
75
76         if (min_varlevel < 0)
77                 min_varlevel = 0;
78         agg->agglevelsup = min_varlevel;
79
80         /* Mark the correct pstate as having aggregates */
81         while (min_varlevel-- > 0)
82                 pstate = pstate->parentParseState;
83         pstate->p_hasAggs = true;
84 }
85
86
87 /*
88  * parseCheckAggregates
89  *      Check for aggregates where they shouldn't be and improper grouping.
90  *
91  *      Ideally this should be done earlier, but it's difficult to distinguish
92  *      aggregates from plain functions at the grammar level.  So instead we
93  *      check here.  This function should be called after the target list and
94  *      qualifications are finalized.
95  */
96 void
97 parseCheckAggregates(ParseState *pstate, Query *qry)
98 {
99         List       *groupClauses = NIL;
100         bool            have_non_var_grouping;
101         ListCell   *l;
102         bool            hasJoinRTEs;
103         PlannerInfo *root;
104         Node       *clause;
105
106         /* This should only be called if we found aggregates or grouping */
107         Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual);
108
109         /*
110          * Aggregates must never appear in WHERE or JOIN/ON clauses.
111          *
112          * (Note this check should appear first to deliver an appropriate error
113          * message; otherwise we are likely to complain about some innocent
114          * variable in the target list, which is outright misleading if the
115          * problem is in WHERE.)
116          */
117         if (checkExprHasAggs(qry->jointree->quals))
118                 ereport(ERROR,
119                                 (errcode(ERRCODE_GROUPING_ERROR),
120                                  errmsg("aggregates not allowed in WHERE clause")));
121         if (checkExprHasAggs((Node *) qry->jointree->fromlist))
122                 ereport(ERROR,
123                                 (errcode(ERRCODE_GROUPING_ERROR),
124                                  errmsg("aggregates not allowed in JOIN conditions")));
125
126         /*
127          * No aggregates allowed in GROUP BY clauses, either.
128          *
129          * While we are at it, build a list of the acceptable GROUP BY expressions
130          * for use by check_ungrouped_columns().
131          */
132         foreach(l, qry->groupClause)
133         {
134                 GroupClause *grpcl = (GroupClause *) lfirst(l);
135                 Node       *expr;
136
137                 expr = get_sortgroupclause_expr(grpcl, qry->targetList);
138                 if (expr == NULL)
139                         continue;                       /* probably cannot happen */
140                 if (checkExprHasAggs(expr))
141                         ereport(ERROR,
142                                         (errcode(ERRCODE_GROUPING_ERROR),
143                                          errmsg("aggregates not allowed in GROUP BY clause")));
144                 groupClauses = lcons(expr, groupClauses);
145         }
146
147         /*
148          * If there are join alias vars involved, we have to flatten them to the
149          * underlying vars, so that aliased and unaliased vars will be correctly
150          * taken as equal.      We can skip the expense of doing this if no rangetable
151          * entries are RTE_JOIN kind.
152          */
153         hasJoinRTEs = false;
154         foreach(l, pstate->p_rtable)
155         {
156                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
157
158                 if (rte->rtekind == RTE_JOIN)
159                 {
160                         hasJoinRTEs = true;
161                         break;
162                 }
163         }
164
165         /*
166          * We use the planner's flatten_join_alias_vars routine to do the
167          * flattening; it wants a PlannerInfo root node, which fortunately can be
168          * mostly dummy.
169          */
170         if (hasJoinRTEs)
171         {
172                 root = makeNode(PlannerInfo);
173                 root->parse = qry;
174                 root->hasJoinRTEs = true;
175
176                 groupClauses = (List *) flatten_join_alias_vars(root,
177                                                                                                           (Node *) groupClauses);
178         }
179         else
180                 root = NULL;                    /* keep compiler quiet */
181
182         /*
183          * Detect whether any of the grouping expressions aren't simple Vars; if
184          * they're all Vars then we don't have to work so hard in the recursive
185          * scans.  (Note we have to flatten aliases before this.)
186          */
187         have_non_var_grouping = false;
188         foreach(l, groupClauses)
189         {
190                 if (!IsA((Node *) lfirst(l), Var))
191                 {
192                         have_non_var_grouping = true;
193                         break;
194                 }
195         }
196
197         /*
198          * Check the targetlist and HAVING clause for ungrouped variables.
199          */
200         clause = (Node *) qry->targetList;
201         if (hasJoinRTEs)
202                 clause = flatten_join_alias_vars(root, clause);
203         check_ungrouped_columns(clause, pstate,
204                                                         groupClauses, have_non_var_grouping);
205
206         clause = (Node *) qry->havingQual;
207         if (hasJoinRTEs)
208                 clause = flatten_join_alias_vars(root, clause);
209         check_ungrouped_columns(clause, pstate,
210                                                         groupClauses, have_non_var_grouping);
211 }
212
213
214 /*
215  * check_ungrouped_columns -
216  *        Scan the given expression tree for ungrouped variables (variables
217  *        that are not listed in the groupClauses list and are not within
218  *        the arguments of aggregate functions).  Emit a suitable error message
219  *        if any are found.
220  *
221  * NOTE: we assume that the given clause has been transformed suitably for
222  * parser output.  This means we can use expression_tree_walker.
223  *
224  * NOTE: we recognize grouping expressions in the main query, but only
225  * grouping Vars in subqueries.  For example, this will be rejected,
226  * although it could be allowed:
227  *              SELECT
228  *                      (SELECT x FROM bar where y = (foo.a + foo.b))
229  *              FROM foo
230  *              GROUP BY a + b;
231  * The difficulty is the need to account for different sublevels_up.
232  * This appears to require a whole custom version of equal(), which is
233  * way more pain than the feature seems worth.
234  */
235 static void
236 check_ungrouped_columns(Node *node, ParseState *pstate,
237                                                 List *groupClauses, bool have_non_var_grouping)
238 {
239         check_ungrouped_columns_context context;
240
241         context.pstate = pstate;
242         context.groupClauses = groupClauses;
243         context.have_non_var_grouping = have_non_var_grouping;
244         context.sublevels_up = 0;
245         check_ungrouped_columns_walker(node, &context);
246 }
247
248 static bool
249 check_ungrouped_columns_walker(Node *node,
250                                                            check_ungrouped_columns_context *context)
251 {
252         ListCell   *gl;
253
254         if (node == NULL)
255                 return false;
256         if (IsA(node, Const) ||
257                 IsA(node, Param))
258                 return false;                   /* constants are always acceptable */
259
260         /*
261          * If we find an aggregate call of the original level, do not recurse into
262          * its arguments; ungrouped vars in the arguments are not an error. We can
263          * also skip looking at the arguments of aggregates of higher levels,
264          * since they could not possibly contain Vars that are of concern to us
265          * (see transformAggregateCall).  We do need to look into the arguments of
266          * aggregates of lower levels, however.
267          */
268         if (IsA(node, Aggref) &&
269                 (int) ((Aggref *) node)->agglevelsup >= context->sublevels_up)
270                 return false;
271
272         /*
273          * If we have any GROUP BY items that are not simple Vars, check to see if
274          * subexpression as a whole matches any GROUP BY item. We need to do this
275          * at every recursion level so that we recognize GROUPed-BY expressions
276          * before reaching variables within them. But this only works at the outer
277          * query level, as noted above.
278          */
279         if (context->have_non_var_grouping && context->sublevels_up == 0)
280         {
281                 foreach(gl, context->groupClauses)
282                 {
283                         if (equal(node, lfirst(gl)))
284                                 return false;   /* acceptable, do not descend more */
285                 }
286         }
287
288         /*
289          * If we have an ungrouped Var of the original query level, we have a
290          * failure.  Vars below the original query level are not a problem, and
291          * neither are Vars from above it.      (If such Vars are ungrouped as far as
292          * their own query level is concerned, that's someone else's problem...)
293          */
294         if (IsA(node, Var))
295         {
296                 Var                *var = (Var *) node;
297                 RangeTblEntry *rte;
298                 char       *attname;
299
300                 if (var->varlevelsup != context->sublevels_up)
301                         return false;           /* it's not local to my query, ignore */
302
303                 /*
304                  * Check for a match, if we didn't do it above.
305                  */
306                 if (!context->have_non_var_grouping || context->sublevels_up != 0)
307                 {
308                         foreach(gl, context->groupClauses)
309                         {
310                                 Var                *gvar = (Var *) lfirst(gl);
311
312                                 if (IsA(gvar, Var) &&
313                                         gvar->varno == var->varno &&
314                                         gvar->varattno == var->varattno &&
315                                         gvar->varlevelsup == 0)
316                                         return false;           /* acceptable, we're okay */
317                         }
318                 }
319
320                 /* Found an ungrouped local variable; generate error message */
321                 Assert(var->varno > 0 &&
322                            (int) var->varno <= list_length(context->pstate->p_rtable));
323                 rte = rt_fetch(var->varno, context->pstate->p_rtable);
324                 attname = get_rte_attribute_name(rte, var->varattno);
325                 if (context->sublevels_up == 0)
326                         ereport(ERROR,
327                                         (errcode(ERRCODE_GROUPING_ERROR),
328                                          errmsg("column \"%s.%s\" must appear in the GROUP BY clause or be used in an aggregate function",
329                                                         rte->eref->aliasname, attname)));
330                 else
331                         ereport(ERROR,
332                                         (errcode(ERRCODE_GROUPING_ERROR),
333                                          errmsg("subquery uses ungrouped column \"%s.%s\" from outer query",
334                                                         rte->eref->aliasname, attname)));
335
336         }
337
338         if (IsA(node, Query))
339         {
340                 /* Recurse into subselects */
341                 bool            result;
342
343                 context->sublevels_up++;
344                 result = query_tree_walker((Query *) node,
345                                                                    check_ungrouped_columns_walker,
346                                                                    (void *) context,
347                                                                    0);
348                 context->sublevels_up--;
349                 return result;
350         }
351         return expression_tree_walker(node, check_ungrouped_columns_walker,
352                                                                   (void *) context);
353 }
354
355 /*
356  * Create expression trees for the transition and final functions
357  * of an aggregate.  These are needed so that polymorphic functions
358  * can be used within an aggregate --- without the expression trees,
359  * such functions would not know the datatypes they are supposed to use.
360  * (The trees will never actually be executed, however, so we can skimp
361  * a bit on correctness.)
362  *
363  * agg_input_type, agg_state_type, agg_result_type identify the input,
364  * transition, and result types of the aggregate.  These should all be
365  * resolved to actual types (ie, none should ever be ANYARRAY or ANYELEMENT).
366  *
367  * transfn_oid and finalfn_oid identify the funcs to be called; the latter
368  * may be InvalidOid.
369  *
370  * Pointers to the constructed trees are returned into *transfnexpr and
371  * *finalfnexpr.  The latter is set to NULL if there's no finalfn.
372  */
373 void
374 build_aggregate_fnexprs(Oid agg_input_type,
375                                                 Oid agg_state_type,
376                                                 Oid agg_result_type,
377                                                 Oid transfn_oid,
378                                                 Oid finalfn_oid,
379                                                 Expr **transfnexpr,
380                                                 Expr **finalfnexpr)
381 {
382         int                     transfn_nargs;
383         Param      *arg0;
384         Param      *arg1;
385         List       *args;
386
387         /* get the transition function arg count */
388         transfn_nargs = get_func_nargs(transfn_oid);
389
390         /*
391          * Build arg list to use in the transfn FuncExpr node. We really only care
392          * that transfn can discover the actual argument types at runtime using
393          * get_fn_expr_argtype(), so it's okay to use Param nodes that don't
394          * correspond to any real Param.
395          */
396         arg0 = makeNode(Param);
397         arg0->paramkind = PARAM_EXEC;
398         arg0->paramid = -1;
399         arg0->paramtype = agg_state_type;
400
401         if (transfn_nargs == 2)
402         {
403                 arg1 = makeNode(Param);
404                 arg1->paramkind = PARAM_EXEC;
405                 arg1->paramid = -1;
406                 arg1->paramtype = agg_input_type;
407
408                 args = list_make2(arg0, arg1);
409         }
410         else
411                 args = list_make1(arg0);
412
413         *transfnexpr = (Expr *) makeFuncExpr(transfn_oid,
414                                                                                  agg_state_type,
415                                                                                  args,
416                                                                                  COERCE_DONTCARE);
417
418         /* see if we have a final function */
419         if (!OidIsValid(finalfn_oid))
420         {
421                 *finalfnexpr = NULL;
422                 return;
423         }
424
425         /*
426          * Build expr tree for final function
427          */
428         arg0 = makeNode(Param);
429         arg0->paramkind = PARAM_EXEC;
430         arg0->paramid = -1;
431         arg0->paramtype = agg_state_type;
432         args = list_make1(arg0);
433
434         *finalfnexpr = (Expr *) makeFuncExpr(finalfn_oid,
435                                                                                  agg_result_type,
436                                                                                  args,
437                                                                                  COERCE_DONTCARE);
438 }