PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
nodeAgg.h File Reference
#include "nodes/execnodes.h"
Include dependency graph for nodeAgg.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

AggStateExecInitAgg (Agg *node, EState *estate, int eflags)
 
void ExecEndAgg (AggState *node)
 
void ExecReScanAgg (AggState *node)
 
Size hash_agg_entry_size (int numAggs)
 
Datum aggregate_dummy (PG_FUNCTION_ARGS)
 

Function Documentation

Datum aggregate_dummy ( PG_FUNCTION_ARGS  )

Definition at line 4148 of file nodeAgg.c.

References elog, and ERROR.

4149 {
4150  elog(ERROR, "aggregate function %u called as normal function",
4151  fcinfo->flinfo->fn_oid);
4152  return (Datum) 0; /* keep compiler quiet */
4153 }
#define ERROR
Definition: elog.h:43
uintptr_t Datum
Definition: postgres.h:372
#define elog
Definition: elog.h:219
void ExecEndAgg ( AggState node)

Definition at line 3850 of file nodeAgg.c.

References AggState::aggcontexts, ExecClearTuple(), ExecEndNode(), ExecFreeExprContext(), AggState::hashcontext, Max, AggState::maxsets, AggState::numtrans, outerPlan, outerPlanState, AggState::pertrans, ScanState::ps, ReScanExprContext(), AggState::sort_in, AggState::sort_out, AggStatePerTransData::sortstates, AggState::ss, ScanState::ss_ScanTupleSlot, and tuplesort_end().

Referenced by ExecEndNode().

3851 {
3853  int transno;
3854  int numGroupingSets = Max(node->maxsets, 1);
3855  int setno;
3856 
3857  /* Make sure we have closed any open tuplesorts */
3858 
3859  if (node->sort_in)
3860  tuplesort_end(node->sort_in);
3861  if (node->sort_out)
3862  tuplesort_end(node->sort_out);
3863 
3864  for (transno = 0; transno < node->numtrans; transno++)
3865  {
3866  AggStatePerTrans pertrans = &node->pertrans[transno];
3867 
3868  for (setno = 0; setno < numGroupingSets; setno++)
3869  {
3870  if (pertrans->sortstates[setno])
3871  tuplesort_end(pertrans->sortstates[setno]);
3872  }
3873  }
3874 
3875  /* And ensure any agg shutdown callbacks have been called */
3876  for (setno = 0; setno < numGroupingSets; setno++)
3877  ReScanExprContext(node->aggcontexts[setno]);
3878  if (node->hashcontext)
3880 
3881  /*
3882  * We don't actually free any ExprContexts here (see comment in
3883  * ExecFreeExprContext), just unlinking the output one from the plan node
3884  * suffices.
3885  */
3886  ExecFreeExprContext(&node->ss.ps);
3887 
3888  /* clean up tuple table */
3890 
3891  outerPlan = outerPlanState(node);
3892  ExecEndNode(outerPlan);
3893 }
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:523
Tuplesortstate * sort_out
Definition: execnodes.h:1807
ScanState ss
Definition: execnodes.h:1781
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1101
AggStatePerTrans pertrans
Definition: execnodes.h:1791
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:521
int numtrans
Definition: execnodes.h:1784
PlanState ps
Definition: execnodes.h:1098
int maxsets
Definition: execnodes.h:1804
Tuplesortstate * sort_in
Definition: execnodes.h:1806
#define outerPlanState(node)
Definition: execnodes.h:893
Tuplesortstate ** sortstates
Definition: nodeAgg.c:380
#define outerPlan(node)
Definition: plannodes.h:174
ExprContext * hashcontext
Definition: execnodes.h:1792
#define Max(x, y)
Definition: c.h:801
ExprContext ** aggcontexts
Definition: execnodes.h:1793
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:381
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1167
AggState* ExecInitAgg ( Agg node,
EState estate,
int  eflags 
)

Definition at line 2670 of file nodeAgg.c.

References ACL_EXECUTE, ACL_KIND_PROC, aclcheck_error(), ACLCHECK_OK, AggState::agg_done, AGG_HASHED, AGG_MIXED, AGG_SORTED, AggState::aggcontexts, Aggref::aggdirectargs, AGGFNOID, Aggref::aggfnoid, Aggref::agglevelsup, AggrefExprState::aggno, AggStatePerPhaseData::aggnode, AggStatePerHashData::aggnode, AggStatePerTransData::aggref, AggStatePerAggData::aggref, AggrefExprState::aggref, AggState::aggs, Aggref::aggsplit, Agg::aggsplit, AggState::aggsplit, AggStatePerPhaseData::aggstrategy, Agg::aggstrategy, AggState::aggstrategy, Aggref::aggtranstype, Aggref::aggtype, AggState::all_grouped_cols, Anum_pg_aggregate_agginitval, arg, Aggref::args, Assert, bms_add_member(), bms_add_members(), bms_next_member(), build_aggregate_finalfn_expr(), build_hash_table(), build_pertrans_for_aggref(), castNode, Agg::chain, AggState::curpertrans, AggState::current_phase, AggState::current_set, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_DESERIALIZE, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, elog, AggStatePerPhaseData::eqfunctions, AggStatePerHashData::eqfunctions, ERROR, AggState::evaldesc, AggState::evalproj, AggState::evalslot, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, EXEC_FLAG_REWIND, ExecAgg(), ExecAssignExprContext(), ExecAssignProjectionInfo(), ExecAssignResultTypeFromTL(), ExecAssignScanTypeFromOuterPlan(), ExecBuildProjectionInfo(), ExecInitExtraTupleSlot(), ExecInitNode(), ExecInitQual(), ExecInitResultTupleSlot(), ExecInitScanTupleSlot(), PlanState::ExecProcNode, ExecSetSlotDescriptor(), execTuplesHashPrepare(), execTuplesMatchPrepare(), ExecTypeFromTL(), AggStatePerAggData::finalfn, AggStatePerAggData::finalfn_oid, find_compatible_peragg(), find_compatible_pertrans(), find_hash_columns(), flatCopyTargetEntry(), fmgr_info(), fmgr_info_set_expr, FUNC_MAX_ARGS, get_aggregate_argtypes(), get_func_name(), get_typlenbyval(), GetAggInitVal(), GETSTRUCT, GetUserId(), AggStatePerPhaseData::grouped_cols, Agg::groupingSets, AggState::grp_firstTuple, Agg::grpColIdx, Agg::grpOperators, AggStatePerPhaseData::gset_lengths, AggState::hash_pergroup, AggState::hashcontext, AggStatePerHashData::hashfunctions, AggStatePerHashData::hashslot, HeapTupleIsValid, i, initialize_phase(), initValue(), AggState::input_done, Aggref::inputcollid, AggStatePerTransData::inputoff, INTERNALOID, InvalidOid, InvokeFunctionExecuteHook, lappend(), lcons_int(), Plan::lefttree, lfirst, lfirst_node, list_length(), list_nth_node, makeNode, Max, AggState::maxsets, NIL, NULL, AggState::num_hashes, AggState::numaggs, AggStatePerHashData::numCols, Agg::numCols, AggStatePerAggData::numFinalArgs, AggState::numphases, AggStatePerPhaseData::numsets, AggState::numtrans, ObjectIdGetDatum, OidIsValid, outerPlan, outerPlanState, palloc(), palloc0(), AggState::peragg, AggState::pergroup, AggState::perhash, AggState::pertrans, pg_proc_aclcheck(), AggState::phases, Agg::plan, PlanState::plan, PROCOID, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, Plan::qual, PlanState::qual, ReleaseSysCache(), TargetEntry::resno, AggStatePerAggData::resulttypeByVal, AggStatePerAggData::resulttypeLen, SearchSysCache1, select_current_set(), AggState::sort_in, AggState::sort_out, AggState::sort_slot, AggStatePerPhaseData::sortnode, AggState::ss, ScanState::ss_ScanTupleSlot, PlanState::state, SysCacheGetAttr(), AggState::table_filled, AggState::tmpcontext, AggStatePerAggData::transno, and TupleTableSlot::tts_tupleDescriptor.

Referenced by ExecInitNode().

2671 {
2672  AggState *aggstate;
2673  AggStatePerAgg peraggs;
2674  AggStatePerTrans pertransstates;
2675  Plan *outerPlan;
2676  ExprContext *econtext;
2677  int numaggs,
2678  transno,
2679  aggno;
2680  int phase;
2681  int phaseidx;
2682  List *combined_inputeval;
2683  ListCell *l;
2684  Bitmapset *all_grouped_cols = NULL;
2685  int numGroupingSets = 1;
2686  int numPhases;
2687  int numHashes;
2688  int column_offset;
2689  int i = 0;
2690  int j = 0;
2691  bool use_hashing = (node->aggstrategy == AGG_HASHED ||
2692  node->aggstrategy == AGG_MIXED);
2693 
2694  /* check for unsupported flags */
2695  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
2696 
2697  /*
2698  * create state structure
2699  */
2700  aggstate = makeNode(AggState);
2701  aggstate->ss.ps.plan = (Plan *) node;
2702  aggstate->ss.ps.state = estate;
2703  aggstate->ss.ps.ExecProcNode = ExecAgg;
2704 
2705  aggstate->aggs = NIL;
2706  aggstate->numaggs = 0;
2707  aggstate->numtrans = 0;
2708  aggstate->aggstrategy = node->aggstrategy;
2709  aggstate->aggsplit = node->aggsplit;
2710  aggstate->maxsets = 0;
2711  aggstate->projected_set = -1;
2712  aggstate->current_set = 0;
2713  aggstate->peragg = NULL;
2714  aggstate->pertrans = NULL;
2715  aggstate->curpertrans = NULL;
2716  aggstate->input_done = false;
2717  aggstate->agg_done = false;
2718  aggstate->pergroup = NULL;
2719  aggstate->grp_firstTuple = NULL;
2720  aggstate->sort_in = NULL;
2721  aggstate->sort_out = NULL;
2722 
2723  /*
2724  * phases[0] always exists, but is dummy in sorted/plain mode
2725  */
2726  numPhases = (use_hashing ? 1 : 2);
2727  numHashes = (use_hashing ? 1 : 0);
2728 
2729  /*
2730  * Calculate the maximum number of grouping sets in any phase; this
2731  * determines the size of some allocations. Also calculate the number of
2732  * phases, since all hashed/mixed nodes contribute to only a single phase.
2733  */
2734  if (node->groupingSets)
2735  {
2736  numGroupingSets = list_length(node->groupingSets);
2737 
2738  foreach(l, node->chain)
2739  {
2740  Agg *agg = lfirst(l);
2741 
2742  numGroupingSets = Max(numGroupingSets,
2743  list_length(agg->groupingSets));
2744 
2745  /*
2746  * additional AGG_HASHED aggs become part of phase 0, but all
2747  * others add an extra phase.
2748  */
2749  if (agg->aggstrategy != AGG_HASHED)
2750  ++numPhases;
2751  else
2752  ++numHashes;
2753  }
2754  }
2755 
2756  aggstate->maxsets = numGroupingSets;
2757  aggstate->numphases = numPhases;
2758 
2759  aggstate->aggcontexts = (ExprContext **)
2760  palloc0(sizeof(ExprContext *) * numGroupingSets);
2761 
2762  /*
2763  * Create expression contexts. We need three or more, one for
2764  * per-input-tuple processing, one for per-output-tuple processing, one
2765  * for all the hashtables, and one for each grouping set. The per-tuple
2766  * memory context of the per-grouping-set ExprContexts (aggcontexts)
2767  * replaces the standalone memory context formerly used to hold transition
2768  * values. We cheat a little by using ExecAssignExprContext() to build
2769  * all of them.
2770  *
2771  * NOTE: the details of what is stored in aggcontexts and what is stored
2772  * in the regular per-query memory context are driven by a simple
2773  * decision: we want to reset the aggcontext at group boundaries (if not
2774  * hashing) and in ExecReScanAgg to recover no-longer-wanted space.
2775  */
2776  ExecAssignExprContext(estate, &aggstate->ss.ps);
2777  aggstate->tmpcontext = aggstate->ss.ps.ps_ExprContext;
2778 
2779  for (i = 0; i < numGroupingSets; ++i)
2780  {
2781  ExecAssignExprContext(estate, &aggstate->ss.ps);
2782  aggstate->aggcontexts[i] = aggstate->ss.ps.ps_ExprContext;
2783  }
2784 
2785  if (use_hashing)
2786  {
2787  ExecAssignExprContext(estate, &aggstate->ss.ps);
2788  aggstate->hashcontext = aggstate->ss.ps.ps_ExprContext;
2789  }
2790 
2791  ExecAssignExprContext(estate, &aggstate->ss.ps);
2792 
2793  /*
2794  * tuple table initialization.
2795  *
2796  * For hashtables, we create some additional slots below.
2797  */
2798  ExecInitScanTupleSlot(estate, &aggstate->ss);
2799  ExecInitResultTupleSlot(estate, &aggstate->ss.ps);
2800  aggstate->sort_slot = ExecInitExtraTupleSlot(estate);
2801 
2802  /*
2803  * initialize child expressions
2804  *
2805  * We rely on the parser to have checked that no aggs contain other agg
2806  * calls in their arguments. This would make no sense under SQL semantics
2807  * (and it's forbidden by the spec). Because it is true, we don't need to
2808  * worry about evaluating the aggs in any particular order.
2809  *
2810  * Note: execExpr.c finds Aggrefs for us, and adds their AggrefExprState
2811  * nodes to aggstate->aggs. Aggrefs in the qual are found here; Aggrefs
2812  * in the targetlist are found during ExecAssignProjectionInfo, below.
2813  */
2814  aggstate->ss.ps.qual =
2815  ExecInitQual(node->plan.qual, (PlanState *) aggstate);
2816 
2817  /*
2818  * Initialize child nodes.
2819  *
2820  * If we are doing a hashed aggregation then the child plan does not need
2821  * to handle REWIND efficiently; see ExecReScanAgg.
2822  */
2823  if (node->aggstrategy == AGG_HASHED)
2824  eflags &= ~EXEC_FLAG_REWIND;
2825  outerPlan = outerPlan(node);
2826  outerPlanState(aggstate) = ExecInitNode(outerPlan, estate, eflags);
2827 
2828  /*
2829  * initialize source tuple type.
2830  */
2831  ExecAssignScanTypeFromOuterPlan(&aggstate->ss);
2832  if (node->chain)
2833  ExecSetSlotDescriptor(aggstate->sort_slot,
2835 
2836  /*
2837  * Initialize result tuple type and projection info.
2838  */
2839  ExecAssignResultTypeFromTL(&aggstate->ss.ps);
2840  ExecAssignProjectionInfo(&aggstate->ss.ps, NULL);
2841 
2842  /*
2843  * We should now have found all Aggrefs in the targetlist and quals.
2844  */
2845  numaggs = aggstate->numaggs;
2846  Assert(numaggs == list_length(aggstate->aggs));
2847  if (numaggs <= 0)
2848  {
2849  /*
2850  * This is not an error condition: we might be using the Agg node just
2851  * to do hash-based grouping. Even in the regular case,
2852  * constant-expression simplification could optimize away all of the
2853  * Aggrefs in the targetlist and qual. So keep going, but force local
2854  * copy of numaggs positive so that palloc()s below don't choke.
2855  */
2856  numaggs = 1;
2857  }
2858 
2859  /*
2860  * For each phase, prepare grouping set data and fmgr lookup data for
2861  * compare functions. Accumulate all_grouped_cols in passing.
2862  */
2863  aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
2864 
2865  aggstate->num_hashes = numHashes;
2866  if (numHashes)
2867  {
2868  aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
2869  aggstate->phases[0].numsets = 0;
2870  aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
2871  aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
2872  }
2873 
2874  phase = 0;
2875  for (phaseidx = 0; phaseidx <= list_length(node->chain); ++phaseidx)
2876  {
2877  Agg *aggnode;
2878  Sort *sortnode;
2879 
2880  if (phaseidx > 0)
2881  {
2882  aggnode = list_nth_node(Agg, node->chain, phaseidx - 1);
2883  sortnode = castNode(Sort, aggnode->plan.lefttree);
2884  }
2885  else
2886  {
2887  aggnode = node;
2888  sortnode = NULL;
2889  }
2890 
2891  Assert(phase <= 1 || sortnode);
2892 
2893  if (aggnode->aggstrategy == AGG_HASHED
2894  || aggnode->aggstrategy == AGG_MIXED)
2895  {
2896  AggStatePerPhase phasedata = &aggstate->phases[0];
2897  AggStatePerHash perhash;
2898  Bitmapset *cols = NULL;
2899 
2900  Assert(phase == 0);
2901  i = phasedata->numsets++;
2902  perhash = &aggstate->perhash[i];
2903 
2904  /* phase 0 always points to the "real" Agg in the hash case */
2905  phasedata->aggnode = node;
2906  phasedata->aggstrategy = node->aggstrategy;
2907 
2908  /* but the actual Agg node representing this hash is saved here */
2909  perhash->aggnode = aggnode;
2910 
2911  phasedata->gset_lengths[i] = perhash->numCols = aggnode->numCols;
2912 
2913  for (j = 0; j < aggnode->numCols; ++j)
2914  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
2915 
2916  phasedata->grouped_cols[i] = cols;
2917 
2918  all_grouped_cols = bms_add_members(all_grouped_cols, cols);
2919  continue;
2920  }
2921  else
2922  {
2923  AggStatePerPhase phasedata = &aggstate->phases[++phase];
2924  int num_sets;
2925 
2926  phasedata->numsets = num_sets = list_length(aggnode->groupingSets);
2927 
2928  if (num_sets)
2929  {
2930  phasedata->gset_lengths = palloc(num_sets * sizeof(int));
2931  phasedata->grouped_cols = palloc(num_sets * sizeof(Bitmapset *));
2932 
2933  i = 0;
2934  foreach(l, aggnode->groupingSets)
2935  {
2936  int current_length = list_length(lfirst(l));
2937  Bitmapset *cols = NULL;
2938 
2939  /* planner forces this to be correct */
2940  for (j = 0; j < current_length; ++j)
2941  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
2942 
2943  phasedata->grouped_cols[i] = cols;
2944  phasedata->gset_lengths[i] = current_length;
2945 
2946  ++i;
2947  }
2948 
2949  all_grouped_cols = bms_add_members(all_grouped_cols,
2950  phasedata->grouped_cols[0]);
2951  }
2952  else
2953  {
2954  Assert(phaseidx == 0);
2955 
2956  phasedata->gset_lengths = NULL;
2957  phasedata->grouped_cols = NULL;
2958  }
2959 
2960  /*
2961  * If we are grouping, precompute fmgr lookup data for inner loop.
2962  */
2963  if (aggnode->aggstrategy == AGG_SORTED)
2964  {
2965  Assert(aggnode->numCols > 0);
2966 
2967  phasedata->eqfunctions =
2969  aggnode->grpOperators);
2970  }
2971 
2972  phasedata->aggnode = aggnode;
2973  phasedata->aggstrategy = aggnode->aggstrategy;
2974  phasedata->sortnode = sortnode;
2975  }
2976  }
2977 
2978  /*
2979  * Convert all_grouped_cols to a descending-order list.
2980  */
2981  i = -1;
2982  while ((i = bms_next_member(all_grouped_cols, i)) >= 0)
2983  aggstate->all_grouped_cols = lcons_int(i, aggstate->all_grouped_cols);
2984 
2985  /*
2986  * Set up aggregate-result storage in the output expr context, and also
2987  * allocate my private per-agg working storage
2988  */
2989  econtext = aggstate->ss.ps.ps_ExprContext;
2990  econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
2991  econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
2992 
2993  peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
2994  pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numaggs);
2995 
2996  aggstate->peragg = peraggs;
2997  aggstate->pertrans = pertransstates;
2998 
2999  /*
3000  * Hashing can only appear in the initial phase.
3001  */
3002  if (use_hashing)
3003  {
3004  for (i = 0; i < numHashes; ++i)
3005  {
3006  aggstate->perhash[i].hashslot = ExecInitExtraTupleSlot(estate);
3007 
3008  execTuplesHashPrepare(aggstate->perhash[i].numCols,
3009  aggstate->perhash[i].aggnode->grpOperators,
3010  &aggstate->perhash[i].eqfunctions,
3011  &aggstate->perhash[i].hashfunctions);
3012  }
3013 
3014  /* this is an array of pointers, not structures */
3015  aggstate->hash_pergroup = palloc0(sizeof(AggStatePerGroup) * numHashes);
3016 
3017  find_hash_columns(aggstate);
3018  build_hash_table(aggstate);
3019  aggstate->table_filled = false;
3020  }
3021 
3022  if (node->aggstrategy != AGG_HASHED)
3023  {
3024  AggStatePerGroup pergroup;
3025 
3026  pergroup = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
3027  * numaggs
3028  * numGroupingSets);
3029 
3030  aggstate->pergroup = pergroup;
3031  }
3032 
3033  /*
3034  * Initialize current phase-dependent values to initial phase. The initial
3035  * phase is 1 (first sort pass) for all strategies that use sorting (if
3036  * hashing is being done too, then phase 0 is processed last); but if only
3037  * hashing is being done, then phase 0 is all there is.
3038  */
3039  if (node->aggstrategy == AGG_HASHED)
3040  {
3041  aggstate->current_phase = 0;
3042  initialize_phase(aggstate, 0);
3043  select_current_set(aggstate, 0, true);
3044  }
3045  else
3046  {
3047  aggstate->current_phase = 1;
3048  initialize_phase(aggstate, 1);
3049  select_current_set(aggstate, 0, false);
3050  }
3051 
3052  /* -----------------
3053  * Perform lookups of aggregate function info, and initialize the
3054  * unchanging fields of the per-agg and per-trans data.
3055  *
3056  * We try to optimize by detecting duplicate aggregate functions so that
3057  * their state and final values are re-used, rather than needlessly being
3058  * re-calculated independently. We also detect aggregates that are not
3059  * the same, but which can share the same transition state.
3060  *
3061  * Scenarios:
3062  *
3063  * 1. An aggregate function appears more than once in query:
3064  *
3065  * SELECT SUM(x) FROM ... HAVING SUM(x) > 0
3066  *
3067  * Since the aggregates are the identical, we only need to calculate
3068  * the calculate it once. Both aggregates will share the same 'aggno'
3069  * value.
3070  *
3071  * 2. Two different aggregate functions appear in the query, but the
3072  * aggregates have the same transition function and initial value, but
3073  * different final function:
3074  *
3075  * SELECT SUM(x), AVG(x) FROM ...
3076  *
3077  * In this case we must create a new peragg for the varying aggregate,
3078  * and need to call the final functions separately, but can share the
3079  * same transition state.
3080  *
3081  * For either of these optimizations to be valid, the aggregate's
3082  * arguments must be the same, including any modifiers such as ORDER BY,
3083  * DISTINCT and FILTER, and they mustn't contain any volatile functions.
3084  * -----------------
3085  */
3086  aggno = -1;
3087  transno = -1;
3088  foreach(l, aggstate->aggs)
3089  {
3090  AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(l);
3091  Aggref *aggref = aggrefstate->aggref;
3092  AggStatePerAgg peragg;
3093  AggStatePerTrans pertrans;
3094  int existing_aggno;
3095  int existing_transno;
3096  List *same_input_transnos;
3097  Oid inputTypes[FUNC_MAX_ARGS];
3098  int numArguments;
3099  int numDirectArgs;
3100  HeapTuple aggTuple;
3101  Form_pg_aggregate aggform;
3102  AclResult aclresult;
3103  Oid transfn_oid,
3104  finalfn_oid;
3105  Oid serialfn_oid,
3106  deserialfn_oid;
3107  Expr *finalfnexpr;
3108  Oid aggtranstype;
3109  Datum textInitVal;
3110  Datum initValue;
3111  bool initValueIsNull;
3112 
3113  /* Planner should have assigned aggregate to correct level */
3114  Assert(aggref->agglevelsup == 0);
3115  /* ... and the split mode should match */
3116  Assert(aggref->aggsplit == aggstate->aggsplit);
3117 
3118  /* 1. Check for already processed aggs which can be re-used */
3119  existing_aggno = find_compatible_peragg(aggref, aggstate, aggno,
3120  &same_input_transnos);
3121  if (existing_aggno != -1)
3122  {
3123  /*
3124  * Existing compatible agg found. so just point the Aggref to the
3125  * same per-agg struct.
3126  */
3127  aggrefstate->aggno = existing_aggno;
3128  continue;
3129  }
3130 
3131  /* Mark Aggref state node with assigned index in the result array */
3132  peragg = &peraggs[++aggno];
3133  peragg->aggref = aggref;
3134  aggrefstate->aggno = aggno;
3135 
3136  /* Fetch the pg_aggregate row */
3137  aggTuple = SearchSysCache1(AGGFNOID,
3138  ObjectIdGetDatum(aggref->aggfnoid));
3139  if (!HeapTupleIsValid(aggTuple))
3140  elog(ERROR, "cache lookup failed for aggregate %u",
3141  aggref->aggfnoid);
3142  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
3143 
3144  /* Check permission to call aggregate function */
3145  aclresult = pg_proc_aclcheck(aggref->aggfnoid, GetUserId(),
3146  ACL_EXECUTE);
3147  if (aclresult != ACLCHECK_OK)
3148  aclcheck_error(aclresult, ACL_KIND_PROC,
3149  get_func_name(aggref->aggfnoid));
3151 
3152  /* planner recorded transition state type in the Aggref itself */
3153  aggtranstype = aggref->aggtranstype;
3154  Assert(OidIsValid(aggtranstype));
3155 
3156  /*
3157  * If this aggregation is performing state combines, then instead of
3158  * using the transition function, we'll use the combine function
3159  */
3160  if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3161  {
3162  transfn_oid = aggform->aggcombinefn;
3163 
3164  /* If not set then the planner messed up */
3165  if (!OidIsValid(transfn_oid))
3166  elog(ERROR, "combinefn not set for aggregate function");
3167  }
3168  else
3169  transfn_oid = aggform->aggtransfn;
3170 
3171  /* Final function only required if we're finalizing the aggregates */
3172  if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
3173  peragg->finalfn_oid = finalfn_oid = InvalidOid;
3174  else
3175  peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
3176 
3177  serialfn_oid = InvalidOid;
3178  deserialfn_oid = InvalidOid;
3179 
3180  /*
3181  * Check if serialization/deserialization is required. We only do it
3182  * for aggregates that have transtype INTERNAL.
3183  */
3184  if (aggtranstype == INTERNALOID)
3185  {
3186  /*
3187  * The planner should only have generated a serialize agg node if
3188  * every aggregate with an INTERNAL state has a serialization
3189  * function. Verify that.
3190  */
3191  if (DO_AGGSPLIT_SERIALIZE(aggstate->aggsplit))
3192  {
3193  /* serialization only valid when not running finalfn */
3195 
3196  if (!OidIsValid(aggform->aggserialfn))
3197  elog(ERROR, "serialfunc not provided for serialization aggregation");
3198  serialfn_oid = aggform->aggserialfn;
3199  }
3200 
3201  /* Likewise for deserialization functions */
3202  if (DO_AGGSPLIT_DESERIALIZE(aggstate->aggsplit))
3203  {
3204  /* deserialization only valid when combining states */
3205  Assert(DO_AGGSPLIT_COMBINE(aggstate->aggsplit));
3206 
3207  if (!OidIsValid(aggform->aggdeserialfn))
3208  elog(ERROR, "deserialfunc not provided for deserialization aggregation");
3209  deserialfn_oid = aggform->aggdeserialfn;
3210  }
3211  }
3212 
3213  /* Check that aggregate owner has permission to call component fns */
3214  {
3215  HeapTuple procTuple;
3216  Oid aggOwner;
3217 
3218  procTuple = SearchSysCache1(PROCOID,
3219  ObjectIdGetDatum(aggref->aggfnoid));
3220  if (!HeapTupleIsValid(procTuple))
3221  elog(ERROR, "cache lookup failed for function %u",
3222  aggref->aggfnoid);
3223  aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
3224  ReleaseSysCache(procTuple);
3225 
3226  aclresult = pg_proc_aclcheck(transfn_oid, aggOwner,
3227  ACL_EXECUTE);
3228  if (aclresult != ACLCHECK_OK)
3229  aclcheck_error(aclresult, ACL_KIND_PROC,
3230  get_func_name(transfn_oid));
3231  InvokeFunctionExecuteHook(transfn_oid);
3232  if (OidIsValid(finalfn_oid))
3233  {
3234  aclresult = pg_proc_aclcheck(finalfn_oid, aggOwner,
3235  ACL_EXECUTE);
3236  if (aclresult != ACLCHECK_OK)
3237  aclcheck_error(aclresult, ACL_KIND_PROC,
3238  get_func_name(finalfn_oid));
3239  InvokeFunctionExecuteHook(finalfn_oid);
3240  }
3241  if (OidIsValid(serialfn_oid))
3242  {
3243  aclresult = pg_proc_aclcheck(serialfn_oid, aggOwner,
3244  ACL_EXECUTE);
3245  if (aclresult != ACLCHECK_OK)
3246  aclcheck_error(aclresult, ACL_KIND_PROC,
3247  get_func_name(serialfn_oid));
3248  InvokeFunctionExecuteHook(serialfn_oid);
3249  }
3250  if (OidIsValid(deserialfn_oid))
3251  {
3252  aclresult = pg_proc_aclcheck(deserialfn_oid, aggOwner,
3253  ACL_EXECUTE);
3254  if (aclresult != ACLCHECK_OK)
3255  aclcheck_error(aclresult, ACL_KIND_PROC,
3256  get_func_name(deserialfn_oid));
3257  InvokeFunctionExecuteHook(deserialfn_oid);
3258  }
3259  }
3260 
3261  /*
3262  * Get actual datatypes of the (nominal) aggregate inputs. These
3263  * could be different from the agg's declared input types, when the
3264  * agg accepts ANY or a polymorphic type.
3265  */
3266  numArguments = get_aggregate_argtypes(aggref, inputTypes);
3267 
3268  /* Count the "direct" arguments, if any */
3269  numDirectArgs = list_length(aggref->aggdirectargs);
3270 
3271  /* Detect how many arguments to pass to the finalfn */
3272  if (aggform->aggfinalextra)
3273  peragg->numFinalArgs = numArguments + 1;
3274  else
3275  peragg->numFinalArgs = numDirectArgs + 1;
3276 
3277  /*
3278  * build expression trees using actual argument & result types for the
3279  * finalfn, if it exists and is required.
3280  */
3281  if (OidIsValid(finalfn_oid))
3282  {
3283  build_aggregate_finalfn_expr(inputTypes,
3284  peragg->numFinalArgs,
3285  aggtranstype,
3286  aggref->aggtype,
3287  aggref->inputcollid,
3288  finalfn_oid,
3289  &finalfnexpr);
3290  fmgr_info(finalfn_oid, &peragg->finalfn);
3291  fmgr_info_set_expr((Node *) finalfnexpr, &peragg->finalfn);
3292  }
3293 
3294  /* get info about the output value's datatype */
3295  get_typlenbyval(aggref->aggtype,
3296  &peragg->resulttypeLen,
3297  &peragg->resulttypeByVal);
3298 
3299  /*
3300  * initval is potentially null, so don't try to access it as a struct
3301  * field. Must do it the hard way with SysCacheGetAttr.
3302  */
3303  textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
3305  &initValueIsNull);
3306  if (initValueIsNull)
3307  initValue = (Datum) 0;
3308  else
3309  initValue = GetAggInitVal(textInitVal, aggtranstype);
3310 
3311  /*
3312  * 2. Build working state for invoking the transition function, or
3313  * look up previously initialized working state, if we can share it.
3314  *
3315  * find_compatible_peragg() already collected a list of per-Trans's
3316  * with the same inputs. Check if any of them have the same transition
3317  * function and initial value.
3318  */
3319  existing_transno = find_compatible_pertrans(aggstate, aggref,
3320  transfn_oid, aggtranstype,
3321  serialfn_oid, deserialfn_oid,
3322  initValue, initValueIsNull,
3323  same_input_transnos);
3324  if (existing_transno != -1)
3325  {
3326  /*
3327  * Existing compatible trans found, so just point the 'peragg' to
3328  * the same per-trans struct.
3329  */
3330  pertrans = &pertransstates[existing_transno];
3331  peragg->transno = existing_transno;
3332  }
3333  else
3334  {
3335  pertrans = &pertransstates[++transno];
3336  build_pertrans_for_aggref(pertrans, aggstate, estate,
3337  aggref, transfn_oid, aggtranstype,
3338  serialfn_oid, deserialfn_oid,
3339  initValue, initValueIsNull,
3340  inputTypes, numArguments);
3341  peragg->transno = transno;
3342  }
3343  ReleaseSysCache(aggTuple);
3344  }
3345 
3346  /*
3347  * Update numaggs to match the number of unique aggregates found. Also set
3348  * numstates to the number of unique aggregate states found.
3349  */
3350  aggstate->numaggs = aggno + 1;
3351  aggstate->numtrans = transno + 1;
3352 
3353  /*
3354  * Build a single projection computing the aggregate arguments for all
3355  * aggregates at once, that's considerably faster than doing it separately
3356  * for each.
3357  *
3358  * First create a targetlist combining the targetlist of all the
3359  * transitions.
3360  */
3361  combined_inputeval = NIL;
3362  column_offset = 0;
3363  for (transno = 0; transno < aggstate->numtrans; transno++)
3364  {
3365  AggStatePerTrans pertrans = &pertransstates[transno];
3366  ListCell *arg;
3367 
3368  pertrans->inputoff = column_offset;
3369 
3370  /*
3371  * Adjust resno in a copied target entries, to point into the combined
3372  * slot.
3373  */
3374  foreach(arg, pertrans->aggref->args)
3375  {
3376  TargetEntry *source_tle = lfirst_node(TargetEntry, arg);
3377  TargetEntry *tle;
3378 
3379  tle = flatCopyTargetEntry(source_tle);
3380  tle->resno += column_offset;
3381 
3382  combined_inputeval = lappend(combined_inputeval, tle);
3383  }
3384 
3385  column_offset += list_length(pertrans->aggref->args);
3386  }
3387 
3388  /* and then create a projection for that targetlist */
3389  aggstate->evaldesc = ExecTypeFromTL(combined_inputeval, false);
3390  aggstate->evalslot = ExecInitExtraTupleSlot(estate);
3391  aggstate->evalproj = ExecBuildProjectionInfo(combined_inputeval,
3392  aggstate->tmpcontext,
3393  aggstate->evalslot,
3394  &aggstate->ss.ps,
3395  NULL);
3396  ExecSetSlotDescriptor(aggstate->evalslot, aggstate->evaldesc);
3397 
3398  return aggstate;
3399 }
FmgrInfo * eqfunctions
Definition: nodeAgg.c:511
struct AggStatePerTransData * AggStatePerTrans
Definition: execnodes.h:1774
AggStatePerGroup * hash_pergroup
Definition: execnodes.h:1816
#define NIL
Definition: pg_list.h:69
struct AggStatePerGroupData * AggStatePerGroup
Definition: execnodes.h:1775
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:586
int numCols
Definition: plannodes.h:785
List * qual
Definition: plannodes.h:145
AggStatePerPhase phases
Definition: execnodes.h:1805
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
Datum * ecxt_aggvalues
Definition: execnodes.h:213
void ExecInitScanTupleSlot(EState *estate, ScanState *scanstate)
Definition: execTuples.c:842
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
AttrNumber * grpColIdx
Definition: plannodes.h:786
#define Anum_pg_aggregate_agginitval
Definition: pg_aggregate.h:113
List * lcons_int(int datum, List *list)
Definition: list.c:277
int numaggs
Definition: execnodes.h:1783
Oid GetUserId(void)
Definition: miscinit.c:284
bool agg_done
Definition: execnodes.h:1798
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
TupleTableSlot * sort_slot
Definition: execnodes.h:1808
List * all_grouped_cols
Definition: execnodes.h:1802
Tuplesortstate * sort_out
Definition: execnodes.h:1807
ProjectionInfo * evalproj
Definition: execnodes.h:1819
ScanState ss
Definition: execnodes.h:1781
ExprContext * ps_ExprContext
Definition: execnodes.h:881
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:937
FmgrInfo * eqfunctions
Definition: nodeAgg.c:493
Oid inputcollid
Definition: primnodes.h:297
int current_phase
Definition: execnodes.h:1789
Definition: nodes.h:509
AggSplit aggsplit
Definition: execnodes.h:1786
static TupleTableSlot * ExecAgg(PlanState *pstate)
Definition: nodeAgg.c:2107
List * args
Definition: primnodes.h:301
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1101
void build_aggregate_finalfn_expr(Oid *agg_input_types, int num_finalfn_inputs, Oid agg_state_type, Oid agg_result_type, Oid agg_input_collation, Oid finalfn_oid, Expr **finalfnexpr)
Definition: parse_agg.c:2019
AggStatePerTrans pertrans
Definition: execnodes.h:1791
EState * state
Definition: execnodes.h:849
int projected_set
Definition: execnodes.h:1799
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple grp_firstTuple
Definition: execnodes.h:1811
Aggref * aggref
Definition: nodeAgg.c:413
int current_set
Definition: execnodes.h:1800
#define OidIsValid(objectId)
Definition: c.h:538
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:768
TupleDesc evaldesc
Definition: execnodes.h:1820
int numtrans
Definition: execnodes.h:1784
void execTuplesHashPrepare(int numCols, Oid *eqOperators, FmgrInfo **eqFunctions, FmgrInfo **hashFunctions)
Definition: execGrouping.c:233
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:160
void ExecAssignResultTypeFromTL(PlanState *planstate)
Definition: execUtils.c:445
ExprContext * tmpcontext
Definition: execnodes.h:1794
#define FUNC_MAX_ARGS
Bitmapset ** grouped_cols
Definition: nodeAgg.c:492
PlanState ps
Definition: execnodes.h:1098
int maxsets
Definition: execnodes.h:1804
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:770
AggStrategy aggstrategy
Definition: plannodes.h:783
bool table_filled
Definition: execnodes.h:1813
AggStrategy aggstrategy
Definition: execnodes.h:1785
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1412
void ExecInitResultTupleSlot(EState *estate, PlanState *planstate)
Definition: execTuples.c:832
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
static void find_hash_columns(AggState *aggstate)
Definition: nodeAgg.c:1910
Tuplesortstate * sort_in
Definition: execnodes.h:1806
#define EXEC_FLAG_BACKWARD
Definition: executor.h:60
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define outerPlanState(node)
Definition: execnodes.h:893
Aggref * aggref
Definition: execnodes.h:657
#define list_nth_node(type, list, n)
Definition: pg_list.h:227
static int find_compatible_pertrans(AggState *aggstate, Aggref *newagg, Oid aggtransfn, Oid aggtranstype, Oid aggserialfn, Oid aggdeserialfn, Datum initValue, bool initValueIsNull, List *transnos)
Definition: nodeAgg.c:3803
static int initValue(long lng_val)
Definition: informix.c:702
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:492
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
static void build_hash_table(AggState *aggstate)
Definition: nodeAgg.c:1861
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:104
AttrNumber resno
Definition: primnodes.h:1369
Index agglevelsup
Definition: primnodes.h:309
List * aggdirectargs
Definition: primnodes.h:300
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
Definition: nodeAgg.c:3702
AggStatePerHash perhash
Definition: execnodes.h:1815
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition: makefuncs.c:268
AggStrategy aggstrategy
Definition: nodeAgg.c:489
#define EXEC_FLAG_REWIND
Definition: executor.h:59
TupleDesc ExecTypeFromTL(List *targetList, bool hasoid)
Definition: execTuples.c:888
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:179
#define outerPlan(node)
Definition: plannodes.h:174
List * lappend(List *list, void *datum)
Definition: list.c:128
int num_hashes
Definition: execnodes.h:1814
Plan plan
Definition: plannodes.h:782
bool input_done
Definition: execnodes.h:1797
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
TupleTableSlot * evalslot
Definition: execnodes.h:1818
ExprContext * hashcontext
Definition: execnodes.h:1792
bool * ecxt_aggnulls
Definition: execnodes.h:214
static int find_compatible_peragg(Aggref *newagg, AggState *aggstate, int lastaggno, List **same_input_transnos)
Definition: nodeAgg.c:3730
void * palloc0(Size size)
Definition: mcxt.c:878
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:853
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
AggStatePerGroup pergroup
Definition: execnodes.h:1810
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1279
List * groupingSets
Definition: plannodes.h:791
int16 resulttypeLen
Definition: nodeAgg.c:439
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:604
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
Plan * plan
Definition: execnodes.h:847
#define InvalidOid
Definition: postgres_ext.h:36
Oid aggfnoid
Definition: primnodes.h:294
#define INTERNALOID
Definition: pg_type.h:698
#define Max(x, y)
Definition: c.h:801
ExprContext ** aggcontexts
Definition: execnodes.h:1793
#define makeNode(_type_)
Definition: nodes.h:557
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
FmgrInfo * hashfunctions
Definition: nodeAgg.c:510
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
#define EXEC_FLAG_MARK
Definition: executor.h:61
AggSplit aggsplit
Definition: plannodes.h:784
struct AggStatePerAggData * AggStatePerAgg
Definition: execnodes.h:1773
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:87
AggSplit aggsplit
Definition: primnodes.h:310
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:423
static int list_length(const List *l)
Definition: pg_list.h:89
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:769
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2001
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:771
struct Plan * lefttree
Definition: plannodes.h:146
int numphases
Definition: execnodes.h:1788
ExprState * qual
Definition: execnodes.h:865
void ExecAssignScanTypeFromOuterPlan(ScanState *scanstate)
Definition: execUtils.c:557
Oid * grpOperators
Definition: plannodes.h:787
void * palloc(Size size)
Definition: mcxt.c:849
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:301
List * chain
Definition: plannodes.h:792
AggStatePerAgg peragg
Definition: execnodes.h:1790
#define ACL_EXECUTE
Definition: parsenodes.h:79
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4446
int i
Oid aggtranstype
Definition: primnodes.h:298
void * arg
AggStatePerTrans curpertrans
Definition: execnodes.h:1796
Oid aggtype
Definition: primnodes.h:295
bool resulttypeByVal
Definition: nodeAgg.c:440
Definition: plannodes.h:780
#define elog
Definition: elog.h:219
List * aggs
Definition: execnodes.h:1782
FmgrInfo * execTuplesMatchPrepare(int numCols, Oid *eqOperators)
Definition: execGrouping.c:204
TupleTableSlot * hashslot
Definition: nodeAgg.c:509
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1801
static void build_pertrans_for_aggref(AggStatePerTrans pertrans, AggState *aggstate, EState *estate, Aggref *aggref, Oid aggtransfn, Oid aggtranstype, Oid aggserialfn, Oid aggdeserialfn, Datum initValue, bool initValueIsNull, Oid *inputTypes, int numArguments)
Definition: nodeAgg.c:3410
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:45
FmgrInfo finalfn
Definition: nodeAgg.c:425
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:755
void ExecReScanAgg ( AggState node)

Definition at line 3896 of file nodeAgg.c.

References AggState::agg_done, AGG_HASHED, AGG_MIXED, AggState::aggcontexts, Agg::aggParams, AggState::aggstrategy, bms_overlap(), build_hash_table(), PlanState::chgParam, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, ExecClearTuple(), ExecReScan(), AggState::grp_firstTuple, AggState::hashcontext, AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, heap_freetuple(), initialize_phase(), AggState::input_done, Max, AggState::maxsets, MemSet, NULL, AggState::numaggs, AggState::numtrans, outerPlan, outerPlanState, AggState::pergroup, AggState::perhash, AggState::pertrans, PlanState::plan, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, ReScanExprContext(), ResetTupleHashIterator, select_current_set(), AggStatePerTransData::sortstates, AggState::ss, ScanState::ss_ScanTupleSlot, AggState::table_filled, and tuplesort_end().

Referenced by ExecReScan().

3897 {
3898  ExprContext *econtext = node->ss.ps.ps_ExprContext;
3900  Agg *aggnode = (Agg *) node->ss.ps.plan;
3901  int transno;
3902  int numGroupingSets = Max(node->maxsets, 1);
3903  int setno;
3904 
3905  node->agg_done = false;
3906 
3907  if (node->aggstrategy == AGG_HASHED)
3908  {
3909  /*
3910  * In the hashed case, if we haven't yet built the hash table then we
3911  * can just return; nothing done yet, so nothing to undo. If subnode's
3912  * chgParam is not NULL then it will be re-scanned by ExecProcNode,
3913  * else no reason to re-scan it at all.
3914  */
3915  if (!node->table_filled)
3916  return;
3917 
3918  /*
3919  * If we do have the hash table, and the subplan does not have any
3920  * parameter changes, and none of our own parameter changes affect
3921  * input expressions of the aggregated functions, then we can just
3922  * rescan the existing hash table; no need to build it again.
3923  */
3924  if (outerPlan->chgParam == NULL &&
3925  !bms_overlap(node->ss.ps.chgParam, aggnode->aggParams))
3926  {
3928  &node->perhash[0].hashiter);
3929  select_current_set(node, 0, true);
3930  return;
3931  }
3932  }
3933 
3934  /* Make sure we have closed any open tuplesorts */
3935  for (transno = 0; transno < node->numtrans; transno++)
3936  {
3937  for (setno = 0; setno < numGroupingSets; setno++)
3938  {
3939  AggStatePerTrans pertrans = &node->pertrans[transno];
3940 
3941  if (pertrans->sortstates[setno])
3942  {
3943  tuplesort_end(pertrans->sortstates[setno]);
3944  pertrans->sortstates[setno] = NULL;
3945  }
3946  }
3947  }
3948 
3949  /*
3950  * We don't need to ReScanExprContext the output tuple context here;
3951  * ExecReScan already did it. But we do need to reset our per-grouping-set
3952  * contexts, which may have transvalues stored in them. (We use rescan
3953  * rather than just reset because transfns may have registered callbacks
3954  * that need to be run now.) For the AGG_HASHED case, see below.
3955  */
3956 
3957  for (setno = 0; setno < numGroupingSets; setno++)
3958  {
3959  ReScanExprContext(node->aggcontexts[setno]);
3960  }
3961 
3962  /* Release first tuple of group, if we have made a copy */
3963  if (node->grp_firstTuple != NULL)
3964  {
3966  node->grp_firstTuple = NULL;
3967  }
3969 
3970  /* Forget current agg values */
3971  MemSet(econtext->ecxt_aggvalues, 0, sizeof(Datum) * node->numaggs);
3972  MemSet(econtext->ecxt_aggnulls, 0, sizeof(bool) * node->numaggs);
3973 
3974  /*
3975  * With AGG_HASHED/MIXED, the hash table is allocated in a sub-context of
3976  * the hashcontext. This used to be an issue, but now, resetting a context
3977  * automatically deletes sub-contexts too.
3978  */
3979  if (node->aggstrategy == AGG_HASHED || node->aggstrategy == AGG_MIXED)
3980  {
3982  /* Rebuild an empty hash table */
3983  build_hash_table(node);
3984  node->table_filled = false;
3985  /* iterator will be reset when the table is filled */
3986  }
3987 
3988  if (node->aggstrategy != AGG_HASHED)
3989  {
3990  /*
3991  * Reset the per-group state (in particular, mark transvalues null)
3992  */
3993  MemSet(node->pergroup, 0,
3994  sizeof(AggStatePerGroupData) * node->numaggs * numGroupingSets);
3995 
3996  /* reset to phase 1 */
3997  initialize_phase(node, 1);
3998 
3999  node->input_done = false;
4000  node->projected_set = -1;
4001  }
4002 
4003  if (outerPlan->chgParam == NULL)
4004  ExecReScan(outerPlan);
4005 }
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:586
Datum * ecxt_aggvalues
Definition: execnodes.h:213
int numaggs
Definition: execnodes.h:1783
bool agg_done
Definition: execnodes.h:1798
ScanState ss
Definition: execnodes.h:1781
ExprContext * ps_ExprContext
Definition: execnodes.h:881
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define MemSet(start, val, len)
Definition: c.h:858
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1101
AggStatePerTrans pertrans
Definition: execnodes.h:1791
int projected_set
Definition: execnodes.h:1799
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1373
HeapTuple grp_firstTuple
Definition: execnodes.h:1811
int numtrans
Definition: execnodes.h:1784
PlanState ps
Definition: execnodes.h:1098
int maxsets
Definition: execnodes.h:1804
bool table_filled
Definition: execnodes.h:1813
AggStrategy aggstrategy
Definition: execnodes.h:1785
#define outerPlanState(node)
Definition: execnodes.h:893
Tuplesortstate ** sortstates
Definition: nodeAgg.c:380
Bitmapset * aggParams
Definition: plannodes.h:789
static void build_hash_table(AggState *aggstate)
Definition: nodeAgg.c:1861
AggStatePerHash perhash
Definition: execnodes.h:1815
Bitmapset * chgParam
Definition: execnodes.h:875
#define outerPlan(node)
Definition: plannodes.h:174
TupleHashIterator hashiter
Definition: nodeAgg.c:508
bool input_done
Definition: execnodes.h:1797
ExprContext * hashcontext
Definition: execnodes.h:1792
bool * ecxt_aggnulls
Definition: execnodes.h:214
uintptr_t Datum
Definition: postgres.h:372
AggStatePerGroup pergroup
Definition: execnodes.h:1810
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:604
Plan * plan
Definition: execnodes.h:847
#define ResetTupleHashIterator(htable, iter)
Definition: execnodes.h:632
#define Max(x, y)
Definition: c.h:801
ExprContext ** aggcontexts
Definition: execnodes.h:1793
#define NULL
Definition: c.h:229
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:381
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:443
Definition: plannodes.h:780
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1167
TupleHashTable hashtable
Definition: nodeAgg.c:507
Size hash_agg_entry_size ( int  numAggs)

Definition at line 2012 of file nodeAgg.c.

References MAXALIGN.

Referenced by create_distinct_paths(), and estimate_hashagg_tablesize().

2013 {
2014  Size entrysize;
2015 
2016  /* This must match build_hash_table */
2017  entrysize = sizeof(TupleHashEntryData) +
2018  numAggs * sizeof(AggStatePerGroupData);
2019  entrysize = MAXALIGN(entrysize);
2020 
2021  return entrysize;
2022 }
struct TupleHashEntryData TupleHashEntryData
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588