PostgreSQL Source Code git master
nodeAgg.h File Reference
#include "access/parallel.h"
#include "nodes/execnodes.h"
Include dependency graph for nodeAgg.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  AggStatePerTransData
 
struct  AggStatePerAggData
 
struct  AggStatePerGroupData
 
struct  AggStatePerPhaseData
 
struct  AggStatePerHashData
 

Macros

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

Typedefs

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

Functions

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

Macro Definition Documentation

◆ FIELDNO_AGGSTATEPERGROUPDATA_NOTRANSVALUE

#define FIELDNO_AGGSTATEPERGROUPDATA_NOTRANSVALUE   2

Definition at line 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 4779 of file nodeAgg.c.

4780{
4781 Size size;
4782
4783 /* don't need this if not instrumenting or no workers */
4784 if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4785 return;
4786
4787 size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4788 size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4789 shm_toc_estimate_chunk(&pcxt->estimator, size);
4791}
size_t Size
Definition: c.h:624
#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:495
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
ScanState ss
Definition: execnodes.h:2535
shm_toc_estimator estimator
Definition: parallel.h:41
Instrumentation * instrument
Definition: execnodes.h:1175
PlanState ps
Definition: execnodes.h:1621

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

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

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

4826{
4827 node->shared_info =
4828 shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
4829}
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 4838 of file nodeAgg.c.

4839{
4840 Size size;
4841 SharedAggInfo *si;
4842
4843 if (node->shared_info == NULL)
4844 return;
4845
4846 size = offsetof(SharedAggInfo, sinstrument)
4848 si = palloc(size);
4849 memcpy(si, node->shared_info, size);
4850 node->shared_info = si;
4851}
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 4394 of file nodeAgg.c.

4395{
4397 int transno;
4398 int numGroupingSets = Max(node->maxsets, 1);
4399 int setno;
4400
4401 /*
4402 * When ending a parallel worker, copy the statistics gathered by the
4403 * worker back into shared memory so that it can be picked up by the main
4404 * process to report in EXPLAIN ANALYZE.
4405 */
4406 if (node->shared_info && IsParallelWorker())
4407 {
4409
4410 Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
4413 si->hash_disk_used = node->hash_disk_used;
4414 si->hash_mem_peak = node->hash_mem_peak;
4415 }
4416
4417 /* Make sure we have closed any open tuplesorts */
4418
4419 if (node->sort_in)
4420 tuplesort_end(node->sort_in);
4421 if (node->sort_out)
4422 tuplesort_end(node->sort_out);
4423
4425
4426 /* Release hash tables too */
4427 if (node->hash_metacxt != NULL)
4428 {
4430 node->hash_metacxt = NULL;
4431 }
4432 if (node->hash_tuplescxt != NULL)
4433 {
4435 node->hash_tuplescxt = NULL;
4436 }
4437
4438 for (transno = 0; transno < node->numtrans; transno++)
4439 {
4440 AggStatePerTrans pertrans = &node->pertrans[transno];
4441
4442 for (setno = 0; setno < numGroupingSets; setno++)
4443 {
4444 if (pertrans->sortstates[setno])
4445 tuplesort_end(pertrans->sortstates[setno]);
4446 }
4447 }
4448
4449 /* And ensure any agg shutdown callbacks have been called */
4450 for (setno = 0; setno < numGroupingSets; setno++)
4451 ReScanExprContext(node->aggcontexts[setno]);
4452 if (node->hashcontext)
4454
4455 outerPlan = outerPlanState(node);
4457}
int ParallelWorkerNumber
Definition: parallel.c:115
#define Max(x, y)
Definition: c.h:1010
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:562
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:443
#define outerPlanState(node)
Definition: execnodes.h:1261
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:3239
#define outerPlan(node)
Definition: plannodes.h:261
Tuplesortstate ** sortstates
Definition: nodeAgg.h:162
MemoryContext hash_metacxt
Definition: execnodes.h:2577
Tuplesortstate * sort_out
Definition: execnodes.h:2568
uint64 hash_disk_used
Definition: execnodes.h:2596
MemoryContext hash_tuplescxt
Definition: execnodes.h:2578
AggStatePerTrans pertrans
Definition: execnodes.h:2545
int numtrans
Definition: execnodes.h:2538
ExprContext * hashcontext
Definition: execnodes.h:2546
Size hash_mem_peak
Definition: execnodes.h:2593
int hash_batches_used
Definition: execnodes.h:2597
Tuplesortstate * sort_in
Definition: execnodes.h:2567
int maxsets
Definition: execnodes.h:2565
ExprContext ** aggcontexts
Definition: execnodes.h:2547
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2511
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:937

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_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 
)

Definition at line 3279 of file nodeAgg.c.

3280{
3281 AggState *aggstate;
3282 AggStatePerAgg peraggs;
3283 AggStatePerTrans pertransstates;
3284 AggStatePerGroup *pergroups;
3285 Plan *outerPlan;
3286 ExprContext *econtext;
3287 TupleDesc scanDesc;
3288 int max_aggno;
3289 int max_transno;
3290 int numaggrefs;
3291 int numaggs;
3292 int numtrans;
3293 int phase;
3294 int phaseidx;
3295 ListCell *l;
3296 Bitmapset *all_grouped_cols = NULL;
3297 int numGroupingSets = 1;
3298 int numPhases;
3299 int numHashes;
3300 int i = 0;
3301 int j = 0;
3302 bool use_hashing = (node->aggstrategy == AGG_HASHED ||
3303 node->aggstrategy == AGG_MIXED);
3304
3305 /* check for unsupported flags */
3306 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3307
3308 /*
3309 * create state structure
3310 */
3311 aggstate = makeNode(AggState);
3312 aggstate->ss.ps.plan = (Plan *) node;
3313 aggstate->ss.ps.state = estate;
3314 aggstate->ss.ps.ExecProcNode = ExecAgg;
3315
3316 aggstate->aggs = NIL;
3317 aggstate->numaggs = 0;
3318 aggstate->numtrans = 0;
3319 aggstate->aggstrategy = node->aggstrategy;
3320 aggstate->aggsplit = node->aggsplit;
3321 aggstate->maxsets = 0;
3322 aggstate->projected_set = -1;
3323 aggstate->current_set = 0;
3324 aggstate->peragg = NULL;
3325 aggstate->pertrans = NULL;
3326 aggstate->curperagg = NULL;
3327 aggstate->curpertrans = NULL;
3328 aggstate->input_done = false;
3329 aggstate->agg_done = false;
3330 aggstate->pergroups = NULL;
3331 aggstate->grp_firstTuple = NULL;
3332 aggstate->sort_in = NULL;
3333 aggstate->sort_out = NULL;
3334
3335 /*
3336 * phases[0] always exists, but is dummy in sorted/plain mode
3337 */
3338 numPhases = (use_hashing ? 1 : 2);
3339 numHashes = (use_hashing ? 1 : 0);
3340
3341 /*
3342 * Calculate the maximum number of grouping sets in any phase; this
3343 * determines the size of some allocations. Also calculate the number of
3344 * phases, since all hashed/mixed nodes contribute to only a single phase.
3345 */
3346 if (node->groupingSets)
3347 {
3348 numGroupingSets = list_length(node->groupingSets);
3349
3350 foreach(l, node->chain)
3351 {
3352 Agg *agg = lfirst(l);
3353
3354 numGroupingSets = Max(numGroupingSets,
3356
3357 /*
3358 * additional AGG_HASHED aggs become part of phase 0, but all
3359 * others add an extra phase.
3360 */
3361 if (agg->aggstrategy != AGG_HASHED)
3362 ++numPhases;
3363 else
3364 ++numHashes;
3365 }
3366 }
3367
3368 aggstate->maxsets = numGroupingSets;
3369 aggstate->numphases = numPhases;
3370
3371 aggstate->aggcontexts = palloc0_array(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_array(AggStatePerPhaseData, numPhases);
3495
3496 aggstate->num_hashes = numHashes;
3497 if (numHashes)
3498 {
3499 aggstate->perhash = palloc0_array(AggStatePerHashData, numHashes);
3500 aggstate->phases[0].numsets = 0;
3501 aggstate->phases[0].gset_lengths = palloc_array(int, numHashes);
3502 aggstate->phases[0].grouped_cols = palloc_array(Bitmapset *, numHashes);
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 = palloc0_array(ExprState *, aggnode->numCols);
3601
3602 /* for each grouping set */
3603 for (int k = 0; k < phasedata->numsets; k++)
3604 {
3605 int length = phasedata->gset_lengths[k];
3606
3607 /* nothing to do for empty grouping set */
3608 if (length == 0)
3609 continue;
3610
3611 /* if we already had one of this length, it'll do */
3612 if (phasedata->eqfunctions[length - 1] != NULL)
3613 continue;
3614
3615 phasedata->eqfunctions[length - 1] =
3616 execTuplesMatchPrepare(scanDesc,
3617 length,
3618 aggnode->grpColIdx,
3619 aggnode->grpOperators,
3620 aggnode->grpCollations,
3621 (PlanState *) aggstate);
3622 }
3623
3624 /* and for all grouped columns, unless already computed */
3625 if (aggnode->numCols > 0 &&
3626 phasedata->eqfunctions[aggnode->numCols - 1] == NULL)
3627 {
3628 phasedata->eqfunctions[aggnode->numCols - 1] =
3629 execTuplesMatchPrepare(scanDesc,
3630 aggnode->numCols,
3631 aggnode->grpColIdx,
3632 aggnode->grpOperators,
3633 aggnode->grpCollations,
3634 (PlanState *) aggstate);
3635 }
3636 }
3637
3638 phasedata->aggnode = aggnode;
3639 phasedata->aggstrategy = aggnode->aggstrategy;
3640 phasedata->sortnode = sortnode;
3641 }
3642 }
3643
3644 /*
3645 * Convert all_grouped_cols to a descending-order list.
3646 */
3647 i = -1;
3648 while ((i = bms_next_member(all_grouped_cols, i)) >= 0)
3649 aggstate->all_grouped_cols = lcons_int(i, aggstate->all_grouped_cols);
3650
3651 /*
3652 * Set up aggregate-result storage in the output expr context, and also
3653 * allocate my private per-agg working storage
3654 */
3655 econtext = aggstate->ss.ps.ps_ExprContext;
3656 econtext->ecxt_aggvalues = palloc0_array(Datum, numaggs);
3657 econtext->ecxt_aggnulls = palloc0_array(bool, numaggs);
3658
3659 peraggs = palloc0_array(AggStatePerAggData, numaggs);
3660 pertransstates = palloc0_array(AggStatePerTransData, numtrans);
3661
3662 aggstate->peragg = peraggs;
3663 aggstate->pertrans = pertransstates;
3664
3665
3666 aggstate->all_pergroups = palloc0_array(AggStatePerGroup, numGroupingSets + numHashes);
3667 pergroups = aggstate->all_pergroups;
3668
3669 if (node->aggstrategy != AGG_HASHED)
3670 {
3671 for (i = 0; i < numGroupingSets; i++)
3672 {
3673 pergroups[i] = palloc0_array(AggStatePerGroupData, numaggs);
3674 }
3675
3676 aggstate->pergroups = pergroups;
3677 pergroups += numGroupingSets;
3678 }
3679
3680 /*
3681 * Hashing can only appear in the initial phase.
3682 */
3683 if (use_hashing)
3684 {
3685 Plan *outerplan = outerPlan(node);
3686 double totalGroups = 0;
3687
3688 aggstate->hash_spill_rslot = ExecInitExtraTupleSlot(estate, scanDesc,
3690 aggstate->hash_spill_wslot = ExecInitExtraTupleSlot(estate, scanDesc,
3691 &TTSOpsVirtual);
3692
3693 /* this is an array of pointers, not structures */
3694 aggstate->hash_pergroup = pergroups;
3695
3696 aggstate->hashentrysize = hash_agg_entry_size(aggstate->numtrans,
3697 outerplan->plan_width,
3698 node->transitionSpace);
3699
3700 /*
3701 * Consider all of the grouping sets together when setting the limits
3702 * and estimating the number of partitions. This can be inaccurate
3703 * when there is more than one grouping set, but should still be
3704 * reasonable.
3705 */
3706 for (int k = 0; k < aggstate->num_hashes; k++)
3707 totalGroups += aggstate->perhash[k].aggnode->numGroups;
3708
3709 hash_agg_set_limits(aggstate->hashentrysize, totalGroups, 0,
3710 &aggstate->hash_mem_limit,
3711 &aggstate->hash_ngroups_limit,
3712 &aggstate->hash_planned_partitions);
3713 find_hash_columns(aggstate);
3714
3715 /* Skip massive memory allocation if we are just doing EXPLAIN */
3716 if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
3717 build_hash_tables(aggstate);
3718
3719 aggstate->table_filled = false;
3720
3721 /* Initialize this to 1, meaning nothing spilled, yet */
3722 aggstate->hash_batches_used = 1;
3723 }
3724
3725 /*
3726 * Initialize current phase-dependent values to initial phase. The initial
3727 * phase is 1 (first sort pass) for all strategies that use sorting (if
3728 * hashing is being done too, then phase 0 is processed last); but if only
3729 * hashing is being done, then phase 0 is all there is.
3730 */
3731 if (node->aggstrategy == AGG_HASHED)
3732 {
3733 aggstate->current_phase = 0;
3734 initialize_phase(aggstate, 0);
3735 select_current_set(aggstate, 0, true);
3736 }
3737 else
3738 {
3739 aggstate->current_phase = 1;
3740 initialize_phase(aggstate, 1);
3741 select_current_set(aggstate, 0, false);
3742 }
3743
3744 /*
3745 * Perform lookups of aggregate function info, and initialize the
3746 * unchanging fields of the per-agg and per-trans data.
3747 */
3748 foreach(l, aggstate->aggs)
3749 {
3750 Aggref *aggref = lfirst(l);
3751 AggStatePerAgg peragg;
3752 AggStatePerTrans pertrans;
3753 Oid aggTransFnInputTypes[FUNC_MAX_ARGS];
3754 int numAggTransFnArgs;
3755 int numDirectArgs;
3756 HeapTuple aggTuple;
3757 Form_pg_aggregate aggform;
3758 AclResult aclresult;
3759 Oid finalfn_oid;
3760 Oid serialfn_oid,
3761 deserialfn_oid;
3762 Oid aggOwner;
3763 Expr *finalfnexpr;
3764 Oid aggtranstype;
3765
3766 /* Planner should have assigned aggregate to correct level */
3767 Assert(aggref->agglevelsup == 0);
3768 /* ... and the split mode should match */
3769 Assert(aggref->aggsplit == aggstate->aggsplit);
3770
3771 peragg = &peraggs[aggref->aggno];
3772
3773 /* Check if we initialized the state for this aggregate already. */
3774 if (peragg->aggref != NULL)
3775 continue;
3776
3777 peragg->aggref = aggref;
3778 peragg->transno = aggref->aggtransno;
3779
3780 /* Fetch the pg_aggregate row */
3781 aggTuple = SearchSysCache1(AGGFNOID,
3782 ObjectIdGetDatum(aggref->aggfnoid));
3783 if (!HeapTupleIsValid(aggTuple))
3784 elog(ERROR, "cache lookup failed for aggregate %u",
3785 aggref->aggfnoid);
3786 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
3787
3788 /* Check permission to call aggregate function */
3789 aclresult = object_aclcheck(ProcedureRelationId, aggref->aggfnoid, GetUserId(),
3790 ACL_EXECUTE);
3791 if (aclresult != ACLCHECK_OK)
3793 get_func_name(aggref->aggfnoid));
3795
3796 /* planner recorded transition state type in the Aggref itself */
3797 aggtranstype = aggref->aggtranstype;
3798 Assert(OidIsValid(aggtranstype));
3799
3800 /* Final function only required if we're finalizing the aggregates */
3801 if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
3802 peragg->finalfn_oid = finalfn_oid = InvalidOid;
3803 else
3804 peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
3805
3806 serialfn_oid = InvalidOid;
3807 deserialfn_oid = InvalidOid;
3808
3809 /*
3810 * Check if serialization/deserialization is required. We only do it
3811 * for aggregates that have transtype INTERNAL.
3812 */
3813 if (aggtranstype == INTERNALOID)
3814 {
3815 /*
3816 * The planner should only have generated a serialize agg node if
3817 * every aggregate with an INTERNAL state has a serialization
3818 * function. Verify that.
3819 */
3820 if (DO_AGGSPLIT_SERIALIZE(aggstate->aggsplit))
3821 {
3822 /* serialization only valid when not running finalfn */
3824
3825 if (!OidIsValid(aggform->aggserialfn))
3826 elog(ERROR, "serialfunc not provided for serialization aggregation");
3827 serialfn_oid = aggform->aggserialfn;
3828 }
3829
3830 /* Likewise for deserialization functions */
3831 if (DO_AGGSPLIT_DESERIALIZE(aggstate->aggsplit))
3832 {
3833 /* deserialization only valid when combining states */
3835
3836 if (!OidIsValid(aggform->aggdeserialfn))
3837 elog(ERROR, "deserialfunc not provided for deserialization aggregation");
3838 deserialfn_oid = aggform->aggdeserialfn;
3839 }
3840 }
3841
3842 /* Check that aggregate owner has permission to call component fns */
3843 {
3844 HeapTuple procTuple;
3845
3846 procTuple = SearchSysCache1(PROCOID,
3847 ObjectIdGetDatum(aggref->aggfnoid));
3848 if (!HeapTupleIsValid(procTuple))
3849 elog(ERROR, "cache lookup failed for function %u",
3850 aggref->aggfnoid);
3851 aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
3852 ReleaseSysCache(procTuple);
3853
3854 if (OidIsValid(finalfn_oid))
3855 {
3856 aclresult = object_aclcheck(ProcedureRelationId, finalfn_oid, aggOwner,
3857 ACL_EXECUTE);
3858 if (aclresult != ACLCHECK_OK)
3860 get_func_name(finalfn_oid));
3861 InvokeFunctionExecuteHook(finalfn_oid);
3862 }
3863 if (OidIsValid(serialfn_oid))
3864 {
3865 aclresult = object_aclcheck(ProcedureRelationId, serialfn_oid, aggOwner,
3866 ACL_EXECUTE);
3867 if (aclresult != ACLCHECK_OK)
3869 get_func_name(serialfn_oid));
3870 InvokeFunctionExecuteHook(serialfn_oid);
3871 }
3872 if (OidIsValid(deserialfn_oid))
3873 {
3874 aclresult = object_aclcheck(ProcedureRelationId, deserialfn_oid, aggOwner,
3875 ACL_EXECUTE);
3876 if (aclresult != ACLCHECK_OK)
3878 get_func_name(deserialfn_oid));
3879 InvokeFunctionExecuteHook(deserialfn_oid);
3880 }
3881 }
3882
3883 /*
3884 * Get actual datatypes of the (nominal) aggregate inputs. These
3885 * could be different from the agg's declared input types, when the
3886 * agg accepts ANY or a polymorphic type.
3887 */
3888 numAggTransFnArgs = get_aggregate_argtypes(aggref,
3889 aggTransFnInputTypes);
3890
3891 /* Count the "direct" arguments, if any */
3892 numDirectArgs = list_length(aggref->aggdirectargs);
3893
3894 /* Detect how many arguments to pass to the finalfn */
3895 if (aggform->aggfinalextra)
3896 peragg->numFinalArgs = numAggTransFnArgs + 1;
3897 else
3898 peragg->numFinalArgs = numDirectArgs + 1;
3899
3900 /* Initialize any direct-argument expressions */
3902 (PlanState *) aggstate);
3903
3904 /*
3905 * build expression trees using actual argument & result types for the
3906 * finalfn, if it exists and is required.
3907 */
3908 if (OidIsValid(finalfn_oid))
3909 {
3910 build_aggregate_finalfn_expr(aggTransFnInputTypes,
3911 peragg->numFinalArgs,
3912 aggtranstype,
3913 aggref->aggtype,
3914 aggref->inputcollid,
3915 finalfn_oid,
3916 &finalfnexpr);
3917 fmgr_info(finalfn_oid, &peragg->finalfn);
3918 fmgr_info_set_expr((Node *) finalfnexpr, &peragg->finalfn);
3919 }
3920
3921 /* get info about the output value's datatype */
3922 get_typlenbyval(aggref->aggtype,
3923 &peragg->resulttypeLen,
3924 &peragg->resulttypeByVal);
3925
3926 /*
3927 * Build working state for invoking the transition function, if we
3928 * haven't done it already.
3929 */
3930 pertrans = &pertransstates[aggref->aggtransno];
3931 if (pertrans->aggref == NULL)
3932 {
3933 Datum textInitVal;
3935 bool initValueIsNull;
3936 Oid transfn_oid;
3937
3938 /*
3939 * If this aggregation is performing state combines, then instead
3940 * of using the transition function, we'll use the combine
3941 * function.
3942 */
3943 if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3944 {
3945 transfn_oid = aggform->aggcombinefn;
3946
3947 /* If not set then the planner messed up */
3948 if (!OidIsValid(transfn_oid))
3949 elog(ERROR, "combinefn not set for aggregate function");
3950 }
3951 else
3952 transfn_oid = aggform->aggtransfn;
3953
3954 aclresult = object_aclcheck(ProcedureRelationId, transfn_oid, aggOwner, ACL_EXECUTE);
3955 if (aclresult != ACLCHECK_OK)
3957 get_func_name(transfn_oid));
3958 InvokeFunctionExecuteHook(transfn_oid);
3959
3960 /*
3961 * initval is potentially null, so don't try to access it as a
3962 * struct field. Must do it the hard way with SysCacheGetAttr.
3963 */
3964 textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
3965 Anum_pg_aggregate_agginitval,
3966 &initValueIsNull);
3967 if (initValueIsNull)
3968 initValue = (Datum) 0;
3969 else
3970 initValue = GetAggInitVal(textInitVal, aggtranstype);
3971
3972 if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3973 {
3974 Oid combineFnInputTypes[] = {aggtranstype,
3975 aggtranstype};
3976
3977 /*
3978 * When combining there's only one input, the to-be-combined
3979 * transition value. The transition value is not counted
3980 * here.
3981 */
3982 pertrans->numTransInputs = 1;
3983
3984 /* aggcombinefn always has two arguments of aggtranstype */
3985 build_pertrans_for_aggref(pertrans, aggstate, estate,
3986 aggref, transfn_oid, aggtranstype,
3987 serialfn_oid, deserialfn_oid,
3988 initValue, initValueIsNull,
3989 combineFnInputTypes, 2);
3990
3991 /*
3992 * Ensure that a combine function to combine INTERNAL states
3993 * is not strict. This should have been checked during CREATE
3994 * AGGREGATE, but the strict property could have been changed
3995 * since then.
3996 */
3997 if (pertrans->transfn.fn_strict && aggtranstype == INTERNALOID)
3998 ereport(ERROR,
3999 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
4000 errmsg("combine function with transition type %s must not be declared STRICT",
4001 format_type_be(aggtranstype))));
4002 }
4003 else
4004 {
4005 /* Detect how many arguments to pass to the transfn */
4006 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
4007 pertrans->numTransInputs = list_length(aggref->args);
4008 else
4009 pertrans->numTransInputs = numAggTransFnArgs;
4010
4011 build_pertrans_for_aggref(pertrans, aggstate, estate,
4012 aggref, transfn_oid, aggtranstype,
4013 serialfn_oid, deserialfn_oid,
4014 initValue, initValueIsNull,
4015 aggTransFnInputTypes,
4016 numAggTransFnArgs);
4017
4018 /*
4019 * If the transfn is strict and the initval is NULL, make sure
4020 * input type and transtype are the same (or at least
4021 * binary-compatible), so that it's OK to use the first
4022 * aggregated input value as the initial transValue. This
4023 * should have been checked at agg definition time, but we
4024 * must check again in case the transfn's strictness property
4025 * has been changed.
4026 */
4027 if (pertrans->transfn.fn_strict && pertrans->initValueIsNull)
4028 {
4029 if (numAggTransFnArgs <= numDirectArgs ||
4030 !IsBinaryCoercible(aggTransFnInputTypes[numDirectArgs],
4031 aggtranstype))
4032 ereport(ERROR,
4033 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
4034 errmsg("aggregate %u needs to have compatible input type and transition type",
4035 aggref->aggfnoid)));
4036 }
4037 }
4038 }
4039 else
4040 pertrans->aggshared = true;
4041 ReleaseSysCache(aggTuple);
4042 }
4043
4044 /*
4045 * Last, check whether any more aggregates got added onto the node while
4046 * we processed the expressions for the aggregate arguments (including not
4047 * only the regular arguments and FILTER expressions handled immediately
4048 * above, but any direct arguments we might've handled earlier). If so,
4049 * we have nested aggregate functions, which is semantically nonsensical,
4050 * so complain. (This should have been caught by the parser, so we don't
4051 * need to work hard on a helpful error message; but we defend against it
4052 * here anyway, just to be sure.)
4053 */
4054 if (numaggrefs != list_length(aggstate->aggs))
4055 ereport(ERROR,
4056 (errcode(ERRCODE_GROUPING_ERROR),
4057 errmsg("aggregate function calls cannot be nested")));
4058
4059 /*
4060 * Build expressions doing all the transition work at once. We build a
4061 * different one for each phase, as the number of transition function
4062 * invocation can differ between phases. Note this'll work both for
4063 * transition and combination functions (although there'll only be one
4064 * phase in the latter case).
4065 */
4066 for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
4067 {
4068 AggStatePerPhase phase = &aggstate->phases[phaseidx];
4069 bool dohash = false;
4070 bool dosort = false;
4071
4072 /* phase 0 doesn't necessarily exist */
4073 if (!phase->aggnode)
4074 continue;
4075
4076 if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
4077 {
4078 /*
4079 * Phase one, and only phase one, in a mixed agg performs both
4080 * sorting and aggregation.
4081 */
4082 dohash = true;
4083 dosort = true;
4084 }
4085 else if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 0)
4086 {
4087 /*
4088 * No need to compute a transition function for an AGG_MIXED phase
4089 * 0 - the contents of the hashtables will have been computed
4090 * during phase 1.
4091 */
4092 continue;
4093 }
4094 else if (phase->aggstrategy == AGG_PLAIN ||
4095 phase->aggstrategy == AGG_SORTED)
4096 {
4097 dohash = false;
4098 dosort = true;
4099 }
4100 else if (phase->aggstrategy == AGG_HASHED)
4101 {
4102 dohash = true;
4103 dosort = false;
4104 }
4105 else
4106 Assert(false);
4107
4108 phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
4109 false);
4110
4111 /* cache compiled expression for outer slot without NULL check */
4112 phase->evaltrans_cache[0][0] = phase->evaltrans;
4113 }
4114
4115 return aggstate;
4116}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2654
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3836
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1305
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:916
#define OidIsValid(objectId)
Definition: c.h:788
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#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:3669
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:61
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
#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
#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: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:2416
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1773
Oid GetUserId(void)
Definition: miscinit.c:469
static void find_hash_columns(AggState *aggstate)
Definition: nodeAgg.c:1567
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
Definition: nodeAgg.c:4378
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:1698
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:4129
static TupleTableSlot * ExecAgg(PlanState *pstate)
Definition: nodeAgg.c:2245
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:1806
static void hash_create_memory(AggState *aggstate)
Definition: nodeAgg.c:1997
#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:2287
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:2050
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:2605
AggStatePerGroup * hash_pergroup
Definition: execnodes.h:2600
List * aggs
Definition: execnodes.h:2536
ExprContext * tmpcontext
Definition: execnodes.h:2548
int hash_planned_partitions
Definition: execnodes.h:2590
HeapTuple grp_firstTuple
Definition: execnodes.h:2573
Size hash_mem_limit
Definition: execnodes.h:2588
AggStatePerTrans curpertrans
Definition: execnodes.h:2553
bool table_filled
Definition: execnodes.h:2575
int current_set
Definition: execnodes.h:2558
AggStrategy aggstrategy
Definition: execnodes.h:2539
AggSplit aggsplit
Definition: execnodes.h:2540
int projected_set
Definition: execnodes.h:2556
uint64 hash_ngroups_limit
Definition: execnodes.h:2589
bool input_done
Definition: execnodes.h:2554
AggStatePerPhase phases
Definition: execnodes.h:2566
List * all_grouped_cols
Definition: execnodes.h:2560
AggStatePerGroup * pergroups
Definition: execnodes.h:2571
AggStatePerHash perhash
Definition: execnodes.h:2599
double hashentrysize
Definition: execnodes.h:2592
int numphases
Definition: execnodes.h:2542
TupleTableSlot * hash_spill_wslot
Definition: execnodes.h:2583
AggStatePerAgg curperagg
Definition: execnodes.h:2551
TupleTableSlot * sort_slot
Definition: execnodes.h:2569
int numaggs
Definition: execnodes.h:2537
int num_hashes
Definition: execnodes.h:2576
AggStatePerAgg peragg
Definition: execnodes.h:2544
TupleTableSlot * hash_spill_rslot
Definition: execnodes.h:2582
int current_phase
Definition: execnodes.h:2543
bool agg_done
Definition: execnodes.h:2555
AggSplit aggsplit
Definition: plannodes.h:1196
List * chain
Definition: plannodes.h:1223
List * groupingSets
Definition: plannodes.h:1220
Cardinality numGroups
Definition: plannodes.h:1209
Plan plan
Definition: plannodes.h:1190
int numCols
Definition: plannodes.h:1199
uint64 transitionSpace
Definition: plannodes.h:1212
AggStrategy aggstrategy
Definition: plannodes.h:1193
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:1248
const TupleTableSlotOps * outerops
Definition: execnodes.h:1240
ExprState * qual
Definition: execnodes.h:1186
bool outeropsfixed
Definition: execnodes.h:1244
EState * state
Definition: execnodes.h:1167
ExprContext * ps_ExprContext
Definition: execnodes.h:1204
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1171
List * qual
Definition: plannodes.h:231
int plan_width
Definition: plannodes.h:207
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1624
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_array, palloc_array, 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 4460 of file nodeAgg.c.

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

Definition at line 1698 of file nodeAgg.c.

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

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

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