PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 257 of file nodeAgg.h.

◆ FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUE

#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUE   0

Definition at line 252 of file nodeAgg.h.

◆ FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUEISNULL

#define FIELDNO_AGGSTATEPERGROUPDATA_TRANSVALUEISNULL   1

Definition at line 254 of file nodeAgg.h.

Typedef Documentation

◆ AggStatePerAggData

◆ AggStatePerGroupData

◆ AggStatePerHashData

◆ AggStatePerPhaseData

◆ AggStatePerTransData

Function Documentation

◆ ExecAggEstimate()

void ExecAggEstimate ( AggState node,
ParallelContext pcxt 
)

Definition at line 4786 of file nodeAgg.c.

4787{
4788 Size size;
4789
4790 /* don't need this if not instrumenting or no workers */
4791 if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4792 return;
4793
4794 size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4795 size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4796 shm_toc_estimate_chunk(&pcxt->estimator, size);
4798}
size_t Size
Definition: c.h:576
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
ScanState ss
Definition: execnodes.h:2527
shm_toc_estimator estimator
Definition: parallel.h:41
Instrumentation * instrument
Definition: execnodes.h:1169
PlanState ps
Definition: execnodes.h:1615

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

Referenced by ExecParallelEstimate().

◆ ExecAggInitializeDSM()

void ExecAggInitializeDSM ( AggState node,
ParallelContext pcxt 
)

Definition at line 4807 of file nodeAgg.c.

4808{
4809 Size size;
4810
4811 /* don't need this if not instrumenting or no workers */
4812 if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4813 return;
4814
4815 size = offsetof(SharedAggInfo, sinstrument)
4816 + pcxt->nworkers * sizeof(AggregateInstrumentation);
4817 node->shared_info = shm_toc_allocate(pcxt->toc, size);
4818 /* ensure any unfilled slots will contain zeroes */
4819 memset(node->shared_info, 0, size);
4820 node->shared_info->num_workers = pcxt->nworkers;
4821 shm_toc_insert(pcxt->toc, node->ss.ps.plan->plan_node_id,
4822 node->shared_info);
4823}
struct AggregateInstrumentation AggregateInstrumentation
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:2599
shm_toc * toc
Definition: parallel.h:44
Plan * plan
Definition: execnodes.h:1159
int plan_node_id
Definition: plannodes.h:207

References PlanState::instrument, SharedAggInfo::num_workers, ParallelContext::nworkers, 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().

◆ ExecAggInitializeWorker()

void ExecAggInitializeWorker ( AggState node,
ParallelWorkerContext pwcxt 
)

Definition at line 4832 of file nodeAgg.c.

4833{
4834 node->shared_info =
4835 shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
4836}
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232

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

Referenced by ExecParallelInitializeWorker().

◆ ExecAggRetrieveInstrumentation()

void ExecAggRetrieveInstrumentation ( AggState node)

Definition at line 4845 of file nodeAgg.c.

4846{
4847 Size size;
4848 SharedAggInfo *si;
4849
4850 if (node->shared_info == NULL)
4851 return;
4852
4853 size = offsetof(SharedAggInfo, sinstrument)
4855 si = palloc(size);
4856 memcpy(si, node->shared_info, size);
4857 node->shared_info = si;
4858}
void * palloc(Size size)
Definition: mcxt.c:1939

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)

Definition at line 4400 of file nodeAgg.c.

4401{
4403 int transno;
4404 int numGroupingSets = Max(node->maxsets, 1);
4405 int setno;
4406
4407 /*
4408 * When ending a parallel worker, copy the statistics gathered by the
4409 * worker back into shared memory so that it can be picked up by the main
4410 * process to report in EXPLAIN ANALYZE.
4411 */
4412 if (node->shared_info && IsParallelWorker())
4413 {
4415
4416 Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
4419 si->hash_disk_used = node->hash_disk_used;
4420 si->hash_mem_peak = node->hash_mem_peak;
4421 }
4422
4423 /* Make sure we have closed any open tuplesorts */
4424
4425 if (node->sort_in)
4426 tuplesort_end(node->sort_in);
4427 if (node->sort_out)
4428 tuplesort_end(node->sort_out);
4429
4431
4432 if (node->hash_metacxt != NULL)
4433 {
4435 node->hash_metacxt = NULL;
4436 }
4437 if (node->hash_tablecxt != NULL)
4438 {
4440 node->hash_tablecxt = NULL;
4441 }
4442
4443
4444 for (transno = 0; transno < node->numtrans; transno++)
4445 {
4446 AggStatePerTrans pertrans = &node->pertrans[transno];
4447
4448 for (setno = 0; setno < numGroupingSets; setno++)
4449 {
4450 if (pertrans->sortstates[setno])
4451 tuplesort_end(pertrans->sortstates[setno]);
4452 }
4453 }
4454
4455 /* And ensure any agg shutdown callbacks have been called */
4456 for (setno = 0; setno < numGroupingSets; setno++)
4457 ReScanExprContext(node->aggcontexts[setno]);
4458 if (node->hashcontext)
4460
4461 outerPlan = outerPlanState(node);
4463}
int ParallelWorkerNumber
Definition: parallel.c:115
#define Max(x, y)
Definition: c.h:969
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:444
#define outerPlanState(node)
Definition: execnodes.h:1255
Assert(PointerIsAligned(start, uint64))
#define IsParallelWorker()
Definition: parallel.h:60
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:485
static void hashagg_reset_spill_state(AggState *aggstate)
Definition: nodeAgg.c:3239
#define outerPlan(node)
Definition: plannodes.h:241
Tuplesortstate ** sortstates
Definition: nodeAgg.h:162
MemoryContext hash_metacxt
Definition: execnodes.h:2569
Tuplesortstate * sort_out
Definition: execnodes.h:2560
uint64 hash_disk_used
Definition: execnodes.h:2588
MemoryContext hash_tablecxt
Definition: execnodes.h:2570
AggStatePerTrans pertrans
Definition: execnodes.h:2537
int numtrans
Definition: execnodes.h:2530
ExprContext * hashcontext
Definition: execnodes.h:2538
Size hash_mem_peak
Definition: execnodes.h:2585
int hash_batches_used
Definition: execnodes.h:2589
Tuplesortstate * sort_in
Definition: execnodes.h:2559
int maxsets
Definition: execnodes.h:2557
ExprContext ** aggcontexts
Definition: execnodes.h:2539
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2503
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:951

References AggState::aggcontexts, Assert(), ExecEndNode(), 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, AggState::hash_tablecxt, hashagg_reset_spill_state(), AggState::hashcontext, IsParallelWorker, Max, AggState::maxsets, MemoryContextDelete(), AggState::numtrans, outerPlan, outerPlanState, ParallelWorkerNumber, AggState::pertrans, ReScanExprContext(), AggState::shared_info, SharedAggInfo::sinstrument, AggState::sort_in, AggState::sort_out, AggStatePerTransData::sortstates, and tuplesort_end().

Referenced by ExecEndNode().

◆ ExecInitAgg()

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

Definition at line 3279 of file nodeAgg.c.

3280{
3281 AggState *aggstate;
3282 AggStatePerAgg peraggs;
3283 AggStatePerTrans pertransstates;
3284 AggStatePerGroup *pergroups;
3285 Plan *outerPlan;
3286 ExprContext *econtext;
3287 TupleDesc scanDesc;
3288 int max_aggno;
3289 int max_transno;
3290 int numaggrefs;
3291 int numaggs;
3292 int numtrans;
3293 int phase;
3294 int phaseidx;
3295 ListCell *l;
3296 Bitmapset *all_grouped_cols = NULL;
3297 int numGroupingSets = 1;
3298 int numPhases;
3299 int numHashes;
3300 int i = 0;
3301 int j = 0;
3302 bool use_hashing = (node->aggstrategy == AGG_HASHED ||
3303 node->aggstrategy == AGG_MIXED);
3304
3305 /* check for unsupported flags */
3306 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3307
3308 /*
3309 * create state structure
3310 */
3311 aggstate = makeNode(AggState);
3312 aggstate->ss.ps.plan = (Plan *) node;
3313 aggstate->ss.ps.state = estate;
3314 aggstate->ss.ps.ExecProcNode = ExecAgg;
3315
3316 aggstate->aggs = NIL;
3317 aggstate->numaggs = 0;
3318 aggstate->numtrans = 0;
3319 aggstate->aggstrategy = node->aggstrategy;
3320 aggstate->aggsplit = node->aggsplit;
3321 aggstate->maxsets = 0;
3322 aggstate->projected_set = -1;
3323 aggstate->current_set = 0;
3324 aggstate->peragg = NULL;
3325 aggstate->pertrans = NULL;
3326 aggstate->curperagg = NULL;
3327 aggstate->curpertrans = NULL;
3328 aggstate->input_done = false;
3329 aggstate->agg_done = false;
3330 aggstate->pergroups = NULL;
3331 aggstate->grp_firstTuple = NULL;
3332 aggstate->sort_in = NULL;
3333 aggstate->sort_out = NULL;
3334
3335 /*
3336 * phases[0] always exists, but is dummy in sorted/plain mode
3337 */
3338 numPhases = (use_hashing ? 1 : 2);
3339 numHashes = (use_hashing ? 1 : 0);
3340
3341 /*
3342 * Calculate the maximum number of grouping sets in any phase; this
3343 * determines the size of some allocations. Also calculate the number of
3344 * phases, since all hashed/mixed nodes contribute to only a single phase.
3345 */
3346 if (node->groupingSets)
3347 {
3348 numGroupingSets = list_length(node->groupingSets);
3349
3350 foreach(l, node->chain)
3351 {
3352 Agg *agg = lfirst(l);
3353
3354 numGroupingSets = Max(numGroupingSets,
3356
3357 /*
3358 * additional AGG_HASHED aggs become part of phase 0, but all
3359 * others add an extra phase.
3360 */
3361 if (agg->aggstrategy != AGG_HASHED)
3362 ++numPhases;
3363 else
3364 ++numHashes;
3365 }
3366 }
3367
3368 aggstate->maxsets = numGroupingSets;
3369 aggstate->numphases = numPhases;
3370
3371 aggstate->aggcontexts = (ExprContext **)
3372 palloc0(sizeof(ExprContext *) * numGroupingSets);
3373
3374 /*
3375 * Create expression contexts. We need three or more, one for
3376 * per-input-tuple processing, one for per-output-tuple processing, one
3377 * for all the hashtables, and one for each grouping set. The per-tuple
3378 * memory context of the per-grouping-set ExprContexts (aggcontexts)
3379 * replaces the standalone memory context formerly used to hold transition
3380 * values. We cheat a little by using ExecAssignExprContext() to build
3381 * all of them.
3382 *
3383 * NOTE: the details of what is stored in aggcontexts and what is stored
3384 * in the regular per-query memory context are driven by a simple
3385 * decision: we want to reset the aggcontext at group boundaries (if not
3386 * hashing) and in ExecReScanAgg to recover no-longer-wanted space.
3387 */
3388 ExecAssignExprContext(estate, &aggstate->ss.ps);
3389 aggstate->tmpcontext = aggstate->ss.ps.ps_ExprContext;
3390
3391 for (i = 0; i < numGroupingSets; ++i)
3392 {
3393 ExecAssignExprContext(estate, &aggstate->ss.ps);
3394 aggstate->aggcontexts[i] = aggstate->ss.ps.ps_ExprContext;
3395 }
3396
3397 if (use_hashing)
3398 hash_create_memory(aggstate);
3399
3400 ExecAssignExprContext(estate, &aggstate->ss.ps);
3401
3402 /*
3403 * Initialize child nodes.
3404 *
3405 * If we are doing a hashed aggregation then the child plan does not need
3406 * to handle REWIND efficiently; see ExecReScanAgg.
3407 */
3408 if (node->aggstrategy == AGG_HASHED)
3409 eflags &= ~EXEC_FLAG_REWIND;
3410 outerPlan = outerPlan(node);
3411 outerPlanState(aggstate) = ExecInitNode(outerPlan, estate, eflags);
3412
3413 /*
3414 * initialize source tuple type.
3415 */
3416 aggstate->ss.ps.outerops =
3418 &aggstate->ss.ps.outeropsfixed);
3419 aggstate->ss.ps.outeropsset = true;
3420
3421 ExecCreateScanSlotFromOuterPlan(estate, &aggstate->ss,
3422 aggstate->ss.ps.outerops);
3423 scanDesc = aggstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
3424
3425 /*
3426 * If there are more than two phases (including a potential dummy phase
3427 * 0), input will be resorted using tuplesort. Need a slot for that.
3428 */
3429 if (numPhases > 2)
3430 {
3431 aggstate->sort_slot = ExecInitExtraTupleSlot(estate, scanDesc,
3433
3434 /*
3435 * The output of the tuplesort, and the output from the outer child
3436 * might not use the same type of slot. In most cases the child will
3437 * be a Sort, and thus return a TTSOpsMinimalTuple type slot - but the
3438 * input can also be presorted due an index, in which case it could be
3439 * a different type of slot.
3440 *
3441 * XXX: For efficiency it would be good to instead/additionally
3442 * generate expressions with corresponding settings of outerops* for
3443 * the individual phases - deforming is often a bottleneck for
3444 * aggregations with lots of rows per group. If there's multiple
3445 * sorts, we know that all but the first use TTSOpsMinimalTuple (via
3446 * the nodeAgg.c internal tuplesort).
3447 */
3448 if (aggstate->ss.ps.outeropsfixed &&
3449 aggstate->ss.ps.outerops != &TTSOpsMinimalTuple)
3450 aggstate->ss.ps.outeropsfixed = false;
3451 }
3452
3453 /*
3454 * Initialize result type, slot and projection.
3455 */
3457 ExecAssignProjectionInfo(&aggstate->ss.ps, NULL);
3458
3459 /*
3460 * initialize child expressions
3461 *
3462 * We expect the parser to have checked that no aggs contain other agg
3463 * calls in their arguments (and just to be sure, we verify it again while
3464 * initializing the plan node). This would make no sense under SQL
3465 * semantics, and it's forbidden by the spec. Because it is true, we
3466 * don't need to worry about evaluating the aggs in any particular order.
3467 *
3468 * Note: execExpr.c finds Aggrefs for us, and adds them to aggstate->aggs.
3469 * Aggrefs in the qual are found here; Aggrefs in the targetlist are found
3470 * during ExecAssignProjectionInfo, above.
3471 */
3472 aggstate->ss.ps.qual =
3473 ExecInitQual(node->plan.qual, (PlanState *) aggstate);
3474
3475 /*
3476 * We should now have found all Aggrefs in the targetlist and quals.
3477 */
3478 numaggrefs = list_length(aggstate->aggs);
3479 max_aggno = -1;
3480 max_transno = -1;
3481 foreach(l, aggstate->aggs)
3482 {
3483 Aggref *aggref = (Aggref *) lfirst(l);
3484
3485 max_aggno = Max(max_aggno, aggref->aggno);
3486 max_transno = Max(max_transno, aggref->aggtransno);
3487 }
3488 aggstate->numaggs = numaggs = max_aggno + 1;
3489 aggstate->numtrans = numtrans = max_transno + 1;
3490
3491 /*
3492 * For each phase, prepare grouping set data and fmgr lookup data for
3493 * compare functions. Accumulate all_grouped_cols in passing.
3494 */
3495 aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
3496
3497 aggstate->num_hashes = numHashes;
3498 if (numHashes)
3499 {
3500 aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
3501 aggstate->phases[0].numsets = 0;
3502 aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
3503 aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
3504 }
3505
3506 phase = 0;
3507 for (phaseidx = 0; phaseidx <= list_length(node->chain); ++phaseidx)
3508 {
3509 Agg *aggnode;
3510 Sort *sortnode;
3511
3512 if (phaseidx > 0)
3513 {
3514 aggnode = list_nth_node(Agg, node->chain, phaseidx - 1);
3515 sortnode = castNode(Sort, outerPlan(aggnode));
3516 }
3517 else
3518 {
3519 aggnode = node;
3520 sortnode = NULL;
3521 }
3522
3523 Assert(phase <= 1 || sortnode);
3524
3525 if (aggnode->aggstrategy == AGG_HASHED
3526 || aggnode->aggstrategy == AGG_MIXED)
3527 {
3528 AggStatePerPhase phasedata = &aggstate->phases[0];
3529 AggStatePerHash perhash;
3530 Bitmapset *cols = NULL;
3531
3532 Assert(phase == 0);
3533 i = phasedata->numsets++;
3534 perhash = &aggstate->perhash[i];
3535
3536 /* phase 0 always points to the "real" Agg in the hash case */
3537 phasedata->aggnode = node;
3538 phasedata->aggstrategy = node->aggstrategy;
3539
3540 /* but the actual Agg node representing this hash is saved here */
3541 perhash->aggnode = aggnode;
3542
3543 phasedata->gset_lengths[i] = perhash->numCols = aggnode->numCols;
3544
3545 for (j = 0; j < aggnode->numCols; ++j)
3546 cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3547
3548 phasedata->grouped_cols[i] = cols;
3549
3550 all_grouped_cols = bms_add_members(all_grouped_cols, cols);
3551 continue;
3552 }
3553 else
3554 {
3555 AggStatePerPhase phasedata = &aggstate->phases[++phase];
3556 int num_sets;
3557
3558 phasedata->numsets = num_sets = list_length(aggnode->groupingSets);
3559
3560 if (num_sets)
3561 {
3562 phasedata->gset_lengths = palloc(num_sets * sizeof(int));
3563 phasedata->grouped_cols = palloc(num_sets * sizeof(Bitmapset *));
3564
3565 i = 0;
3566 foreach(l, aggnode->groupingSets)
3567 {
3568 int current_length = list_length(lfirst(l));
3569 Bitmapset *cols = NULL;
3570
3571 /* planner forces this to be correct */
3572 for (j = 0; j < current_length; ++j)
3573 cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3574
3575 phasedata->grouped_cols[i] = cols;
3576 phasedata->gset_lengths[i] = current_length;
3577
3578 ++i;
3579 }
3580
3581 all_grouped_cols = bms_add_members(all_grouped_cols,
3582 phasedata->grouped_cols[0]);
3583 }
3584 else
3585 {
3586 Assert(phaseidx == 0);
3587
3588 phasedata->gset_lengths = NULL;
3589 phasedata->grouped_cols = NULL;
3590 }
3591
3592 /*
3593 * If we are grouping, precompute fmgr lookup data for inner loop.
3594 */
3595 if (aggnode->aggstrategy == AGG_SORTED)
3596 {
3597 /*
3598 * Build a separate function for each subset of columns that
3599 * need to be compared.
3600 */
3601 phasedata->eqfunctions =
3602 (ExprState **) palloc0(aggnode->numCols * sizeof(ExprState *));
3603
3604 /* for each grouping set */
3605 for (int k = 0; k < phasedata->numsets; k++)
3606 {
3607 int length = phasedata->gset_lengths[k];
3608
3609 /* nothing to do for empty grouping set */
3610 if (length == 0)
3611 continue;
3612
3613 /* if we already had one of this length, it'll do */
3614 if (phasedata->eqfunctions[length - 1] != NULL)
3615 continue;
3616
3617 phasedata->eqfunctions[length - 1] =
3618 execTuplesMatchPrepare(scanDesc,
3619 length,
3620 aggnode->grpColIdx,
3621 aggnode->grpOperators,
3622 aggnode->grpCollations,
3623 (PlanState *) aggstate);
3624 }
3625
3626 /* and for all grouped columns, unless already computed */
3627 if (aggnode->numCols > 0 &&
3628 phasedata->eqfunctions[aggnode->numCols - 1] == NULL)
3629 {
3630 phasedata->eqfunctions[aggnode->numCols - 1] =
3631 execTuplesMatchPrepare(scanDesc,
3632 aggnode->numCols,
3633 aggnode->grpColIdx,
3634 aggnode->grpOperators,
3635 aggnode->grpCollations,
3636 (PlanState *) aggstate);
3637 }
3638 }
3639
3640 phasedata->aggnode = aggnode;
3641 phasedata->aggstrategy = aggnode->aggstrategy;
3642 phasedata->sortnode = sortnode;
3643 }
3644 }
3645
3646 /*
3647 * Convert all_grouped_cols to a descending-order list.
3648 */
3649 i = -1;
3650 while ((i = bms_next_member(all_grouped_cols, i)) >= 0)
3651 aggstate->all_grouped_cols = lcons_int(i, aggstate->all_grouped_cols);
3652
3653 /*
3654 * Set up aggregate-result storage in the output expr context, and also
3655 * allocate my private per-agg working storage
3656 */
3657 econtext = aggstate->ss.ps.ps_ExprContext;
3658 econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
3659 econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
3660
3661 peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
3662 pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numtrans);
3663
3664 aggstate->peragg = peraggs;
3665 aggstate->pertrans = pertransstates;
3666
3667
3668 aggstate->all_pergroups =
3670 * (numGroupingSets + numHashes));
3671 pergroups = aggstate->all_pergroups;
3672
3673 if (node->aggstrategy != AGG_HASHED)
3674 {
3675 for (i = 0; i < numGroupingSets; i++)
3676 {
3677 pergroups[i] = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
3678 * numaggs);
3679 }
3680
3681 aggstate->pergroups = pergroups;
3682 pergroups += numGroupingSets;
3683 }
3684
3685 /*
3686 * Hashing can only appear in the initial phase.
3687 */
3688 if (use_hashing)
3689 {
3690 Plan *outerplan = outerPlan(node);
3691 uint64 totalGroups = 0;
3692
3693 aggstate->hash_spill_rslot = ExecInitExtraTupleSlot(estate, scanDesc,
3695 aggstate->hash_spill_wslot = ExecInitExtraTupleSlot(estate, scanDesc,
3696 &TTSOpsVirtual);
3697
3698 /* this is an array of pointers, not structures */
3699 aggstate->hash_pergroup = pergroups;
3700
3701 aggstate->hashentrysize = hash_agg_entry_size(aggstate->numtrans,
3702 outerplan->plan_width,
3703 node->transitionSpace);
3704
3705 /*
3706 * Consider all of the grouping sets together when setting the limits
3707 * and estimating the number of partitions. This can be inaccurate
3708 * when there is more than one grouping set, but should still be
3709 * reasonable.
3710 */
3711 for (int k = 0; k < aggstate->num_hashes; k++)
3712 totalGroups += aggstate->perhash[k].aggnode->numGroups;
3713
3714 hash_agg_set_limits(aggstate->hashentrysize, totalGroups, 0,
3715 &aggstate->hash_mem_limit,
3716 &aggstate->hash_ngroups_limit,
3717 &aggstate->hash_planned_partitions);
3718 find_hash_columns(aggstate);
3719
3720 /* Skip massive memory allocation if we are just doing EXPLAIN */
3721 if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
3722 build_hash_tables(aggstate);
3723
3724 aggstate->table_filled = false;
3725
3726 /* Initialize this to 1, meaning nothing spilled, yet */
3727 aggstate->hash_batches_used = 1;
3728 }
3729
3730 /*
3731 * Initialize current phase-dependent values to initial phase. The initial
3732 * phase is 1 (first sort pass) for all strategies that use sorting (if
3733 * hashing is being done too, then phase 0 is processed last); but if only
3734 * hashing is being done, then phase 0 is all there is.
3735 */
3736 if (node->aggstrategy == AGG_HASHED)
3737 {
3738 aggstate->current_phase = 0;
3739 initialize_phase(aggstate, 0);
3740 select_current_set(aggstate, 0, true);
3741 }
3742 else
3743 {
3744 aggstate->current_phase = 1;
3745 initialize_phase(aggstate, 1);
3746 select_current_set(aggstate, 0, false);
3747 }
3748
3749 /*
3750 * Perform lookups of aggregate function info, and initialize the
3751 * unchanging fields of the per-agg and per-trans data.
3752 */
3753 foreach(l, aggstate->aggs)
3754 {
3755 Aggref *aggref = lfirst(l);
3756 AggStatePerAgg peragg;
3757 AggStatePerTrans pertrans;
3758 Oid aggTransFnInputTypes[FUNC_MAX_ARGS];
3759 int numAggTransFnArgs;
3760 int numDirectArgs;
3761 HeapTuple aggTuple;
3762 Form_pg_aggregate aggform;
3763 AclResult aclresult;
3764 Oid finalfn_oid;
3765 Oid serialfn_oid,
3766 deserialfn_oid;
3767 Oid aggOwner;
3768 Expr *finalfnexpr;
3769 Oid aggtranstype;
3770
3771 /* Planner should have assigned aggregate to correct level */
3772 Assert(aggref->agglevelsup == 0);
3773 /* ... and the split mode should match */
3774 Assert(aggref->aggsplit == aggstate->aggsplit);
3775
3776 peragg = &peraggs[aggref->aggno];
3777
3778 /* Check if we initialized the state for this aggregate already. */
3779 if (peragg->aggref != NULL)
3780 continue;
3781
3782 peragg->aggref = aggref;
3783 peragg->transno = aggref->aggtransno;
3784
3785 /* Fetch the pg_aggregate row */
3786 aggTuple = SearchSysCache1(AGGFNOID,
3787 ObjectIdGetDatum(aggref->aggfnoid));
3788 if (!HeapTupleIsValid(aggTuple))
3789 elog(ERROR, "cache lookup failed for aggregate %u",
3790 aggref->aggfnoid);
3791 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
3792
3793 /* Check permission to call aggregate function */
3794 aclresult = object_aclcheck(ProcedureRelationId, aggref->aggfnoid, GetUserId(),
3795 ACL_EXECUTE);
3796 if (aclresult != ACLCHECK_OK)
3798 get_func_name(aggref->aggfnoid));
3800
3801 /* planner recorded transition state type in the Aggref itself */
3802 aggtranstype = aggref->aggtranstype;
3803 Assert(OidIsValid(aggtranstype));
3804
3805 /* Final function only required if we're finalizing the aggregates */
3806 if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
3807 peragg->finalfn_oid = finalfn_oid = InvalidOid;
3808 else
3809 peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
3810
3811 serialfn_oid = InvalidOid;
3812 deserialfn_oid = InvalidOid;
3813
3814 /*
3815 * Check if serialization/deserialization is required. We only do it
3816 * for aggregates that have transtype INTERNAL.
3817 */
3818 if (aggtranstype == INTERNALOID)
3819 {
3820 /*
3821 * The planner should only have generated a serialize agg node if
3822 * every aggregate with an INTERNAL state has a serialization
3823 * function. Verify that.
3824 */
3825 if (DO_AGGSPLIT_SERIALIZE(aggstate->aggsplit))
3826 {
3827 /* serialization only valid when not running finalfn */
3829
3830 if (!OidIsValid(aggform->aggserialfn))
3831 elog(ERROR, "serialfunc not provided for serialization aggregation");
3832 serialfn_oid = aggform->aggserialfn;
3833 }
3834
3835 /* Likewise for deserialization functions */
3836 if (DO_AGGSPLIT_DESERIALIZE(aggstate->aggsplit))
3837 {
3838 /* deserialization only valid when combining states */
3840
3841 if (!OidIsValid(aggform->aggdeserialfn))
3842 elog(ERROR, "deserialfunc not provided for deserialization aggregation");
3843 deserialfn_oid = aggform->aggdeserialfn;
3844 }
3845 }
3846
3847 /* Check that aggregate owner has permission to call component fns */
3848 {
3849 HeapTuple procTuple;
3850
3851 procTuple = SearchSysCache1(PROCOID,
3852 ObjectIdGetDatum(aggref->aggfnoid));
3853 if (!HeapTupleIsValid(procTuple))
3854 elog(ERROR, "cache lookup failed for function %u",
3855 aggref->aggfnoid);
3856 aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
3857 ReleaseSysCache(procTuple);
3858
3859 if (OidIsValid(finalfn_oid))
3860 {
3861 aclresult = object_aclcheck(ProcedureRelationId, finalfn_oid, aggOwner,
3862 ACL_EXECUTE);
3863 if (aclresult != ACLCHECK_OK)
3865 get_func_name(finalfn_oid));
3866 InvokeFunctionExecuteHook(finalfn_oid);
3867 }
3868 if (OidIsValid(serialfn_oid))
3869 {
3870 aclresult = object_aclcheck(ProcedureRelationId, serialfn_oid, aggOwner,
3871 ACL_EXECUTE);
3872 if (aclresult != ACLCHECK_OK)
3874 get_func_name(serialfn_oid));
3875 InvokeFunctionExecuteHook(serialfn_oid);
3876 }
3877 if (OidIsValid(deserialfn_oid))
3878 {
3879 aclresult = object_aclcheck(ProcedureRelationId, deserialfn_oid, aggOwner,
3880 ACL_EXECUTE);
3881 if (aclresult != ACLCHECK_OK)
3883 get_func_name(deserialfn_oid));
3884 InvokeFunctionExecuteHook(deserialfn_oid);
3885 }
3886 }
3887
3888 /*
3889 * Get actual datatypes of the (nominal) aggregate inputs. These
3890 * could be different from the agg's declared input types, when the
3891 * agg accepts ANY or a polymorphic type.
3892 */
3893 numAggTransFnArgs = get_aggregate_argtypes(aggref,
3894 aggTransFnInputTypes);
3895
3896 /* Count the "direct" arguments, if any */
3897 numDirectArgs = list_length(aggref->aggdirectargs);
3898
3899 /* Detect how many arguments to pass to the finalfn */
3900 if (aggform->aggfinalextra)
3901 peragg->numFinalArgs = numAggTransFnArgs + 1;
3902 else
3903 peragg->numFinalArgs = numDirectArgs + 1;
3904
3905 /* Initialize any direct-argument expressions */
3907 (PlanState *) aggstate);
3908
3909 /*
3910 * build expression trees using actual argument & result types for the
3911 * finalfn, if it exists and is required.
3912 */
3913 if (OidIsValid(finalfn_oid))
3914 {
3915 build_aggregate_finalfn_expr(aggTransFnInputTypes,
3916 peragg->numFinalArgs,
3917 aggtranstype,
3918 aggref->aggtype,
3919 aggref->inputcollid,
3920 finalfn_oid,
3921 &finalfnexpr);
3922 fmgr_info(finalfn_oid, &peragg->finalfn);
3923 fmgr_info_set_expr((Node *) finalfnexpr, &peragg->finalfn);
3924 }
3925
3926 /* get info about the output value's datatype */
3927 get_typlenbyval(aggref->aggtype,
3928 &peragg->resulttypeLen,
3929 &peragg->resulttypeByVal);
3930
3931 /*
3932 * Build working state for invoking the transition function, if we
3933 * haven't done it already.
3934 */
3935 pertrans = &pertransstates[aggref->aggtransno];
3936 if (pertrans->aggref == NULL)
3937 {
3938 Datum textInitVal;
3940 bool initValueIsNull;
3941 Oid transfn_oid;
3942
3943 /*
3944 * If this aggregation is performing state combines, then instead
3945 * of using the transition function, we'll use the combine
3946 * function.
3947 */
3948 if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3949 {
3950 transfn_oid = aggform->aggcombinefn;
3951
3952 /* If not set then the planner messed up */
3953 if (!OidIsValid(transfn_oid))
3954 elog(ERROR, "combinefn not set for aggregate function");
3955 }
3956 else
3957 transfn_oid = aggform->aggtransfn;
3958
3959 aclresult = object_aclcheck(ProcedureRelationId, transfn_oid, aggOwner, ACL_EXECUTE);
3960 if (aclresult != ACLCHECK_OK)
3962 get_func_name(transfn_oid));
3963 InvokeFunctionExecuteHook(transfn_oid);
3964
3965 /*
3966 * initval is potentially null, so don't try to access it as a
3967 * struct field. Must do it the hard way with SysCacheGetAttr.
3968 */
3969 textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
3970 Anum_pg_aggregate_agginitval,
3971 &initValueIsNull);
3972 if (initValueIsNull)
3973 initValue = (Datum) 0;
3974 else
3975 initValue = GetAggInitVal(textInitVal, aggtranstype);
3976
3977 if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3978 {
3979 Oid combineFnInputTypes[] = {aggtranstype,
3980 aggtranstype};
3981
3982 /*
3983 * When combining there's only one input, the to-be-combined
3984 * transition value. The transition value is not counted
3985 * here.
3986 */
3987 pertrans->numTransInputs = 1;
3988
3989 /* aggcombinefn always has two arguments of aggtranstype */
3990 build_pertrans_for_aggref(pertrans, aggstate, estate,
3991 aggref, transfn_oid, aggtranstype,
3992 serialfn_oid, deserialfn_oid,
3993 initValue, initValueIsNull,
3994 combineFnInputTypes, 2);
3995
3996 /*
3997 * Ensure that a combine function to combine INTERNAL states
3998 * is not strict. This should have been checked during CREATE
3999 * AGGREGATE, but the strict property could have been changed
4000 * since then.
4001 */
4002 if (pertrans->transfn.fn_strict && aggtranstype == INTERNALOID)
4003 ereport(ERROR,
4004 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
4005 errmsg("combine function with transition type %s must not be declared STRICT",
4006 format_type_be(aggtranstype))));
4007 }
4008 else
4009 {
4010 /* Detect how many arguments to pass to the transfn */
4011 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
4012 pertrans->numTransInputs = list_length(aggref->args);
4013 else
4014 pertrans->numTransInputs = numAggTransFnArgs;
4015
4016 build_pertrans_for_aggref(pertrans, aggstate, estate,
4017 aggref, transfn_oid, aggtranstype,
4018 serialfn_oid, deserialfn_oid,
4019 initValue, initValueIsNull,
4020 aggTransFnInputTypes,
4021 numAggTransFnArgs);
4022
4023 /*
4024 * If the transfn is strict and the initval is NULL, make sure
4025 * input type and transtype are the same (or at least
4026 * binary-compatible), so that it's OK to use the first
4027 * aggregated input value as the initial transValue. This
4028 * should have been checked at agg definition time, but we
4029 * must check again in case the transfn's strictness property
4030 * has been changed.
4031 */
4032 if (pertrans->transfn.fn_strict && pertrans->initValueIsNull)
4033 {
4034 if (numAggTransFnArgs <= numDirectArgs ||
4035 !IsBinaryCoercible(aggTransFnInputTypes[numDirectArgs],
4036 aggtranstype))
4037 ereport(ERROR,
4038 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
4039 errmsg("aggregate %u needs to have compatible input type and transition type",
4040 aggref->aggfnoid)));
4041 }
4042 }
4043 }
4044 else
4045 pertrans->aggshared = true;
4046 ReleaseSysCache(aggTuple);
4047 }
4048
4049 /*
4050 * Last, check whether any more aggregates got added onto the node while
4051 * we processed the expressions for the aggregate arguments (including not
4052 * only the regular arguments and FILTER expressions handled immediately
4053 * above, but any direct arguments we might've handled earlier). If so,
4054 * we have nested aggregate functions, which is semantically nonsensical,
4055 * so complain. (This should have been caught by the parser, so we don't
4056 * need to work hard on a helpful error message; but we defend against it
4057 * here anyway, just to be sure.)
4058 */
4059 if (numaggrefs != list_length(aggstate->aggs))
4060 ereport(ERROR,
4061 (errcode(ERRCODE_GROUPING_ERROR),
4062 errmsg("aggregate function calls cannot be nested")));
4063
4064 /*
4065 * Build expressions doing all the transition work at once. We build a
4066 * different one for each phase, as the number of transition function
4067 * invocation can differ between phases. Note this'll work both for
4068 * transition and combination functions (although there'll only be one
4069 * phase in the latter case).
4070 */
4071 for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
4072 {
4073 AggStatePerPhase phase = &aggstate->phases[phaseidx];
4074 bool dohash = false;
4075 bool dosort = false;
4076
4077 /* phase 0 doesn't necessarily exist */
4078 if (!phase->aggnode)
4079 continue;
4080
4081 if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
4082 {
4083 /*
4084 * Phase one, and only phase one, in a mixed agg performs both
4085 * sorting and aggregation.
4086 */
4087 dohash = true;
4088 dosort = true;
4089 }
4090 else if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 0)
4091 {
4092 /*
4093 * No need to compute a transition function for an AGG_MIXED phase
4094 * 0 - the contents of the hashtables will have been computed
4095 * during phase 1.
4096 */
4097 continue;
4098 }
4099 else if (phase->aggstrategy == AGG_PLAIN ||
4100 phase->aggstrategy == AGG_SORTED)
4101 {
4102 dohash = false;
4103 dosort = true;
4104 }
4105 else if (phase->aggstrategy == AGG_HASHED)
4106 {
4107 dohash = true;
4108 dosort = false;
4109 }
4110 else
4111 Assert(false);
4112
4113 phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
4114 false);
4115
4116 /* cache compiled expression for outer slot without NULL check */
4117 phase->evaltrans_cache[0][0] = phase->evaltrans;
4118 }
4119
4120 return aggstate;
4121}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2639
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3821
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
uint64_t uint64
Definition: c.h:503
#define OidIsValid(objectId)
Definition: c.h:746
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:229
List * ExecInitExprList(List *nodes, PlanState *parent)
Definition: execExpr.c:335
ExprState * ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase, bool doSort, bool doHash, bool nullcheck)
Definition: execExpr.c:3677
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:58
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2020
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1988
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
void ExecCreateScanSlotFromOuterPlan(EState *estate, ScanState *scanstate, const TupleTableSlotOps *tts_ops)
Definition: execUtils.c:705
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:486
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:584
const TupleTableSlotOps * ExecGetResultSlotOps(PlanState *planstate, bool *isfixed)
Definition: execUtils.c:505
struct AggStatePerGroupData * AggStatePerGroup
Definition: execnodes.h:2521
struct AggStatePerTransData * AggStatePerTrans
Definition: execnodes.h:2520
struct AggStatePerAggData * AggStatePerAgg
Definition: execnodes.h:2519
#define EXEC_FLAG_BACKWARD
Definition: executor.h:69
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:66
#define EXEC_FLAG_MARK
Definition: executor.h:70
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
static int initValue(long lng_val)
Definition: informix.c:702
int j
Definition: isn.c:78
int i
Definition: isn.c:77
List * lcons_int(int datum, List *list)
Definition: list.c:513
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2391
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1748
void * palloc0(Size size)
Definition: mcxt.c:1969
Oid GetUserId(void)
Definition: miscinit.c:520
static void find_hash_columns(AggState *aggstate)
Definition: nodeAgg.c:1570
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
Definition: nodeAgg.c:4384
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:479
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1701
static void build_pertrans_for_aggref(AggStatePerTrans pertrans, AggState *aggstate, EState *estate, Aggref *aggref, Oid transfn_oid, Oid aggtranstype, Oid aggserialfn, Oid aggdeserialfn, Datum initValue, bool initValueIsNull, Oid *inputTypes, int numArguments)
Definition: nodeAgg.c:4134
static TupleTableSlot * ExecAgg(PlanState *pstate)
Definition: nodeAgg.c:2244
static void build_hash_tables(AggState *aggstate)
Definition: nodeAgg.c:1466
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:457
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:1809
static void hash_create_memory(AggState *aggstate)
Definition: nodeAgg.c:2000
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:392
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:394
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:391
@ AGG_SORTED
Definition: nodes.h:361
@ AGG_HASHED
Definition: nodes.h:362
@ AGG_MIXED
Definition: nodes.h:363
@ AGG_PLAIN
Definition: nodes.h:360
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:393
#define makeNode(_type_)
Definition: nodes.h:161
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
#define InvokeFunctionExecuteHook(objectId)
Definition: objectaccess.h:213
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:2234
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1997
bool IsBinaryCoercible(Oid srctype, Oid targettype)
@ OBJECT_AGGREGATE
Definition: parsenodes.h:2318
@ OBJECT_FUNCTION
Definition: parsenodes.h:2336
#define ACL_EXECUTE
Definition: parsenodes.h:83
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
#define FUNC_MAX_ARGS
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define list_nth_node(type, list, n)
Definition: pg_list.h:327
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
uintptr_t Datum
Definition: postgres.h:69
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
FmgrInfo finalfn
Definition: nodeAgg.h:207
bool resulttypeByVal
Definition: nodeAgg.h:225
List * aggdirectargs
Definition: nodeAgg.h:218
Aggref * aggref
Definition: nodeAgg.h:195
int16 resulttypeLen
Definition: nodeAgg.h:224
Bitmapset ** grouped_cols
Definition: nodeAgg.h:285
ExprState * evaltrans
Definition: nodeAgg.h:291
ExprState * evaltrans_cache[2][2]
Definition: nodeAgg.h:299
ExprState ** eqfunctions
Definition: nodeAgg.h:286
AggStrategy aggstrategy
Definition: nodeAgg.h:282
FmgrInfo transfn
Definition: nodeAgg.h:86
Aggref * aggref
Definition: nodeAgg.h:44
AggStatePerGroup * all_pergroups
Definition: execnodes.h:2597
AggStatePerGroup * hash_pergroup
Definition: execnodes.h:2592
List * aggs
Definition: execnodes.h:2528
ExprContext * tmpcontext
Definition: execnodes.h:2540
int hash_planned_partitions
Definition: execnodes.h:2582
HeapTuple grp_firstTuple
Definition: execnodes.h:2565
Size hash_mem_limit
Definition: execnodes.h:2580
AggStatePerTrans curpertrans
Definition: execnodes.h:2545
bool table_filled
Definition: execnodes.h:2567
int current_set
Definition: execnodes.h:2550
AggStrategy aggstrategy
Definition: execnodes.h:2531
AggSplit aggsplit
Definition: execnodes.h:2532
int projected_set
Definition: execnodes.h:2548
uint64 hash_ngroups_limit
Definition: execnodes.h:2581
bool input_done
Definition: execnodes.h:2546
AggStatePerPhase phases
Definition: execnodes.h:2558
List * all_grouped_cols
Definition: execnodes.h:2552
AggStatePerGroup * pergroups
Definition: execnodes.h:2563
AggStatePerHash perhash
Definition: execnodes.h:2591
double hashentrysize
Definition: execnodes.h:2584
int numphases
Definition: execnodes.h:2534
TupleTableSlot * hash_spill_wslot
Definition: execnodes.h:2575
AggStatePerAgg curperagg
Definition: execnodes.h:2543
TupleTableSlot * sort_slot
Definition: execnodes.h:2561
int numaggs
Definition: execnodes.h:2529
int num_hashes
Definition: execnodes.h:2568
AggStatePerAgg peragg
Definition: execnodes.h:2536
TupleTableSlot * hash_spill_rslot
Definition: execnodes.h:2574
int current_phase
Definition: execnodes.h:2535
bool agg_done
Definition: execnodes.h:2547
AggSplit aggsplit
Definition: plannodes.h:1146
List * chain
Definition: plannodes.h:1173
long numGroups
Definition: plannodes.h:1159
List * groupingSets
Definition: plannodes.h:1170
Plan plan
Definition: plannodes.h:1140
int numCols
Definition: plannodes.h:1149
uint64 transitionSpace
Definition: plannodes.h:1162
AggStrategy aggstrategy
Definition: plannodes.h:1143
Oid aggfnoid
Definition: primnodes.h:461
List * aggdirectargs
Definition: primnodes.h:482
List * args
Definition: primnodes.h:485
Datum * ecxt_aggvalues
Definition: execnodes.h:287
bool * ecxt_aggnulls
Definition: execnodes.h:289
bool fn_strict
Definition: fmgr.h:61
Definition: nodes.h:135
bool outeropsset
Definition: execnodes.h:1242
const TupleTableSlotOps * outerops
Definition: execnodes.h:1234
ExprState * qual
Definition: execnodes.h:1180
bool outeropsfixed
Definition: execnodes.h:1238
EState * state
Definition: execnodes.h:1161
ExprContext * ps_ExprContext
Definition: execnodes.h:1198
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1165
List * qual
Definition: plannodes.h:211
int plan_width
Definition: plannodes.h:187
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1618
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, AggState::agg_done, AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, AggState::aggcontexts, AggStatePerAggData::aggdirectargs, Aggref::aggdirectargs, Aggref::aggfnoid, AggStatePerPhaseData::aggnode, AggStatePerHashData::aggnode, AggStatePerTransData::aggref, AggStatePerAggData::aggref, AggState::aggs, AggStatePerTransData::aggshared, AggState::aggsplit, Agg::aggsplit, AggStatePerPhaseData::aggstrategy, AggState::aggstrategy, Agg::aggstrategy, AggState::all_grouped_cols, AggState::all_pergroups, Aggref::args, Assert(), bms_add_member(), bms_add_members(), bms_next_member(), build_aggregate_finalfn_expr(), build_hash_tables(), build_pertrans_for_aggref(), castNode, Agg::chain, AggState::curperagg, 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, ereport, errcode(), errmsg(), ERROR, AggStatePerPhaseData::evaltrans, AggStatePerPhaseData::evaltrans_cache, EXEC_FLAG_BACKWARD, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_MARK, ExecAgg(), ExecAssignExprContext(), ExecAssignProjectionInfo(), ExecBuildAggTrans(), ExecCreateScanSlotFromOuterPlan(), ExecGetResultSlotOps(), ExecInitExprList(), ExecInitExtraTupleSlot(), ExecInitNode(), ExecInitQual(), ExecInitResultTupleSlotTL(), PlanState::ExecProcNode, execTuplesMatchPrepare(), AggStatePerAggData::finalfn, AggStatePerAggData::finalfn_oid, find_hash_columns(), fmgr_info(), fmgr_info_set_expr, FmgrInfo::fn_strict, format_type_be(), FUNC_MAX_ARGS, get_aggregate_argtypes(), get_func_name(), get_typlenbyval(), GetAggInitVal(), GETSTRUCT(), GetUserId(), AggStatePerPhaseData::grouped_cols, Agg::groupingSets, AggState::grp_firstTuple, AggStatePerPhaseData::gset_lengths, hash_agg_entry_size(), hash_agg_set_limits(), AggState::hash_batches_used, hash_create_memory(), AggState::hash_mem_limit, AggState::hash_ngroups_limit, AggState::hash_pergroup, AggState::hash_planned_partitions, AggState::hash_spill_rslot, AggState::hash_spill_wslot, AggState::hashentrysize, HeapTupleIsValid, i, initialize_phase(), initValue(), AggStatePerTransData::initValueIsNull, AggState::input_done, InvalidOid, InvokeFunctionExecuteHook, IsBinaryCoercible(), j, lcons_int(), lfirst, list_length(), list_nth_node, makeNode, Max, AggState::maxsets, NIL, AggState::num_hashes, AggState::numaggs, AggStatePerHashData::numCols, Agg::numCols, AggStatePerAggData::numFinalArgs, Agg::numGroups, AggState::numphases, AggStatePerPhaseData::numsets, AggState::numtrans, AggStatePerTransData::numTransInputs, object_aclcheck(), OBJECT_AGGREGATE, OBJECT_FUNCTION, ObjectIdGetDatum(), OidIsValid, PlanState::outerops, PlanState::outeropsfixed, PlanState::outeropsset, outerPlan, outerPlanState, palloc(), palloc0(), AggState::peragg, AggState::pergroups, AggState::perhash, AggState::pertrans, AggState::phases, PlanState::plan, Agg::plan, Plan::plan_width, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, PlanState::qual, Plan::qual, ReleaseSysCache(), 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, AggStatePerTransData::transfn, Agg::transitionSpace, AggStatePerAggData::transno, TupleTableSlot::tts_tupleDescriptor, TTSOpsMinimalTuple, and TTSOpsVirtual.

Referenced by ExecInitNode().

◆ ExecReScanAgg()

void ExecReScanAgg ( AggState node)

Definition at line 4466 of file nodeAgg.c.

4467{
4468 ExprContext *econtext = node->ss.ps.ps_ExprContext;
4470 Agg *aggnode = (Agg *) node->ss.ps.plan;
4471 int transno;
4472 int numGroupingSets = Max(node->maxsets, 1);
4473 int setno;
4474
4475 node->agg_done = false;
4476
4477 if (node->aggstrategy == AGG_HASHED)
4478 {
4479 /*
4480 * In the hashed case, if we haven't yet built the hash table then we
4481 * can just return; nothing done yet, so nothing to undo. If subnode's
4482 * chgParam is not NULL then it will be re-scanned by ExecProcNode,
4483 * else no reason to re-scan it at all.
4484 */
4485 if (!node->table_filled)
4486 return;
4487
4488 /*
4489 * If we do have the hash table, and it never spilled, and the subplan
4490 * does not have any parameter changes, and none of our own parameter
4491 * changes affect input expressions of the aggregated functions, then
4492 * we can just rescan the existing hash table; no need to build it
4493 * again.
4494 */
4495 if (outerPlan->chgParam == NULL && !node->hash_ever_spilled &&
4496 !bms_overlap(node->ss.ps.chgParam, aggnode->aggParams))
4497 {
4499 &node->perhash[0].hashiter);
4500 select_current_set(node, 0, true);
4501 return;
4502 }
4503 }
4504
4505 /* Make sure we have closed any open tuplesorts */
4506 for (transno = 0; transno < node->numtrans; transno++)
4507 {
4508 for (setno = 0; setno < numGroupingSets; setno++)
4509 {
4510 AggStatePerTrans pertrans = &node->pertrans[transno];
4511
4512 if (pertrans->sortstates[setno])
4513 {
4514 tuplesort_end(pertrans->sortstates[setno]);
4515 pertrans->sortstates[setno] = NULL;
4516 }
4517 }
4518 }
4519
4520 /*
4521 * We don't need to ReScanExprContext the output tuple context here;
4522 * ExecReScan already did it. But we do need to reset our per-grouping-set
4523 * contexts, which may have transvalues stored in them. (We use rescan
4524 * rather than just reset because transfns may have registered callbacks
4525 * that need to be run now.) For the AGG_HASHED case, see below.
4526 */
4527
4528 for (setno = 0; setno < numGroupingSets; setno++)
4529 {
4530 ReScanExprContext(node->aggcontexts[setno]);
4531 }
4532
4533 /* Release first tuple of group, if we have made a copy */
4534 if (node->grp_firstTuple != NULL)
4535 {
4537 node->grp_firstTuple = NULL;
4538 }
4540
4541 /* Forget current agg values */
4542 MemSet(econtext->ecxt_aggvalues, 0, sizeof(Datum) * node->numaggs);
4543 MemSet(econtext->ecxt_aggnulls, 0, sizeof(bool) * node->numaggs);
4544
4545 /*
4546 * With AGG_HASHED/MIXED, the hash table is allocated in a sub-context of
4547 * the hashcontext. This used to be an issue, but now, resetting a context
4548 * automatically deletes sub-contexts too.
4549 */
4550 if (node->aggstrategy == AGG_HASHED || node->aggstrategy == AGG_MIXED)
4551 {
4553
4554 node->hash_ever_spilled = false;
4555 node->hash_spill_mode = false;
4556 node->hash_ngroups_current = 0;
4557
4560 /* Rebuild an empty hash table */
4561 build_hash_tables(node);
4562 node->table_filled = false;
4563 /* iterator will be reset when the table is filled */
4564
4565 hashagg_recompile_expressions(node, false, false);
4566 }
4567
4568 if (node->aggstrategy != AGG_HASHED)
4569 {
4570 /*
4571 * Reset the per-group state (in particular, mark transvalues null)
4572 */
4573 for (setno = 0; setno < numGroupingSets; setno++)
4574 {
4575 MemSet(node->pergroups[setno], 0,
4576 sizeof(AggStatePerGroupData) * node->numaggs);
4577 }
4578
4579 /* reset to phase 1 */
4580 initialize_phase(node, 1);
4581
4582 node->input_done = false;
4583 node->projected_set = -1;
4584 }
4585
4586 if (outerPlan->chgParam == NULL)
4588}
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
#define MemSet(start, val, len)
Definition: c.h:991
void ExecReScan(PlanState *node)
Definition: execAmi.c:77
#define ResetTupleHashIterator(htable, iter)
Definition: execnodes.h:891
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:414
static void hashagg_recompile_expressions(AggState *aggstate, bool minslot, bool nullcheck)
Definition: nodeAgg.c:1752
TupleHashTable hashtable
Definition: nodeAgg.h:311
TupleHashIterator hashiter
Definition: nodeAgg.h:312
bool hash_spill_mode
Definition: execnodes.h:2578
uint64 hash_ngroups_current
Definition: execnodes.h:2586
bool hash_ever_spilled
Definition: execnodes.h:2577
Bitmapset * aggParams
Definition: plannodes.h:1165
Bitmapset * chgParam
Definition: execnodes.h:1191
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458

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, AggState::hash_tablecxt, hashagg_recompile_expressions(), hashagg_reset_spill_state(), AggState::hashcontext, AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, heap_freetuple(), initialize_phase(), AggState::input_done, Max, AggState::maxsets, MemoryContextReset(), 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().

◆ hash_agg_entry_size()

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

Definition at line 1701 of file nodeAgg.c.

1702{
1703 Size tupleChunkSize;
1704 Size pergroupChunkSize;
1705 Size transitionChunkSize;
1706 Size tupleSize = (MAXALIGN(SizeofMinimalTupleHeader) +
1707 tupleWidth);
1708 Size pergroupSize = numTrans * sizeof(AggStatePerGroupData);
1709
1710 /*
1711 * Entries use the Bump allocator, so the chunk sizes are the same as the
1712 * requested sizes.
1713 */
1714 tupleChunkSize = MAXALIGN(tupleSize);
1715 pergroupChunkSize = pergroupSize;
1716
1717 /*
1718 * Transition values use AllocSet, which has a chunk header and also uses
1719 * power-of-two allocations.
1720 */
1721 if (transitionSpace > 0)
1722 transitionChunkSize = CHUNKHDRSZ + pg_nextpower2_size_t(transitionSpace);
1723 else
1724 transitionChunkSize = 0;
1725
1726 return
1728 tupleChunkSize +
1729 pergroupChunkSize +
1730 transitionChunkSize;
1731}
#define MAXALIGN(LEN)
Definition: c.h:782
static size_t TupleHashEntrySize(void)
Definition: executor.h:166
#define SizeofMinimalTupleHeader
Definition: htup_details.h:699
#define CHUNKHDRSZ
Definition: nodeAgg.c:321
struct AggStatePerGroupData AggStatePerGroupData
#define pg_nextpower2_size_t
Definition: pg_bitutils.h:441

References CHUNKHDRSZ, MAXALIGN, pg_nextpower2_size_t, SizeofMinimalTupleHeader, and TupleHashEntrySize().

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

◆ 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 1809 of file nodeAgg.c.

1812{
1813 int npartitions;
1814 Size partition_mem;
1815 Size hash_mem_limit = get_hash_memory_limit();
1816
1817 /* if not expected to spill, use all of hash_mem */
1818 if (input_groups * hashentrysize <= hash_mem_limit)
1819 {
1820 if (num_partitions != NULL)
1821 *num_partitions = 0;
1822 *mem_limit = hash_mem_limit;
1823 *ngroups_limit = hash_mem_limit / hashentrysize;
1824 return;
1825 }
1826
1827 /*
1828 * Calculate expected memory requirements for spilling, which is the size
1829 * of the buffers needed for all the tapes that need to be open at once.
1830 * Then, subtract that from the memory available for holding hash tables.
1831 */
1832 npartitions = hash_choose_num_partitions(input_groups,
1833 hashentrysize,
1834 used_bits,
1835 NULL);
1836 if (num_partitions != NULL)
1837 *num_partitions = npartitions;
1838
1839 partition_mem =
1841 HASHAGG_WRITE_BUFFER_SIZE * npartitions;
1842
1843 /*
1844 * Don't set the limit below 3/4 of hash_mem. In that case, we are at the
1845 * minimum number of partitions, so we aren't going to dramatically exceed
1846 * work mem anyway.
1847 */
1848 if (hash_mem_limit > 4 * partition_mem)
1849 *mem_limit = hash_mem_limit - partition_mem;
1850 else
1851 *mem_limit = hash_mem_limit * 0.75;
1852
1853 if (*mem_limit > hashentrysize)
1854 *ngroups_limit = *mem_limit / hashentrysize;
1855 else
1856 *ngroups_limit = 1;
1857}
#define HASHAGG_READ_BUFFER_SIZE
Definition: nodeAgg.c:307
#define HASHAGG_WRITE_BUFFER_SIZE
Definition: nodeAgg.c:308
static int hash_choose_num_partitions(double input_groups, double hashentrysize, int used_bits, int *log2_npartitions)
Definition: nodeAgg.c:2083
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3616

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

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