LCOV - code coverage report
Current view: top level - src/backend/optimizer/prep - prepagg.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 176 180 97.8 %
Date: 2021-12-05 02:08:31 Functions: 7 7 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * prepagg.c
       4             :  *    Routines to preprocess aggregate function calls
       5             :  *
       6             :  * If there are identical aggregate calls in the query, they only need to
       7             :  * be computed once.  Also, some aggregate functions can share the same
       8             :  * transition state, so that we only need to call the final function for
       9             :  * them separately.  These optimizations are independent of how the
      10             :  * aggregates are executed.
      11             :  *
      12             :  * preprocess_aggrefs() detects those cases, creates AggInfo and
      13             :  * AggTransInfo structs for each aggregate and transition state that needs
      14             :  * to be computed, and sets the 'aggno' and 'transno' fields in the Aggrefs
      15             :  * accordingly.  It also resolves polymorphic transition types, and sets
      16             :  * the 'aggtranstype' fields accordingly.
      17             :  *
      18             :  * XXX: The AggInfo and AggTransInfo structs are thrown away after
      19             :  * planning, so executor startup has to perform some of the same lookups
      20             :  * of transition functions and initial values that we do here.  One day, we
      21             :  * might want to carry that information to the Agg nodes to save the effort
      22             :  * at executor startup.  The Agg nodes are constructed much later in the
      23             :  * planning, however, so it's not trivial.
      24             :  *
      25             :  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
      26             :  * Portions Copyright (c) 1994, Regents of the University of California
      27             :  *
      28             :  *
      29             :  * IDENTIFICATION
      30             :  *    src/backend/optimizer/prep/prepagg.c
      31             :  *
      32             :  *-------------------------------------------------------------------------
      33             :  */
      34             : 
      35             : #include "postgres.h"
      36             : 
      37             : #include "access/htup_details.h"
      38             : #include "catalog/pg_aggregate.h"
      39             : #include "catalog/pg_type.h"
      40             : #include "nodes/nodeFuncs.h"
      41             : #include "nodes/pathnodes.h"
      42             : #include "optimizer/clauses.h"
      43             : #include "optimizer/cost.h"
      44             : #include "optimizer/optimizer.h"
      45             : #include "optimizer/plancat.h"
      46             : #include "optimizer/prep.h"
      47             : #include "parser/parse_agg.h"
      48             : #include "utils/builtins.h"
      49             : #include "utils/datum.h"
      50             : #include "utils/fmgroids.h"
      51             : #include "utils/lsyscache.h"
      52             : #include "utils/memutils.h"
      53             : #include "utils/syscache.h"
      54             : 
      55             : static bool preprocess_aggrefs_walker(Node *node, PlannerInfo *root);
      56             : static int  find_compatible_agg(PlannerInfo *root, Aggref *newagg,
      57             :                                 List **same_input_transnos);
      58             : static int  find_compatible_trans(PlannerInfo *root, Aggref *newagg,
      59             :                                   bool shareable,
      60             :                                   Oid aggtransfn, Oid aggtranstype,
      61             :                                   int transtypeLen, bool transtypeByVal,
      62             :                                   Oid aggcombinefn,
      63             :                                   Oid aggserialfn, Oid aggdeserialfn,
      64             :                                   Datum initValue, bool initValueIsNull,
      65             :                                   List *transnos);
      66             : static Datum GetAggInitVal(Datum textInitVal, Oid transtype);
      67             : 
      68             : /* -----------------
      69             :  * Resolve the transition type of all Aggrefs, and determine which Aggrefs
      70             :  * can share aggregate or transition state.
      71             :  *
      72             :  * Information about the aggregates and transition functions are collected
      73             :  * in the root->agginfos and root->aggtransinfos lists.  The 'aggtranstype',
      74             :  * 'aggno', and 'aggtransno' fields of each Aggref are filled in.
      75             :  *
      76             :  * NOTE: This modifies the Aggrefs in the input expression in-place!
      77             :  *
      78             :  * We try to optimize by detecting duplicate aggregate functions so that
      79             :  * their state and final values are re-used, rather than needlessly being
      80             :  * re-calculated independently.  We also detect aggregates that are not
      81             :  * the same, but which can share the same transition state.
      82             :  *
      83             :  * Scenarios:
      84             :  *
      85             :  * 1. Identical aggregate function calls appear in the query:
      86             :  *
      87             :  *    SELECT SUM(x) FROM ... HAVING SUM(x) > 0
      88             :  *
      89             :  *    Since these aggregates are identical, we only need to calculate
      90             :  *    the value once.  Both aggregates will share the same 'aggno' value.
      91             :  *
      92             :  * 2. Two different aggregate functions appear in the query, but the
      93             :  *    aggregates have the same arguments, transition functions and
      94             :  *    initial values (and, presumably, different final functions):
      95             :  *
      96             :  *    SELECT AVG(x), STDDEV(x) FROM ...
      97             :  *
      98             :  *    In this case we must create a new AggInfo for the varying aggregate,
      99             :  *    and we need to call the final functions separately, but we need
     100             :  *    only run the transition function once.  (This requires that the
     101             :  *    final functions be nondestructive of the transition state, but
     102             :  *    that's required anyway for other reasons.)
     103             :  *
     104             :  * For either of these optimizations to be valid, all aggregate properties
     105             :  * used in the transition phase must be the same, including any modifiers
     106             :  * such as ORDER BY, DISTINCT and FILTER, and the arguments mustn't
     107             :  * contain any volatile functions.
     108             :  * -----------------
     109             :  */
     110             : void
     111      101532 : preprocess_aggrefs(PlannerInfo *root, Node *clause)
     112             : {
     113      101532 :     (void) preprocess_aggrefs_walker(clause, root);
     114      101532 : }
     115             : 
     116             : static void
     117       53358 : preprocess_aggref(Aggref *aggref, PlannerInfo *root)
     118             : {
     119             :     HeapTuple   aggTuple;
     120             :     Form_pg_aggregate aggform;
     121             :     Oid         aggtransfn;
     122             :     Oid         aggfinalfn;
     123             :     Oid         aggcombinefn;
     124             :     Oid         aggserialfn;
     125             :     Oid         aggdeserialfn;
     126             :     Oid         aggtranstype;
     127             :     int32       aggtranstypmod;
     128             :     int32       aggtransspace;
     129             :     bool        shareable;
     130             :     int         aggno;
     131             :     int         transno;
     132             :     List       *same_input_transnos;
     133             :     int16       resulttypeLen;
     134             :     bool        resulttypeByVal;
     135             :     Datum       textInitVal;
     136             :     Datum       initValue;
     137             :     bool        initValueIsNull;
     138             :     bool        transtypeByVal;
     139             :     int16       transtypeLen;
     140             :     Oid         inputTypes[FUNC_MAX_ARGS];
     141             :     int         numArguments;
     142             : 
     143             :     Assert(aggref->agglevelsup == 0);
     144             : 
     145             :     /*
     146             :      * Fetch info about the aggregate from pg_aggregate.  Note it's correct to
     147             :      * ignore the moving-aggregate variant, since what we're concerned with
     148             :      * here is aggregates not window functions.
     149             :      */
     150       53358 :     aggTuple = SearchSysCache1(AGGFNOID,
     151       53358 :                                ObjectIdGetDatum(aggref->aggfnoid));
     152       53358 :     if (!HeapTupleIsValid(aggTuple))
     153           0 :         elog(ERROR, "cache lookup failed for aggregate %u",
     154             :              aggref->aggfnoid);
     155       53358 :     aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
     156       53358 :     aggtransfn = aggform->aggtransfn;
     157       53358 :     aggfinalfn = aggform->aggfinalfn;
     158       53358 :     aggcombinefn = aggform->aggcombinefn;
     159       53358 :     aggserialfn = aggform->aggserialfn;
     160       53358 :     aggdeserialfn = aggform->aggdeserialfn;
     161       53358 :     aggtranstype = aggform->aggtranstype;
     162       53358 :     aggtransspace = aggform->aggtransspace;
     163             : 
     164             :     /*
     165             :      * Resolve the possibly-polymorphic aggregate transition type.
     166             :      */
     167             : 
     168             :     /* extract argument types (ignoring any ORDER BY expressions) */
     169       53358 :     numArguments = get_aggregate_argtypes(aggref, inputTypes);
     170             : 
     171             :     /* resolve actual type of transition state, if polymorphic */
     172       53358 :     aggtranstype = resolve_aggregate_transtype(aggref->aggfnoid,
     173             :                                                aggtranstype,
     174             :                                                inputTypes,
     175             :                                                numArguments);
     176       53358 :     aggref->aggtranstype = aggtranstype;
     177             : 
     178             :     /*
     179             :      * If transition state is of same type as first aggregated input, assume
     180             :      * it's the same typmod (same width) as well.  This works for cases like
     181             :      * MAX/MIN and is probably somewhat reasonable otherwise.
     182             :      */
     183       53358 :     aggtranstypmod = -1;
     184       53358 :     if (aggref->args)
     185             :     {
     186       45764 :         TargetEntry *tle = (TargetEntry *) linitial(aggref->args);
     187             : 
     188       45764 :         if (aggtranstype == exprType((Node *) tle->expr))
     189        1720 :             aggtranstypmod = exprTypmod((Node *) tle->expr);
     190             :     }
     191             : 
     192             :     /*
     193             :      * If finalfn is marked read-write, we can't share transition states; but
     194             :      * it is okay to share states for AGGMODIFY_SHAREABLE aggs.
     195             :      *
     196             :      * In principle, in a partial aggregate, we could share the transition
     197             :      * state even if the final function is marked as read-write, because the
     198             :      * partial aggregate doesn't execute the final function.  But it's too
     199             :      * early to know whether we're going perform a partial aggregate.
     200             :      */
     201       53358 :     shareable = (aggform->aggfinalmodify != AGGMODIFY_READ_WRITE);
     202             : 
     203             :     /* get info about the output value's datatype */
     204       53358 :     get_typlenbyval(aggref->aggtype,
     205             :                     &resulttypeLen,
     206             :                     &resulttypeByVal);
     207             : 
     208             :     /* get initial value */
     209       53358 :     textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
     210             :                                   Anum_pg_aggregate_agginitval,
     211             :                                   &initValueIsNull);
     212       53358 :     if (initValueIsNull)
     213       43418 :         initValue = (Datum) 0;
     214             :     else
     215        9940 :         initValue = GetAggInitVal(textInitVal, aggtranstype);
     216             : 
     217       53358 :     ReleaseSysCache(aggTuple);
     218             : 
     219             :     /*
     220             :      * 1. See if this is identical to another aggregate function call that
     221             :      * we've seen already.
     222             :      */
     223       53358 :     aggno = find_compatible_agg(root, aggref, &same_input_transnos);
     224       53358 :     if (aggno != -1)
     225             :     {
     226         312 :         AggInfo    *agginfo = list_nth(root->agginfos, aggno);
     227             : 
     228         312 :         transno = agginfo->transno;
     229             :     }
     230             :     else
     231             :     {
     232       53046 :         AggInfo    *agginfo = palloc(sizeof(AggInfo));
     233             : 
     234       53046 :         agginfo->finalfn_oid = aggfinalfn;
     235       53046 :         agginfo->representative_aggref = aggref;
     236       53046 :         agginfo->shareable = shareable;
     237             : 
     238       53046 :         aggno = list_length(root->agginfos);
     239       53046 :         root->agginfos = lappend(root->agginfos, agginfo);
     240             : 
     241             :         /*
     242             :          * Count it, and check for cases requiring ordered input.  Note that
     243             :          * ordered-set aggs always have nonempty aggorder.  Any ordered-input
     244             :          * case also defeats partial aggregation.
     245             :          */
     246       53046 :         if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
     247             :         {
     248       31974 :             root->numOrderedAggs++;
     249       31974 :             root->hasNonPartialAggs = true;
     250             :         }
     251             : 
     252       53046 :         get_typlenbyval(aggtranstype,
     253             :                         &transtypeLen,
     254             :                         &transtypeByVal);
     255             : 
     256             :         /*
     257             :          * 2. See if this aggregate can share transition state with another
     258             :          * aggregate that we've initialized already.
     259             :          */
     260       53046 :         transno = find_compatible_trans(root, aggref, shareable,
     261             :                                         aggtransfn, aggtranstype,
     262             :                                         transtypeLen, transtypeByVal,
     263             :                                         aggcombinefn,
     264             :                                         aggserialfn, aggdeserialfn,
     265             :                                         initValue, initValueIsNull,
     266             :                                         same_input_transnos);
     267       53046 :         if (transno == -1)
     268             :         {
     269       52874 :             AggTransInfo *transinfo = palloc(sizeof(AggTransInfo));
     270             : 
     271       52874 :             transinfo->args = aggref->args;
     272       52874 :             transinfo->aggfilter = aggref->aggfilter;
     273       52874 :             transinfo->transfn_oid = aggtransfn;
     274       52874 :             transinfo->combinefn_oid = aggcombinefn;
     275       52874 :             transinfo->serialfn_oid = aggserialfn;
     276       52874 :             transinfo->deserialfn_oid = aggdeserialfn;
     277       52874 :             transinfo->aggtranstype = aggtranstype;
     278       52874 :             transinfo->aggtranstypmod = aggtranstypmod;
     279       52874 :             transinfo->transtypeLen = transtypeLen;
     280       52874 :             transinfo->transtypeByVal = transtypeByVal;
     281       52874 :             transinfo->aggtransspace = aggtransspace;
     282       52874 :             transinfo->initValue = initValue;
     283       52874 :             transinfo->initValueIsNull = initValueIsNull;
     284             : 
     285       52874 :             transno = list_length(root->aggtransinfos);
     286       52874 :             root->aggtransinfos = lappend(root->aggtransinfos, transinfo);
     287             : 
     288             :             /*
     289             :              * Check whether partial aggregation is feasible, unless we
     290             :              * already found out that we can't do it.
     291             :              */
     292       52874 :             if (!root->hasNonPartialAggs)
     293             :             {
     294             :                 /*
     295             :                  * If there is no combine function, then partial aggregation
     296             :                  * is not possible.
     297             :                  */
     298       20824 :                 if (!OidIsValid(transinfo->combinefn_oid))
     299        8272 :                     root->hasNonPartialAggs = true;
     300             : 
     301             :                 /*
     302             :                  * If we have any aggs with transtype INTERNAL then we must
     303             :                  * check whether they have serialization/deserialization
     304             :                  * functions; if not, we can't serialize partial-aggregation
     305             :                  * results.
     306             :                  */
     307       12552 :                 else if (transinfo->aggtranstype == INTERNALOID &&
     308         440 :                          (!OidIsValid(transinfo->serialfn_oid) ||
     309         440 :                           !OidIsValid(transinfo->deserialfn_oid)))
     310           0 :                     root->hasNonSerialAggs = true;
     311             :             }
     312             :         }
     313       53046 :         agginfo->transno = transno;
     314             :     }
     315             : 
     316             :     /*
     317             :      * Fill in the fields in the Aggref (aggtranstype was set above already)
     318             :      */
     319       53358 :     aggref->aggno = aggno;
     320       53358 :     aggref->aggtransno = transno;
     321       53358 : }
     322             : 
     323             : static bool
     324      223586 : preprocess_aggrefs_walker(Node *node, PlannerInfo *root)
     325             : {
     326      223586 :     if (node == NULL)
     327       50734 :         return false;
     328      172852 :     if (IsA(node, Aggref))
     329             :     {
     330       53358 :         Aggref     *aggref = (Aggref *) node;
     331             : 
     332       53358 :         preprocess_aggref(aggref, root);
     333             : 
     334             :         /*
     335             :          * We assume that the parser checked that there are no aggregates (of
     336             :          * this level anyway) in the aggregated arguments, direct arguments,
     337             :          * or filter clause.  Hence, we need not recurse into any of them.
     338             :          */
     339       53358 :         return false;
     340             :     }
     341             :     Assert(!IsA(node, SubLink));
     342      119494 :     return expression_tree_walker(node, preprocess_aggrefs_walker,
     343             :                                   (void *) root);
     344             : }
     345             : 
     346             : 
     347             : /*
     348             :  * find_compatible_agg - search for a previously initialized per-Agg struct
     349             :  *
     350             :  * Searches the previously looked at aggregates to find one which is compatible
     351             :  * with this one, with the same input parameters.  If no compatible aggregate
     352             :  * can be found, returns -1.
     353             :  *
     354             :  * As a side-effect, this also collects a list of existing, shareable per-Trans
     355             :  * structs with matching inputs.  If no identical Aggref is found, the list is
     356             :  * passed later to find_compatible_trans, to see if we can at least reuse
     357             :  * the state value of another aggregate.
     358             :  */
     359             : static int
     360       53358 : find_compatible_agg(PlannerInfo *root, Aggref *newagg,
     361             :                     List **same_input_transnos)
     362             : {
     363             :     ListCell   *lc;
     364             :     int         aggno;
     365             : 
     366       53358 :     *same_input_transnos = NIL;
     367             : 
     368             :     /* we mustn't reuse the aggref if it contains volatile function calls */
     369       53358 :     if (contain_volatile_functions((Node *) newagg))
     370          28 :         return -1;
     371             : 
     372             :     /*
     373             :      * Search through the list of already seen aggregates.  If we find an
     374             :      * existing identical aggregate call, then we can re-use that one.  While
     375             :      * searching, we'll also collect a list of Aggrefs with the same input
     376             :      * parameters.  If no matching Aggref is found, the caller can potentially
     377             :      * still re-use the transition state of one of them.  (At this stage we
     378             :      * just compare the parsetrees; whether different aggregates share the
     379             :      * same transition function will be checked later.)
     380             :      */
     381       53330 :     aggno = -1;
     382       58264 :     foreach(lc, root->agginfos)
     383             :     {
     384        5246 :         AggInfo    *agginfo = (AggInfo *) lfirst(lc);
     385             :         Aggref     *existingRef;
     386             : 
     387        5246 :         aggno++;
     388             : 
     389        5246 :         existingRef = agginfo->representative_aggref;
     390             : 
     391             :         /* all of the following must be the same or it's no match */
     392        5246 :         if (newagg->inputcollid != existingRef->inputcollid ||
     393        4758 :             newagg->aggtranstype != existingRef->aggtranstype ||
     394        2646 :             newagg->aggstar != existingRef->aggstar ||
     395        1980 :             newagg->aggvariadic != existingRef->aggvariadic ||
     396        1980 :             newagg->aggkind != existingRef->aggkind ||
     397        1844 :             !equal(newagg->args, existingRef->args) ||
     398         896 :             !equal(newagg->aggorder, existingRef->aggorder) ||
     399         892 :             !equal(newagg->aggdistinct, existingRef->aggdistinct) ||
     400         892 :             !equal(newagg->aggfilter, existingRef->aggfilter))
     401        4374 :             continue;
     402             : 
     403             :         /* if it's the same aggregate function then report exact match */
     404         872 :         if (newagg->aggfnoid == existingRef->aggfnoid &&
     405         320 :             newagg->aggtype == existingRef->aggtype &&
     406         640 :             newagg->aggcollid == existingRef->aggcollid &&
     407         320 :             equal(newagg->aggdirectargs, existingRef->aggdirectargs))
     408             :         {
     409         312 :             list_free(*same_input_transnos);
     410         312 :             *same_input_transnos = NIL;
     411         312 :             return aggno;
     412             :         }
     413             : 
     414             :         /*
     415             :          * Not identical, but it had the same inputs.  If the final function
     416             :          * permits sharing, return its transno to the caller, in case we can
     417             :          * re-use its per-trans state.  (If there's already sharing going on,
     418             :          * we might report a transno more than once.  find_compatible_trans is
     419             :          * cheap enough that it's not worth spending cycles to avoid that.)
     420             :          */
     421         560 :         if (agginfo->shareable)
     422         556 :             *same_input_transnos = lappend_int(*same_input_transnos,
     423             :                                                agginfo->transno);
     424             :     }
     425             : 
     426       53018 :     return -1;
     427             : }
     428             : 
     429             : /*
     430             :  * find_compatible_trans - search for a previously initialized per-Trans
     431             :  * struct
     432             :  *
     433             :  * Searches the list of transnos for a per-Trans struct with the same
     434             :  * transition function and initial condition. (The inputs have already been
     435             :  * verified to match.)
     436             :  */
     437             : static int
     438       53046 : find_compatible_trans(PlannerInfo *root, Aggref *newagg, bool shareable,
     439             :                       Oid aggtransfn, Oid aggtranstype,
     440             :                       int transtypeLen, bool transtypeByVal,
     441             :                       Oid aggcombinefn,
     442             :                       Oid aggserialfn, Oid aggdeserialfn,
     443             :                       Datum initValue, bool initValueIsNull,
     444             :                       List *transnos)
     445             : {
     446             :     ListCell   *lc;
     447             : 
     448             :     /* If this aggregate can't share transition states, give up */
     449       53046 :     if (!shareable)
     450          84 :         return -1;
     451             : 
     452       53322 :     foreach(lc, transnos)
     453             :     {
     454         532 :         int         transno = lfirst_int(lc);
     455         532 :         AggTransInfo *pertrans = (AggTransInfo *) list_nth(root->aggtransinfos, transno);
     456             : 
     457             :         /*
     458             :          * if the transfns or transition state types are not the same then the
     459             :          * state can't be shared.
     460             :          */
     461         532 :         if (aggtransfn != pertrans->transfn_oid ||
     462         176 :             aggtranstype != pertrans->aggtranstype)
     463         356 :             continue;
     464             : 
     465             :         /*
     466             :          * The serialization and deserialization functions must match, if
     467             :          * present, as we're unable to share the trans state for aggregates
     468             :          * which will serialize or deserialize into different formats.
     469             :          * Remember that these will be InvalidOid if they're not required for
     470             :          * this agg node.
     471             :          */
     472         176 :         if (aggserialfn != pertrans->serialfn_oid ||
     473         176 :             aggdeserialfn != pertrans->deserialfn_oid)
     474           0 :             continue;
     475             : 
     476             :         /*
     477             :          * Combine function must also match.  We only care about the combine
     478             :          * function with partial aggregates, but it's too early in the
     479             :          * planning to know if we will do partial aggregation, so be
     480             :          * conservative.
     481             :          */
     482         176 :         if (aggcombinefn != pertrans->combinefn_oid)
     483           0 :             continue;
     484             : 
     485             :         /*
     486             :          * Check that the initial condition matches, too.
     487             :          */
     488         176 :         if (initValueIsNull && pertrans->initValueIsNull)
     489         172 :             return transno;
     490             : 
     491         224 :         if (!initValueIsNull && !pertrans->initValueIsNull &&
     492         112 :             datumIsEqual(initValue, pertrans->initValue,
     493             :                          transtypeByVal, transtypeLen))
     494         108 :             return transno;
     495             :     }
     496       52790 :     return -1;
     497             : }
     498             : 
     499             : static Datum
     500        9940 : GetAggInitVal(Datum textInitVal, Oid transtype)
     501             : {
     502             :     Oid         typinput,
     503             :                 typioparam;
     504             :     char       *strInitVal;
     505             :     Datum       initVal;
     506             : 
     507        9940 :     getTypeInputInfo(transtype, &typinput, &typioparam);
     508        9940 :     strInitVal = TextDatumGetCString(textInitVal);
     509        9940 :     initVal = OidInputFunctionCall(typinput, strInitVal,
     510             :                                    typioparam, -1);
     511        9940 :     pfree(strInitVal);
     512        9940 :     return initVal;
     513             : }
     514             : 
     515             : 
     516             : /*
     517             :  * get_agg_clause_costs
     518             :  *    Process the PlannerInfo's 'aggtransinfos' and 'agginfos' lists
     519             :  *    accumulating the cost information about them.
     520             :  *
     521             :  * 'aggsplit' tells us the expected partial-aggregation mode, which affects
     522             :  * the cost estimates.
     523             :  *
     524             :  * NOTE that the costs are ADDED to those already in *costs ... so the caller
     525             :  * is responsible for zeroing the struct initially.
     526             :  *
     527             :  * For each AggTransInfo, we add the cost of an aggregate transition using
     528             :  * either the transfn or combinefn depending on the 'aggsplit' value.  We also
     529             :  * account for the costs of any aggfilters and any serializations and
     530             :  * deserializations of the transition state and also estimate the total space
     531             :  * needed for the transition states as if each aggregate's state was stored in
     532             :  * memory concurrently (as would be done in a HashAgg plan).
     533             :  *
     534             :  * For each AggInfo in the 'agginfos' list we add the cost of running the
     535             :  * final function and the direct args, if any.
     536             :  */
     537             : void
     538       52614 : get_agg_clause_costs(PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
     539             : {
     540             :     ListCell   *lc;
     541             : 
     542      108024 :     foreach(lc, root->aggtransinfos)
     543             :     {
     544       55410 :         AggTransInfo *transinfo = (AggTransInfo *) lfirst(lc);
     545             : 
     546             :         /*
     547             :          * Add the appropriate component function execution costs to
     548             :          * appropriate totals.
     549             :          */
     550       55410 :         if (DO_AGGSPLIT_COMBINE(aggsplit))
     551             :         {
     552             :             /* charge for combining previously aggregated states */
     553        1130 :             add_function_cost(root, transinfo->combinefn_oid, NULL,
     554             :                               &costs->transCost);
     555             :         }
     556             :         else
     557       54280 :             add_function_cost(root, transinfo->transfn_oid, NULL,
     558             :                               &costs->transCost);
     559       55410 :         if (DO_AGGSPLIT_DESERIALIZE(aggsplit) &&
     560        1130 :             OidIsValid(transinfo->deserialfn_oid))
     561          48 :             add_function_cost(root, transinfo->deserialfn_oid, NULL,
     562             :                               &costs->transCost);
     563       55410 :         if (DO_AGGSPLIT_SERIALIZE(aggsplit) &&
     564        1130 :             OidIsValid(transinfo->serialfn_oid))
     565          48 :             add_function_cost(root, transinfo->serialfn_oid, NULL,
     566             :                               &costs->finalCost);
     567             : 
     568             :         /*
     569             :          * These costs are incurred only by the initial aggregate node, so we
     570             :          * mustn't include them again at upper levels.
     571             :          */
     572       55410 :         if (!DO_AGGSPLIT_COMBINE(aggsplit))
     573             :         {
     574             :             /* add the input expressions' cost to per-input-row costs */
     575             :             QualCost    argcosts;
     576             : 
     577       54280 :             cost_qual_eval_node(&argcosts, (Node *) transinfo->args, root);
     578       54280 :             costs->transCost.startup += argcosts.startup;
     579       54280 :             costs->transCost.per_tuple += argcosts.per_tuple;
     580             : 
     581             :             /*
     582             :              * Add any filter's cost to per-input-row costs.
     583             :              *
     584             :              * XXX Ideally we should reduce input expression costs according
     585             :              * to filter selectivity, but it's not clear it's worth the
     586             :              * trouble.
     587             :              */
     588       54280 :             if (transinfo->aggfilter)
     589             :             {
     590         546 :                 cost_qual_eval_node(&argcosts, (Node *) transinfo->aggfilter,
     591             :                                     root);
     592         546 :                 costs->transCost.startup += argcosts.startup;
     593         546 :                 costs->transCost.per_tuple += argcosts.per_tuple;
     594             :             }
     595             :         }
     596             : 
     597             :         /*
     598             :          * If the transition type is pass-by-value then it doesn't add
     599             :          * anything to the required size of the hashtable.  If it is
     600             :          * pass-by-reference then we have to add the estimated size of the
     601             :          * value itself, plus palloc overhead.
     602             :          */
     603       55410 :         if (!transinfo->transtypeByVal)
     604             :         {
     605             :             int32       avgwidth;
     606             : 
     607             :             /* Use average width if aggregate definition gave one */
     608        1822 :             if (transinfo->aggtransspace > 0)
     609          60 :                 avgwidth = transinfo->aggtransspace;
     610        1762 :             else if (transinfo->transfn_oid == F_ARRAY_APPEND)
     611             :             {
     612             :                 /*
     613             :                  * If the transition function is array_append(), it'll use an
     614             :                  * expanded array as transvalue, which will occupy at least
     615             :                  * ALLOCSET_SMALL_INITSIZE and possibly more.  Use that as the
     616             :                  * estimate for lack of a better idea.
     617             :                  */
     618           4 :                 avgwidth = ALLOCSET_SMALL_INITSIZE;
     619             :             }
     620             :             else
     621             :             {
     622        1758 :                 avgwidth = get_typavgwidth(transinfo->aggtranstype, transinfo->aggtranstypmod);
     623             :             }
     624             : 
     625        1822 :             avgwidth = MAXALIGN(avgwidth);
     626        1822 :             costs->transitionSpace += avgwidth + 2 * sizeof(void *);
     627             :         }
     628       53588 :         else if (transinfo->aggtranstype == INTERNALOID)
     629             :         {
     630             :             /*
     631             :              * INTERNAL transition type is a special case: although INTERNAL
     632             :              * is pass-by-value, it's almost certainly being used as a pointer
     633             :              * to some large data structure.  The aggregate definition can
     634             :              * provide an estimate of the size.  If it doesn't, then we assume
     635             :              * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
     636             :              * being kept in a private memory context, as is done by
     637             :              * array_agg() for instance.
     638             :              */
     639       40334 :             if (transinfo->aggtransspace > 0)
     640         544 :                 costs->transitionSpace += transinfo->aggtransspace;
     641             :             else
     642       39790 :                 costs->transitionSpace += ALLOCSET_DEFAULT_INITSIZE;
     643             :         }
     644             :     }
     645             : 
     646      108196 :     foreach(lc, root->agginfos)
     647             :     {
     648       55582 :         AggInfo    *agginfo = (AggInfo *) lfirst(lc);
     649       55582 :         Aggref     *aggref = agginfo->representative_aggref;
     650             : 
     651             :         /*
     652             :          * Add the appropriate component function execution costs to
     653             :          * appropriate totals.
     654             :          */
     655       55582 :         if (!DO_AGGSPLIT_SKIPFINAL(aggsplit) &&
     656       54452 :             OidIsValid(agginfo->finalfn_oid))
     657       41544 :             add_function_cost(root, agginfo->finalfn_oid, NULL,
     658             :                               &costs->finalCost);
     659             : 
     660             :         /*
     661             :          * If there are direct arguments, treat their evaluation cost like the
     662             :          * cost of the finalfn.
     663             :          */
     664       55582 :         if (aggref->aggdirectargs)
     665             :         {
     666             :             QualCost    argcosts;
     667             : 
     668         206 :             cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
     669             :                                 root);
     670         206 :             costs->finalCost.startup += argcosts.startup;
     671         206 :             costs->finalCost.per_tuple += argcosts.per_tuple;
     672             :         }
     673             :     }
     674       52614 : }

Generated by: LCOV version 1.14