PostgreSQL Source Code  git master
nodeAgg.h File Reference
#include "access/parallel.h"
#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.

Data Structures

struct  AggStatePerTransData
 
struct  AggStatePerAggData
 
struct  AggStatePerGroupData
 
struct  AggStatePerPhaseData
 
struct  AggStatePerHashData
 

Macros

#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUE   0
 
#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUEISNULL   1
 
#define FIELDNO_AGGSTATEPERGROUPDATA_NOTRANSVALUE   2
 

Typedefs

typedef struct AggStatePerTransData AggStatePerTransData
 
typedef struct AggStatePerAggData AggStatePerAggData
 
typedef struct AggStatePerGroupData AggStatePerGroupData
 
typedef struct AggStatePerPhaseData AggStatePerPhaseData
 
typedef struct AggStatePerHashData AggStatePerHashData
 

Functions

AggStateExecInitAgg (Agg *node, EState *estate, int eflags)
 
void ExecEndAgg (AggState *node)
 
void ExecReScanAgg (AggState *node)
 
Size hash_agg_entry_size (int numTrans, Size tupleWidth, Size transitionSpace)
 
void hash_agg_set_limits (double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
 
void ExecAggEstimate (AggState *node, ParallelContext *pcxt)
 
void ExecAggInitializeDSM (AggState *node, ParallelContext *pcxt)
 
void ExecAggInitializeWorker (AggState *node, ParallelWorkerContext *pwcxt)
 
void ExecAggRetrieveInstrumentation (AggState *node)
 

Macro Definition Documentation

◆ FIELDNO_AGGSTATEPERGROUPDATA_NOTRANSVALUE

#define FIELDNO_AGGSTATEPERGROUPDATA_NOTRANSVALUE   2

Definition at line 249 of file nodeAgg.h.

Referenced by llvm_compile_expr().

◆ FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUE

#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUE   0

Definition at line 244 of file nodeAgg.h.

Referenced by llvm_compile_expr().

◆ FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUEISNULL

#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUEISNULL   1

Definition at line 246 of file nodeAgg.h.

Referenced by llvm_compile_expr().

Typedef Documentation

◆ AggStatePerAggData

◆ AggStatePerGroupData

◆ AggStatePerHashData

◆ AggStatePerPhaseData

◆ AggStatePerTransData

Function Documentation

◆ ExecAggEstimate()

void ExecAggEstimate ( AggState node,
ParallelContext pcxt 
)

Definition at line 4964 of file nodeAgg.c.

References add_size(), ParallelContext::estimator, PlanState::instrument, mul_size(), ParallelContext::nworkers, offsetof, ScanState::ps, shm_toc_estimate_chunk, shm_toc_estimate_keys, and AggState::ss.

Referenced by ExecParallelEstimate().

4965 {
4966  Size size;
4967 
4968  /* don't need this if not instrumenting or no workers */
4969  if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4970  return;
4971 
4972  size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4973  size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4974  shm_toc_estimate_chunk(&pcxt->estimator, size);
4975  shm_toc_estimate_keys(&pcxt->estimator, 1);
4976 }
Instrumentation * instrument
Definition: execnodes.h:955
ScanState ss
Definition: execnodes.h:2146
shm_toc_estimator estimator
Definition: parallel.h:42
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
PlanState ps
Definition: execnodes.h:1332
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:473
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
#define offsetof(type, field)
Definition: c.h:668

◆ ExecAggInitializeDSM()

void ExecAggInitializeDSM ( AggState node,
ParallelContext pcxt 
)

Definition at line 4985 of file nodeAgg.c.

References PlanState::instrument, SharedAggInfo::num_workers, ParallelContext::nworkers, offsetof, PlanState::plan, Plan::plan_node_id, ScanState::ps, AggState::shared_info, shm_toc_allocate(), shm_toc_insert(), AggState::ss, and ParallelContext::toc.

Referenced by ExecParallelInitializeDSM().

4986 {
4987  Size size;
4988 
4989  /* don't need this if not instrumenting or no workers */
4990  if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4991  return;
4992 
4993  size = offsetof(SharedAggInfo, sinstrument)
4994  + pcxt->nworkers * sizeof(AggregateInstrumentation);
4995  node->shared_info = shm_toc_allocate(pcxt->toc, size);
4996  /* ensure any unfilled slots will contain zeroes */
4997  memset(node->shared_info, 0, size);
4998  node->shared_info->num_workers = pcxt->nworkers;
4999  shm_toc_insert(pcxt->toc, node->ss.ps.plan->plan_node_id,
5000  node->shared_info);
5001 }
Instrumentation * instrument
Definition: execnodes.h:955
ScanState ss
Definition: execnodes.h:2146
int plan_node_id
Definition: plannodes.h:141
PlanState ps
Definition: execnodes.h:1332
struct AggregateInstrumentation AggregateInstrumentation
Plan * plan
Definition: execnodes.h:945
size_t Size
Definition: c.h:473
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
SharedAggInfo * shared_info
Definition: execnodes.h:2218
#define offsetof(type, field)
Definition: c.h:668
shm_toc * toc
Definition: parallel.h:45

◆ ExecAggInitializeWorker()

void ExecAggInitializeWorker ( AggState node,
ParallelWorkerContext pwcxt 
)

Definition at line 5010 of file nodeAgg.c.

References PlanState::plan, Plan::plan_node_id, ScanState::ps, AggState::shared_info, shm_toc_lookup(), AggState::ss, and ParallelWorkerContext::toc.

Referenced by ExecParallelInitializeWorker().

5011 {
5012  node->shared_info =
5013  shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
5014 }
ScanState ss
Definition: execnodes.h:2146
int plan_node_id
Definition: plannodes.h:141
PlanState ps
Definition: execnodes.h:1332
Plan * plan
Definition: execnodes.h:945
SharedAggInfo * shared_info
Definition: execnodes.h:2218
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232

◆ ExecAggRetrieveInstrumentation()

void ExecAggRetrieveInstrumentation ( AggState node)

Definition at line 5023 of file nodeAgg.c.

References SharedAggInfo::num_workers, offsetof, palloc(), and AggState::shared_info.

Referenced by ExecParallelRetrieveInstrumentation().

5024 {
5025  Size size;
5026  SharedAggInfo *si;
5027 
5028  if (node->shared_info == NULL)
5029  return;
5030 
5031  size = offsetof(SharedAggInfo, sinstrument)
5033  si = palloc(size);
5034  memcpy(si, node->shared_info, size);
5035  node->shared_info = si;
5036 }
struct AggregateInstrumentation AggregateInstrumentation
size_t Size
Definition: c.h:473
void * palloc(Size size)
Definition: mcxt.c:949
SharedAggInfo * shared_info
Definition: execnodes.h:2218
#define offsetof(type, field)
Definition: c.h:668

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)

Definition at line 4557 of file nodeAgg.c.

References AggState::aggcontexts, Assert, ExecClearTuple(), ExecEndNode(), ExecFreeExprContext(), AggregateInstrumentation::hash_batches_used, AggState::hash_batches_used, AggregateInstrumentation::hash_disk_used, AggState::hash_disk_used, AggregateInstrumentation::hash_mem_peak, AggState::hash_mem_peak, AggState::hash_metacxt, hashagg_reset_spill_state(), AggState::hashcontext, IsParallelWorker, Max, AggState::maxsets, MemoryContextDelete(), AggState::numtrans, outerPlan, outerPlanState, ParallelWorkerNumber, AggState::pertrans, ScanState::ps, ReScanExprContext(), AggState::shared_info, SharedAggInfo::sinstrument, AggState::sort_in, AggState::sort_out, AggStatePerTransData::sortstates, AggState::ss, ScanState::ss_ScanTupleSlot, and tuplesort_end().

Referenced by ExecEndNode().

4558 {
4560  int transno;
4561  int numGroupingSets = Max(node->maxsets, 1);
4562  int setno;
4563 
4564  /*
4565  * When ending a parallel worker, copy the statistics gathered by the
4566  * worker back into shared memory so that it can be picked up by the main
4567  * process to report in EXPLAIN ANALYZE.
4568  */
4569  if (node->shared_info && IsParallelWorker())
4570  {
4572 
4573  Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
4576  si->hash_disk_used = node->hash_disk_used;
4577  si->hash_mem_peak = node->hash_mem_peak;
4578  }
4579 
4580  /* Make sure we have closed any open tuplesorts */
4581 
4582  if (node->sort_in)
4583  tuplesort_end(node->sort_in);
4584  if (node->sort_out)
4585  tuplesort_end(node->sort_out);
4586 
4588 
4589  if (node->hash_metacxt != NULL)
4590  {
4592  node->hash_metacxt = NULL;
4593  }
4594 
4595  for (transno = 0; transno < node->numtrans; transno++)
4596  {
4597  AggStatePerTrans pertrans = &node->pertrans[transno];
4598 
4599  for (setno = 0; setno < numGroupingSets; setno++)
4600  {
4601  if (pertrans->sortstates[setno])
4602  tuplesort_end(pertrans->sortstates[setno]);
4603  }
4604  }
4605 
4606  /* And ensure any agg shutdown callbacks have been called */
4607  for (setno = 0; setno < numGroupingSets; setno++)
4608  ReScanExprContext(node->aggcontexts[setno]);
4609  if (node->hashcontext)
4611 
4612  /*
4613  * We don't actually free any ExprContexts here (see comment in
4614  * ExecFreeExprContext), just unlinking the output one from the plan node
4615  * suffices.
4616  */
4617  ExecFreeExprContext(&node->ss.ps);
4618 
4619  /* clean up tuple table */
4621 
4622  outerPlan = outerPlanState(node);
4623  ExecEndNode(outerPlan);
4624 }
static void hashagg_reset_spill_state(AggState *aggstate)
Definition: nodeAgg.c:3182
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:543
Tuplesortstate * sort_out
Definition: execnodes.h:2179
ScanState ss
Definition: execnodes.h:2146
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1335
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2122
AggStatePerTrans pertrans
Definition: execnodes.h:2156
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:655
int numtrans
Definition: execnodes.h:2149
PlanState ps
Definition: execnodes.h:1332
int maxsets
Definition: execnodes.h:2176
MemoryContext hash_metacxt
Definition: execnodes.h:2188
Tuplesortstate * sort_in
Definition: execnodes.h:2178
#define outerPlanState(node)
Definition: execnodes.h:1039
Tuplesortstate ** sortstates
Definition: nodeAgg.h:154
int ParallelWorkerNumber
Definition: parallel.c:112
#define IsParallelWorker()
Definition: parallel.h:61
int hash_batches_used
Definition: execnodes.h:2207
#define outerPlan(node)
Definition: plannodes.h:172
ExprContext * hashcontext
Definition: execnodes.h:2157
uint64 hash_disk_used
Definition: execnodes.h:2206
#define Max(x, y)
Definition: c.h:921
ExprContext ** aggcontexts
Definition: execnodes.h:2158
#define Assert(condition)
Definition: c.h:745
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:443
Size hash_mem_peak
Definition: execnodes.h:2203
SharedAggInfo * shared_info
Definition: execnodes.h:2218
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1388

◆ ExecInitAgg()

AggState* ExecInitAgg ( Agg node,
EState estate,
int  eflags 
)

Definition at line 3234 of file nodeAgg.c.

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, AggState::agg_done, AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, AggState::aggcontexts, AggStatePerAggData::aggdirectargs, Aggref::aggdirectargs, AGGFNOID, Aggref::aggfnoid, Aggref::agglevelsup, AggrefExprState::aggno, AggStatePerPhaseData::aggnode, AggStatePerHashData::aggnode, AggStatePerAggData::aggref, AggrefExprState::aggref, AggState::aggs, AggStatePerTransData::aggshared, Aggref::aggsplit, Agg::aggsplit, AggState::aggsplit, AggStatePerPhaseData::aggstrategy, Agg::aggstrategy, AggState::aggstrategy, Aggref::aggtranstype, Aggref::aggtype, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, bms_add_member(), bms_add_members(), bms_next_member(), build_aggregate_finalfn_expr(), build_hash_tables(), build_pertrans_for_aggref(), castNode, Agg::chain, CreateWorkExprContext(), AggState::curperagg, AggState::curpertrans, AggState::current_set, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_DESERIALIZE, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, elog, AggStatePerPhaseData::eqfunctions, ereport, errcode(), errmsg(), ERROR, EState::es_query_cxt, AggStatePerPhaseData::evaltrans, AggStatePerPhaseData::evaltrans_cache, EXEC_FLAG_BACKWARD, EXEC_FLAG_MARK, EXEC_FLAG_REWIND, ExecAgg(), ExecAssignExprContext(), ExecAssignProjectionInfo(), ExecBuildAggTrans(), ExecCreateScanSlotFromOuterPlan(), ExecGetResultSlotOps(), ExecInitExprList(), ExecInitExtraTupleSlot(), ExecInitNode(), ExecInitQual(), ExecInitResultTupleSlotTL(), PlanState::ExecProcNode, execTuplesMatchPrepare(), AggStatePerAggData::finalfn, AggStatePerAggData::finalfn_oid, find_compatible_peragg(), find_compatible_pertrans(), find_hash_columns(), 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::grpCollations, Agg::grpOperators, AggStatePerPhaseData::gset_lengths, hash_agg_entry_size(), hash_agg_set_limits(), AggState::hashcontext, HeapTupleIsValid, i, initialize_phase(), initValue(), AggState::input_done, Aggref::inputcollid, InvalidOid, InvokeFunctionExecuteHook, lcons_int(), Plan::lefttree, lfirst, list_length(), list_nth_node, makeNode, Max, AggState::maxsets, NIL, AggState::numaggs, AggStatePerHashData::numCols, Agg::numCols, AggStatePerAggData::numFinalArgs, AggState::numphases, AggStatePerPhaseData::numsets, AggState::numtrans, OBJECT_AGGREGATE, OBJECT_FUNCTION, ObjectIdGetDatum, OidIsValid, PlanState::outerops, PlanState::outeropsfixed, PlanState::outeropsset, outerPlan, outerPlanState, palloc(), palloc0(), AggState::peragg, AggState::pergroups, AggState::pertrans, pg_proc_aclcheck(), Agg::plan, PlanState::plan, Plan::plan_width, PROCOID, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, Plan::qual, PlanState::qual, ReleaseSysCache(), AggStatePerAggData::resulttypeByVal, AggStatePerAggData::resulttypeLen, SearchSysCache1(), select_current_set(), AggStatePerAggData::shareable, AggState::sort_in, AggState::sort_out, AggState::sort_slot, AggStatePerPhaseData::sortnode, AggState::ss, ScanState::ss_ScanTupleSlot, PlanState::state, SysCacheGetAttr(), AggState::tmpcontext, Agg::transitionSpace, AggStatePerAggData::transno, TupleTableSlot::tts_tupleDescriptor, TTSOpsMinimalTuple, and TTSOpsVirtual.

Referenced by ExecInitNode().

3235 {
3236  AggState *aggstate;
3237  AggStatePerAgg peraggs;
3238  AggStatePerTrans pertransstates;
3239  AggStatePerGroup *pergroups;
3240  Plan *outerPlan;
3241  ExprContext *econtext;
3242  TupleDesc scanDesc;
3243  int numaggs,
3244  transno,
3245  aggno;
3246  int phase;
3247  int phaseidx;
3248  ListCell *l;
3249  Bitmapset *all_grouped_cols = NULL;
3250  int numGroupingSets = 1;
3251  int numPhases;
3252  int numHashes;
3253  int i = 0;
3254  int j = 0;
3255  bool use_hashing = (node->aggstrategy == AGG_HASHED ||
3256  node->aggstrategy == AGG_MIXED);
3257 
3258  /* check for unsupported flags */
3259  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3260 
3261  /*
3262  * create state structure
3263  */
3264  aggstate = makeNode(AggState);
3265  aggstate->ss.ps.plan = (Plan *) node;
3266  aggstate->ss.ps.state = estate;
3267  aggstate->ss.ps.ExecProcNode = ExecAgg;
3268 
3269  aggstate->aggs = NIL;
3270  aggstate->numaggs = 0;
3271  aggstate->numtrans = 0;
3272  aggstate->aggstrategy = node->aggstrategy;
3273  aggstate->aggsplit = node->aggsplit;
3274  aggstate->maxsets = 0;
3275  aggstate->projected_set = -1;
3276  aggstate->current_set = 0;
3277  aggstate->peragg = NULL;
3278  aggstate->pertrans = NULL;
3279  aggstate->curperagg = NULL;
3280  aggstate->curpertrans = NULL;
3281  aggstate->input_done = false;
3282  aggstate->agg_done = false;
3283  aggstate->pergroups = NULL;
3284  aggstate->grp_firstTuple = NULL;
3285  aggstate->sort_in = NULL;
3286  aggstate->sort_out = NULL;
3287 
3288  /*
3289  * phases[0] always exists, but is dummy in sorted/plain mode
3290  */
3291  numPhases = (use_hashing ? 1 : 2);
3292  numHashes = (use_hashing ? 1 : 0);
3293 
3294  /*
3295  * Calculate the maximum number of grouping sets in any phase; this
3296  * determines the size of some allocations. Also calculate the number of
3297  * phases, since all hashed/mixed nodes contribute to only a single phase.
3298  */
3299  if (node->groupingSets)
3300  {
3301  numGroupingSets = list_length(node->groupingSets);
3302 
3303  foreach(l, node->chain)
3304  {
3305  Agg *agg = lfirst(l);
3306 
3307  numGroupingSets = Max(numGroupingSets,
3308  list_length(agg->groupingSets));
3309 
3310  /*
3311  * additional AGG_HASHED aggs become part of phase 0, but all
3312  * others add an extra phase.
3313  */
3314  if (agg->aggstrategy != AGG_HASHED)
3315  ++numPhases;
3316  else
3317  ++numHashes;
3318  }
3319  }
3320 
3321  aggstate->maxsets = numGroupingSets;
3322  aggstate->numphases = numPhases;
3323 
3324  aggstate->aggcontexts = (ExprContext **)
3325  palloc0(sizeof(ExprContext *) * numGroupingSets);
3326 
3327  /*
3328  * Create expression contexts. We need three or more, one for
3329  * per-input-tuple processing, one for per-output-tuple processing, one
3330  * for all the hashtables, and one for each grouping set. The per-tuple
3331  * memory context of the per-grouping-set ExprContexts (aggcontexts)
3332  * replaces the standalone memory context formerly used to hold transition
3333  * values. We cheat a little by using ExecAssignExprContext() to build
3334  * all of them.
3335  *
3336  * NOTE: the details of what is stored in aggcontexts and what is stored
3337  * in the regular per-query memory context are driven by a simple
3338  * decision: we want to reset the aggcontext at group boundaries (if not
3339  * hashing) and in ExecReScanAgg to recover no-longer-wanted space.
3340  */
3341  ExecAssignExprContext(estate, &aggstate->ss.ps);
3342  aggstate->tmpcontext = aggstate->ss.ps.ps_ExprContext;
3343 
3344  for (i = 0; i < numGroupingSets; ++i)
3345  {
3346  ExecAssignExprContext(estate, &aggstate->ss.ps);
3347  aggstate->aggcontexts[i] = aggstate->ss.ps.ps_ExprContext;
3348  }
3349 
3350  if (use_hashing)
3351  aggstate->hashcontext = CreateWorkExprContext(estate);
3352 
3353  ExecAssignExprContext(estate, &aggstate->ss.ps);
3354 
3355  /*
3356  * Initialize child nodes.
3357  *
3358  * If we are doing a hashed aggregation then the child plan does not need
3359  * to handle REWIND efficiently; see ExecReScanAgg.
3360  */
3361  if (node->aggstrategy == AGG_HASHED)
3362  eflags &= ~EXEC_FLAG_REWIND;
3363  outerPlan = outerPlan(node);
3364  outerPlanState(aggstate) = ExecInitNode(outerPlan, estate, eflags);
3365 
3366  /*
3367  * initialize source tuple type.
3368  */
3369  aggstate->ss.ps.outerops =
3371  &aggstate->ss.ps.outeropsfixed);
3372  aggstate->ss.ps.outeropsset = true;
3373 
3374  ExecCreateScanSlotFromOuterPlan(estate, &aggstate->ss,
3375  aggstate->ss.ps.outerops);
3376  scanDesc = aggstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
3377 
3378  /*
3379  * If there are more than two phases (including a potential dummy phase
3380  * 0), input will be resorted using tuplesort. Need a slot for that.
3381  */
3382  if (numPhases > 2)
3383  {
3384  aggstate->sort_slot = ExecInitExtraTupleSlot(estate, scanDesc,
3386 
3387  /*
3388  * The output of the tuplesort, and the output from the outer child
3389  * might not use the same type of slot. In most cases the child will
3390  * be a Sort, and thus return a TTSOpsMinimalTuple type slot - but the
3391  * input can also be presorted due an index, in which case it could be
3392  * a different type of slot.
3393  *
3394  * XXX: For efficiency it would be good to instead/additionally
3395  * generate expressions with corresponding settings of outerops* for
3396  * the individual phases - deforming is often a bottleneck for
3397  * aggregations with lots of rows per group. If there's multiple
3398  * sorts, we know that all but the first use TTSOpsMinimalTuple (via
3399  * the nodeAgg.c internal tuplesort).
3400  */
3401  if (aggstate->ss.ps.outeropsfixed &&
3402  aggstate->ss.ps.outerops != &TTSOpsMinimalTuple)
3403  aggstate->ss.ps.outeropsfixed = false;
3404  }
3405 
3406  /*
3407  * Initialize result type, slot and projection.
3408  */
3410  ExecAssignProjectionInfo(&aggstate->ss.ps, NULL);
3411 
3412  /*
3413  * initialize child expressions
3414  *
3415  * We expect the parser to have checked that no aggs contain other agg
3416  * calls in their arguments (and just to be sure, we verify it again while
3417  * initializing the plan node). This would make no sense under SQL
3418  * semantics, and it's forbidden by the spec. Because it is true, we
3419  * don't need to worry about evaluating the aggs in any particular order.
3420  *
3421  * Note: execExpr.c finds Aggrefs for us, and adds their AggrefExprState
3422  * nodes to aggstate->aggs. Aggrefs in the qual are found here; Aggrefs
3423  * in the targetlist are found during ExecAssignProjectionInfo, below.
3424  */
3425  aggstate->ss.ps.qual =
3426  ExecInitQual(node->plan.qual, (PlanState *) aggstate);
3427 
3428  /*
3429  * We should now have found all Aggrefs in the targetlist and quals.
3430  */
3431  numaggs = aggstate->numaggs;
3432  Assert(numaggs == list_length(aggstate->aggs));
3433 
3434  /*
3435  * For each phase, prepare grouping set data and fmgr lookup data for
3436  * compare functions. Accumulate all_grouped_cols in passing.
3437  */
3438  aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
3439 
3440  aggstate->num_hashes = numHashes;
3441  if (numHashes)
3442  {
3443  aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
3444  aggstate->phases[0].numsets = 0;
3445  aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
3446  aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
3447  }
3448 
3449  phase = 0;
3450  for (phaseidx = 0; phaseidx <= list_length(node->chain); ++phaseidx)
3451  {
3452  Agg *aggnode;
3453  Sort *sortnode;
3454 
3455  if (phaseidx > 0)
3456  {
3457  aggnode = list_nth_node(Agg, node->chain, phaseidx - 1);
3458  sortnode = castNode(Sort, aggnode->plan.lefttree);
3459  }
3460  else
3461  {
3462  aggnode = node;
3463  sortnode = NULL;
3464  }
3465 
3466  Assert(phase <= 1 || sortnode);
3467 
3468  if (aggnode->aggstrategy == AGG_HASHED
3469  || aggnode->aggstrategy == AGG_MIXED)
3470  {
3471  AggStatePerPhase phasedata = &aggstate->phases[0];
3472  AggStatePerHash perhash;
3473  Bitmapset *cols = NULL;
3474 
3475  Assert(phase == 0);
3476  i = phasedata->numsets++;
3477  perhash = &aggstate->perhash[i];
3478 
3479  /* phase 0 always points to the "real" Agg in the hash case */
3480  phasedata->aggnode = node;
3481  phasedata->aggstrategy = node->aggstrategy;
3482 
3483  /* but the actual Agg node representing this hash is saved here */
3484  perhash->aggnode = aggnode;
3485 
3486  phasedata->gset_lengths[i] = perhash->numCols = aggnode->numCols;
3487 
3488  for (j = 0; j < aggnode->numCols; ++j)
3489  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3490 
3491  phasedata->grouped_cols[i] = cols;
3492 
3493  all_grouped_cols = bms_add_members(all_grouped_cols, cols);
3494  continue;
3495  }
3496  else
3497  {
3498  AggStatePerPhase phasedata = &aggstate->phases[++phase];
3499  int num_sets;
3500 
3501  phasedata->numsets = num_sets = list_length(aggnode->groupingSets);
3502 
3503  if (num_sets)
3504  {
3505  phasedata->gset_lengths = palloc(num_sets * sizeof(int));
3506  phasedata->grouped_cols = palloc(num_sets * sizeof(Bitmapset *));
3507 
3508  i = 0;
3509  foreach(l, aggnode->groupingSets)
3510  {
3511  int current_length = list_length(lfirst(l));
3512  Bitmapset *cols = NULL;
3513 
3514  /* planner forces this to be correct */
3515  for (j = 0; j < current_length; ++j)
3516  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3517 
3518  phasedata->grouped_cols[i] = cols;
3519  phasedata->gset_lengths[i] = current_length;
3520 
3521  ++i;
3522  }
3523 
3524  all_grouped_cols = bms_add_members(all_grouped_cols,
3525  phasedata->grouped_cols[0]);
3526  }
3527  else
3528  {
3529  Assert(phaseidx == 0);
3530 
3531  phasedata->gset_lengths = NULL;
3532  phasedata->grouped_cols = NULL;
3533  }
3534 
3535  /*
3536  * If we are grouping, precompute fmgr lookup data for inner loop.
3537  */
3538  if (aggnode->aggstrategy == AGG_SORTED)
3539  {
3540  int i = 0;
3541 
3542  Assert(aggnode->numCols > 0);
3543 
3544  /*
3545  * Build a separate function for each subset of columns that
3546  * need to be compared.
3547  */
3548  phasedata->eqfunctions =
3549  (ExprState **) palloc0(aggnode->numCols * sizeof(ExprState *));
3550 
3551  /* for each grouping set */
3552  for (i = 0; i < phasedata->numsets; i++)
3553  {
3554  int length = phasedata->gset_lengths[i];
3555 
3556  if (phasedata->eqfunctions[length - 1] != NULL)
3557  continue;
3558 
3559  phasedata->eqfunctions[length - 1] =
3560  execTuplesMatchPrepare(scanDesc,
3561  length,
3562  aggnode->grpColIdx,
3563  aggnode->grpOperators,
3564  aggnode->grpCollations,
3565  (PlanState *) aggstate);
3566  }
3567 
3568  /* and for all grouped columns, unless already computed */
3569  if (phasedata->eqfunctions[aggnode->numCols - 1] == NULL)
3570  {
3571  phasedata->eqfunctions[aggnode->numCols - 1] =
3572  execTuplesMatchPrepare(scanDesc,
3573  aggnode->numCols,
3574  aggnode->grpColIdx,
3575  aggnode->grpOperators,
3576  aggnode->grpCollations,
3577  (PlanState *) aggstate);
3578  }
3579  }
3580 
3581  phasedata->aggnode = aggnode;
3582  phasedata->aggstrategy = aggnode->aggstrategy;
3583  phasedata->sortnode = sortnode;
3584  }
3585  }
3586 
3587  /*
3588  * Convert all_grouped_cols to a descending-order list.
3589  */
3590  i = -1;
3591  while ((i = bms_next_member(all_grouped_cols, i)) >= 0)
3592  aggstate->all_grouped_cols = lcons_int(i, aggstate->all_grouped_cols);
3593 
3594  /*
3595  * Set up aggregate-result storage in the output expr context, and also
3596  * allocate my private per-agg working storage
3597  */
3598  econtext = aggstate->ss.ps.ps_ExprContext;
3599  econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
3600  econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
3601 
3602  peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
3603  pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numaggs);
3604 
3605  aggstate->peragg = peraggs;
3606  aggstate->pertrans = pertransstates;
3607 
3608 
3609  aggstate->all_pergroups =
3611  * (numGroupingSets + numHashes));
3612  pergroups = aggstate->all_pergroups;
3613 
3614  if (node->aggstrategy != AGG_HASHED)
3615  {
3616  for (i = 0; i < numGroupingSets; i++)
3617  {
3618  pergroups[i] = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
3619  * numaggs);
3620  }
3621 
3622  aggstate->pergroups = pergroups;
3623  pergroups += numGroupingSets;
3624  }
3625 
3626  /*
3627  * Hashing can only appear in the initial phase.
3628  */
3629  if (use_hashing)
3630  {
3631  Plan *outerplan = outerPlan(node);
3632  uint64 totalGroups = 0;
3633  int i;
3634 
3635  aggstate->hash_metacxt = AllocSetContextCreate(aggstate->ss.ps.state->es_query_cxt,
3636  "HashAgg meta context",
3638  aggstate->hash_spill_rslot = ExecInitExtraTupleSlot(estate, scanDesc,
3640  aggstate->hash_spill_wslot = ExecInitExtraTupleSlot(estate, scanDesc,
3641  &TTSOpsVirtual);
3642 
3643  /* this is an array of pointers, not structures */
3644  aggstate->hash_pergroup = pergroups;
3645 
3646  aggstate->hashentrysize = hash_agg_entry_size(aggstate->numtrans,
3647  outerplan->plan_width,
3648  node->transitionSpace);
3649 
3650  /*
3651  * Consider all of the grouping sets together when setting the limits
3652  * and estimating the number of partitions. This can be inaccurate
3653  * when there is more than one grouping set, but should still be
3654  * reasonable.
3655  */
3656  for (i = 0; i < aggstate->num_hashes; i++)
3657  totalGroups += aggstate->perhash[i].aggnode->numGroups;
3658 
3659  hash_agg_set_limits(aggstate->hashentrysize, totalGroups, 0,
3660  &aggstate->hash_mem_limit,
3661  &aggstate->hash_ngroups_limit,
3662  &aggstate->hash_planned_partitions);
3663  find_hash_columns(aggstate);
3664  build_hash_tables(aggstate);
3665  aggstate->table_filled = false;
3666 
3667  /* Initialize this to 1, meaning nothing spilled, yet */
3668  aggstate->hash_batches_used = 1;
3669  }
3670 
3671  /*
3672  * Initialize current phase-dependent values to initial phase. The initial
3673  * phase is 1 (first sort pass) for all strategies that use sorting (if
3674  * hashing is being done too, then phase 0 is processed last); but if only
3675  * hashing is being done, then phase 0 is all there is.
3676  */
3677  if (node->aggstrategy == AGG_HASHED)
3678  {
3679  aggstate->current_phase = 0;
3680  initialize_phase(aggstate, 0);
3681  select_current_set(aggstate, 0, true);
3682  }
3683  else
3684  {
3685  aggstate->current_phase = 1;
3686  initialize_phase(aggstate, 1);
3687  select_current_set(aggstate, 0, false);
3688  }
3689 
3690  /* -----------------
3691  * Perform lookups of aggregate function info, and initialize the
3692  * unchanging fields of the per-agg and per-trans data.
3693  *
3694  * We try to optimize by detecting duplicate aggregate functions so that
3695  * their state and final values are re-used, rather than needlessly being
3696  * re-calculated independently. We also detect aggregates that are not
3697  * the same, but which can share the same transition state.
3698  *
3699  * Scenarios:
3700  *
3701  * 1. Identical aggregate function calls appear in the query:
3702  *
3703  * SELECT SUM(x) FROM ... HAVING SUM(x) > 0
3704  *
3705  * Since these aggregates are identical, we only need to calculate
3706  * the value once. Both aggregates will share the same 'aggno' value.
3707  *
3708  * 2. Two different aggregate functions appear in the query, but the
3709  * aggregates have the same arguments, transition functions and
3710  * initial values (and, presumably, different final functions):
3711  *
3712  * SELECT AVG(x), STDDEV(x) FROM ...
3713  *
3714  * In this case we must create a new peragg for the varying aggregate,
3715  * and we need to call the final functions separately, but we need
3716  * only run the transition function once. (This requires that the
3717  * final functions be nondestructive of the transition state, but
3718  * that's required anyway for other reasons.)
3719  *
3720  * For either of these optimizations to be valid, all aggregate properties
3721  * used in the transition phase must be the same, including any modifiers
3722  * such as ORDER BY, DISTINCT and FILTER, and the arguments mustn't
3723  * contain any volatile functions.
3724  * -----------------
3725  */
3726  aggno = -1;
3727  transno = -1;
3728  foreach(l, aggstate->aggs)
3729  {
3730  AggrefExprState *aggrefstate = (AggrefExprState *) lfirst(l);
3731  Aggref *aggref = aggrefstate->aggref;
3732  AggStatePerAgg peragg;
3733  AggStatePerTrans pertrans;
3734  int existing_aggno;
3735  int existing_transno;
3736  List *same_input_transnos;
3737  Oid inputTypes[FUNC_MAX_ARGS];
3738  int numArguments;
3739  int numDirectArgs;
3740  HeapTuple aggTuple;
3741  Form_pg_aggregate aggform;
3742  AclResult aclresult;
3743  Oid transfn_oid,
3744  finalfn_oid;
3745  bool shareable;
3746  Oid serialfn_oid,
3747  deserialfn_oid;
3748  Expr *finalfnexpr;
3749  Oid aggtranstype;
3750  Datum textInitVal;
3751  Datum initValue;
3752  bool initValueIsNull;
3753 
3754  /* Planner should have assigned aggregate to correct level */
3755  Assert(aggref->agglevelsup == 0);
3756  /* ... and the split mode should match */
3757  Assert(aggref->aggsplit == aggstate->aggsplit);
3758 
3759  /* 1. Check for already processed aggs which can be re-used */
3760  existing_aggno = find_compatible_peragg(aggref, aggstate, aggno,
3761  &same_input_transnos);
3762  if (existing_aggno != -1)
3763  {
3764  /*
3765  * Existing compatible agg found. so just point the Aggref to the
3766  * same per-agg struct.
3767  */
3768  aggrefstate->aggno = existing_aggno;
3769  continue;
3770  }
3771 
3772  /* Mark Aggref state node with assigned index in the result array */
3773  peragg = &peraggs[++aggno];
3774  peragg->aggref = aggref;
3775  aggrefstate->aggno = aggno;
3776 
3777  /* Fetch the pg_aggregate row */
3778  aggTuple = SearchSysCache1(AGGFNOID,
3779  ObjectIdGetDatum(aggref->aggfnoid));
3780  if (!HeapTupleIsValid(aggTuple))
3781  elog(ERROR, "cache lookup failed for aggregate %u",
3782  aggref->aggfnoid);
3783  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
3784 
3785  /* Check permission to call aggregate function */
3786  aclresult = pg_proc_aclcheck(aggref->aggfnoid, GetUserId(),
3787  ACL_EXECUTE);
3788  if (aclresult != ACLCHECK_OK)
3789  aclcheck_error(aclresult, OBJECT_AGGREGATE,
3790  get_func_name(aggref->aggfnoid));
3792 
3793  /* planner recorded transition state type in the Aggref itself */
3794  aggtranstype = aggref->aggtranstype;
3795  Assert(OidIsValid(aggtranstype));
3796 
3797  /*
3798  * If this aggregation is performing state combines, then instead of
3799  * using the transition function, we'll use the combine function
3800  */
3801  if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3802  {
3803  transfn_oid = aggform->aggcombinefn;
3804 
3805  /* If not set then the planner messed up */
3806  if (!OidIsValid(transfn_oid))
3807  elog(ERROR, "combinefn not set for aggregate function");
3808  }
3809  else
3810  transfn_oid = aggform->aggtransfn;
3811 
3812  /* Final function only required if we're finalizing the aggregates */
3813  if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
3814  peragg->finalfn_oid = finalfn_oid = InvalidOid;
3815  else
3816  peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
3817 
3818  /*
3819  * If finalfn is marked read-write, we can't share transition states;
3820  * but it is okay to share states for AGGMODIFY_SHAREABLE aggs. Also,
3821  * if we're not executing the finalfn here, we can share regardless.
3822  */
3823  shareable = (aggform->aggfinalmodify != AGGMODIFY_READ_WRITE) ||
3824  (finalfn_oid == InvalidOid);
3825  peragg->shareable = shareable;
3826 
3827  serialfn_oid = InvalidOid;
3828  deserialfn_oid = InvalidOid;
3829 
3830  /*
3831  * Check if serialization/deserialization is required. We only do it
3832  * for aggregates that have transtype INTERNAL.
3833  */
3834  if (aggtranstype == INTERNALOID)
3835  {
3836  /*
3837  * The planner should only have generated a serialize agg node if
3838  * every aggregate with an INTERNAL state has a serialization
3839  * function. Verify that.
3840  */
3841  if (DO_AGGSPLIT_SERIALIZE(aggstate->aggsplit))
3842  {
3843  /* serialization only valid when not running finalfn */
3845 
3846  if (!OidIsValid(aggform->aggserialfn))
3847  elog(ERROR, "serialfunc not provided for serialization aggregation");
3848  serialfn_oid = aggform->aggserialfn;
3849  }
3850 
3851  /* Likewise for deserialization functions */
3852  if (DO_AGGSPLIT_DESERIALIZE(aggstate->aggsplit))
3853  {
3854  /* deserialization only valid when combining states */
3855  Assert(DO_AGGSPLIT_COMBINE(aggstate->aggsplit));
3856 
3857  if (!OidIsValid(aggform->aggdeserialfn))
3858  elog(ERROR, "deserialfunc not provided for deserialization aggregation");
3859  deserialfn_oid = aggform->aggdeserialfn;
3860  }
3861  }
3862 
3863  /* Check that aggregate owner has permission to call component fns */
3864  {
3865  HeapTuple procTuple;
3866  Oid aggOwner;
3867 
3868  procTuple = SearchSysCache1(PROCOID,
3869  ObjectIdGetDatum(aggref->aggfnoid));
3870  if (!HeapTupleIsValid(procTuple))
3871  elog(ERROR, "cache lookup failed for function %u",
3872  aggref->aggfnoid);
3873  aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
3874  ReleaseSysCache(procTuple);
3875 
3876  aclresult = pg_proc_aclcheck(transfn_oid, aggOwner,
3877  ACL_EXECUTE);
3878  if (aclresult != ACLCHECK_OK)
3879  aclcheck_error(aclresult, OBJECT_FUNCTION,
3880  get_func_name(transfn_oid));
3881  InvokeFunctionExecuteHook(transfn_oid);
3882  if (OidIsValid(finalfn_oid))
3883  {
3884  aclresult = pg_proc_aclcheck(finalfn_oid, aggOwner,
3885  ACL_EXECUTE);
3886  if (aclresult != ACLCHECK_OK)
3887  aclcheck_error(aclresult, OBJECT_FUNCTION,
3888  get_func_name(finalfn_oid));
3889  InvokeFunctionExecuteHook(finalfn_oid);
3890  }
3891  if (OidIsValid(serialfn_oid))
3892  {
3893  aclresult = pg_proc_aclcheck(serialfn_oid, aggOwner,
3894  ACL_EXECUTE);
3895  if (aclresult != ACLCHECK_OK)
3896  aclcheck_error(aclresult, OBJECT_FUNCTION,
3897  get_func_name(serialfn_oid));
3898  InvokeFunctionExecuteHook(serialfn_oid);
3899  }
3900  if (OidIsValid(deserialfn_oid))
3901  {
3902  aclresult = pg_proc_aclcheck(deserialfn_oid, aggOwner,
3903  ACL_EXECUTE);
3904  if (aclresult != ACLCHECK_OK)
3905  aclcheck_error(aclresult, OBJECT_FUNCTION,
3906  get_func_name(deserialfn_oid));
3907  InvokeFunctionExecuteHook(deserialfn_oid);
3908  }
3909  }
3910 
3911  /*
3912  * Get actual datatypes of the (nominal) aggregate inputs. These
3913  * could be different from the agg's declared input types, when the
3914  * agg accepts ANY or a polymorphic type.
3915  */
3916  numArguments = get_aggregate_argtypes(aggref, inputTypes);
3917 
3918  /* Count the "direct" arguments, if any */
3919  numDirectArgs = list_length(aggref->aggdirectargs);
3920 
3921  /* Detect how many arguments to pass to the finalfn */
3922  if (aggform->aggfinalextra)
3923  peragg->numFinalArgs = numArguments + 1;
3924  else
3925  peragg->numFinalArgs = numDirectArgs + 1;
3926 
3927  /* Initialize any direct-argument expressions */
3928  peragg->aggdirectargs = ExecInitExprList(aggref->aggdirectargs,
3929  (PlanState *) aggstate);
3930 
3931  /*
3932  * build expression trees using actual argument & result types for the
3933  * finalfn, if it exists and is required.
3934  */
3935  if (OidIsValid(finalfn_oid))
3936  {
3937  build_aggregate_finalfn_expr(inputTypes,
3938  peragg->numFinalArgs,
3939  aggtranstype,
3940  aggref->aggtype,
3941  aggref->inputcollid,
3942  finalfn_oid,
3943  &finalfnexpr);
3944  fmgr_info(finalfn_oid, &peragg->finalfn);
3945  fmgr_info_set_expr((Node *) finalfnexpr, &peragg->finalfn);
3946  }
3947 
3948  /* get info about the output value's datatype */
3949  get_typlenbyval(aggref->aggtype,
3950  &peragg->resulttypeLen,
3951  &peragg->resulttypeByVal);
3952 
3953  /*
3954  * initval is potentially null, so don't try to access it as a struct
3955  * field. Must do it the hard way with SysCacheGetAttr.
3956  */
3957  textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
3958  Anum_pg_aggregate_agginitval,
3959  &initValueIsNull);
3960  if (initValueIsNull)
3961  initValue = (Datum) 0;
3962  else
3963  initValue = GetAggInitVal(textInitVal, aggtranstype);
3964 
3965  /*
3966  * 2. Build working state for invoking the transition function, or
3967  * look up previously initialized working state, if we can share it.
3968  *
3969  * find_compatible_peragg() already collected a list of shareable
3970  * per-Trans's with the same inputs. Check if any of them have the
3971  * same transition function and initial value.
3972  */
3973  existing_transno = find_compatible_pertrans(aggstate, aggref,
3974  shareable,
3975  transfn_oid, aggtranstype,
3976  serialfn_oid, deserialfn_oid,
3977  initValue, initValueIsNull,
3978  same_input_transnos);
3979  if (existing_transno != -1)
3980  {
3981  /*
3982  * Existing compatible trans found, so just point the 'peragg' to
3983  * the same per-trans struct, and mark the trans state as shared.
3984  */
3985  pertrans = &pertransstates[existing_transno];
3986  pertrans->aggshared = true;
3987  peragg->transno = existing_transno;
3988  }
3989  else
3990  {
3991  pertrans = &pertransstates[++transno];
3992  build_pertrans_for_aggref(pertrans, aggstate, estate,
3993  aggref, transfn_oid, aggtranstype,
3994  serialfn_oid, deserialfn_oid,
3995  initValue, initValueIsNull,
3996  inputTypes, numArguments);
3997  peragg->transno = transno;
3998  }
3999  ReleaseSysCache(aggTuple);
4000  }
4001 
4002  /*
4003  * Update aggstate->numaggs to be the number of unique aggregates found.
4004  * Also set numstates to the number of unique transition states found.
4005  */
4006  aggstate->numaggs = aggno + 1;
4007  aggstate->numtrans = transno + 1;
4008 
4009  /*
4010  * Last, check whether any more aggregates got added onto the node while
4011  * we processed the expressions for the aggregate arguments (including not
4012  * only the regular arguments and FILTER expressions handled immediately
4013  * above, but any direct arguments we might've handled earlier). If so,
4014  * we have nested aggregate functions, which is semantically nonsensical,
4015  * so complain. (This should have been caught by the parser, so we don't
4016  * need to work hard on a helpful error message; but we defend against it
4017  * here anyway, just to be sure.)
4018  */
4019  if (numaggs != list_length(aggstate->aggs))
4020  ereport(ERROR,
4021  (errcode(ERRCODE_GROUPING_ERROR),
4022  errmsg("aggregate function calls cannot be nested")));
4023 
4024  /*
4025  * Build expressions doing all the transition work at once. We build a
4026  * different one for each phase, as the number of transition function
4027  * invocation can differ between phases. Note this'll work both for
4028  * transition and combination functions (although there'll only be one
4029  * phase in the latter case).
4030  */
4031  for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
4032  {
4033  AggStatePerPhase phase = &aggstate->phases[phaseidx];
4034  bool dohash = false;
4035  bool dosort = false;
4036 
4037  /* phase 0 doesn't necessarily exist */
4038  if (!phase->aggnode)
4039  continue;
4040 
4041  if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
4042  {
4043  /*
4044  * Phase one, and only phase one, in a mixed agg performs both
4045  * sorting and aggregation.
4046  */
4047  dohash = true;
4048  dosort = true;
4049  }
4050  else if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 0)
4051  {
4052  /*
4053  * No need to compute a transition function for an AGG_MIXED phase
4054  * 0 - the contents of the hashtables will have been computed
4055  * during phase 1.
4056  */
4057  continue;
4058  }
4059  else if (phase->aggstrategy == AGG_PLAIN ||
4060  phase->aggstrategy == AGG_SORTED)
4061  {
4062  dohash = false;
4063  dosort = true;
4064  }
4065  else if (phase->aggstrategy == AGG_HASHED)
4066  {
4067  dohash = true;
4068  dosort = false;
4069  }
4070  else
4071  Assert(false);
4072 
4073  phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
4074  false);
4075 
4076  /* cache compiled expression for outer slot without NULL check */
4077  phase->evaltrans_cache[0][0] = phase->evaltrans;
4078  }
4079 
4080  return aggstate;
4081 }
struct AggStatePerTransData * AggStatePerTrans
Definition: execnodes.h:2139
ExprState ** eqfunctions
Definition: nodeAgg.h:278
AggStatePerGroup * hash_pergroup
Definition: execnodes.h:2210
#define NIL
Definition: pg_list.h:65
struct AggStatePerGroupData * AggStatePerGroup
Definition: execnodes.h:2140
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:483
int numCols
Definition: plannodes.h:821
List * qual
Definition: plannodes.h:143
AggStatePerPhase phases
Definition: execnodes.h:2177
double hashentrysize
Definition: execnodes.h:2202
#define AllocSetContextCreate
Definition: memutils.h:170
Datum * ecxt_aggvalues
Definition: execnodes.h:245
uint64 hash_ngroups_limit
Definition: execnodes.h:2199
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1801
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
AttrNumber * grpColIdx
Definition: plannodes.h:822
uint64 transitionSpace
Definition: plannodes.h:826
const TupleTableSlotOps * ExecGetResultSlotOps(PlanState *planstate, bool *isfixed)
Definition: execUtils.c:504
List * lcons_int(int datum, List *list)
Definition: list.c:471
int numaggs
Definition: execnodes.h:2148
Oid GetUserId(void)
Definition: miscinit.c:450
bool agg_done
Definition: execnodes.h:2166
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
Oid * grpCollations
Definition: plannodes.h:824
TupleTableSlot * sort_slot
Definition: execnodes.h:2180
List * all_grouped_cols
Definition: execnodes.h:2171
Tuplesortstate * sort_out
Definition: execnodes.h:2179
ScanState ss
Definition: execnodes.h:2146
ExprContext * ps_ExprContext
Definition: execnodes.h:984
ExprState * evaltrans
Definition: nodeAgg.h:283
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
Oid inputcollid
Definition: primnodes.h:315
int current_phase
Definition: execnodes.h:2154
Definition: nodes.h:529
AggSplit aggsplit
Definition: execnodes.h:2151
static TupleTableSlot * ExecAgg(PlanState *pstate)
Definition: nodeAgg.c:2150
int errcode(int sqlerrcode)
Definition: elog.c:610
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1335
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:2037
TupleTableSlot * hash_spill_rslot
Definition: execnodes.h:2192
static int find_compatible_pertrans(AggState *aggstate, Aggref *newagg, bool shareable, Oid aggtransfn, Oid aggtranstype, Oid aggserialfn, Oid aggdeserialfn, Datum initValue, bool initValueIsNull, List *transnos)
Definition: nodeAgg.c:4506
AggStatePerTrans pertrans
Definition: execnodes.h:2156
EState * state
Definition: execnodes.h:947
int projected_set
Definition: execnodes.h:2167
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple grp_firstTuple
Definition: execnodes.h:2184
Aggref * aggref
Definition: nodeAgg.h:187
int current_set
Definition: execnodes.h:2169
#define OidIsValid(objectId)
Definition: c.h:651
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:791
int numtrans
Definition: execnodes.h:2149
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:209
ExprContext * tmpcontext
Definition: execnodes.h:2159
#define FUNC_MAX_ARGS
Bitmapset ** grouped_cols
Definition: nodeAgg.h:277
PlanState ps
Definition: execnodes.h:1332
int maxsets
Definition: execnodes.h:2176
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1695
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3294
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:793
MemoryContext es_query_cxt
Definition: execnodes.h:555
AggStrategy aggstrategy
Definition: plannodes.h:819
bool table_filled
Definition: execnodes.h:2186
AggStrategy aggstrategy
Definition: execnodes.h:2150
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1520
MemoryContext hash_metacxt
Definition: execnodes.h:2188
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
static void find_hash_columns(AggState *aggstate)
Definition: nodeAgg.c:1566
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Tuplesortstate * sort_in
Definition: execnodes.h:2178
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define outerPlanState(node)
Definition: execnodes.h:1039
Aggref * aggref
Definition: execnodes.h:752
#define list_nth_node(type, list, n)
Definition: pg_list.h:305
static int initValue(long lng_val)
Definition: informix.c:677
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:540
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
List * ExecInitExprList(List *nodes, PlanState *parent)
Definition: execExpr.c:318
Index agglevelsup
Definition: primnodes.h:327
int hash_planned_partitions
Definition: execnodes.h:2200
List * aggdirectargs
Definition: primnodes.h:318
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
Definition: nodeAgg.c:4400
AggStatePerAgg curperagg
Definition: execnodes.h:2162
AggStatePerHash perhash
Definition: execnodes.h:2209
bool outeropsset
Definition: execnodes.h:1026
AggStrategy aggstrategy
Definition: nodeAgg.h:274
ExprState * evaltrans_cache[2][2]
Definition: nodeAgg.h:291
#define EXEC_FLAG_REWIND
Definition: executor.h:57
int hash_batches_used
Definition: execnodes.h:2207
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:191
#define outerPlan(node)
Definition: plannodes.h:172
int num_hashes
Definition: execnodes.h:2187
Plan plan
Definition: plannodes.h:818
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
bool input_done
Definition: execnodes.h:2165
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
ExprContext * hashcontext
Definition: execnodes.h:2157
bool * ecxt_aggnulls
Definition: execnodes.h:247
static int find_compatible_peragg(Aggref *newagg, AggState *aggstate, int lastaggno, List **same_input_transnos)
Definition: nodeAgg.c:4428
void * palloc0(Size size)
Definition: mcxt.c:980
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:951
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:367
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1377
List * groupingSets
Definition: plannodes.h:829
int16 resulttypeLen
Definition: nodeAgg.h:216
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:505
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:133
Plan * plan
Definition: execnodes.h:945
#define InvalidOid
Definition: postgres_ext.h:36
Oid aggfnoid
Definition: primnodes.h:312
#define ereport(elevel,...)
Definition: elog.h:144
#define Max(x, y)
Definition: c.h:921
ExprContext ** aggcontexts
Definition: execnodes.h:2158
#define makeNode(_type_)
Definition: nodes.h:577
int plan_width
Definition: plannodes.h:130
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:190
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:59
#define EXEC_FLAG_MARK
Definition: executor.h:59
AggSplit aggsplit
Definition: plannodes.h:820
struct AggStatePerAggData * AggStatePerAgg
Definition: execnodes.h:2138
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
AggSplit aggsplit
Definition: primnodes.h:328
AggStatePerGroup * pergroups
Definition: execnodes.h:2182
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:485
static int list_length(const List *l)
Definition: pg_list.h:169
long numGroups
Definition: plannodes.h:825
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:792
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2139
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1769
bool outeropsfixed
Definition: execnodes.h:1022
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:794
Size hash_mem_limit
Definition: execnodes.h:2198
struct Plan * lefttree
Definition: plannodes.h:144
int numphases
Definition: execnodes.h:2153
ExprState * qual
Definition: execnodes.h:966
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1793
Oid * grpOperators
Definition: plannodes.h:823
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:824
List * chain
Definition: plannodes.h:830
AggStatePerAgg peragg
Definition: execnodes.h:2155
#define ACL_EXECUTE
Definition: parsenodes.h:81
#define elog(elevel,...)
Definition: elog.h:214
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4587
int i
List * aggdirectargs
Definition: nodeAgg.h:210
Oid aggtranstype
Definition: primnodes.h:316
AggStatePerTrans curpertrans
Definition: execnodes.h:2164
Oid aggtype
Definition: primnodes.h:313
bool resulttypeByVal
Definition: nodeAgg.h:217
Definition: plannodes.h:816
ExprContext * CreateWorkExprContext(EState *estate)
Definition: execUtils.c:321
List * aggs
Definition: execnodes.h:2147
void ExecCreateScanSlotFromOuterPlan(EState *estate, ScanState *scanstate, const TupleTableSlotOps *tts_ops)
Definition: execUtils.c:687
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1819
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:4092
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:50
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
FmgrInfo finalfn
Definition: nodeAgg.h:199
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
TupleTableSlot * hash_spill_wslot
Definition: execnodes.h:2193
static void build_hash_tables(AggState *aggstate)
Definition: nodeAgg.c:1471
const TupleTableSlotOps * outerops
Definition: execnodes.h:1018
ExprState * ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase, bool doSort, bool doHash, bool nullcheck)
Definition: execExpr.c:2934
AggStatePerGroup * all_pergroups
Definition: execnodes.h:2215

◆ ExecReScanAgg()

void ExecReScanAgg ( AggState node)

Definition at line 4627 of file nodeAgg.c.

References AggState::agg_done, AGG_HASHED, AGG_MIXED, AggState::aggcontexts, Agg::aggParams, AggState::aggstrategy, bms_overlap(), build_hash_tables(), PlanState::chgParam, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, ExecClearTuple(), ExecReScan(), AggState::grp_firstTuple, AggState::hash_ever_spilled, AggState::hash_ngroups_current, AggState::hash_spill_mode, hashagg_recompile_expressions(), hashagg_reset_spill_state(), AggState::hashcontext, AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, heap_freetuple(), initialize_phase(), AggState::input_done, Max, AggState::maxsets, MemSet, AggState::numaggs, AggState::numtrans, outerPlan, outerPlanState, AggState::pergroups, 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().

4628 {
4629  ExprContext *econtext = node->ss.ps.ps_ExprContext;
4631  Agg *aggnode = (Agg *) node->ss.ps.plan;
4632  int transno;
4633  int numGroupingSets = Max(node->maxsets, 1);
4634  int setno;
4635 
4636  node->agg_done = false;
4637 
4638  if (node->aggstrategy == AGG_HASHED)
4639  {
4640  /*
4641  * In the hashed case, if we haven't yet built the hash table then we
4642  * can just return; nothing done yet, so nothing to undo. If subnode's
4643  * chgParam is not NULL then it will be re-scanned by ExecProcNode,
4644  * else no reason to re-scan it at all.
4645  */
4646  if (!node->table_filled)
4647  return;
4648 
4649  /*
4650  * If we do have the hash table, and it never spilled, and the subplan
4651  * does not have any parameter changes, and none of our own parameter
4652  * changes affect input expressions of the aggregated functions, then
4653  * we can just rescan the existing hash table; no need to build it
4654  * again.
4655  */
4656  if (outerPlan->chgParam == NULL && !node->hash_ever_spilled &&
4657  !bms_overlap(node->ss.ps.chgParam, aggnode->aggParams))
4658  {
4660  &node->perhash[0].hashiter);
4661  select_current_set(node, 0, true);
4662  return;
4663  }
4664  }
4665 
4666  /* Make sure we have closed any open tuplesorts */
4667  for (transno = 0; transno < node->numtrans; transno++)
4668  {
4669  for (setno = 0; setno < numGroupingSets; setno++)
4670  {
4671  AggStatePerTrans pertrans = &node->pertrans[transno];
4672 
4673  if (pertrans->sortstates[setno])
4674  {
4675  tuplesort_end(pertrans->sortstates[setno]);
4676  pertrans->sortstates[setno] = NULL;
4677  }
4678  }
4679  }
4680 
4681  /*
4682  * We don't need to ReScanExprContext the output tuple context here;
4683  * ExecReScan already did it. But we do need to reset our per-grouping-set
4684  * contexts, which may have transvalues stored in them. (We use rescan
4685  * rather than just reset because transfns may have registered callbacks
4686  * that need to be run now.) For the AGG_HASHED case, see below.
4687  */
4688 
4689  for (setno = 0; setno < numGroupingSets; setno++)
4690  {
4691  ReScanExprContext(node->aggcontexts[setno]);
4692  }
4693 
4694  /* Release first tuple of group, if we have made a copy */
4695  if (node->grp_firstTuple != NULL)
4696  {
4698  node->grp_firstTuple = NULL;
4699  }
4701 
4702  /* Forget current agg values */
4703  MemSet(econtext->ecxt_aggvalues, 0, sizeof(Datum) * node->numaggs);
4704  MemSet(econtext->ecxt_aggnulls, 0, sizeof(bool) * node->numaggs);
4705 
4706  /*
4707  * With AGG_HASHED/MIXED, the hash table is allocated in a sub-context of
4708  * the hashcontext. This used to be an issue, but now, resetting a context
4709  * automatically deletes sub-contexts too.
4710  */
4711  if (node->aggstrategy == AGG_HASHED || node->aggstrategy == AGG_MIXED)
4712  {
4714 
4715  node->hash_ever_spilled = false;
4716  node->hash_spill_mode = false;
4717  node->hash_ngroups_current = 0;
4718 
4720  /* Rebuild an empty hash table */
4721  build_hash_tables(node);
4722  node->table_filled = false;
4723  /* iterator will be reset when the table is filled */
4724 
4725  hashagg_recompile_expressions(node, false, false);
4726  }
4727 
4728  if (node->aggstrategy != AGG_HASHED)
4729  {
4730  /*
4731  * Reset the per-group state (in particular, mark transvalues null)
4732  */
4733  for (setno = 0; setno < numGroupingSets; setno++)
4734  {
4735  MemSet(node->pergroups[setno], 0,
4736  sizeof(AggStatePerGroupData) * node->numaggs);
4737  }
4738 
4739  /* reset to phase 1 */
4740  initialize_phase(node, 1);
4741 
4742  node->input_done = false;
4743  node->projected_set = -1;
4744  }
4745 
4746  if (outerPlan->chgParam == NULL)
4747  ExecReScan(outerPlan);
4748 }
static void hashagg_reset_spill_state(AggState *aggstate)
Definition: nodeAgg.c:3182
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:483
Datum * ecxt_aggvalues
Definition: execnodes.h:245
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
int numaggs
Definition: execnodes.h:2148
bool agg_done
Definition: execnodes.h:2166
ScanState ss
Definition: execnodes.h:2146
ExprContext * ps_ExprContext
Definition: execnodes.h:984
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
#define MemSet(start, val, len)
Definition: c.h:978
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1335
AggStatePerTrans pertrans
Definition: execnodes.h:2156
int projected_set
Definition: execnodes.h:2167
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
HeapTuple grp_firstTuple
Definition: execnodes.h:2184
int numtrans
Definition: execnodes.h:2149
bool hash_spill_mode
Definition: execnodes.h:2196
PlanState ps
Definition: execnodes.h:1332
int maxsets
Definition: execnodes.h:2176
bool table_filled
Definition: execnodes.h:2186
AggStrategy aggstrategy
Definition: execnodes.h:2150
#define outerPlanState(node)
Definition: execnodes.h:1039
Tuplesortstate ** sortstates
Definition: nodeAgg.h:154
Bitmapset * aggParams
Definition: plannodes.h:827
AggStatePerHash perhash
Definition: execnodes.h:2209
Bitmapset * chgParam
Definition: execnodes.h:977
#define outerPlan(node)
Definition: plannodes.h:172
TupleHashIterator hashiter
Definition: nodeAgg.h:304
bool input_done
Definition: execnodes.h:2165
ExprContext * hashcontext
Definition: execnodes.h:2157
bool * ecxt_aggnulls
Definition: execnodes.h:247
uintptr_t Datum
Definition: postgres.h:367
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:505
Plan * plan
Definition: execnodes.h:945
#define ResetTupleHashIterator(htable, iter)
Definition: execnodes.h:727
static void hashagg_recompile_expressions(AggState *aggstate, bool minslot, bool nullcheck)
Definition: nodeAgg.c:1742
#define Max(x, y)
Definition: c.h:921
ExprContext ** aggcontexts
Definition: execnodes.h:2158
bool hash_ever_spilled
Definition: execnodes.h:2195
AggStatePerGroup * pergroups
Definition: execnodes.h:2182
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:443
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:494
uint64 hash_ngroups_current
Definition: execnodes.h:2204
Definition: plannodes.h:816
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:1388
TupleHashTable hashtable
Definition: nodeAgg.h:303
static void build_hash_tables(AggState *aggstate)
Definition: nodeAgg.c:1471

◆ hash_agg_entry_size()

Size hash_agg_entry_size ( int  numTrans,
Size  tupleWidth,
Size  transitionSpace 
)

Definition at line 1695 of file nodeAgg.c.

References CHUNKHDRSZ, MAXALIGN, and SizeofMinimalTupleHeader.

Referenced by cost_agg(), estimate_hashagg_tablesize(), and ExecInitAgg().

1696 {
1697  Size tupleChunkSize;
1698  Size pergroupChunkSize;
1699  Size transitionChunkSize;
1700  Size tupleSize = (MAXALIGN(SizeofMinimalTupleHeader) +
1701  tupleWidth);
1702  Size pergroupSize = numTrans * sizeof(AggStatePerGroupData);
1703 
1704  tupleChunkSize = CHUNKHDRSZ + tupleSize;
1705 
1706  if (pergroupSize > 0)
1707  pergroupChunkSize = CHUNKHDRSZ + pergroupSize;
1708  else
1709  pergroupChunkSize = 0;
1710 
1711  if (transitionSpace > 0)
1712  transitionChunkSize = CHUNKHDRSZ + transitionSpace;
1713  else
1714  transitionChunkSize = 0;
1715 
1716  return
1717  sizeof(TupleHashEntryData) +
1718  tupleChunkSize +
1719  pergroupChunkSize +
1720  transitionChunkSize;
1721 }
struct TupleHashEntryData TupleHashEntryData
struct AggStatePerGroupData AggStatePerGroupData
#define SizeofMinimalTupleHeader
Definition: htup_details.h:649
size_t Size
Definition: c.h:473
#define MAXALIGN(LEN)
Definition: c.h:698
#define CHUNKHDRSZ
Definition: nodeAgg.c:312

◆ hash_agg_set_limits()

void hash_agg_set_limits ( double  hashentrysize,
double  input_groups,
int  used_bits,
Size mem_limit,
uint64 *  ngroups_limit,
int *  num_partitions 
)

Definition at line 1793 of file nodeAgg.c.

References get_hash_mem(), hash_choose_num_partitions(), HASHAGG_READ_BUFFER_SIZE, and HASHAGG_WRITE_BUFFER_SIZE.

Referenced by agg_refill_hash_table(), cost_agg(), and ExecInitAgg().

1796 {
1797  int npartitions;
1798  Size partition_mem;
1799  int hash_mem = get_hash_mem();
1800 
1801  /* if not expected to spill, use all of hash_mem */
1802  if (input_groups * hashentrysize < hash_mem * 1024L)
1803  {
1804  if (num_partitions != NULL)
1805  *num_partitions = 0;
1806  *mem_limit = hash_mem * 1024L;
1807  *ngroups_limit = *mem_limit / hashentrysize;
1808  return;
1809  }
1810 
1811  /*
1812  * Calculate expected memory requirements for spilling, which is the size
1813  * of the buffers needed for all the tapes that need to be open at once.
1814  * Then, subtract that from the memory available for holding hash tables.
1815  */
1816  npartitions = hash_choose_num_partitions(input_groups,
1817  hashentrysize,
1818  used_bits,
1819  NULL);
1820  if (num_partitions != NULL)
1821  *num_partitions = npartitions;
1822 
1823  partition_mem =
1825  HASHAGG_WRITE_BUFFER_SIZE * npartitions;
1826 
1827  /*
1828  * Don't set the limit below 3/4 of hash_mem. In that case, we are at the
1829  * minimum number of partitions, so we aren't going to dramatically exceed
1830  * work mem anyway.
1831  */
1832  if (hash_mem * 1024L > 4 * partition_mem)
1833  *mem_limit = hash_mem * 1024L - partition_mem;
1834  else
1835  *mem_limit = hash_mem * 1024L * 0.75;
1836 
1837  if (*mem_limit > hashentrysize)
1838  *ngroups_limit = *mem_limit / hashentrysize;
1839  else
1840  *ngroups_limit = 1;
1841 }
static int hash_choose_num_partitions(double input_groups, double hashentrysize, int used_bits, int *log2_npartittions)
Definition: nodeAgg.c:1986
#define HASHAGG_READ_BUFFER_SIZE
Definition: nodeAgg.c:297
size_t Size
Definition: c.h:473
#define HASHAGG_WRITE_BUFFER_SIZE
Definition: nodeAgg.c:298
int get_hash_mem(void)
Definition: nodeHash.c:3389