PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 
)
extern

Definition at line 4781 of file nodeAgg.c.

4782{
4783 Size size;
4784
4785 /* don't need this if not instrumenting or no workers */
4786 if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4787 return;
4788
4789 size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4790 size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4791 shm_toc_estimate_chunk(&pcxt->estimator, size);
4793}
size_t Size
Definition c.h:691
static int fb(int x)
#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:485
Size mul_size(Size s1, Size s2)
Definition shmem.c:500
ScanState ss
Definition execnodes.h:2404
shm_toc_estimator estimator
Definition parallel.h:43
Instrumentation * instrument
Definition execnodes.h:1187
PlanState ps
Definition execnodes.h:1633

References add_size(), ParallelContext::estimator, fb(), 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 
)
extern

Definition at line 4802 of file nodeAgg.c.

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

References fb(), 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 
)
extern

Definition at line 4827 of file nodeAgg.c.

4828{
4829 node->shared_info =
4830 shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
4831}
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition shm_toc.c:232

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

Referenced by ExecParallelInitializeWorker().

◆ ExecAggRetrieveInstrumentation()

void ExecAggRetrieveInstrumentation ( AggState node)
extern

Definition at line 4840 of file nodeAgg.c.

4841{
4842 Size size;
4844
4845 if (node->shared_info == NULL)
4846 return;
4847
4848 size = offsetof(SharedAggInfo, sinstrument)
4850 si = palloc(size);
4851 memcpy(si, node->shared_info, size);
4852 node->shared_info = si;
4853}
void * palloc(Size size)
Definition mcxt.c:1387

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)
extern

Definition at line 4396 of file nodeAgg.c.

4397{
4399 int transno;
4400 int numGroupingSets = Max(node->maxsets, 1);
4401 int setno;
4402
4403 /*
4404 * When ending a parallel worker, copy the statistics gathered by the
4405 * worker back into shared memory so that it can be picked up by the main
4406 * process to report in EXPLAIN ANALYZE.
4407 */
4408 if (node->shared_info && IsParallelWorker())
4409 {
4411
4412 Assert(ParallelWorkerNumber < node->shared_info->num_workers);
4415 si->hash_disk_used = node->hash_disk_used;
4416 si->hash_mem_peak = node->hash_mem_peak;
4417 }
4418
4419 /* Make sure we have closed any open tuplesorts */
4420
4421 if (node->sort_in)
4422 tuplesort_end(node->sort_in);
4423 if (node->sort_out)
4424 tuplesort_end(node->sort_out);
4425
4427
4428 /* Release hash tables too */
4429 if (node->hash_metacxt != NULL)
4430 {
4432 node->hash_metacxt = NULL;
4433 }
4434 if (node->hash_tuplescxt != NULL)
4435 {
4437 node->hash_tuplescxt = NULL;
4438 }
4439
4440 for (transno = 0; transno < node->numtrans; transno++)
4441 {
4442 AggStatePerTrans pertrans = &node->pertrans[transno];
4443
4444 for (setno = 0; setno < numGroupingSets; setno++)
4445 {
4446 if (pertrans->sortstates[setno])
4447 tuplesort_end(pertrans->sortstates[setno]);
4448 }
4449 }
4450
4451 /* And ensure any agg shutdown callbacks have been called */
4452 for (setno = 0; setno < numGroupingSets; setno++)
4453 ReScanExprContext(node->aggcontexts[setno]);
4454 if (node->hashcontext)
4456
4457 outerPlan = outerPlanState(node);
4459}
int ParallelWorkerNumber
Definition parallel.c:117
#define Max(x, y)
Definition c.h:1087
#define Assert(condition)
Definition c.h:945
void ExecEndNode(PlanState *node)
void ReScanExprContext(ExprContext *econtext)
Definition execUtils.c:448
#define outerPlanState(node)
Definition execnodes.h:1273
#define IsParallelWorker()
Definition parallel.h:62
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
static void hashagg_reset_spill_state(AggState *aggstate)
Definition nodeAgg.c:3241
#define outerPlan(node)
Definition plannodes.h:265
Tuplesortstate ** sortstates
Definition nodeAgg.h:162
MemoryContext hash_metacxt
Definition execnodes.h:2446
Tuplesortstate * sort_out
Definition execnodes.h:2437
uint64 hash_disk_used
Definition execnodes.h:2465
MemoryContext hash_tuplescxt
Definition execnodes.h:2447
AggStatePerTrans pertrans
Definition execnodes.h:2414
int numtrans
Definition execnodes.h:2407
ExprContext * hashcontext
Definition execnodes.h:2415
Size hash_mem_peak
Definition execnodes.h:2462
int hash_batches_used
Definition execnodes.h:2466
Tuplesortstate * sort_in
Definition execnodes.h:2436
int maxsets
Definition execnodes.h:2434
ExprContext ** aggcontexts
Definition execnodes.h:2416
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
void tuplesort_end(Tuplesortstate *state)
Definition tuplesort.c:847

References AggState::aggcontexts, Assert, ExecEndNode(), fb(), AggregateInstrumentation::hash_batches_used, AggState::hash_batches_used, AggState::hash_disk_used, AggState::hash_mem_peak, AggState::hash_metacxt, AggState::hash_tuplescxt, 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 
)
extern

Definition at line 3281 of file nodeAgg.c.

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

References ACL_EXECUTE, aclcheck_error(), ACLCHECK_OK, AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, AggStatePerAggData::aggdirectargs, Aggref::aggdirectargs, Aggref::aggfnoid, AggStatePerPhaseData::aggnode, AggStatePerHashData::aggnode, AggStatePerTransData::aggref, AggStatePerAggData::aggref, AggStatePerTransData::aggshared, Agg::aggsplit, AggStatePerPhaseData::aggstrategy, Agg::aggstrategy, 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, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_DESERIALIZE, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, elog, 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(), execTuplesMatchPrepare(), fb(), AggStatePerAggData::finalfn, AggStatePerAggData::finalfn_oid, find_hash_columns(), fmgr_info(), fmgr_info_set_expr, FmgrInfo::fn_strict, Form_pg_aggregate, Form_pg_proc, format_type_be(), FUNC_MAX_ARGS, get_aggregate_argtypes(), get_func_name(), get_typlenbyval(), GetAggInitVal(), GETSTRUCT(), GetUserId(), Agg::groupingSets, hash_agg_entry_size(), hash_agg_set_limits(), hash_create_memory(), HeapTupleIsValid, i, initialize_phase(), initValue(), AggStatePerTransData::initValueIsNull, InvalidOid, InvokeFunctionExecuteHook, IsBinaryCoercible(), j, lcons_int(), lfirst, list_length(), list_nth_node, makeNode, Max, NIL, AggStatePerHashData::numCols, Agg::numCols, AggStatePerAggData::numFinalArgs, AggStatePerPhaseData::numsets, AggStatePerTransData::numTransInputs, object_aclcheck(), OBJECT_AGGREGATE, OBJECT_FUNCTION, ObjectIdGetDatum(), OidIsValid, outerPlan, outerPlanState, palloc(), palloc0_array, palloc_array, Agg::plan, Plan::qual, ReleaseSysCache(), AggStatePerAggData::resulttypeByVal, AggStatePerAggData::resulttypeLen, SearchSysCache1(), select_current_set(), SysCacheGetAttr(), AggStatePerTransData::transfn, Agg::transitionSpace, AggStatePerAggData::transno, TTSOpsMinimalTuple, and TTSOpsVirtual.

Referenced by ExecInitNode().

◆ ExecReScanAgg()

void ExecReScanAgg ( AggState node)
extern

Definition at line 4462 of file nodeAgg.c.

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

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(), fb(), AggState::grp_firstTuple, AggState::hash_ever_spilled, AggState::hash_ngroups_current, AggState::hash_spill_mode, hashagg_recompile_expressions(), hashagg_reset_spill_state(), AggState::hashcontext, AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, heap_freetuple(), initialize_phase(), AggState::input_done, Max, AggState::maxsets, MemSet, AggState::numaggs, AggState::numtrans, outerPlan, outerPlanState, AggState::pergroups, AggState::perhash, AggState::pertrans, PlanState::plan, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, ReScanExprContext(), ResetTupleHashIterator, select_current_set(), AggStatePerTransData::sortstates, AggState::ss, ScanState::ss_ScanTupleSlot, AggState::table_filled, and tuplesort_end().

Referenced by ExecReScan().

◆ hash_agg_entry_size()

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

Definition at line 1700 of file nodeAgg.c.

1701{
1706 tupleWidth);
1708
1709 /*
1710 * Entries use the Bump allocator, so the chunk sizes are the same as the
1711 * requested sizes.
1712 */
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)
1722 else
1724
1725 return
1730}
#define MAXALIGN(LEN)
Definition c.h:898
static size_t TupleHashEntrySize(void)
Definition executor.h:170
#define SizeofMinimalTupleHeader
#define CHUNKHDRSZ
Definition nodeAgg.c:322
#define pg_nextpower2_size_t

References CHUNKHDRSZ, fb(), 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 
)
extern

Definition at line 1808 of file nodeAgg.c.

1811{
1812 int npartitions;
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 */
1832 hashentrysize,
1833 used_bits,
1834 NULL);
1835 if (num_partitions != NULL)
1836 *num_partitions = npartitions;
1837
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:308
#define HASHAGG_WRITE_BUFFER_SIZE
Definition nodeAgg.c:309
static int hash_choose_num_partitions(double input_groups, double hashentrysize, int used_bits, int *log2_npartitions)
Definition nodeAgg.c:2086
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680

References fb(), 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().