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

4786{
4787 Size size;
4788
4789 /* don't need this if not instrumenting or no workers */
4790 if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4791 return;
4792
4793 size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4794 size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4795 shm_toc_estimate_chunk(&pcxt->estimator, size);
4797}
size_t Size
Definition: c.h:610
#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 4806 of file nodeAgg.c.

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

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

4832{
4833 node->shared_info =
4834 shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
4835}
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 4844 of file nodeAgg.c.

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

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)

Definition at line 4399 of file nodeAgg.c.

4400{
4402 int transno;
4403 int numGroupingSets = Max(node->maxsets, 1);
4404 int setno;
4405
4406 /*
4407 * When ending a parallel worker, copy the statistics gathered by the
4408 * worker back into shared memory so that it can be picked up by the main
4409 * process to report in EXPLAIN ANALYZE.
4410 */
4411 if (node->shared_info && IsParallelWorker())
4412 {
4414
4415 Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
4418 si->hash_disk_used = node->hash_disk_used;
4419 si->hash_mem_peak = node->hash_mem_peak;
4420 }
4421
4422 /* Make sure we have closed any open tuplesorts */
4423
4424 if (node->sort_in)
4425 tuplesort_end(node->sort_in);
4426 if (node->sort_out)
4427 tuplesort_end(node->sort_out);
4428
4430
4431 if (node->hash_metacxt != NULL)
4432 {
4434 node->hash_metacxt = NULL;
4435 }
4436 if (node->hash_tablecxt != NULL)
4437 {
4439 node->hash_tablecxt = NULL;
4440 }
4441
4442
4443 for (transno = 0; transno < node->numtrans; transno++)
4444 {
4445 AggStatePerTrans pertrans = &node->pertrans[transno];
4446
4447 for (setno = 0; setno < numGroupingSets; setno++)
4448 {
4449 if (pertrans->sortstates[setno])
4450 tuplesort_end(pertrans->sortstates[setno]);
4451 }
4452 }
4453
4454 /* And ensure any agg shutdown callbacks have been called */
4455 for (setno = 0; setno < numGroupingSets; setno++)
4456 ReScanExprContext(node->aggcontexts[setno]);
4457 if (node->hashcontext)
4459
4460 outerPlan = outerPlanState(node);
4462}
int ParallelWorkerNumber
Definition: parallel.c:115
#define Max(x, y)
Definition: c.h:997
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:443
#define outerPlanState(node)
Definition: execnodes.h:1255
Assert(PointerIsAligned(start, uint64))
#define IsParallelWorker()
Definition: parallel.h:60
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
static void hashagg_reset_spill_state(AggState *aggstate)
Definition: nodeAgg.c:3238
#define outerPlan(node)
Definition: plannodes.h:252
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:947

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

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

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

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

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

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

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

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().