PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
nodeAgg.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/parallel.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "executor/execExpr.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "lib/hyperloglog.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_agg.h"
#include "parser/parse_coerce.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/dynahash.h"
#include "utils/expandeddatum.h"
#include "utils/injection_point.h"
#include "utils/logtape.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/memutils_memorychunk.h"
#include "utils/syscache.h"
#include "utils/tuplesort.h"
Include dependency graph for nodeAgg.c:

Go to the source code of this file.

Data Structures

struct  HashAggSpill
 
struct  HashAggBatch
 
struct  FindColsContext
 

Macros

#define HASHAGG_PARTITION_FACTOR   1.50
 
#define HASHAGG_MIN_PARTITIONS   4
 
#define HASHAGG_MAX_PARTITIONS   1024
 
#define HASHAGG_READ_BUFFER_SIZE   BLCKSZ
 
#define HASHAGG_WRITE_BUFFER_SIZE   BLCKSZ
 
#define HASHAGG_HLL_BIT_WIDTH   5
 
#define CHUNKHDRSZ   sizeof(MemoryChunk)
 

Typedefs

typedef struct HashAggSpill HashAggSpill
 
typedef struct HashAggBatch HashAggBatch
 
typedef struct FindColsContext FindColsContext
 

Functions

static void select_current_set (AggState *aggstate, int setno, bool is_hash)
 
static void initialize_phase (AggState *aggstate, int newphase)
 
static TupleTableSlotfetch_input_tuple (AggState *aggstate)
 
static void initialize_aggregates (AggState *aggstate, AggStatePerGroup *pergroups, int numReset)
 
static void advance_transition_function (AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
 
static void advance_aggregates (AggState *aggstate)
 
static void process_ordered_aggregate_single (AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
 
static void process_ordered_aggregate_multi (AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
 
static void finalize_aggregate (AggState *aggstate, AggStatePerAgg peragg, AggStatePerGroup pergroupstate, Datum *resultVal, bool *resultIsNull)
 
static void finalize_partialaggregate (AggState *aggstate, AggStatePerAgg peragg, AggStatePerGroup pergroupstate, Datum *resultVal, bool *resultIsNull)
 
static void prepare_hash_slot (AggStatePerHash perhash, TupleTableSlot *inputslot, TupleTableSlot *hashslot)
 
static void prepare_projection_slot (AggState *aggstate, TupleTableSlot *slot, int currentSet)
 
static void finalize_aggregates (AggState *aggstate, AggStatePerAgg peraggs, AggStatePerGroup pergroup)
 
static TupleTableSlotproject_aggregates (AggState *aggstate)
 
static void find_cols (AggState *aggstate, Bitmapset **aggregated, Bitmapset **unaggregated)
 
static bool find_cols_walker (Node *node, FindColsContext *context)
 
static void build_hash_tables (AggState *aggstate)
 
static void build_hash_table (AggState *aggstate, int setno, long nbuckets)
 
static void hashagg_recompile_expressions (AggState *aggstate, bool minslot, bool nullcheck)
 
static void hash_create_memory (AggState *aggstate)
 
static long hash_choose_num_buckets (double hashentrysize, long ngroups, Size memory)
 
static int hash_choose_num_partitions (double input_groups, double hashentrysize, int used_bits, int *log2_npartitions)
 
static void initialize_hash_entry (AggState *aggstate, TupleHashTable hashtable, TupleHashEntry entry)
 
static void lookup_hash_entries (AggState *aggstate)
 
static TupleTableSlotagg_retrieve_direct (AggState *aggstate)
 
static void agg_fill_hash_table (AggState *aggstate)
 
static bool agg_refill_hash_table (AggState *aggstate)
 
static TupleTableSlotagg_retrieve_hash_table (AggState *aggstate)
 
static TupleTableSlotagg_retrieve_hash_table_in_memory (AggState *aggstate)
 
static void hash_agg_check_limits (AggState *aggstate)
 
static void hash_agg_enter_spill_mode (AggState *aggstate)
 
static void hash_agg_update_metrics (AggState *aggstate, bool from_tape, int npartitions)
 
static void hashagg_finish_initial_spills (AggState *aggstate)
 
static void hashagg_reset_spill_state (AggState *aggstate)
 
static HashAggBatchhashagg_batch_new (LogicalTape *input_tape, int setno, int64 input_tuples, double input_card, int used_bits)
 
static MinimalTuple hashagg_batch_read (HashAggBatch *batch, uint32 *hashp)
 
static void hashagg_spill_init (HashAggSpill *spill, LogicalTapeSet *tapeset, int used_bits, double input_groups, double hashentrysize)
 
static Size hashagg_spill_tuple (AggState *aggstate, HashAggSpill *spill, TupleTableSlot *inputslot, uint32 hash)
 
static void hashagg_spill_finish (AggState *aggstate, HashAggSpill *spill, int setno)
 
static Datum GetAggInitVal (Datum textInitVal, Oid transtype)
 
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)
 
static void initialize_aggregate (AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
 
static void find_hash_columns (AggState *aggstate)
 
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)
 
static TupleTableSlotExecAgg (PlanState *pstate)
 
AggStateExecInitAgg (Agg *node, EState *estate, int eflags)
 
void ExecEndAgg (AggState *node)
 
void ExecReScanAgg (AggState *node)
 
int AggCheckCallContext (FunctionCallInfo fcinfo, MemoryContext *aggcontext)
 
AggrefAggGetAggref (FunctionCallInfo fcinfo)
 
MemoryContext AggGetTempMemoryContext (FunctionCallInfo fcinfo)
 
bool AggStateIsShared (FunctionCallInfo fcinfo)
 
void AggRegisterCallback (FunctionCallInfo fcinfo, ExprContextCallbackFunction func, Datum arg)
 
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

◆ CHUNKHDRSZ

#define CHUNKHDRSZ   sizeof(MemoryChunk)

Definition at line 321 of file nodeAgg.c.

◆ HASHAGG_HLL_BIT_WIDTH

#define HASHAGG_HLL_BIT_WIDTH   5

Definition at line 316 of file nodeAgg.c.

◆ HASHAGG_MAX_PARTITIONS

#define HASHAGG_MAX_PARTITIONS   1024

Definition at line 299 of file nodeAgg.c.

◆ HASHAGG_MIN_PARTITIONS

#define HASHAGG_MIN_PARTITIONS   4

Definition at line 298 of file nodeAgg.c.

◆ HASHAGG_PARTITION_FACTOR

#define HASHAGG_PARTITION_FACTOR   1.50

Definition at line 297 of file nodeAgg.c.

◆ HASHAGG_READ_BUFFER_SIZE

#define HASHAGG_READ_BUFFER_SIZE   BLCKSZ

Definition at line 307 of file nodeAgg.c.

◆ HASHAGG_WRITE_BUFFER_SIZE

#define HASHAGG_WRITE_BUFFER_SIZE   BLCKSZ

Definition at line 308 of file nodeAgg.c.

Typedef Documentation

◆ FindColsContext

◆ HashAggBatch

typedef struct HashAggBatch HashAggBatch

◆ HashAggSpill

typedef struct HashAggSpill HashAggSpill

Function Documentation

◆ advance_aggregates()

static void advance_aggregates ( AggState aggstate)
static

Definition at line 818 of file nodeAgg.c.

819{
821 aggstate->tmpcontext);
822}
static void ExecEvalExprNoReturnSwitchContext(ExprState *state, ExprContext *econtext)
Definition: executor.h:480
ExprState * evaltrans
Definition: nodeAgg.h:291
AggStatePerPhase phase
Definition: execnodes.h:2533
ExprContext * tmpcontext
Definition: execnodes.h:2540

References AggStatePerPhaseData::evaltrans, ExecEvalExprNoReturnSwitchContext(), AggState::phase, and AggState::tmpcontext.

Referenced by agg_fill_hash_table(), agg_refill_hash_table(), and agg_retrieve_direct().

◆ advance_transition_function()

static void advance_transition_function ( AggState aggstate,
AggStatePerTrans  pertrans,
AggStatePerGroup  pergroupstate 
)
static

Definition at line 708 of file nodeAgg.c.

711{
712 FunctionCallInfo fcinfo = pertrans->transfn_fcinfo;
713 MemoryContext oldContext;
714 Datum newVal;
715
716 if (pertrans->transfn.fn_strict)
717 {
718 /*
719 * For a strict transfn, nothing happens when there's a NULL input; we
720 * just keep the prior transValue.
721 */
722 int numTransInputs = pertrans->numTransInputs;
723 int i;
724
725 for (i = 1; i <= numTransInputs; i++)
726 {
727 if (fcinfo->args[i].isnull)
728 return;
729 }
730 if (pergroupstate->noTransValue)
731 {
732 /*
733 * transValue has not been initialized. This is the first non-NULL
734 * input value. We use it as the initial value for transValue. (We
735 * already checked that the agg's input type is binary-compatible
736 * with its transtype, so straight copy here is OK.)
737 *
738 * We must copy the datum into aggcontext if it is pass-by-ref. We
739 * do not need to pfree the old transValue, since it's NULL.
740 */
742 pergroupstate->transValue = datumCopy(fcinfo->args[1].value,
743 pertrans->transtypeByVal,
744 pertrans->transtypeLen);
745 pergroupstate->transValueIsNull = false;
746 pergroupstate->noTransValue = false;
747 MemoryContextSwitchTo(oldContext);
748 return;
749 }
750 if (pergroupstate->transValueIsNull)
751 {
752 /*
753 * Don't call a strict function with NULL inputs. Note it is
754 * possible to get here despite the above tests, if the transfn is
755 * strict *and* returned a NULL on a prior cycle. If that happens
756 * we will propagate the NULL all the way to the end.
757 */
758 return;
759 }
760 }
761
762 /* We run the transition functions in per-input-tuple memory context */
764
765 /* set up aggstate->curpertrans for AggGetAggref() */
766 aggstate->curpertrans = pertrans;
767
768 /*
769 * OK to call the transition function
770 */
771 fcinfo->args[0].value = pergroupstate->transValue;
772 fcinfo->args[0].isnull = pergroupstate->transValueIsNull;
773 fcinfo->isnull = false; /* just in case transfn doesn't set it */
774
775 newVal = FunctionCallInvoke(fcinfo);
776
777 aggstate->curpertrans = NULL;
778
779 /*
780 * If pass-by-ref datatype, must copy the new value into aggcontext and
781 * free the prior transValue. But if transfn returned a pointer to its
782 * first input, we don't need to do anything.
783 *
784 * It's safe to compare newVal with pergroup->transValue without regard
785 * for either being NULL, because ExecAggCopyTransValue takes care to set
786 * transValue to 0 when NULL. Otherwise we could end up accidentally not
787 * reparenting, when the transValue has the same numerical value as
788 * newValue, despite being NULL. This is a somewhat hot path, making it
789 * undesirable to instead solve this with another branch for the common
790 * case of the transition function returning its (modified) input
791 * argument.
792 */
793 if (!pertrans->transtypeByVal &&
794 DatumGetPointer(newVal) != DatumGetPointer(pergroupstate->transValue))
795 newVal = ExecAggCopyTransValue(aggstate, pertrans,
796 newVal, fcinfo->isnull,
797 pergroupstate->transValue,
798 pergroupstate->transValueIsNull);
799
800 pergroupstate->transValue = newVal;
801 pergroupstate->transValueIsNull = fcinfo->isnull;
802
803 MemoryContextSwitchTo(oldContext);
804}
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
Datum ExecAggCopyTransValue(AggState *aggstate, AggStatePerTrans pertrans, Datum newValue, bool newValueIsNull, Datum oldValue, bool oldValueIsNull)
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:172
int i
Definition: isn.c:77
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
uintptr_t Datum
Definition: postgres.h:69
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:317
FmgrInfo transfn
Definition: nodeAgg.h:86
FunctionCallInfo transfn_fcinfo
Definition: nodeAgg.h:170
ExprContext * curaggcontext
Definition: execnodes.h:2542
AggStatePerTrans curpertrans
Definition: execnodes.h:2545
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:276
bool fn_strict
Definition: fmgr.h:61
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
Datum value
Definition: postgres.h:80
bool isnull
Definition: postgres.h:82

References FunctionCallInfoBaseData::args, AggState::curaggcontext, AggState::curpertrans, datumCopy(), DatumGetPointer(), ExprContext::ecxt_per_tuple_memory, ExecAggCopyTransValue(), FmgrInfo::fn_strict, FunctionCallInvoke, i, FunctionCallInfoBaseData::isnull, NullableDatum::isnull, MemoryContextSwitchTo(), AggStatePerGroupData::noTransValue, AggStatePerTransData::numTransInputs, AggState::tmpcontext, AggStatePerTransData::transfn, AggStatePerTransData::transfn_fcinfo, AggStatePerTransData::transtypeByVal, AggStatePerTransData::transtypeLen, AggStatePerGroupData::transValue, AggStatePerGroupData::transValueIsNull, and NullableDatum::value.

Referenced by process_ordered_aggregate_multi(), and process_ordered_aggregate_single().

◆ agg_fill_hash_table()

static void agg_fill_hash_table ( AggState aggstate)
static

Definition at line 2626 of file nodeAgg.c.

2627{
2628 TupleTableSlot *outerslot;
2629 ExprContext *tmpcontext = aggstate->tmpcontext;
2630
2631 /*
2632 * Process each outer-plan tuple, and then fetch the next one, until we
2633 * exhaust the outer plan.
2634 */
2635 for (;;)
2636 {
2637 outerslot = fetch_input_tuple(aggstate);
2638 if (TupIsNull(outerslot))
2639 break;
2640
2641 /* set up for lookup_hash_entries and advance_aggregates */
2642 tmpcontext->ecxt_outertuple = outerslot;
2643
2644 /* Find or build hashtable entries */
2645 lookup_hash_entries(aggstate);
2646
2647 /* Advance the aggregates (or combine functions) */
2648 advance_aggregates(aggstate);
2649
2650 /*
2651 * Reset per-input-tuple context after each tuple, but note that the
2652 * hash lookups do this too
2653 */
2654 ResetExprContext(aggstate->tmpcontext);
2655 }
2656
2657 /* finalize spills, if any */
2659
2660 aggstate->table_filled = true;
2661 /* Initialize to walk the first hash table */
2662 select_current_set(aggstate, 0, true);
2664 &aggstate->perhash[0].hashiter);
2665}
#define ResetTupleHashIterator(htable, iter)
Definition: execnodes.h:891
#define ResetExprContext(econtext)
Definition: executor.h:672
static void hashagg_finish_initial_spills(AggState *aggstate)
Definition: nodeAgg.c:3165
static TupleTableSlot * fetch_input_tuple(AggState *aggstate)
Definition: nodeAgg.c:549
static void lookup_hash_entries(AggState *aggstate)
Definition: nodeAgg.c:2181
static void advance_aggregates(AggState *aggstate)
Definition: nodeAgg.c:818
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:457
TupleHashTable hashtable
Definition: nodeAgg.h:311
TupleHashIterator hashiter
Definition: nodeAgg.h:312
bool table_filled
Definition: execnodes.h:2567
AggStatePerHash perhash
Definition: execnodes.h:2591
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:272
#define TupIsNull(slot)
Definition: tuptable.h:310

References advance_aggregates(), ExprContext::ecxt_outertuple, fetch_input_tuple(), hashagg_finish_initial_spills(), AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, lookup_hash_entries(), AggState::perhash, ResetExprContext, ResetTupleHashIterator, select_current_set(), AggState::table_filled, AggState::tmpcontext, and TupIsNull.

Referenced by ExecAgg().

◆ agg_refill_hash_table()

static bool agg_refill_hash_table ( AggState aggstate)
static

Definition at line 2680 of file nodeAgg.c.

2681{
2682 HashAggBatch *batch;
2683 AggStatePerHash perhash;
2684 HashAggSpill spill;
2685 LogicalTapeSet *tapeset = aggstate->hash_tapeset;
2686 bool spill_initialized = false;
2687
2688 if (aggstate->hash_batches == NIL)
2689 return false;
2690
2691 /* hash_batches is a stack, with the top item at the end of the list */
2692 batch = llast(aggstate->hash_batches);
2693 aggstate->hash_batches = list_delete_last(aggstate->hash_batches);
2694
2696 batch->used_bits, &aggstate->hash_mem_limit,
2697 &aggstate->hash_ngroups_limit, NULL);
2698
2699 /*
2700 * Each batch only processes one grouping set; set the rest to NULL so
2701 * that advance_aggregates() knows to ignore them. We don't touch
2702 * pergroups for sorted grouping sets here, because they will be needed if
2703 * we rescan later. The expressions for sorted grouping sets will not be
2704 * evaluated after we recompile anyway.
2705 */
2706 MemSet(aggstate->hash_pergroup, 0,
2707 sizeof(AggStatePerGroup) * aggstate->num_hashes);
2708
2709 /* free memory and reset hash tables */
2710 ReScanExprContext(aggstate->hashcontext);
2712 for (int setno = 0; setno < aggstate->num_hashes; setno++)
2713 ResetTupleHashTable(aggstate->perhash[setno].hashtable);
2714
2715 aggstate->hash_ngroups_current = 0;
2716
2717 /*
2718 * In AGG_MIXED mode, hash aggregation happens in phase 1 and the output
2719 * happens in phase 0. So, we switch to phase 1 when processing a batch,
2720 * and back to phase 0 after the batch is done.
2721 */
2722 Assert(aggstate->current_phase == 0);
2723 if (aggstate->phase->aggstrategy == AGG_MIXED)
2724 {
2725 aggstate->current_phase = 1;
2726 aggstate->phase = &aggstate->phases[aggstate->current_phase];
2727 }
2728
2729 select_current_set(aggstate, batch->setno, true);
2730
2731 perhash = &aggstate->perhash[aggstate->current_set];
2732
2733 /*
2734 * Spilled tuples are always read back as MinimalTuples, which may be
2735 * different from the outer plan, so recompile the aggregate expressions.
2736 *
2737 * We still need the NULL check, because we are only processing one
2738 * grouping set at a time and the rest will be NULL.
2739 */
2740 hashagg_recompile_expressions(aggstate, true, true);
2741
2742 INJECTION_POINT("hash-aggregate-process-batch");
2743 for (;;)
2744 {
2745 TupleTableSlot *spillslot = aggstate->hash_spill_rslot;
2746 TupleTableSlot *hashslot = perhash->hashslot;
2747 TupleHashTable hashtable = perhash->hashtable;
2748 TupleHashEntry entry;
2749 MinimalTuple tuple;
2750 uint32 hash;
2751 bool isnew = false;
2752 bool *p_isnew = aggstate->hash_spill_mode ? NULL : &isnew;
2753
2755
2756 tuple = hashagg_batch_read(batch, &hash);
2757 if (tuple == NULL)
2758 break;
2759
2760 ExecStoreMinimalTuple(tuple, spillslot, true);
2761 aggstate->tmpcontext->ecxt_outertuple = spillslot;
2762
2763 prepare_hash_slot(perhash,
2764 aggstate->tmpcontext->ecxt_outertuple,
2765 hashslot);
2766 entry = LookupTupleHashEntryHash(hashtable, hashslot,
2767 p_isnew, hash);
2768
2769 if (entry != NULL)
2770 {
2771 if (isnew)
2772 initialize_hash_entry(aggstate, hashtable, entry);
2773 aggstate->hash_pergroup[batch->setno] = TupleHashEntryGetAdditional(hashtable, entry);
2774 advance_aggregates(aggstate);
2775 }
2776 else
2777 {
2778 if (!spill_initialized)
2779 {
2780 /*
2781 * Avoid initializing the spill until we actually need it so
2782 * that we don't assign tapes that will never be used.
2783 */
2784 spill_initialized = true;
2785 hashagg_spill_init(&spill, tapeset, batch->used_bits,
2786 batch->input_card, aggstate->hashentrysize);
2787 }
2788 /* no memory for a new group, spill */
2789 hashagg_spill_tuple(aggstate, &spill, spillslot, hash);
2790
2791 aggstate->hash_pergroup[batch->setno] = NULL;
2792 }
2793
2794 /*
2795 * Reset per-input-tuple context after each tuple, but note that the
2796 * hash lookups do this too
2797 */
2798 ResetExprContext(aggstate->tmpcontext);
2799 }
2800
2802
2803 /* change back to phase 0 */
2804 aggstate->current_phase = 0;
2805 aggstate->phase = &aggstate->phases[aggstate->current_phase];
2806
2807 if (spill_initialized)
2808 {
2809 hashagg_spill_finish(aggstate, &spill, batch->setno);
2810 hash_agg_update_metrics(aggstate, true, spill.npartitions);
2811 }
2812 else
2813 hash_agg_update_metrics(aggstate, true, 0);
2814
2815 aggstate->hash_spill_mode = false;
2816
2817 /* prepare to walk the first hash table */
2818 select_current_set(aggstate, batch->setno, true);
2820 &aggstate->perhash[batch->setno].hashiter);
2821
2822 pfree(batch);
2823
2824 return true;
2825}
uint32_t uint32
Definition: c.h:502
#define MemSet(start, val, len)
Definition: c.h:991
TupleHashEntry LookupTupleHashEntryHash(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew, uint32 hash)
Definition: execGrouping.c:350
void ResetTupleHashTable(TupleHashTable hashtable)
Definition: execGrouping.c:274
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1635
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:444
static void * TupleHashEntryGetAdditional(TupleHashTable hashtable, TupleHashEntry entry)
Definition: executor.h:189
Assert(PointerIsAligned(start, uint64))
#define INJECTION_POINT(name)
List * list_delete_last(List *list)
Definition: list.c:957
void LogicalTapeClose(LogicalTape *lt)
Definition: logtape.c:733
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:414
void pfree(void *pointer)
Definition: mcxt.c:2146
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
static void initialize_hash_entry(AggState *aggstate, TupleHashTable hashtable, TupleHashEntry entry)
Definition: nodeAgg.c:2137
static void hashagg_spill_finish(AggState *aggstate, HashAggSpill *spill, int setno)
Definition: nodeAgg.c:3199
static MinimalTuple hashagg_batch_read(HashAggBatch *batch, uint32 *hashp)
Definition: nodeAgg.c:3116
static void hash_agg_update_metrics(AggState *aggstate, bool from_tape, int npartitions)
Definition: nodeAgg.c:1947
static void hashagg_recompile_expressions(AggState *aggstate, bool minslot, bool nullcheck)
Definition: nodeAgg.c:1752
static void prepare_hash_slot(AggStatePerHash perhash, TupleTableSlot *inputslot, TupleTableSlot *hashslot)
Definition: nodeAgg.c:1203
static Size hashagg_spill_tuple(AggState *aggstate, HashAggSpill *spill, TupleTableSlot *inputslot, uint32 hash)
Definition: nodeAgg.c:3027
static void hashagg_spill_init(HashAggSpill *spill, LogicalTapeSet *tapeset, int used_bits, double input_groups, double hashentrysize)
Definition: nodeAgg.c:2984
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1809
@ AGG_MIXED
Definition: nodes.h:363
#define llast(l)
Definition: pg_list.h:198
#define NIL
Definition: pg_list.h:68
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715
TupleTableSlot * hashslot
Definition: nodeAgg.h:313
AggStrategy aggstrategy
Definition: nodeAgg.h:282
AggStatePerGroup * hash_pergroup
Definition: execnodes.h:2592
Size hash_mem_limit
Definition: execnodes.h:2580
MemoryContext hash_tablecxt
Definition: execnodes.h:2570
int current_set
Definition: execnodes.h:2550
struct LogicalTapeSet * hash_tapeset
Definition: execnodes.h:2571
ExprContext * hashcontext
Definition: execnodes.h:2538
uint64 hash_ngroups_limit
Definition: execnodes.h:2581
AggStatePerPhase phases
Definition: execnodes.h:2558
bool hash_spill_mode
Definition: execnodes.h:2578
double hashentrysize
Definition: execnodes.h:2584
uint64 hash_ngroups_current
Definition: execnodes.h:2586
int num_hashes
Definition: execnodes.h:2568
List * hash_batches
Definition: execnodes.h:2576
TupleTableSlot * hash_spill_rslot
Definition: execnodes.h:2574
int current_phase
Definition: execnodes.h:2535
int used_bits
Definition: nodeAgg.c:354
double input_card
Definition: nodeAgg.c:357
LogicalTape * input_tape
Definition: nodeAgg.c:355
int npartitions
Definition: nodeAgg.c:334

References advance_aggregates(), AGG_MIXED, AggStatePerPhaseData::aggstrategy, Assert(), CHECK_FOR_INTERRUPTS, AggState::current_phase, AggState::current_set, ExprContext::ecxt_outertuple, ExecStoreMinimalTuple(), hash(), hash_agg_set_limits(), hash_agg_update_metrics(), AggState::hash_batches, AggState::hash_mem_limit, AggState::hash_ngroups_current, AggState::hash_ngroups_limit, AggState::hash_pergroup, AggState::hash_spill_mode, AggState::hash_spill_rslot, AggState::hash_tablecxt, AggState::hash_tapeset, hashagg_batch_read(), hashagg_recompile_expressions(), hashagg_spill_finish(), hashagg_spill_init(), hashagg_spill_tuple(), AggState::hashcontext, AggState::hashentrysize, AggStatePerHashData::hashiter, AggStatePerHashData::hashslot, AggStatePerHashData::hashtable, initialize_hash_entry(), INJECTION_POINT, HashAggBatch::input_card, HashAggBatch::input_tape, list_delete_last(), llast, LogicalTapeClose(), LookupTupleHashEntryHash(), MemoryContextReset(), MemSet, NIL, HashAggSpill::npartitions, AggState::num_hashes, AggState::perhash, pfree(), AggState::phase, AggState::phases, prepare_hash_slot(), ReScanExprContext(), ResetExprContext, ResetTupleHashIterator, ResetTupleHashTable(), select_current_set(), HashAggBatch::setno, AggState::tmpcontext, TupleHashEntryGetAdditional(), and HashAggBatch::used_bits.

Referenced by agg_retrieve_hash_table().

◆ agg_retrieve_direct()

static TupleTableSlot * agg_retrieve_direct ( AggState aggstate)
static

Definition at line 2280 of file nodeAgg.c.

2281{
2282 Agg *node = aggstate->phase->aggnode;
2283 ExprContext *econtext;
2284 ExprContext *tmpcontext;
2285 AggStatePerAgg peragg;
2286 AggStatePerGroup *pergroups;
2287 TupleTableSlot *outerslot;
2288 TupleTableSlot *firstSlot;
2289 TupleTableSlot *result;
2290 bool hasGroupingSets = aggstate->phase->numsets > 0;
2291 int numGroupingSets = Max(aggstate->phase->numsets, 1);
2292 int currentSet;
2293 int nextSetSize;
2294 int numReset;
2295 int i;
2296
2297 /*
2298 * get state info from node
2299 *
2300 * econtext is the per-output-tuple expression context
2301 *
2302 * tmpcontext is the per-input-tuple expression context
2303 */
2304 econtext = aggstate->ss.ps.ps_ExprContext;
2305 tmpcontext = aggstate->tmpcontext;
2306
2307 peragg = aggstate->peragg;
2308 pergroups = aggstate->pergroups;
2309 firstSlot = aggstate->ss.ss_ScanTupleSlot;
2310
2311 /*
2312 * We loop retrieving groups until we find one matching
2313 * aggstate->ss.ps.qual
2314 *
2315 * For grouping sets, we have the invariant that aggstate->projected_set
2316 * is either -1 (initial call) or the index (starting from 0) in
2317 * gset_lengths for the group we just completed (either by projecting a
2318 * row or by discarding it in the qual).
2319 */
2320 while (!aggstate->agg_done)
2321 {
2322 /*
2323 * Clear the per-output-tuple context for each group, as well as
2324 * aggcontext (which contains any pass-by-ref transvalues of the old
2325 * group). Some aggregate functions store working state in child
2326 * contexts; those now get reset automatically without us needing to
2327 * do anything special.
2328 *
2329 * We use ReScanExprContext not just ResetExprContext because we want
2330 * any registered shutdown callbacks to be called. That allows
2331 * aggregate functions to ensure they've cleaned up any non-memory
2332 * resources.
2333 */
2334 ReScanExprContext(econtext);
2335
2336 /*
2337 * Determine how many grouping sets need to be reset at this boundary.
2338 */
2339 if (aggstate->projected_set >= 0 &&
2340 aggstate->projected_set < numGroupingSets)
2341 numReset = aggstate->projected_set + 1;
2342 else
2343 numReset = numGroupingSets;
2344
2345 /*
2346 * numReset can change on a phase boundary, but that's OK; we want to
2347 * reset the contexts used in _this_ phase, and later, after possibly
2348 * changing phase, initialize the right number of aggregates for the
2349 * _new_ phase.
2350 */
2351
2352 for (i = 0; i < numReset; i++)
2353 {
2354 ReScanExprContext(aggstate->aggcontexts[i]);
2355 }
2356
2357 /*
2358 * Check if input is complete and there are no more groups to project
2359 * in this phase; move to next phase or mark as done.
2360 */
2361 if (aggstate->input_done == true &&
2362 aggstate->projected_set >= (numGroupingSets - 1))
2363 {
2364 if (aggstate->current_phase < aggstate->numphases - 1)
2365 {
2366 initialize_phase(aggstate, aggstate->current_phase + 1);
2367 aggstate->input_done = false;
2368 aggstate->projected_set = -1;
2369 numGroupingSets = Max(aggstate->phase->numsets, 1);
2370 node = aggstate->phase->aggnode;
2371 numReset = numGroupingSets;
2372 }
2373 else if (aggstate->aggstrategy == AGG_MIXED)
2374 {
2375 /*
2376 * Mixed mode; we've output all the grouped stuff and have
2377 * full hashtables, so switch to outputting those.
2378 */
2379 initialize_phase(aggstate, 0);
2380 aggstate->table_filled = true;
2382 &aggstate->perhash[0].hashiter);
2383 select_current_set(aggstate, 0, true);
2384 return agg_retrieve_hash_table(aggstate);
2385 }
2386 else
2387 {
2388 aggstate->agg_done = true;
2389 break;
2390 }
2391 }
2392
2393 /*
2394 * Get the number of columns in the next grouping set after the last
2395 * projected one (if any). This is the number of columns to compare to
2396 * see if we reached the boundary of that set too.
2397 */
2398 if (aggstate->projected_set >= 0 &&
2399 aggstate->projected_set < (numGroupingSets - 1))
2400 nextSetSize = aggstate->phase->gset_lengths[aggstate->projected_set + 1];
2401 else
2402 nextSetSize = 0;
2403
2404 /*----------
2405 * If a subgroup for the current grouping set is present, project it.
2406 *
2407 * We have a new group if:
2408 * - we're out of input but haven't projected all grouping sets
2409 * (checked above)
2410 * OR
2411 * - we already projected a row that wasn't from the last grouping
2412 * set
2413 * AND
2414 * - the next grouping set has at least one grouping column (since
2415 * empty grouping sets project only once input is exhausted)
2416 * AND
2417 * - the previous and pending rows differ on the grouping columns
2418 * of the next grouping set
2419 *----------
2420 */
2421 tmpcontext->ecxt_innertuple = econtext->ecxt_outertuple;
2422 if (aggstate->input_done ||
2423 (node->aggstrategy != AGG_PLAIN &&
2424 aggstate->projected_set != -1 &&
2425 aggstate->projected_set < (numGroupingSets - 1) &&
2426 nextSetSize > 0 &&
2427 !ExecQualAndReset(aggstate->phase->eqfunctions[nextSetSize - 1],
2428 tmpcontext)))
2429 {
2430 aggstate->projected_set += 1;
2431
2432 Assert(aggstate->projected_set < numGroupingSets);
2433 Assert(nextSetSize > 0 || aggstate->input_done);
2434 }
2435 else
2436 {
2437 /*
2438 * We no longer care what group we just projected, the next
2439 * projection will always be the first (or only) grouping set
2440 * (unless the input proves to be empty).
2441 */
2442 aggstate->projected_set = 0;
2443
2444 /*
2445 * If we don't already have the first tuple of the new group,
2446 * fetch it from the outer plan.
2447 */
2448 if (aggstate->grp_firstTuple == NULL)
2449 {
2450 outerslot = fetch_input_tuple(aggstate);
2451 if (!TupIsNull(outerslot))
2452 {
2453 /*
2454 * Make a copy of the first input tuple; we will use this
2455 * for comparisons (in group mode) and for projection.
2456 */
2457 aggstate->grp_firstTuple = ExecCopySlotHeapTuple(outerslot);
2458 }
2459 else
2460 {
2461 /* outer plan produced no tuples at all */
2462 if (hasGroupingSets)
2463 {
2464 /*
2465 * If there was no input at all, we need to project
2466 * rows only if there are grouping sets of size 0.
2467 * Note that this implies that there can't be any
2468 * references to ungrouped Vars, which would otherwise
2469 * cause issues with the empty output slot.
2470 *
2471 * XXX: This is no longer true, we currently deal with
2472 * this in finalize_aggregates().
2473 */
2474 aggstate->input_done = true;
2475
2476 while (aggstate->phase->gset_lengths[aggstate->projected_set] > 0)
2477 {
2478 aggstate->projected_set += 1;
2479 if (aggstate->projected_set >= numGroupingSets)
2480 {
2481 /*
2482 * We can't set agg_done here because we might
2483 * have more phases to do, even though the
2484 * input is empty. So we need to restart the
2485 * whole outer loop.
2486 */
2487 break;
2488 }
2489 }
2490
2491 if (aggstate->projected_set >= numGroupingSets)
2492 continue;
2493 }
2494 else
2495 {
2496 aggstate->agg_done = true;
2497 /* If we are grouping, we should produce no tuples too */
2498 if (node->aggstrategy != AGG_PLAIN)
2499 return NULL;
2500 }
2501 }
2502 }
2503
2504 /*
2505 * Initialize working state for a new input tuple group.
2506 */
2507 initialize_aggregates(aggstate, pergroups, numReset);
2508
2509 if (aggstate->grp_firstTuple != NULL)
2510 {
2511 /*
2512 * Store the copied first input tuple in the tuple table slot
2513 * reserved for it. The tuple will be deleted when it is
2514 * cleared from the slot.
2515 */
2517 firstSlot, true);
2518 aggstate->grp_firstTuple = NULL; /* don't keep two pointers */
2519
2520 /* set up for first advance_aggregates call */
2521 tmpcontext->ecxt_outertuple = firstSlot;
2522
2523 /*
2524 * Process each outer-plan tuple, and then fetch the next one,
2525 * until we exhaust the outer plan or cross a group boundary.
2526 */
2527 for (;;)
2528 {
2529 /*
2530 * During phase 1 only of a mixed agg, we need to update
2531 * hashtables as well in advance_aggregates.
2532 */
2533 if (aggstate->aggstrategy == AGG_MIXED &&
2534 aggstate->current_phase == 1)
2535 {
2536 lookup_hash_entries(aggstate);
2537 }
2538
2539 /* Advance the aggregates (or combine functions) */
2540 advance_aggregates(aggstate);
2541
2542 /* Reset per-input-tuple context after each tuple */
2543 ResetExprContext(tmpcontext);
2544
2545 outerslot = fetch_input_tuple(aggstate);
2546 if (TupIsNull(outerslot))
2547 {
2548 /* no more outer-plan tuples available */
2549
2550 /* if we built hash tables, finalize any spills */
2551 if (aggstate->aggstrategy == AGG_MIXED &&
2552 aggstate->current_phase == 1)
2554
2555 if (hasGroupingSets)
2556 {
2557 aggstate->input_done = true;
2558 break;
2559 }
2560 else
2561 {
2562 aggstate->agg_done = true;
2563 break;
2564 }
2565 }
2566 /* set up for next advance_aggregates call */
2567 tmpcontext->ecxt_outertuple = outerslot;
2568
2569 /*
2570 * If we are grouping, check whether we've crossed a group
2571 * boundary.
2572 */
2573 if (node->aggstrategy != AGG_PLAIN && node->numCols > 0)
2574 {
2575 tmpcontext->ecxt_innertuple = firstSlot;
2576 if (!ExecQual(aggstate->phase->eqfunctions[node->numCols - 1],
2577 tmpcontext))
2578 {
2579 aggstate->grp_firstTuple = ExecCopySlotHeapTuple(outerslot);
2580 break;
2581 }
2582 }
2583 }
2584 }
2585
2586 /*
2587 * Use the representative input tuple for any references to
2588 * non-aggregated input columns in aggregate direct args, the node
2589 * qual, and the tlist. (If we are not grouping, and there are no
2590 * input rows at all, we will come here with an empty firstSlot
2591 * ... but if not grouping, there can't be any references to
2592 * non-aggregated input columns, so no problem.)
2593 */
2594 econtext->ecxt_outertuple = firstSlot;
2595 }
2596
2597 Assert(aggstate->projected_set >= 0);
2598
2599 currentSet = aggstate->projected_set;
2600
2601 prepare_projection_slot(aggstate, econtext->ecxt_outertuple, currentSet);
2602
2603 select_current_set(aggstate, currentSet, false);
2604
2605 finalize_aggregates(aggstate,
2606 peragg,
2607 pergroups[currentSet]);
2608
2609 /*
2610 * If there's no row to project right now, we must continue rather
2611 * than returning a null since there might be more groups.
2612 */
2613 result = project_aggregates(aggstate);
2614 if (result)
2615 return result;
2616 }
2617
2618 /* No more groups */
2619 return NULL;
2620}
#define Max(x, y)
Definition: c.h:969
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1658
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:541
static bool ExecQualAndReset(ExprState *state, ExprContext *econtext)
Definition: executor.h:568
static TupleTableSlot * project_aggregates(AggState *aggstate)
Definition: nodeAgg.c:1370
static void finalize_aggregates(AggState *aggstate, AggStatePerAgg peraggs, AggStatePerGroup pergroup)
Definition: nodeAgg.c:1293
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:479
static void initialize_aggregates(AggState *aggstate, AggStatePerGroup *pergroups, int numReset)
Definition: nodeAgg.c:667
static void prepare_projection_slot(AggState *aggstate, TupleTableSlot *slot, int currentSet)
Definition: nodeAgg.c:1248
static TupleTableSlot * agg_retrieve_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2835
@ AGG_PLAIN
Definition: nodes.h:360
ExprState ** eqfunctions
Definition: nodeAgg.h:286
ScanState ss
Definition: execnodes.h:2527
HeapTuple grp_firstTuple
Definition: execnodes.h:2565
AggStrategy aggstrategy
Definition: execnodes.h:2531
int projected_set
Definition: execnodes.h:2548
bool input_done
Definition: execnodes.h:2546
AggStatePerGroup * pergroups
Definition: execnodes.h:2563
int numphases
Definition: execnodes.h:2534
AggStatePerAgg peragg
Definition: execnodes.h:2536
ExprContext ** aggcontexts
Definition: execnodes.h:2539
bool agg_done
Definition: execnodes.h:2547
int numCols
Definition: plannodes.h:1149
AggStrategy aggstrategy
Definition: plannodes.h:1143
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:270
ExprContext * ps_ExprContext
Definition: execnodes.h:1198
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1618
PlanState ps
Definition: execnodes.h:1615
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:485

References advance_aggregates(), AggState::agg_done, AGG_MIXED, AGG_PLAIN, agg_retrieve_hash_table(), AggState::aggcontexts, AggStatePerPhaseData::aggnode, AggState::aggstrategy, Agg::aggstrategy, Assert(), AggState::current_phase, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, AggStatePerPhaseData::eqfunctions, ExecCopySlotHeapTuple(), ExecForceStoreHeapTuple(), ExecQual(), ExecQualAndReset(), fetch_input_tuple(), finalize_aggregates(), AggState::grp_firstTuple, AggStatePerPhaseData::gset_lengths, hashagg_finish_initial_spills(), AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, i, initialize_aggregates(), initialize_phase(), AggState::input_done, lookup_hash_entries(), Max, Agg::numCols, AggState::numphases, AggStatePerPhaseData::numsets, AggState::peragg, AggState::pergroups, AggState::perhash, AggState::phase, prepare_projection_slot(), project_aggregates(), AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, ReScanExprContext(), ResetExprContext, ResetTupleHashIterator, select_current_set(), AggState::ss, ScanState::ss_ScanTupleSlot, AggState::table_filled, AggState::tmpcontext, and TupIsNull.

Referenced by ExecAgg().

◆ agg_retrieve_hash_table()

static TupleTableSlot * agg_retrieve_hash_table ( AggState aggstate)
static

Definition at line 2835 of file nodeAgg.c.

2836{
2837 TupleTableSlot *result = NULL;
2838
2839 while (result == NULL)
2840 {
2841 result = agg_retrieve_hash_table_in_memory(aggstate);
2842 if (result == NULL)
2843 {
2844 if (!agg_refill_hash_table(aggstate))
2845 {
2846 aggstate->agg_done = true;
2847 break;
2848 }
2849 }
2850 }
2851
2852 return result;
2853}
static bool agg_refill_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2680
static TupleTableSlot * agg_retrieve_hash_table_in_memory(AggState *aggstate)
Definition: nodeAgg.c:2860

References AggState::agg_done, agg_refill_hash_table(), and agg_retrieve_hash_table_in_memory().

Referenced by agg_retrieve_direct(), and ExecAgg().

◆ agg_retrieve_hash_table_in_memory()

static TupleTableSlot * agg_retrieve_hash_table_in_memory ( AggState aggstate)
static

Definition at line 2860 of file nodeAgg.c.

2861{
2862 ExprContext *econtext;
2863 AggStatePerAgg peragg;
2864 AggStatePerGroup pergroup;
2865 TupleHashEntry entry;
2866 TupleTableSlot *firstSlot;
2867 TupleTableSlot *result;
2868 AggStatePerHash perhash;
2869
2870 /*
2871 * get state info from node.
2872 *
2873 * econtext is the per-output-tuple expression context.
2874 */
2875 econtext = aggstate->ss.ps.ps_ExprContext;
2876 peragg = aggstate->peragg;
2877 firstSlot = aggstate->ss.ss_ScanTupleSlot;
2878
2879 /*
2880 * Note that perhash (and therefore anything accessed through it) can
2881 * change inside the loop, as we change between grouping sets.
2882 */
2883 perhash = &aggstate->perhash[aggstate->current_set];
2884
2885 /*
2886 * We loop retrieving groups until we find one satisfying
2887 * aggstate->ss.ps.qual
2888 */
2889 for (;;)
2890 {
2891 TupleTableSlot *hashslot = perhash->hashslot;
2892 TupleHashTable hashtable = perhash->hashtable;
2893 int i;
2894
2896
2897 /*
2898 * Find the next entry in the hash table
2899 */
2900 entry = ScanTupleHashTable(hashtable, &perhash->hashiter);
2901 if (entry == NULL)
2902 {
2903 int nextset = aggstate->current_set + 1;
2904
2905 if (nextset < aggstate->num_hashes)
2906 {
2907 /*
2908 * Switch to next grouping set, reinitialize, and restart the
2909 * loop.
2910 */
2911 select_current_set(aggstate, nextset, true);
2912
2913 perhash = &aggstate->perhash[aggstate->current_set];
2914
2915 ResetTupleHashIterator(hashtable, &perhash->hashiter);
2916
2917 continue;
2918 }
2919 else
2920 {
2921 return NULL;
2922 }
2923 }
2924
2925 /*
2926 * Clear the per-output-tuple context for each group
2927 *
2928 * We intentionally don't use ReScanExprContext here; if any aggs have
2929 * registered shutdown callbacks, they mustn't be called yet, since we
2930 * might not be done with that agg.
2931 */
2932 ResetExprContext(econtext);
2933
2934 /*
2935 * Transform representative tuple back into one with the right
2936 * columns.
2937 */
2938 ExecStoreMinimalTuple(TupleHashEntryGetTuple(entry), hashslot, false);
2939 slot_getallattrs(hashslot);
2940
2941 ExecClearTuple(firstSlot);
2942 memset(firstSlot->tts_isnull, true,
2943 firstSlot->tts_tupleDescriptor->natts * sizeof(bool));
2944
2945 for (i = 0; i < perhash->numhashGrpCols; i++)
2946 {
2947 int varNumber = perhash->hashGrpColIdxInput[i] - 1;
2948
2949 firstSlot->tts_values[varNumber] = hashslot->tts_values[i];
2950 firstSlot->tts_isnull[varNumber] = hashslot->tts_isnull[i];
2951 }
2952 ExecStoreVirtualTuple(firstSlot);
2953
2954 pergroup = (AggStatePerGroup) TupleHashEntryGetAdditional(hashtable, entry);
2955
2956 /*
2957 * Use the representative input tuple for any references to
2958 * non-aggregated input columns in the qual and tlist.
2959 */
2960 econtext->ecxt_outertuple = firstSlot;
2961
2962 prepare_projection_slot(aggstate,
2963 econtext->ecxt_outertuple,
2964 aggstate->current_set);
2965
2966 finalize_aggregates(aggstate, peragg, pergroup);
2967
2968 result = project_aggregates(aggstate);
2969 if (result)
2970 return result;
2971 }
2972
2973 /* No more groups */
2974 return NULL;
2975}
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1741
#define ScanTupleHashTable(htable, iter)
Definition: execnodes.h:893
struct AggStatePerGroupData * AggStatePerGroup
Definition: execnodes.h:2521
static MinimalTuple TupleHashEntryGetTuple(TupleHashEntry entry)
Definition: executor.h:175
AttrNumber * hashGrpColIdxInput
Definition: nodeAgg.h:319
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:372

References CHECK_FOR_INTERRUPTS, AggState::current_set, ExprContext::ecxt_outertuple, ExecClearTuple(), ExecStoreMinimalTuple(), ExecStoreVirtualTuple(), finalize_aggregates(), AggStatePerHashData::hashGrpColIdxInput, AggStatePerHashData::hashiter, AggStatePerHashData::hashslot, AggStatePerHashData::hashtable, i, TupleDescData::natts, AggStatePerHashData::numhashGrpCols, AggState::peragg, AggState::perhash, prepare_projection_slot(), project_aggregates(), ScanState::ps, PlanState::ps_ExprContext, ResetExprContext, ResetTupleHashIterator, ScanTupleHashTable, select_current_set(), slot_getallattrs(), AggState::ss, ScanState::ss_ScanTupleSlot, TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, TupleTableSlot::tts_values, TupleHashEntryGetAdditional(), and TupleHashEntryGetTuple().

Referenced by agg_retrieve_hash_table().

◆ AggCheckCallContext()

int AggCheckCallContext ( FunctionCallInfo  fcinfo,
MemoryContext aggcontext 
)

Definition at line 4614 of file nodeAgg.c.

4615{
4616 if (fcinfo->context && IsA(fcinfo->context, AggState))
4617 {
4618 if (aggcontext)
4619 {
4620 AggState *aggstate = ((AggState *) fcinfo->context);
4621 ExprContext *cxt = aggstate->curaggcontext;
4622
4623 *aggcontext = cxt->ecxt_per_tuple_memory;
4624 }
4625 return AGG_CONTEXT_AGGREGATE;
4626 }
4627 if (fcinfo->context && IsA(fcinfo->context, WindowAggState))
4628 {
4629 if (aggcontext)
4630 *aggcontext = ((WindowAggState *) fcinfo->context)->curaggcontext;
4631 return AGG_CONTEXT_WINDOW;
4632 }
4633
4634 /* this is just to prevent "uninitialized variable" warnings */
4635 if (aggcontext)
4636 *aggcontext = NULL;
4637 return 0;
4638}
#define AGG_CONTEXT_WINDOW
Definition: fmgr.h:813
#define AGG_CONTEXT_AGGREGATE
Definition: fmgr.h:812
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
fmNodePtr context
Definition: fmgr.h:88

References AGG_CONTEXT_AGGREGATE, AGG_CONTEXT_WINDOW, FunctionCallInfoBaseData::context, AggState::curaggcontext, ExprContext::ecxt_per_tuple_memory, and IsA.

Referenced by array_agg_array_combine(), array_agg_array_deserialize(), array_agg_array_finalfn(), array_agg_array_serialize(), array_agg_array_transfn(), array_agg_combine(), array_agg_deserialize(), array_agg_finalfn(), array_agg_serialize(), array_agg_transfn(), bytea_string_agg_finalfn(), fetch_array_arg_replace_nulls(), float4_accum(), float8_accum(), float8_combine(), float8_regr_accum(), float8_regr_combine(), hypothetical_dense_rank_final(), hypothetical_rank_common(), int2_avg_accum(), int2_avg_accum_inv(), int2_sum(), int4_avg_accum(), int4_avg_accum_inv(), int4_avg_combine(), int4_sum(), int8_avg_combine(), int8_avg_deserialize(), int8_avg_serialize(), int8dec(), int8inc(), interval_avg_deserialize(), interval_avg_serialize(), json_agg_finalfn(), json_agg_transfn_worker(), json_object_agg_finalfn(), json_object_agg_transfn_worker(), jsonb_agg_finalfn(), jsonb_agg_transfn_worker(), jsonb_object_agg_finalfn(), jsonb_object_agg_transfn_worker(), makeBoolAggState(), makeIntervalAggState(), makeNumericAggState(), makeStringAggState(), mode_final(), multirange_agg_transfn(), multirange_intersect_agg_transfn(), numeric_avg_combine(), numeric_avg_deserialize(), numeric_avg_serialize(), numeric_combine(), numeric_deserialize(), numeric_poly_combine(), numeric_poly_deserialize(), numeric_poly_serialize(), numeric_serialize(), ordered_set_startup(), percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), percentile_disc_multi_final(), range_agg_finalfn(), range_agg_transfn(), range_intersect_agg_transfn(), string_agg_combine(), string_agg_deserialize(), string_agg_finalfn(), and string_agg_serialize().

◆ AggGetAggref()

Aggref * AggGetAggref ( FunctionCallInfo  fcinfo)

Definition at line 4658 of file nodeAgg.c.

4659{
4660 if (fcinfo->context && IsA(fcinfo->context, AggState))
4661 {
4662 AggState *aggstate = (AggState *) fcinfo->context;
4663 AggStatePerAgg curperagg;
4664 AggStatePerTrans curpertrans;
4665
4666 /* check curperagg (valid when in a final function) */
4667 curperagg = aggstate->curperagg;
4668
4669 if (curperagg)
4670 return curperagg->aggref;
4671
4672 /* check curpertrans (valid when in a transition function) */
4673 curpertrans = aggstate->curpertrans;
4674
4675 if (curpertrans)
4676 return curpertrans->aggref;
4677 }
4678 return NULL;
4679}
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
Aggref * aggref
Definition: nodeAgg.h:44
AggStatePerAgg curperagg
Definition: execnodes.h:2543

References AggStatePerTransData::aggref, FunctionCallInfoBaseData::context, AggState::curperagg, AggState::curpertrans, if(), and IsA.

Referenced by ordered_set_startup().

◆ AggGetTempMemoryContext()

MemoryContext AggGetTempMemoryContext ( FunctionCallInfo  fcinfo)

Definition at line 4692 of file nodeAgg.c.

4693{
4694 if (fcinfo->context && IsA(fcinfo->context, AggState))
4695 {
4696 AggState *aggstate = (AggState *) fcinfo->context;
4697
4698 return aggstate->tmpcontext->ecxt_per_tuple_memory;
4699 }
4700 return NULL;
4701}

References FunctionCallInfoBaseData::context, ExprContext::ecxt_per_tuple_memory, IsA, and AggState::tmpcontext.

◆ AggRegisterCallback()

void AggRegisterCallback ( FunctionCallInfo  fcinfo,
ExprContextCallbackFunction  func,
Datum  arg 
)

Definition at line 4757 of file nodeAgg.c.

4760{
4761 if (fcinfo->context && IsA(fcinfo->context, AggState))
4762 {
4763 AggState *aggstate = (AggState *) fcinfo->context;
4764 ExprContext *cxt = aggstate->curaggcontext;
4765
4766 RegisterExprContextCallback(cxt, func, arg);
4767
4768 return;
4769 }
4770 elog(ERROR, "aggregate function cannot register a callback in this context");
4771}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:964
void * arg

References arg, FunctionCallInfoBaseData::context, AggState::curaggcontext, elog, ERROR, IsA, and RegisterExprContextCallback().

Referenced by ordered_set_startup().

◆ AggStateIsShared()

bool AggStateIsShared ( FunctionCallInfo  fcinfo)

Definition at line 4718 of file nodeAgg.c.

4719{
4720 if (fcinfo->context && IsA(fcinfo->context, AggState))
4721 {
4722 AggState *aggstate = (AggState *) fcinfo->context;
4723 AggStatePerAgg curperagg;
4724 AggStatePerTrans curpertrans;
4725
4726 /* check curperagg (valid when in a final function) */
4727 curperagg = aggstate->curperagg;
4728
4729 if (curperagg)
4730 return aggstate->pertrans[curperagg->transno].aggshared;
4731
4732 /* check curpertrans (valid when in a transition function) */
4733 curpertrans = aggstate->curpertrans;
4734
4735 if (curpertrans)
4736 return curpertrans->aggshared;
4737 }
4738 return true;
4739}
AggStatePerTrans pertrans
Definition: execnodes.h:2537

References AggStatePerTransData::aggshared, FunctionCallInfoBaseData::context, AggState::curperagg, AggState::curpertrans, if(), IsA, and AggState::pertrans.

Referenced by ordered_set_startup().

◆ build_hash_table()

static void build_hash_table ( AggState aggstate,
int  setno,
long  nbuckets 
)
static

Definition at line 1509 of file nodeAgg.c.

1510{
1511 AggStatePerHash perhash = &aggstate->perhash[setno];
1512 MemoryContext metacxt = aggstate->hash_metacxt;
1513 MemoryContext tablecxt = aggstate->hash_tablecxt;
1515 Size additionalsize;
1516
1517 Assert(aggstate->aggstrategy == AGG_HASHED ||
1518 aggstate->aggstrategy == AGG_MIXED);
1519
1520 /*
1521 * Used to make sure initial hash table allocation does not exceed
1522 * hash_mem. Note that the estimate does not include space for
1523 * pass-by-reference transition data values, nor for the representative
1524 * tuple of each group.
1525 */
1526 additionalsize = aggstate->numtrans * sizeof(AggStatePerGroupData);
1527
1528 perhash->hashtable = BuildTupleHashTable(&aggstate->ss.ps,
1529 perhash->hashslot->tts_tupleDescriptor,
1530 perhash->hashslot->tts_ops,
1531 perhash->numCols,
1532 perhash->hashGrpColIdxHash,
1533 perhash->eqfuncoids,
1534 perhash->hashfunctions,
1535 perhash->aggnode->grpCollations,
1536 nbuckets,
1537 additionalsize,
1538 metacxt,
1539 tablecxt,
1540 tmpcxt,
1541 DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit));
1542}
size_t Size
Definition: c.h:576
TupleHashTable BuildTupleHashTable(PlanState *parent, TupleDesc inputDesc, const TupleTableSlotOps *inputOps, int numCols, AttrNumber *keyColIdx, const Oid *eqfuncoids, FmgrInfo *hashfunctions, Oid *collations, long nbuckets, Size additionalsize, MemoryContext metacxt, MemoryContext tablecxt, MemoryContext tempcxt, bool use_variable_hash_iv)
Definition: execGrouping.c:161
struct AggStatePerGroupData AggStatePerGroupData
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:392
@ AGG_HASHED
Definition: nodes.h:362
FmgrInfo * hashfunctions
Definition: nodeAgg.h:314
AttrNumber * hashGrpColIdxHash
Definition: nodeAgg.h:320
MemoryContext hash_metacxt
Definition: execnodes.h:2569
int numtrans
Definition: execnodes.h:2530
AggSplit aggsplit
Definition: execnodes.h:2532
const TupleTableSlotOps *const tts_ops
Definition: tuptable.h:121

References AGG_HASHED, AGG_MIXED, AggStatePerHashData::aggnode, AggState::aggsplit, AggState::aggstrategy, Assert(), BuildTupleHashTable(), DO_AGGSPLIT_SKIPFINAL, ExprContext::ecxt_per_tuple_memory, AggStatePerHashData::eqfuncoids, AggState::hash_metacxt, AggState::hash_tablecxt, AggStatePerHashData::hashfunctions, AggStatePerHashData::hashGrpColIdxHash, AggStatePerHashData::hashslot, AggStatePerHashData::hashtable, AggStatePerHashData::numCols, AggState::numtrans, AggState::perhash, ScanState::ps, AggState::ss, AggState::tmpcontext, TupleTableSlot::tts_ops, and TupleTableSlot::tts_tupleDescriptor.

Referenced by build_hash_tables().

◆ build_hash_tables()

static void build_hash_tables ( AggState aggstate)
static

Definition at line 1466 of file nodeAgg.c.

1467{
1468 int setno;
1469
1470 for (setno = 0; setno < aggstate->num_hashes; ++setno)
1471 {
1472 AggStatePerHash perhash = &aggstate->perhash[setno];
1473 long nbuckets;
1474 Size memory;
1475
1476 if (perhash->hashtable != NULL)
1477 {
1479 continue;
1480 }
1481
1482 Assert(perhash->aggnode->numGroups > 0);
1483
1484 memory = aggstate->hash_mem_limit / aggstate->num_hashes;
1485
1486 /* choose reasonable number of buckets per hashtable */
1487 nbuckets = hash_choose_num_buckets(aggstate->hashentrysize,
1488 perhash->aggnode->numGroups,
1489 memory);
1490
1491#ifdef USE_INJECTION_POINTS
1492 if (IS_INJECTION_POINT_ATTACHED("hash-aggregate-oversize-table"))
1493 {
1494 nbuckets = memory / TupleHashEntrySize();
1495 INJECTION_POINT_CACHED("hash-aggregate-oversize-table");
1496 }
1497#endif
1498
1499 build_hash_table(aggstate, setno, nbuckets);
1500 }
1501
1502 aggstate->hash_ngroups_current = 0;
1503}
static size_t TupleHashEntrySize(void)
Definition: executor.h:166
#define INJECTION_POINT_CACHED(name)
#define IS_INJECTION_POINT_ATTACHED(name)
static long hash_choose_num_buckets(double hashentrysize, long ngroups, Size memory)
Definition: nodeAgg.c:2058
static void build_hash_table(AggState *aggstate, int setno, long nbuckets)
Definition: nodeAgg.c:1509
long numGroups
Definition: plannodes.h:1159

References AggStatePerHashData::aggnode, Assert(), build_hash_table(), hash_choose_num_buckets(), AggState::hash_mem_limit, AggState::hash_ngroups_current, AggState::hashentrysize, AggStatePerHashData::hashtable, INJECTION_POINT_CACHED, IS_INJECTION_POINT_ATTACHED, AggState::num_hashes, Agg::numGroups, AggState::perhash, ResetTupleHashTable(), and TupleHashEntrySize().

Referenced by ExecInitAgg(), and ExecReScanAgg().

◆ build_pertrans_for_aggref()

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

Definition at line 4134 of file nodeAgg.c.

4141{
4142 int numGroupingSets = Max(aggstate->maxsets, 1);
4143 Expr *transfnexpr;
4144 int numTransArgs;
4145 Expr *serialfnexpr = NULL;
4146 Expr *deserialfnexpr = NULL;
4147 ListCell *lc;
4148 int numInputs;
4149 int numDirectArgs;
4150 List *sortlist;
4151 int numSortCols;
4152 int numDistinctCols;
4153 int i;
4154
4155 /* Begin filling in the pertrans data */
4156 pertrans->aggref = aggref;
4157 pertrans->aggshared = false;
4158 pertrans->aggCollation = aggref->inputcollid;
4159 pertrans->transfn_oid = transfn_oid;
4160 pertrans->serialfn_oid = aggserialfn;
4161 pertrans->deserialfn_oid = aggdeserialfn;
4162 pertrans->initValue = initValue;
4163 pertrans->initValueIsNull = initValueIsNull;
4164
4165 /* Count the "direct" arguments, if any */
4166 numDirectArgs = list_length(aggref->aggdirectargs);
4167
4168 /* Count the number of aggregated input columns */
4169 pertrans->numInputs = numInputs = list_length(aggref->args);
4170
4171 pertrans->aggtranstype = aggtranstype;
4172
4173 /* account for the current transition state */
4174 numTransArgs = pertrans->numTransInputs + 1;
4175
4176 /*
4177 * Set up infrastructure for calling the transfn. Note that invtransfn is
4178 * not needed here.
4179 */
4181 numArguments,
4182 numDirectArgs,
4183 aggref->aggvariadic,
4184 aggtranstype,
4185 aggref->inputcollid,
4186 transfn_oid,
4187 InvalidOid,
4188 &transfnexpr,
4189 NULL);
4190
4191 fmgr_info(transfn_oid, &pertrans->transfn);
4192 fmgr_info_set_expr((Node *) transfnexpr, &pertrans->transfn);
4193
4194 pertrans->transfn_fcinfo =
4197 &pertrans->transfn,
4198 numTransArgs,
4199 pertrans->aggCollation,
4200 (Node *) aggstate, NULL);
4201
4202 /* get info about the state value's datatype */
4203 get_typlenbyval(aggtranstype,
4204 &pertrans->transtypeLen,
4205 &pertrans->transtypeByVal);
4206
4207 if (OidIsValid(aggserialfn))
4208 {
4210 &serialfnexpr);
4211 fmgr_info(aggserialfn, &pertrans->serialfn);
4212 fmgr_info_set_expr((Node *) serialfnexpr, &pertrans->serialfn);
4213
4214 pertrans->serialfn_fcinfo =
4217 &pertrans->serialfn,
4218 1,
4219 InvalidOid,
4220 (Node *) aggstate, NULL);
4221 }
4222
4223 if (OidIsValid(aggdeserialfn))
4224 {
4225 build_aggregate_deserialfn_expr(aggdeserialfn,
4226 &deserialfnexpr);
4227 fmgr_info(aggdeserialfn, &pertrans->deserialfn);
4228 fmgr_info_set_expr((Node *) deserialfnexpr, &pertrans->deserialfn);
4229
4230 pertrans->deserialfn_fcinfo =
4233 &pertrans->deserialfn,
4234 2,
4235 InvalidOid,
4236 (Node *) aggstate, NULL);
4237 }
4238
4239 /*
4240 * If we're doing either DISTINCT or ORDER BY for a plain agg, then we
4241 * have a list of SortGroupClause nodes; fish out the data in them and
4242 * stick them into arrays. We ignore ORDER BY for an ordered-set agg,
4243 * however; the agg's transfn and finalfn are responsible for that.
4244 *
4245 * When the planner has set the aggpresorted flag, the input to the
4246 * aggregate is already correctly sorted. For ORDER BY aggregates we can
4247 * simply treat these as normal aggregates. For presorted DISTINCT
4248 * aggregates an extra step must be added to remove duplicate consecutive
4249 * inputs.
4250 *
4251 * Note that by construction, if there is a DISTINCT clause then the ORDER
4252 * BY clause is a prefix of it (see transformDistinctClause).
4253 */
4254 if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
4255 {
4256 sortlist = NIL;
4257 numSortCols = numDistinctCols = 0;
4258 pertrans->aggsortrequired = false;
4259 }
4260 else if (aggref->aggpresorted && aggref->aggdistinct == NIL)
4261 {
4262 sortlist = NIL;
4263 numSortCols = numDistinctCols = 0;
4264 pertrans->aggsortrequired = false;
4265 }
4266 else if (aggref->aggdistinct)
4267 {
4268 sortlist = aggref->aggdistinct;
4269 numSortCols = numDistinctCols = list_length(sortlist);
4270 Assert(numSortCols >= list_length(aggref->aggorder));
4271 pertrans->aggsortrequired = !aggref->aggpresorted;
4272 }
4273 else
4274 {
4275 sortlist = aggref->aggorder;
4276 numSortCols = list_length(sortlist);
4277 numDistinctCols = 0;
4278 pertrans->aggsortrequired = (numSortCols > 0);
4279 }
4280
4281 pertrans->numSortCols = numSortCols;
4282 pertrans->numDistinctCols = numDistinctCols;
4283
4284 /*
4285 * If we have either sorting or filtering to do, create a tupledesc and
4286 * slot corresponding to the aggregated inputs (including sort
4287 * expressions) of the agg.
4288 */
4289 if (numSortCols > 0 || aggref->aggfilter)
4290 {
4291 pertrans->sortdesc = ExecTypeFromTL(aggref->args);
4292 pertrans->sortslot =
4293 ExecInitExtraTupleSlot(estate, pertrans->sortdesc,
4295 }
4296
4297 if (numSortCols > 0)
4298 {
4299 /*
4300 * We don't implement DISTINCT or ORDER BY aggs in the HASHED case
4301 * (yet)
4302 */
4303 Assert(aggstate->aggstrategy != AGG_HASHED && aggstate->aggstrategy != AGG_MIXED);
4304
4305 /* ORDER BY aggregates are not supported with partial aggregation */
4306 Assert(!DO_AGGSPLIT_COMBINE(aggstate->aggsplit));
4307
4308 /* If we have only one input, we need its len/byval info. */
4309 if (numInputs == 1)
4310 {
4311 get_typlenbyval(inputTypes[numDirectArgs],
4312 &pertrans->inputtypeLen,
4313 &pertrans->inputtypeByVal);
4314 }
4315 else if (numDistinctCols > 0)
4316 {
4317 /* we will need an extra slot to store prior values */
4318 pertrans->uniqslot =
4319 ExecInitExtraTupleSlot(estate, pertrans->sortdesc,
4321 }
4322
4323 /* Extract the sort information for use later */
4324 pertrans->sortColIdx =
4325 (AttrNumber *) palloc(numSortCols * sizeof(AttrNumber));
4326 pertrans->sortOperators =
4327 (Oid *) palloc(numSortCols * sizeof(Oid));
4328 pertrans->sortCollations =
4329 (Oid *) palloc(numSortCols * sizeof(Oid));
4330 pertrans->sortNullsFirst =
4331 (bool *) palloc(numSortCols * sizeof(bool));
4332
4333 i = 0;
4334 foreach(lc, sortlist)
4335 {
4336 SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
4337 TargetEntry *tle = get_sortgroupclause_tle(sortcl, aggref->args);
4338
4339 /* the parser should have made sure of this */
4340 Assert(OidIsValid(sortcl->sortop));
4341
4342 pertrans->sortColIdx[i] = tle->resno;
4343 pertrans->sortOperators[i] = sortcl->sortop;
4344 pertrans->sortCollations[i] = exprCollation((Node *) tle->expr);
4345 pertrans->sortNullsFirst[i] = sortcl->nulls_first;
4346 i++;
4347 }
4348 Assert(i == numSortCols);
4349 }
4350
4351 if (aggref->aggdistinct)
4352 {
4353 Oid *ops;
4354
4355 Assert(numArguments > 0);
4356 Assert(list_length(aggref->aggdistinct) == numDistinctCols);
4357
4358 ops = palloc(numDistinctCols * sizeof(Oid));
4359
4360 i = 0;
4361 foreach(lc, aggref->aggdistinct)
4362 ops[i++] = ((SortGroupClause *) lfirst(lc))->eqop;
4363
4364 /* lookup / build the necessary comparators */
4365 if (numDistinctCols == 1)
4366 fmgr_info(get_opcode(ops[0]), &pertrans->equalfnOne);
4367 else
4368 pertrans->equalfnMulti =
4370 numDistinctCols,
4371 pertrans->sortColIdx,
4372 ops,
4373 pertrans->sortCollations,
4374 &aggstate->ss.ps);
4375 pfree(ops);
4376 }
4377
4378 pertrans->sortstates = (Tuplesortstate **)
4379 palloc0(sizeof(Tuplesortstate *) * numGroupingSets);
4380}
int16 AttrNumber
Definition: attnum.h:21
#define OidIsValid(objectId)
Definition: c.h:746
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:58
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:2020
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
TupleDesc ExecTypeFromTL(List *targetList)
Definition: execTuples.c:2127
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define SizeForFunctionCallInfo(nargs)
Definition: fmgr.h:102
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
struct FunctionCallInfoBaseData * FunctionCallInfo
Definition: fmgr.h:38
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
static int initValue(long lng_val)
Definition: informix.c:702
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2391
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1425
void * palloc0(Size size)
Definition: mcxt.c:1969
void * palloc(Size size)
Definition: mcxt.c:1939
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:821
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:391
void build_aggregate_deserialfn_expr(Oid deserialfn_oid, Expr **deserialfnexpr)
Definition: parse_agg.c:2210
void build_aggregate_transfn_expr(Oid *agg_input_types, int agg_num_inputs, int agg_num_direct_inputs, bool agg_variadic, Oid agg_state_type, Oid agg_input_collation, Oid transfn_oid, Oid invtransfn_oid, Expr **transfnexpr, Expr **invtransfnexpr)
Definition: parse_agg.c:2126
void build_aggregate_serialfn_expr(Oid serialfn_oid, Expr **serialfnexpr)
Definition: parse_agg.c:2187
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
bool * sortNullsFirst
Definition: nodeAgg.h:108
FmgrInfo serialfn
Definition: nodeAgg.h:89
FmgrInfo equalfnOne
Definition: nodeAgg.h:115
TupleDesc sortdesc
Definition: nodeAgg.h:143
TupleTableSlot * sortslot
Definition: nodeAgg.h:141
ExprState * equalfnMulti
Definition: nodeAgg.h:116
Tuplesortstate ** sortstates
Definition: nodeAgg.h:162
TupleTableSlot * uniqslot
Definition: nodeAgg.h:142
FmgrInfo deserialfn
Definition: nodeAgg.h:92
FunctionCallInfo deserialfn_fcinfo
Definition: nodeAgg.h:175
AttrNumber * sortColIdx
Definition: nodeAgg.h:105
FunctionCallInfo serialfn_fcinfo
Definition: nodeAgg.h:173
int maxsets
Definition: execnodes.h:2557
List * aggdistinct
Definition: primnodes.h:491
List * aggdirectargs
Definition: primnodes.h:482
List * args
Definition: primnodes.h:485
Expr * aggfilter
Definition: primnodes.h:494
List * aggorder
Definition: primnodes.h:488
Definition: pg_list.h:54
Definition: nodes.h:135
Expr * expr
Definition: primnodes.h:2219
AttrNumber resno
Definition: primnodes.h:2221
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

References AGG_HASHED, AGG_MIXED, AggStatePerTransData::aggCollation, Aggref::aggdirectargs, Aggref::aggdistinct, Aggref::aggfilter, Aggref::aggorder, AggStatePerTransData::aggref, AggStatePerTransData::aggshared, AggStatePerTransData::aggsortrequired, AggState::aggsplit, AggState::aggstrategy, AggStatePerTransData::aggtranstype, Aggref::args, Assert(), build_aggregate_deserialfn_expr(), build_aggregate_serialfn_expr(), build_aggregate_transfn_expr(), AggStatePerTransData::deserialfn, AggStatePerTransData::deserialfn_fcinfo, AggStatePerTransData::deserialfn_oid, DO_AGGSPLIT_COMBINE, AggStatePerTransData::equalfnMulti, AggStatePerTransData::equalfnOne, ExecInitExtraTupleSlot(), execTuplesMatchPrepare(), ExecTypeFromTL(), TargetEntry::expr, exprCollation(), fmgr_info(), fmgr_info_set_expr, get_opcode(), get_sortgroupclause_tle(), get_typlenbyval(), i, InitFunctionCallInfoData, AggStatePerTransData::initValue, initValue(), AggStatePerTransData::initValueIsNull, AggStatePerTransData::inputtypeByVal, AggStatePerTransData::inputtypeLen, InvalidOid, lfirst, list_length(), Max, AggState::maxsets, NIL, SortGroupClause::nulls_first, AggStatePerTransData::numDistinctCols, AggStatePerTransData::numInputs, AggStatePerTransData::numSortCols, AggStatePerTransData::numTransInputs, OidIsValid, palloc(), palloc0(), pfree(), ScanState::ps, TargetEntry::resno, AggStatePerTransData::serialfn, AggStatePerTransData::serialfn_fcinfo, AggStatePerTransData::serialfn_oid, SizeForFunctionCallInfo, AggStatePerTransData::sortColIdx, AggStatePerTransData::sortCollations, AggStatePerTransData::sortdesc, AggStatePerTransData::sortNullsFirst, SortGroupClause::sortop, AggStatePerTransData::sortOperators, AggStatePerTransData::sortslot, AggStatePerTransData::sortstates, AggState::ss, AggStatePerTransData::transfn, AggStatePerTransData::transfn_fcinfo, AggStatePerTransData::transfn_oid, AggStatePerTransData::transtypeByVal, AggStatePerTransData::transtypeLen, TTSOpsMinimalTuple, and AggStatePerTransData::uniqslot.

Referenced by ExecInitAgg().

◆ ExecAgg()

static TupleTableSlot * ExecAgg ( PlanState pstate)
static

Definition at line 2244 of file nodeAgg.c.

2245{
2246 AggState *node = castNode(AggState, pstate);
2247 TupleTableSlot *result = NULL;
2248
2250
2251 if (!node->agg_done)
2252 {
2253 /* Dispatch based on strategy */
2254 switch (node->phase->aggstrategy)
2255 {
2256 case AGG_HASHED:
2257 if (!node->table_filled)
2258 agg_fill_hash_table(node);
2259 /* FALLTHROUGH */
2260 case AGG_MIXED:
2261 result = agg_retrieve_hash_table(node);
2262 break;
2263 case AGG_PLAIN:
2264 case AGG_SORTED:
2265 result = agg_retrieve_direct(node);
2266 break;
2267 }
2268
2269 if (!TupIsNull(result))
2270 return result;
2271 }
2272
2273 return NULL;
2274}
static void agg_fill_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2626
static TupleTableSlot * agg_retrieve_direct(AggState *aggstate)
Definition: nodeAgg.c:2280
@ AGG_SORTED
Definition: nodes.h:361
#define castNode(_type_, nodeptr)
Definition: nodes.h:182

References AggState::agg_done, agg_fill_hash_table(), AGG_HASHED, AGG_MIXED, AGG_PLAIN, agg_retrieve_direct(), agg_retrieve_hash_table(), AGG_SORTED, AggStatePerPhaseData::aggstrategy, castNode, CHECK_FOR_INTERRUPTS, AggState::phase, AggState::table_filled, and TupIsNull.

Referenced by ExecInitAgg().

◆ ExecAggEstimate()

void ExecAggEstimate ( AggState node,
ParallelContext pcxt 
)

Definition at line 4786 of file nodeAgg.c.

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

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

Referenced by ExecParallelEstimate().

◆ ExecAggInitializeDSM()

void ExecAggInitializeDSM ( AggState node,
ParallelContext pcxt 
)

Definition at line 4807 of file nodeAgg.c.

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

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

Referenced by ExecParallelInitializeDSM().

◆ ExecAggInitializeWorker()

void ExecAggInitializeWorker ( AggState node,
ParallelWorkerContext pwcxt 
)

Definition at line 4832 of file nodeAgg.c.

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

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

Referenced by ExecParallelInitializeWorker().

◆ ExecAggRetrieveInstrumentation()

void ExecAggRetrieveInstrumentation ( AggState node)

Definition at line 4845 of file nodeAgg.c.

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

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)

Definition at line 4400 of file nodeAgg.c.

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

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

Referenced by ExecEndNode().

◆ ExecInitAgg()

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

Definition at line 3279 of file nodeAgg.c.

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

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

Referenced by ExecInitNode().

◆ ExecReScanAgg()

void ExecReScanAgg ( AggState node)

Definition at line 4466 of file nodeAgg.c.

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

References AggState::agg_done, AGG_HASHED, AGG_MIXED, AggState::aggcontexts, Agg::aggParams, AggState::aggstrategy, bms_overlap(), build_hash_tables(), PlanState::chgParam, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, ExecClearTuple(), ExecReScan(), AggState::grp_firstTuple, AggState::hash_ever_spilled, AggState::hash_ngroups_current, AggState::hash_spill_mode, AggState::hash_tablecxt, hashagg_recompile_expressions(), hashagg_reset_spill_state(), AggState::hashcontext, AggStatePerHashData::hashiter, AggStatePerHashData::hashtable, heap_freetuple(), initialize_phase(), AggState::input_done, Max, AggState::maxsets, MemoryContextReset(), MemSet, AggState::numaggs, AggState::numtrans, outerPlan, outerPlanState, AggState::pergroups, AggState::perhash, AggState::pertrans, PlanState::plan, AggState::projected_set, ScanState::ps, PlanState::ps_ExprContext, ReScanExprContext(), ResetTupleHashIterator, select_current_set(), AggStatePerTransData::sortstates, AggState::ss, ScanState::ss_ScanTupleSlot, AggState::table_filled, and tuplesort_end().

Referenced by ExecReScan().

◆ fetch_input_tuple()

static TupleTableSlot * fetch_input_tuple ( AggState aggstate)
static

Definition at line 549 of file nodeAgg.c.

550{
551 TupleTableSlot *slot;
552
553 if (aggstate->sort_in)
554 {
555 /* make sure we check for interrupts in either path through here */
557 if (!tuplesort_gettupleslot(aggstate->sort_in, true, false,
558 aggstate->sort_slot, NULL))
559 return NULL;
560 slot = aggstate->sort_slot;
561 }
562 else
563 slot = ExecProcNode(outerPlanState(aggstate));
564
565 if (!TupIsNull(slot) && aggstate->sort_out)
566 tuplesort_puttupleslot(aggstate->sort_out, slot);
567
568 return slot;
569}
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:336
void tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot)
bool tuplesort_gettupleslot(Tuplesortstate *state, bool forward, bool copy, TupleTableSlot *slot, Datum *abbrev)

References CHECK_FOR_INTERRUPTS, ExecProcNode(), outerPlanState, AggState::sort_in, AggState::sort_out, AggState::sort_slot, TupIsNull, tuplesort_gettupleslot(), and tuplesort_puttupleslot().

Referenced by agg_fill_hash_table(), and agg_retrieve_direct().

◆ finalize_aggregate()

static void finalize_aggregate ( AggState aggstate,
AggStatePerAgg  peragg,
AggStatePerGroup  pergroupstate,
Datum resultVal,
bool *  resultIsNull 
)
static

Definition at line 1045 of file nodeAgg.c.

1049{
1050 LOCAL_FCINFO(fcinfo, FUNC_MAX_ARGS);
1051 bool anynull = false;
1052 MemoryContext oldContext;
1053 int i;
1054 ListCell *lc;
1055 AggStatePerTrans pertrans = &aggstate->pertrans[peragg->transno];
1056
1058
1059 /*
1060 * Evaluate any direct arguments. We do this even if there's no finalfn
1061 * (which is unlikely anyway), so that side-effects happen as expected.
1062 * The direct arguments go into arg positions 1 and up, leaving position 0
1063 * for the transition state value.
1064 */
1065 i = 1;
1066 foreach(lc, peragg->aggdirectargs)
1067 {
1068 ExprState *expr = (ExprState *) lfirst(lc);
1069
1070 fcinfo->args[i].value = ExecEvalExpr(expr,
1071 aggstate->ss.ps.ps_ExprContext,
1072 &fcinfo->args[i].isnull);
1073 anynull |= fcinfo->args[i].isnull;
1074 i++;
1075 }
1076
1077 /*
1078 * Apply the agg's finalfn if one is provided, else return transValue.
1079 */
1080 if (OidIsValid(peragg->finalfn_oid))
1081 {
1082 int numFinalArgs = peragg->numFinalArgs;
1083
1084 /* set up aggstate->curperagg for AggGetAggref() */
1085 aggstate->curperagg = peragg;
1086
1087 InitFunctionCallInfoData(*fcinfo, &peragg->finalfn,
1088 numFinalArgs,
1089 pertrans->aggCollation,
1090 (Node *) aggstate, NULL);
1091
1092 /* Fill in the transition state value */
1093 fcinfo->args[0].value =
1095 pergroupstate->transValueIsNull,
1096 pertrans->transtypeLen);
1097 fcinfo->args[0].isnull = pergroupstate->transValueIsNull;
1098 anynull |= pergroupstate->transValueIsNull;
1099
1100 /* Fill any remaining argument positions with nulls */
1101 for (; i < numFinalArgs; i++)
1102 {
1103 fcinfo->args[i].value = (Datum) 0;
1104 fcinfo->args[i].isnull = true;
1105 anynull = true;
1106 }
1107
1108 if (fcinfo->flinfo->fn_strict && anynull)
1109 {
1110 /* don't call a strict function with NULL inputs */
1111 *resultVal = (Datum) 0;
1112 *resultIsNull = true;
1113 }
1114 else
1115 {
1116 Datum result;
1117
1118 result = FunctionCallInvoke(fcinfo);
1119 *resultIsNull = fcinfo->isnull;
1120 *resultVal = MakeExpandedObjectReadOnly(result,
1121 fcinfo->isnull,
1122 peragg->resulttypeLen);
1123 }
1124 aggstate->curperagg = NULL;
1125 }
1126 else
1127 {
1128 *resultVal =
1130 pergroupstate->transValueIsNull,
1131 pertrans->transtypeLen);
1132 *resultIsNull = pergroupstate->transValueIsNull;
1133 }
1134
1135 MemoryContextSwitchTo(oldContext);
1136}
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:415
#define MakeExpandedObjectReadOnly(d, isnull, typlen)
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110

References AggStatePerTransData::aggCollation, AggStatePerAggData::aggdirectargs, AggState::curperagg, ExprContext::ecxt_per_tuple_memory, ExecEvalExpr(), AggStatePerAggData::finalfn, AggStatePerAggData::finalfn_oid, FUNC_MAX_ARGS, FunctionCallInvoke, i, InitFunctionCallInfoData, lfirst, LOCAL_FCINFO, MakeExpandedObjectReadOnly, MemoryContextSwitchTo(), AggStatePerAggData::numFinalArgs, OidIsValid, AggState::pertrans, ScanState::ps, PlanState::ps_ExprContext, AggStatePerAggData::resulttypeLen, AggState::ss, AggStatePerAggData::transno, AggStatePerTransData::transtypeLen, AggStatePerGroupData::transValue, and AggStatePerGroupData::transValueIsNull.

Referenced by finalize_aggregates().

◆ finalize_aggregates()

static void finalize_aggregates ( AggState aggstate,
AggStatePerAgg  peraggs,
AggStatePerGroup  pergroup 
)
static

Definition at line 1293 of file nodeAgg.c.

1296{
1297 ExprContext *econtext = aggstate->ss.ps.ps_ExprContext;
1298 Datum *aggvalues = econtext->ecxt_aggvalues;
1299 bool *aggnulls = econtext->ecxt_aggnulls;
1300 int aggno;
1301
1302 /*
1303 * If there were any DISTINCT and/or ORDER BY aggregates, sort their
1304 * inputs and run the transition functions.
1305 */
1306 for (int transno = 0; transno < aggstate->numtrans; transno++)
1307 {
1308 AggStatePerTrans pertrans = &aggstate->pertrans[transno];
1309 AggStatePerGroup pergroupstate;
1310
1311 pergroupstate = &pergroup[transno];
1312
1313 if (pertrans->aggsortrequired)
1314 {
1315 Assert(aggstate->aggstrategy != AGG_HASHED &&
1316 aggstate->aggstrategy != AGG_MIXED);
1317
1318 if (pertrans->numInputs == 1)
1320 pertrans,
1321 pergroupstate);
1322 else
1324 pertrans,
1325 pergroupstate);
1326 }
1327 else if (pertrans->numDistinctCols > 0 && pertrans->haslast)
1328 {
1329 pertrans->haslast = false;
1330
1331 if (pertrans->numDistinctCols == 1)
1332 {
1333 if (!pertrans->inputtypeByVal && !pertrans->lastisnull)
1334 pfree(DatumGetPointer(pertrans->lastdatum));
1335
1336 pertrans->lastisnull = false;
1337 pertrans->lastdatum = (Datum) 0;
1338 }
1339 else
1340 ExecClearTuple(pertrans->uniqslot);
1341 }
1342 }
1343
1344 /*
1345 * Run the final functions.
1346 */
1347 for (aggno = 0; aggno < aggstate->numaggs; aggno++)
1348 {
1349 AggStatePerAgg peragg = &peraggs[aggno];
1350 int transno = peragg->transno;
1351 AggStatePerGroup pergroupstate;
1352
1353 pergroupstate = &pergroup[transno];
1354
1355 if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
1356 finalize_partialaggregate(aggstate, peragg, pergroupstate,
1357 &aggvalues[aggno], &aggnulls[aggno]);
1358 else
1359 finalize_aggregate(aggstate, peragg, pergroupstate,
1360 &aggvalues[aggno], &aggnulls[aggno]);
1361 }
1362}
static void process_ordered_aggregate_multi(AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
Definition: nodeAgg.c:948
static void finalize_aggregate(AggState *aggstate, AggStatePerAgg peragg, AggStatePerGroup pergroupstate, Datum *resultVal, bool *resultIsNull)
Definition: nodeAgg.c:1045
static void process_ordered_aggregate_single(AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
Definition: nodeAgg.c:847
static void finalize_partialaggregate(AggState *aggstate, AggStatePerAgg peragg, AggStatePerGroup pergroupstate, Datum *resultVal, bool *resultIsNull)
Definition: nodeAgg.c:1145

References AGG_HASHED, AGG_MIXED, AggStatePerTransData::aggsortrequired, AggState::aggsplit, AggState::aggstrategy, Assert(), DatumGetPointer(), DO_AGGSPLIT_SKIPFINAL, ExprContext::ecxt_aggnulls, ExprContext::ecxt_aggvalues, ExecClearTuple(), finalize_aggregate(), finalize_partialaggregate(), AggStatePerTransData::haslast, AggStatePerTransData::inputtypeByVal, AggStatePerTransData::lastdatum, AggStatePerTransData::lastisnull, AggState::numaggs, AggStatePerTransData::numDistinctCols, AggStatePerTransData::numInputs, AggState::numtrans, AggState::pertrans, pfree(), process_ordered_aggregate_multi(), process_ordered_aggregate_single(), ScanState::ps, PlanState::ps_ExprContext, AggState::ss, AggStatePerAggData::transno, and AggStatePerTransData::uniqslot.

Referenced by agg_retrieve_direct(), and agg_retrieve_hash_table_in_memory().

◆ finalize_partialaggregate()

static void finalize_partialaggregate ( AggState aggstate,
AggStatePerAgg  peragg,
AggStatePerGroup  pergroupstate,
Datum resultVal,
bool *  resultIsNull 
)
static

Definition at line 1145 of file nodeAgg.c.

1149{
1150 AggStatePerTrans pertrans = &aggstate->pertrans[peragg->transno];
1151 MemoryContext oldContext;
1152
1154
1155 /*
1156 * serialfn_oid will be set if we must serialize the transvalue before
1157 * returning it
1158 */
1159 if (OidIsValid(pertrans->serialfn_oid))
1160 {
1161 /* Don't call a strict serialization function with NULL input. */
1162 if (pertrans->serialfn.fn_strict && pergroupstate->transValueIsNull)
1163 {
1164 *resultVal = (Datum) 0;
1165 *resultIsNull = true;
1166 }
1167 else
1168 {
1169 FunctionCallInfo fcinfo = pertrans->serialfn_fcinfo;
1170 Datum result;
1171
1172 fcinfo->args[0].value =
1174 pergroupstate->transValueIsNull,
1175 pertrans->transtypeLen);
1176 fcinfo->args[0].isnull = pergroupstate->transValueIsNull;
1177 fcinfo->isnull = false;
1178
1179 result = FunctionCallInvoke(fcinfo);
1180 *resultIsNull = fcinfo->isnull;
1181 *resultVal = MakeExpandedObjectReadOnly(result,
1182 fcinfo->isnull,
1183 peragg->resulttypeLen);
1184 }
1185 }
1186 else
1187 {
1188 *resultVal =
1190 pergroupstate->transValueIsNull,
1191 pertrans->transtypeLen);
1192 *resultIsNull = pergroupstate->transValueIsNull;
1193 }
1194
1195 MemoryContextSwitchTo(oldContext);
1196}

References FunctionCallInfoBaseData::args, ExprContext::ecxt_per_tuple_memory, FmgrInfo::fn_strict, FunctionCallInvoke, FunctionCallInfoBaseData::isnull, NullableDatum::isnull, MakeExpandedObjectReadOnly, MemoryContextSwitchTo(), OidIsValid, AggState::pertrans, ScanState::ps, PlanState::ps_ExprContext, AggStatePerAggData::resulttypeLen, AggStatePerTransData::serialfn, AggStatePerTransData::serialfn_fcinfo, AggStatePerTransData::serialfn_oid, AggState::ss, AggStatePerAggData::transno, AggStatePerTransData::transtypeLen, AggStatePerGroupData::transValue, AggStatePerGroupData::transValueIsNull, and NullableDatum::value.

Referenced by finalize_aggregates().

◆ find_cols()

static void find_cols ( AggState aggstate,
Bitmapset **  aggregated,
Bitmapset **  unaggregated 
)
static

Definition at line 1396 of file nodeAgg.c.

1397{
1398 Agg *agg = (Agg *) aggstate->ss.ps.plan;
1399 FindColsContext context;
1400
1401 context.is_aggref = false;
1402 context.aggregated = NULL;
1403 context.unaggregated = NULL;
1404
1405 /* Examine tlist and quals */
1406 (void) find_cols_walker((Node *) agg->plan.targetlist, &context);
1407 (void) find_cols_walker((Node *) agg->plan.qual, &context);
1408
1409 /* In some cases, grouping columns will not appear in the tlist */
1410 for (int i = 0; i < agg->numCols; i++)
1411 context.unaggregated = bms_add_member(context.unaggregated,
1412 agg->grpColIdx[i]);
1413
1414 *aggregated = context.aggregated;
1415 *unaggregated = context.unaggregated;
1416}
static bool find_cols_walker(Node *node, FindColsContext *context)
Definition: nodeAgg.c:1419
bool is_aggref
Definition: nodeAgg.c:363
List * targetlist
Definition: plannodes.h:209

References bms_add_member(), find_cols_walker(), i, FindColsContext::is_aggref, Agg::numCols, PlanState::plan, Agg::plan, ScanState::ps, Plan::qual, AggState::ss, and Plan::targetlist.

Referenced by find_hash_columns().

◆ find_cols_walker()

static bool find_cols_walker ( Node node,
FindColsContext context 
)
static

Definition at line 1419 of file nodeAgg.c.

1420{
1421 if (node == NULL)
1422 return false;
1423 if (IsA(node, Var))
1424 {
1425 Var *var = (Var *) node;
1426
1427 /* setrefs.c should have set the varno to OUTER_VAR */
1428 Assert(var->varno == OUTER_VAR);
1429 Assert(var->varlevelsup == 0);
1430 if (context->is_aggref)
1431 context->aggregated = bms_add_member(context->aggregated,
1432 var->varattno);
1433 else
1434 context->unaggregated = bms_add_member(context->unaggregated,
1435 var->varattno);
1436 return false;
1437 }
1438 if (IsA(node, Aggref))
1439 {
1440 Assert(!context->is_aggref);
1441 context->is_aggref = true;
1443 context->is_aggref = false;
1444 return false;
1445 }
1446 return expression_tree_walker(node, find_cols_walker, context);
1447}
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define OUTER_VAR
Definition: primnodes.h:243
Bitmapset * aggregated
Definition: nodeAgg.c:364
Bitmapset * unaggregated
Definition: nodeAgg.c:365
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
int varno
Definition: primnodes.h:269
Index varlevelsup
Definition: primnodes.h:294

References FindColsContext::aggregated, Assert(), bms_add_member(), expression_tree_walker, find_cols_walker(), FindColsContext::is_aggref, IsA, OUTER_VAR, FindColsContext::unaggregated, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by find_cols(), and find_cols_walker().

◆ find_hash_columns()

static void find_hash_columns ( AggState aggstate)
static

Definition at line 1570 of file nodeAgg.c.

1571{
1572 Bitmapset *base_colnos;
1573 Bitmapset *aggregated_colnos;
1574 TupleDesc scanDesc = aggstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
1575 List *outerTlist = outerPlanState(aggstate)->plan->targetlist;
1576 int numHashes = aggstate->num_hashes;
1577 EState *estate = aggstate->ss.ps.state;
1578 int j;
1579
1580 /* Find Vars that will be needed in tlist and qual */
1581 find_cols(aggstate, &aggregated_colnos, &base_colnos);
1582 aggstate->colnos_needed = bms_union(base_colnos, aggregated_colnos);
1583 aggstate->max_colno_needed = 0;
1584 aggstate->all_cols_needed = true;
1585
1586 for (int i = 0; i < scanDesc->natts; i++)
1587 {
1588 int colno = i + 1;
1589
1590 if (bms_is_member(colno, aggstate->colnos_needed))
1591 aggstate->max_colno_needed = colno;
1592 else
1593 aggstate->all_cols_needed = false;
1594 }
1595
1596 for (j = 0; j < numHashes; ++j)
1597 {
1598 AggStatePerHash perhash = &aggstate->perhash[j];
1599 Bitmapset *colnos = bms_copy(base_colnos);
1600 AttrNumber *grpColIdx = perhash->aggnode->grpColIdx;
1601 List *hashTlist = NIL;
1602 TupleDesc hashDesc;
1603 int maxCols;
1604 int i;
1605
1606 perhash->largestGrpColIdx = 0;
1607
1608 /*
1609 * If we're doing grouping sets, then some Vars might be referenced in
1610 * tlist/qual for the benefit of other grouping sets, but not needed
1611 * when hashing; i.e. prepare_projection_slot will null them out, so
1612 * there'd be no point storing them. Use prepare_projection_slot's
1613 * logic to determine which.
1614 */
1615 if (aggstate->phases[0].grouped_cols)
1616 {
1617 Bitmapset *grouped_cols = aggstate->phases[0].grouped_cols[j];
1618 ListCell *lc;
1619
1620 foreach(lc, aggstate->all_grouped_cols)
1621 {
1622 int attnum = lfirst_int(lc);
1623
1624 if (!bms_is_member(attnum, grouped_cols))
1625 colnos = bms_del_member(colnos, attnum);
1626 }
1627 }
1628
1629 /*
1630 * Compute maximum number of input columns accounting for possible
1631 * duplications in the grpColIdx array, which can happen in some edge
1632 * cases where HashAggregate was generated as part of a semijoin or a
1633 * DISTINCT.
1634 */
1635 maxCols = bms_num_members(colnos) + perhash->numCols;
1636
1637 perhash->hashGrpColIdxInput =
1638 palloc(maxCols * sizeof(AttrNumber));
1639 perhash->hashGrpColIdxHash =
1640 palloc(perhash->numCols * sizeof(AttrNumber));
1641
1642 /* Add all the grouping columns to colnos */
1643 for (i = 0; i < perhash->numCols; i++)
1644 colnos = bms_add_member(colnos, grpColIdx[i]);
1645
1646 /*
1647 * First build mapping for columns directly hashed. These are the
1648 * first, because they'll be accessed when computing hash values and
1649 * comparing tuples for exact matches. We also build simple mapping
1650 * for execGrouping, so it knows where to find the to-be-hashed /
1651 * compared columns in the input.
1652 */
1653 for (i = 0; i < perhash->numCols; i++)
1654 {
1655 perhash->hashGrpColIdxInput[i] = grpColIdx[i];
1656 perhash->hashGrpColIdxHash[i] = i + 1;
1657 perhash->numhashGrpCols++;
1658 /* delete already mapped columns */
1659 colnos = bms_del_member(colnos, grpColIdx[i]);
1660 }
1661
1662 /* and add the remaining columns */
1663 i = -1;
1664 while ((i = bms_next_member(colnos, i)) >= 0)
1665 {
1666 perhash->hashGrpColIdxInput[perhash->numhashGrpCols] = i;
1667 perhash->numhashGrpCols++;
1668 }
1669
1670 /* and build a tuple descriptor for the hashtable */
1671 for (i = 0; i < perhash->numhashGrpCols; i++)
1672 {
1673 int varNumber = perhash->hashGrpColIdxInput[i] - 1;
1674
1675 hashTlist = lappend(hashTlist, list_nth(outerTlist, varNumber));
1676 perhash->largestGrpColIdx =
1677 Max(varNumber + 1, perhash->largestGrpColIdx);
1678 }
1679
1680 hashDesc = ExecTypeFromTL(hashTlist);
1681
1683 perhash->aggnode->grpOperators,
1684 &perhash->eqfuncoids,
1685 &perhash->hashfunctions);
1686 perhash->hashslot =
1687 ExecAllocTableSlot(&estate->es_tupleTable, hashDesc,
1689
1690 list_free(hashTlist);
1691 bms_free(colnos);
1692 }
1693
1694 bms_free(base_colnos);
1695}
Bitmapset * bms_del_member(Bitmapset *a, int x)
Definition: bitmapset.c:868
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition: bitmapset.c:751
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
void execTuplesHashPrepare(int numCols, const Oid *eqOperators, Oid **eqFuncOids, FmgrInfo **hashFunctions)
Definition: execGrouping.c:97
TupleTableSlot * ExecAllocTableSlot(List **tupleTable, TupleDesc desc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1360
List * lappend(List *list, void *datum)
Definition: list.c:339
void list_free(List *list)
Definition: list.c:1546
static void find_cols(AggState *aggstate, Bitmapset **aggregated, Bitmapset **unaggregated)
Definition: nodeAgg.c:1396
int16 attnum
Definition: pg_attribute.h:74
#define lfirst_int(lc)
Definition: pg_list.h:173
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
int max_colno_needed
Definition: execnodes.h:2554
Bitmapset * colnos_needed
Definition: execnodes.h:2553
bool all_cols_needed
Definition: execnodes.h:2555
List * es_tupleTable
Definition: execnodes.h:710

References AggStatePerHashData::aggnode, AggState::all_cols_needed, AggState::all_grouped_cols, attnum, bms_add_member(), bms_copy(), bms_del_member(), bms_free(), bms_is_member(), bms_next_member(), bms_num_members(), bms_union(), AggState::colnos_needed, AggStatePerHashData::eqfuncoids, EState::es_tupleTable, ExecAllocTableSlot(), execTuplesHashPrepare(), ExecTypeFromTL(), find_cols(), AggStatePerPhaseData::grouped_cols, AggStatePerHashData::hashfunctions, AggStatePerHashData::hashGrpColIdxHash, AggStatePerHashData::hashGrpColIdxInput, AggStatePerHashData::hashslot, i, j, lappend(), AggStatePerHashData::largestGrpColIdx, lfirst_int, list_free(), list_nth(), Max, AggState::max_colno_needed, TupleDescData::natts, NIL, AggState::num_hashes, AggStatePerHashData::numCols, AggStatePerHashData::numhashGrpCols, outerPlanState, palloc(), AggState::perhash, AggState::phases, ScanState::ps, AggState::ss, ScanState::ss_ScanTupleSlot, PlanState::state, TupleTableSlot::tts_tupleDescriptor, and TTSOpsMinimalTuple.

Referenced by ExecInitAgg().

◆ GetAggInitVal()

static Datum GetAggInitVal ( Datum  textInitVal,
Oid  transtype 
)
static

Definition at line 4384 of file nodeAgg.c.

4385{
4386 Oid typinput,
4387 typioparam;
4388 char *strInitVal;
4389 Datum initVal;
4390
4391 getTypeInputInfo(transtype, &typinput, &typioparam);
4392 strInitVal = TextDatumGetCString(textInitVal);
4393 initVal = OidInputFunctionCall(typinput, strInitVal,
4394 typioparam, -1);
4395 pfree(strInitVal);
4396 return initVal;
4397}
#define TextDatumGetCString(d)
Definition: builtins.h:98
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1754
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:3014

References getTypeInputInfo(), OidInputFunctionCall(), pfree(), and TextDatumGetCString.

Referenced by ExecInitAgg().

◆ hash_agg_check_limits()

static void hash_agg_check_limits ( AggState aggstate)
static

Definition at line 1867 of file nodeAgg.c.

1868{
1869 uint64 ngroups = aggstate->hash_ngroups_current;
1870 Size meta_mem = MemoryContextMemAllocated(aggstate->hash_metacxt,
1871 true);
1872 Size entry_mem = MemoryContextMemAllocated(aggstate->hash_tablecxt,
1873 true);
1875 true);
1876 Size total_mem = meta_mem + entry_mem + tval_mem;
1877 bool do_spill = false;
1878
1879#ifdef USE_INJECTION_POINTS
1880 if (ngroups >= 1000)
1881 {
1882 if (IS_INJECTION_POINT_ATTACHED("hash-aggregate-spill-1000"))
1883 {
1884 do_spill = true;
1885 INJECTION_POINT_CACHED("hash-aggregate-spill-1000");
1886 }
1887 }
1888#endif
1889
1890 /*
1891 * Don't spill unless there's at least one group in the hash table so we
1892 * can be sure to make progress even in edge cases.
1893 */
1894 if (aggstate->hash_ngroups_current > 0 &&
1895 (total_mem > aggstate->hash_mem_limit ||
1896 ngroups > aggstate->hash_ngroups_limit))
1897 {
1898 do_spill = true;
1899 }
1900
1901 if (do_spill)
1902 hash_agg_enter_spill_mode(aggstate);
1903}
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:793
static void hash_agg_enter_spill_mode(AggState *aggstate)
Definition: nodeAgg.c:1911

References ExprContext::ecxt_per_tuple_memory, hash_agg_enter_spill_mode(), AggState::hash_mem_limit, AggState::hash_metacxt, AggState::hash_ngroups_current, AggState::hash_ngroups_limit, AggState::hash_tablecxt, AggState::hashcontext, INJECTION_POINT_CACHED, IS_INJECTION_POINT_ATTACHED, and MemoryContextMemAllocated().

Referenced by initialize_hash_entry().

◆ hash_agg_enter_spill_mode()

static void hash_agg_enter_spill_mode ( AggState aggstate)
static

Definition at line 1911 of file nodeAgg.c.

1912{
1913 INJECTION_POINT("hash-aggregate-enter-spill-mode");
1914 aggstate->hash_spill_mode = true;
1915 hashagg_recompile_expressions(aggstate, aggstate->table_filled, true);
1916
1917 if (!aggstate->hash_ever_spilled)
1918 {
1919 Assert(aggstate->hash_tapeset == NULL);
1920 Assert(aggstate->hash_spills == NULL);
1921
1922 aggstate->hash_ever_spilled = true;
1923
1924 aggstate->hash_tapeset = LogicalTapeSetCreate(true, NULL, -1);
1925
1926 aggstate->hash_spills = palloc(sizeof(HashAggSpill) * aggstate->num_hashes);
1927
1928 for (int setno = 0; setno < aggstate->num_hashes; setno++)
1929 {
1930 AggStatePerHash perhash = &aggstate->perhash[setno];
1931 HashAggSpill *spill = &aggstate->hash_spills[setno];
1932
1933 hashagg_spill_init(spill, aggstate->hash_tapeset, 0,
1934 perhash->aggnode->numGroups,
1935 aggstate->hashentrysize);
1936 }
1937 }
1938}
LogicalTapeSet * LogicalTapeSetCreate(bool preallocate, SharedFileSet *fileset, int worker)
Definition: logtape.c:556
struct HashAggSpill * hash_spills
Definition: execnodes.h:2572

References AggStatePerHashData::aggnode, Assert(), AggState::hash_ever_spilled, AggState::hash_spill_mode, AggState::hash_spills, AggState::hash_tapeset, hashagg_recompile_expressions(), hashagg_spill_init(), AggState::hashentrysize, INJECTION_POINT, LogicalTapeSetCreate(), AggState::num_hashes, Agg::numGroups, palloc(), AggState::perhash, and AggState::table_filled.

Referenced by hash_agg_check_limits().

◆ hash_agg_entry_size()

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

Definition at line 1701 of file nodeAgg.c.

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

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

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

◆ hash_agg_set_limits()

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

Definition at line 1809 of file nodeAgg.c.

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

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

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

◆ hash_agg_update_metrics()

static void hash_agg_update_metrics ( AggState aggstate,
bool  from_tape,
int  npartitions 
)
static

Definition at line 1947 of file nodeAgg.c.

1948{
1949 Size meta_mem;
1950 Size entry_mem;
1951 Size hashkey_mem;
1952 Size buffer_mem;
1953 Size total_mem;
1954
1955 if (aggstate->aggstrategy != AGG_MIXED &&
1956 aggstate->aggstrategy != AGG_HASHED)
1957 return;
1958
1959 /* memory for the hash table itself */
1960 meta_mem = MemoryContextMemAllocated(aggstate->hash_metacxt, true);
1961
1962 /* memory for hash entries */
1963 entry_mem = MemoryContextMemAllocated(aggstate->hash_tablecxt, true);
1964
1965 /* memory for byref transition states */
1966 hashkey_mem = MemoryContextMemAllocated(aggstate->hashcontext->ecxt_per_tuple_memory, true);
1967
1968 /* memory for read/write tape buffers, if spilled */
1969 buffer_mem = npartitions * HASHAGG_WRITE_BUFFER_SIZE;
1970 if (from_tape)
1971 buffer_mem += HASHAGG_READ_BUFFER_SIZE;
1972
1973 /* update peak mem */
1974 total_mem = meta_mem + entry_mem + hashkey_mem + buffer_mem;
1975 if (total_mem > aggstate->hash_mem_peak)
1976 aggstate->hash_mem_peak = total_mem;
1977
1978 /* update disk usage */
1979 if (aggstate->hash_tapeset != NULL)
1980 {
1981 uint64 disk_used = LogicalTapeSetBlocks(aggstate->hash_tapeset) * (BLCKSZ / 1024);
1982
1983 if (aggstate->hash_disk_used < disk_used)
1984 aggstate->hash_disk_used = disk_used;
1985 }
1986
1987 /* update hashentrysize estimate based on contents */
1988 if (aggstate->hash_ngroups_current > 0)
1989 {
1990 aggstate->hashentrysize =
1992 (hashkey_mem / (double) aggstate->hash_ngroups_current);
1993 }
1994}
int64 LogicalTapeSetBlocks(LogicalTapeSet *lts)
Definition: logtape.c:1181

References AGG_HASHED, AGG_MIXED, AggState::aggstrategy, ExprContext::ecxt_per_tuple_memory, AggState::hash_disk_used, AggState::hash_mem_peak, AggState::hash_metacxt, AggState::hash_ngroups_current, AggState::hash_tablecxt, AggState::hash_tapeset, HASHAGG_READ_BUFFER_SIZE, HASHAGG_WRITE_BUFFER_SIZE, AggState::hashcontext, AggState::hashentrysize, LogicalTapeSetBlocks(), MemoryContextMemAllocated(), and TupleHashEntrySize().

Referenced by agg_refill_hash_table(), and hashagg_finish_initial_spills().

◆ hash_choose_num_buckets()

static long hash_choose_num_buckets ( double  hashentrysize,
long  ngroups,
Size  memory 
)
static

Definition at line 2058 of file nodeAgg.c.

2059{
2060 long max_nbuckets;
2061 long nbuckets = ngroups;
2062
2063 max_nbuckets = memory / hashentrysize;
2064
2065 /*
2066 * Underestimating is better than overestimating. Too many buckets crowd
2067 * out space for group keys and transition state values.
2068 */
2069 max_nbuckets >>= 1;
2070
2071 if (nbuckets > max_nbuckets)
2072 nbuckets = max_nbuckets;
2073
2074 return Max(nbuckets, 1);
2075}

References Max.

Referenced by build_hash_tables().

◆ hash_choose_num_partitions()

static int hash_choose_num_partitions ( double  input_groups,
double  hashentrysize,
int  used_bits,
int *  log2_npartitions 
)
static

Definition at line 2083 of file nodeAgg.c.

2085{
2086 Size hash_mem_limit = get_hash_memory_limit();
2087 double partition_limit;
2088 double mem_wanted;
2089 double dpartitions;
2090 int npartitions;
2091 int partition_bits;
2092
2093 /*
2094 * Avoid creating so many partitions that the memory requirements of the
2095 * open partition files are greater than 1/4 of hash_mem.
2096 */
2097 partition_limit =
2098 (hash_mem_limit * 0.25 - HASHAGG_READ_BUFFER_SIZE) /
2100
2101 mem_wanted = HASHAGG_PARTITION_FACTOR * input_groups * hashentrysize;
2102
2103 /* make enough partitions so that each one is likely to fit in memory */
2104 dpartitions = 1 + (mem_wanted / hash_mem_limit);
2105
2106 if (dpartitions > partition_limit)
2107 dpartitions = partition_limit;
2108
2109 if (dpartitions < HASHAGG_MIN_PARTITIONS)
2110 dpartitions = HASHAGG_MIN_PARTITIONS;
2111 if (dpartitions > HASHAGG_MAX_PARTITIONS)
2112 dpartitions = HASHAGG_MAX_PARTITIONS;
2113
2114 /* HASHAGG_MAX_PARTITIONS limit makes this safe */
2115 npartitions = (int) dpartitions;
2116
2117 /* ceil(log2(npartitions)) */
2118 partition_bits = my_log2(npartitions);
2119
2120 /* make sure that we don't exhaust the hash bits */
2121 if (partition_bits + used_bits >= 32)
2122 partition_bits = 32 - used_bits;
2123
2124 if (log2_npartitions != NULL)
2125 *log2_npartitions = partition_bits;
2126
2127 /* number of partitions will be a power of two */
2128 npartitions = 1 << partition_bits;
2129
2130 return npartitions;
2131}
int my_log2(long num)
Definition: dynahash.c:1794
#define HASHAGG_MAX_PARTITIONS
Definition: nodeAgg.c:299
#define HASHAGG_MIN_PARTITIONS
Definition: nodeAgg.c:298
#define HASHAGG_PARTITION_FACTOR
Definition: nodeAgg.c:297

References get_hash_memory_limit(), HASHAGG_MAX_PARTITIONS, HASHAGG_MIN_PARTITIONS, HASHAGG_PARTITION_FACTOR, HASHAGG_READ_BUFFER_SIZE, HASHAGG_WRITE_BUFFER_SIZE, and my_log2().

Referenced by hash_agg_set_limits(), and hashagg_spill_init().

◆ hash_create_memory()

static void hash_create_memory ( AggState aggstate)
static

Definition at line 2000 of file nodeAgg.c.

2001{
2002 Size maxBlockSize = ALLOCSET_DEFAULT_MAXSIZE;
2003
2004 /*
2005 * The hashcontext's per-tuple memory will be used for byref transition
2006 * values and returned by AggCheckCallContext().
2007 */
2008 aggstate->hashcontext = CreateWorkExprContext(aggstate->ss.ps.state);
2009
2010 /*
2011 * The meta context will be used for the bucket array of
2012 * TupleHashEntryData (or arrays, in the case of grouping sets). As the
2013 * hash table grows, the bucket array will double in size and the old one
2014 * will be freed, so an AllocSet is appropriate. For large bucket arrays,
2015 * the large allocation path will be used, so it's not worth worrying
2016 * about wasting space due to power-of-two allocations.
2017 */
2019 "HashAgg meta context",
2021
2022 /*
2023 * The hash entries themselves, which include the grouping key
2024 * (firstTuple) and pergroup data, are stored in the table context. The
2025 * bump allocator can be used because the entries are not freed until the
2026 * entire hash table is reset. The bump allocator is faster for
2027 * allocations and avoids wasting space on the chunk header or
2028 * power-of-two allocations.
2029 *
2030 * Like CreateWorkExprContext(), use smaller sizings for smaller work_mem,
2031 * to avoid large jumps in memory usage.
2032 */
2033
2034 /*
2035 * Like CreateWorkExprContext(), use smaller sizings for smaller work_mem,
2036 * to avoid large jumps in memory usage.
2037 */
2038 maxBlockSize = pg_prevpower2_size_t(work_mem * (Size) 1024 / 16);
2039
2040 /* But no bigger than ALLOCSET_DEFAULT_MAXSIZE */
2041 maxBlockSize = Min(maxBlockSize, ALLOCSET_DEFAULT_MAXSIZE);
2042
2043 /* and no smaller than ALLOCSET_DEFAULT_INITSIZE */
2044 maxBlockSize = Max(maxBlockSize, ALLOCSET_DEFAULT_INITSIZE);
2045
2046 aggstate->hash_tablecxt = BumpContextCreate(aggstate->ss.ps.state->es_query_cxt,
2047 "HashAgg table context",
2050 maxBlockSize);
2051
2052}
MemoryContext BumpContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: bump.c:131
#define Min(x, y)
Definition: c.h:975
ExprContext * CreateWorkExprContext(EState *estate)
Definition: execUtils.c:323
int work_mem
Definition: globals.c:132
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:179
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:177
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:180
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:178
#define pg_prevpower2_size_t
Definition: pg_bitutils.h:442
MemoryContext es_query_cxt
Definition: execnodes.h:708

References ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE, ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, BumpContextCreate(), CreateWorkExprContext(), EState::es_query_cxt, AggState::hash_metacxt, AggState::hash_tablecxt, AggState::hashcontext, Max, Min, pg_prevpower2_size_t, ScanState::ps, AggState::ss, PlanState::state, and work_mem.

Referenced by ExecInitAgg().

◆ hashagg_batch_new()

static HashAggBatch * hashagg_batch_new ( LogicalTape input_tape,
int  setno,
int64  input_tuples,
double  input_card,
int  used_bits 
)
static

Definition at line 3097 of file nodeAgg.c.

3099{
3100 HashAggBatch *batch = palloc0(sizeof(HashAggBatch));
3101
3102 batch->setno = setno;
3103 batch->used_bits = used_bits;
3104 batch->input_tape = input_tape;
3105 batch->input_tuples = input_tuples;
3106 batch->input_card = input_card;
3107
3108 return batch;
3109}
int64 input_tuples
Definition: nodeAgg.c:356

References HashAggBatch::input_card, HashAggBatch::input_tape, HashAggBatch::input_tuples, palloc0(), HashAggBatch::setno, and HashAggBatch::used_bits.

Referenced by hashagg_spill_finish().

◆ hashagg_batch_read()

static MinimalTuple hashagg_batch_read ( HashAggBatch batch,
uint32 hashp 
)
static

Definition at line 3116 of file nodeAgg.c.

3117{
3118 LogicalTape *tape = batch->input_tape;
3119 MinimalTuple tuple;
3120 uint32 t_len;
3121 size_t nread;
3122 uint32 hash;
3123
3124 nread = LogicalTapeRead(tape, &hash, sizeof(uint32));
3125 if (nread == 0)
3126 return NULL;
3127 if (nread != sizeof(uint32))
3128 ereport(ERROR,
3130 errmsg_internal("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3131 tape, sizeof(uint32), nread)));
3132 if (hashp != NULL)
3133 *hashp = hash;
3134
3135 nread = LogicalTapeRead(tape, &t_len, sizeof(t_len));
3136 if (nread != sizeof(uint32))
3137 ereport(ERROR,
3139 errmsg_internal("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3140 tape, sizeof(uint32), nread)));
3141
3142 tuple = (MinimalTuple) palloc(t_len);
3143 tuple->t_len = t_len;
3144
3145 nread = LogicalTapeRead(tape,
3146 (char *) tuple + sizeof(uint32),
3147 t_len - sizeof(uint32));
3148 if (nread != t_len - sizeof(uint32))
3149 ereport(ERROR,
3151 errmsg_internal("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3152 tape, t_len - sizeof(uint32), nread)));
3153
3154 return tuple;
3155}
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
int errcode_for_file_access(void)
Definition: elog.c:877
MinimalTupleData * MinimalTuple
Definition: htup.h:27
size_t LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:928

References ereport, errcode_for_file_access(), errmsg_internal(), ERROR, hash(), HashAggBatch::input_tape, LogicalTapeRead(), palloc(), and MinimalTupleData::t_len.

Referenced by agg_refill_hash_table().

◆ hashagg_finish_initial_spills()

static void hashagg_finish_initial_spills ( AggState aggstate)
static

Definition at line 3165 of file nodeAgg.c.

3166{
3167 int setno;
3168 int total_npartitions = 0;
3169
3170 if (aggstate->hash_spills != NULL)
3171 {
3172 for (setno = 0; setno < aggstate->num_hashes; setno++)
3173 {
3174 HashAggSpill *spill = &aggstate->hash_spills[setno];
3175
3176 total_npartitions += spill->npartitions;
3177 hashagg_spill_finish(aggstate, spill, setno);
3178 }
3179
3180 /*
3181 * We're not processing tuples from outer plan any more; only
3182 * processing batches of spilled tuples. The initial spill structures
3183 * are no longer needed.
3184 */
3185 pfree(aggstate->hash_spills);
3186 aggstate->hash_spills = NULL;
3187 }
3188
3189 hash_agg_update_metrics(aggstate, false, total_npartitions);
3190 aggstate->hash_spill_mode = false;
3191}

References hash_agg_update_metrics(), AggState::hash_spill_mode, AggState::hash_spills, hashagg_spill_finish(), HashAggSpill::npartitions, AggState::num_hashes, and pfree().

Referenced by agg_fill_hash_table(), and agg_retrieve_direct().

◆ hashagg_recompile_expressions()

static void hashagg_recompile_expressions ( AggState aggstate,
bool  minslot,
bool  nullcheck 
)
static

Definition at line 1752 of file nodeAgg.c.

1753{
1754 AggStatePerPhase phase;
1755 int i = minslot ? 1 : 0;
1756 int j = nullcheck ? 1 : 0;
1757
1758 Assert(aggstate->aggstrategy == AGG_HASHED ||
1759 aggstate->aggstrategy == AGG_MIXED);
1760
1761 if (aggstate->aggstrategy == AGG_HASHED)
1762 phase = &aggstate->phases[0];
1763 else /* AGG_MIXED */
1764 phase = &aggstate->phases[1];
1765
1766 if (phase->evaltrans_cache[i][j] == NULL)
1767 {
1768 const TupleTableSlotOps *outerops = aggstate->ss.ps.outerops;
1769 bool outerfixed = aggstate->ss.ps.outeropsfixed;
1770 bool dohash = true;
1771 bool dosort = false;
1772
1773 /*
1774 * If minslot is true, that means we are processing a spilled batch
1775 * (inside agg_refill_hash_table()), and we must not advance the
1776 * sorted grouping sets.
1777 */
1778 if (aggstate->aggstrategy == AGG_MIXED && !minslot)
1779 dosort = true;
1780
1781 /* temporarily change the outerops while compiling the expression */
1782 if (minslot)
1783 {
1784 aggstate->ss.ps.outerops = &TTSOpsMinimalTuple;
1785 aggstate->ss.ps.outeropsfixed = true;
1786 }
1787
1788 phase->evaltrans_cache[i][j] = ExecBuildAggTrans(aggstate, phase,
1789 dosort, dohash,
1790 nullcheck);
1791
1792 /* change back */
1793 aggstate->ss.ps.outerops = outerops;
1794 aggstate->ss.ps.outeropsfixed = outerfixed;
1795 }
1796
1797 phase->evaltrans = phase->evaltrans_cache[i][j];
1798}

References AGG_HASHED, AGG_MIXED, AggState::aggstrategy, Assert(), AggStatePerPhaseData::evaltrans, AggStatePerPhaseData::evaltrans_cache, ExecBuildAggTrans(), i, j, PlanState::outerops, PlanState::outeropsfixed, AggState::phases, ScanState::ps, AggState::ss, and TTSOpsMinimalTuple.

Referenced by agg_refill_hash_table(), ExecReScanAgg(), and hash_agg_enter_spill_mode().

◆ hashagg_reset_spill_state()

static void hashagg_reset_spill_state ( AggState aggstate)
static

Definition at line 3239 of file nodeAgg.c.

3240{
3241 /* free spills from initial pass */
3242 if (aggstate->hash_spills != NULL)
3243 {
3244 int setno;
3245
3246 for (setno = 0; setno < aggstate->num_hashes; setno++)
3247 {
3248 HashAggSpill *spill = &aggstate->hash_spills[setno];
3249
3250 pfree(spill->ntuples);
3251 pfree(spill->partitions);
3252 }
3253 pfree(aggstate->hash_spills);
3254 aggstate->hash_spills = NULL;
3255 }
3256
3257 /* free batches */
3258 list_free_deep(aggstate->hash_batches);
3259 aggstate->hash_batches = NIL;
3260
3261 /* close tape set */
3262 if (aggstate->hash_tapeset != NULL)
3263 {
3265 aggstate->hash_tapeset = NULL;
3266 }
3267}
void list_free_deep(List *list)
Definition: list.c:1560
void LogicalTapeSetClose(LogicalTapeSet *lts)
Definition: logtape.c:667
int64 * ntuples
Definition: nodeAgg.c:336
LogicalTape ** partitions
Definition: nodeAgg.c:335

References AggState::hash_batches, AggState::hash_spills, AggState::hash_tapeset, list_free_deep(), LogicalTapeSetClose(), NIL, HashAggSpill::ntuples, AggState::num_hashes, HashAggSpill::partitions, and pfree().

Referenced by ExecEndAgg(), and ExecReScanAgg().

◆ hashagg_spill_finish()

static void hashagg_spill_finish ( AggState aggstate,
HashAggSpill spill,
int  setno 
)
static

Definition at line 3199 of file nodeAgg.c.

3200{
3201 int i;
3202 int used_bits = 32 - spill->shift;
3203
3204 if (spill->npartitions == 0)
3205 return; /* didn't spill */
3206
3207 for (i = 0; i < spill->npartitions; i++)
3208 {
3209 LogicalTape *tape = spill->partitions[i];
3210 HashAggBatch *new_batch;
3211 double cardinality;
3212
3213 /* if the partition is empty, don't create a new batch of work */
3214 if (spill->ntuples[i] == 0)
3215 continue;
3216
3217 cardinality = estimateHyperLogLog(&spill->hll_card[i]);
3218 freeHyperLogLog(&spill->hll_card[i]);
3219
3220 /* rewinding frees the buffer while not in use */
3222
3223 new_batch = hashagg_batch_new(tape, setno,
3224 spill->ntuples[i], cardinality,
3225 used_bits);
3226 aggstate->hash_batches = lappend(aggstate->hash_batches, new_batch);
3227 aggstate->hash_batches_used++;
3228 }
3229
3230 pfree(spill->ntuples);
3231 pfree(spill->hll_card);
3232 pfree(spill->partitions);
3233}
double estimateHyperLogLog(hyperLogLogState *cState)
Definition: hyperloglog.c:186
void freeHyperLogLog(hyperLogLogState *cState)
Definition: hyperloglog.c:151
void LogicalTapeRewindForRead(LogicalTape *lt, size_t buffer_size)
Definition: logtape.c:846
static HashAggBatch * hashagg_batch_new(LogicalTape *input_tape, int setno, int64 input_tuples, double input_card, int used_bits)
Definition: nodeAgg.c:3097
hyperLogLogState * hll_card
Definition: nodeAgg.c:339

References estimateHyperLogLog(), freeHyperLogLog(), AggState::hash_batches, AggState::hash_batches_used, hashagg_batch_new(), HASHAGG_READ_BUFFER_SIZE, HashAggSpill::hll_card, i, lappend(), LogicalTapeRewindForRead(), HashAggSpill::npartitions, HashAggSpill::ntuples, HashAggSpill::partitions, pfree(), and HashAggSpill::shift.

Referenced by agg_refill_hash_table(), and hashagg_finish_initial_spills().

◆ hashagg_spill_init()

static void hashagg_spill_init ( HashAggSpill spill,
LogicalTapeSet tapeset,
int  used_bits,
double  input_groups,
double  hashentrysize 
)
static

Definition at line 2984 of file nodeAgg.c.

2986{
2987 int npartitions;
2988 int partition_bits;
2989
2990 npartitions = hash_choose_num_partitions(input_groups, hashentrysize,
2991 used_bits, &partition_bits);
2992
2993#ifdef USE_INJECTION_POINTS
2994 if (IS_INJECTION_POINT_ATTACHED("hash-aggregate-single-partition"))
2995 {
2996 npartitions = 1;
2997 partition_bits = 0;
2998 INJECTION_POINT_CACHED("hash-aggregate-single-partition");
2999 }
3000#endif
3001
3002 spill->partitions = palloc0(sizeof(LogicalTape *) * npartitions);
3003 spill->ntuples = palloc0(sizeof(int64) * npartitions);
3004 spill->hll_card = palloc0(sizeof(hyperLogLogState) * npartitions);
3005
3006 for (int i = 0; i < npartitions; i++)
3007 spill->partitions[i] = LogicalTapeCreate(tapeset);
3008
3009 spill->shift = 32 - used_bits - partition_bits;
3010 if (spill->shift < 32)
3011 spill->mask = (npartitions - 1) << spill->shift;
3012 else
3013 spill->mask = 0;
3014 spill->npartitions = npartitions;
3015
3016 for (int i = 0; i < npartitions; i++)
3018}
int64_t int64
Definition: c.h:499
for(;;)
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:66
LogicalTape * LogicalTapeCreate(LogicalTapeSet *lts)
Definition: logtape.c:680
#define HASHAGG_HLL_BIT_WIDTH
Definition: nodeAgg.c:316
uint32 mask
Definition: nodeAgg.c:337

References for(), hash_choose_num_partitions(), HASHAGG_HLL_BIT_WIDTH, HashAggSpill::hll_card, i, initHyperLogLog(), INJECTION_POINT_CACHED, IS_INJECTION_POINT_ATTACHED, LogicalTapeCreate(), HashAggSpill::mask, HashAggSpill::npartitions, HashAggSpill::ntuples, palloc0(), HashAggSpill::partitions, and HashAggSpill::shift.

Referenced by agg_refill_hash_table(), hash_agg_enter_spill_mode(), and lookup_hash_entries().

◆ hashagg_spill_tuple()

static Size hashagg_spill_tuple ( AggState aggstate,
HashAggSpill spill,
TupleTableSlot inputslot,
uint32  hash 
)
static

Definition at line 3027 of file nodeAgg.c.

3029{
3030 TupleTableSlot *spillslot;
3031 int partition;
3032 MinimalTuple tuple;
3033 LogicalTape *tape;
3034 int total_written = 0;
3035 bool shouldFree;
3036
3037 Assert(spill->partitions != NULL);
3038
3039 /* spill only attributes that we actually need */
3040 if (!aggstate->all_cols_needed)
3041 {
3042 spillslot = aggstate->hash_spill_wslot;
3043 slot_getsomeattrs(inputslot, aggstate->max_colno_needed);
3044 ExecClearTuple(spillslot);
3045 for (int i = 0; i < spillslot->tts_tupleDescriptor->natts; i++)
3046 {
3047 if (bms_is_member(i + 1, aggstate->colnos_needed))
3048 {
3049 spillslot->tts_values[i] = inputslot->tts_values[i];
3050 spillslot->tts_isnull[i] = inputslot->tts_isnull[i];
3051 }
3052 else
3053 spillslot->tts_isnull[i] = true;
3054 }
3055 ExecStoreVirtualTuple(spillslot);
3056 }
3057 else
3058 spillslot = inputslot;
3059
3060 tuple = ExecFetchSlotMinimalTuple(spillslot, &shouldFree);
3061
3062 if (spill->shift < 32)
3063 partition = (hash & spill->mask) >> spill->shift;
3064 else
3065 partition = 0;
3066
3067 spill->ntuples[partition]++;
3068
3069 /*
3070 * All hash values destined for a given partition have some bits in
3071 * common, which causes bad HLL cardinality estimates. Hash the hash to
3072 * get a more uniform distribution.
3073 */
3074 addHyperLogLog(&spill->hll_card[partition], hash_bytes_uint32(hash));
3075
3076 tape = spill->partitions[partition];
3077
3078 LogicalTapeWrite(tape, &hash, sizeof(uint32));
3079 total_written += sizeof(uint32);
3080
3081 LogicalTapeWrite(tape, tuple, tuple->t_len);
3082 total_written += tuple->t_len;
3083
3084 if (shouldFree)
3085 pfree(tuple);
3086
3087 return total_written;
3088}
MinimalTuple ExecFetchSlotMinimalTuple(TupleTableSlot *slot, bool *shouldFree)
Definition: execTuples.c:1881
uint32 hash_bytes_uint32(uint32 k)
Definition: hashfn.c:610
void addHyperLogLog(hyperLogLogState *cState, uint32 hash)
Definition: hyperloglog.c:167
void LogicalTapeWrite(LogicalTape *lt, const void *ptr, size_t size)
Definition: logtape.c:761
static void slot_getsomeattrs(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:359

References addHyperLogLog(), AggState::all_cols_needed, Assert(), bms_is_member(), AggState::colnos_needed, ExecClearTuple(), ExecFetchSlotMinimalTuple(), ExecStoreVirtualTuple(), hash(), hash_bytes_uint32(), AggState::hash_spill_wslot, HashAggSpill::hll_card, i, LogicalTapeWrite(), HashAggSpill::mask, AggState::max_colno_needed, TupleDescData::natts, HashAggSpill::ntuples, HashAggSpill::partitions, pfree(), HashAggSpill::shift, slot_getsomeattrs(), MinimalTupleData::t_len, TupleTableSlot::tts_isnull, TupleTableSlot::tts_tupleDescriptor, and TupleTableSlot::tts_values.

Referenced by agg_refill_hash_table(), and lookup_hash_entries().

◆ initialize_aggregate()

static void initialize_aggregate ( AggState aggstate,
AggStatePerTrans  pertrans,
AggStatePerGroup  pergroupstate 
)
static

Definition at line 580 of file nodeAgg.c.

582{
583 /*
584 * Start a fresh sort operation for each DISTINCT/ORDER BY aggregate.
585 */
586 if (pertrans->aggsortrequired)
587 {
588 /*
589 * In case of rescan, maybe there could be an uncompleted sort
590 * operation? Clean it up if so.
591 */
592 if (pertrans->sortstates[aggstate->current_set])
593 tuplesort_end(pertrans->sortstates[aggstate->current_set]);
594
595
596 /*
597 * We use a plain Datum sorter when there's a single input column;
598 * otherwise sort the full tuple. (See comments for
599 * process_ordered_aggregate_single.)
600 */
601 if (pertrans->numInputs == 1)
602 {
603 Form_pg_attribute attr = TupleDescAttr(pertrans->sortdesc, 0);
604
605 pertrans->sortstates[aggstate->current_set] =
606 tuplesort_begin_datum(attr->atttypid,
607 pertrans->sortOperators[0],
608 pertrans->sortCollations[0],
609 pertrans->sortNullsFirst[0],
610 work_mem, NULL, TUPLESORT_NONE);
611 }
612 else
613 pertrans->sortstates[aggstate->current_set] =
615 pertrans->numSortCols,
616 pertrans->sortColIdx,
617 pertrans->sortOperators,
618 pertrans->sortCollations,
619 pertrans->sortNullsFirst,
620 work_mem, NULL, TUPLESORT_NONE);
621 }
622
623 /*
624 * (Re)set transValue to the initial value.
625 *
626 * Note that when the initial value is pass-by-ref, we must copy it (into
627 * the aggcontext) since we will pfree the transValue later.
628 */
629 if (pertrans->initValueIsNull)
630 pergroupstate->transValue = pertrans->initValue;
631 else
632 {
633 MemoryContext oldContext;
634
636 pergroupstate->transValue = datumCopy(pertrans->initValue,
637 pertrans->transtypeByVal,
638 pertrans->transtypeLen);
639 MemoryContextSwitchTo(oldContext);
640 }
641 pergroupstate->transValueIsNull = pertrans->initValueIsNull;
642
643 /*
644 * If the initial value for the transition state doesn't exist in the
645 * pg_aggregate table then we will let the first non-NULL value returned
646 * from the outer procNode become the initial value. (This is useful for
647 * aggregates like max() and min().) The noTransValue flag signals that we
648 * still need to do this.
649 */
650 pergroupstate->noTransValue = pertrans->initValueIsNull;
651}
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
#define TUPLESORT_NONE
Definition: tuplesort.h:94
Tuplesortstate * tuplesort_begin_heap(TupleDesc tupDesc, int nkeys, AttrNumber *attNums, Oid *sortOperators, Oid *sortCollations, bool *nullsFirstFlags, int workMem, SortCoordinate coordinate, int sortopt)
Tuplesortstate * tuplesort_begin_datum(Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, int sortopt)

References AggStatePerTransData::aggsortrequired, AggState::curaggcontext, AggState::current_set, datumCopy(), ExprContext::ecxt_per_tuple_memory, AggStatePerTransData::initValue, AggStatePerTransData::initValueIsNull, MemoryContextSwitchTo(), AggStatePerGroupData::noTransValue, AggStatePerTransData::numInputs, AggStatePerTransData::numSortCols, AggStatePerTransData::sortColIdx, AggStatePerTransData::sortCollations, AggStatePerTransData::sortdesc, AggStatePerTransData::sortNullsFirst, AggStatePerTransData::sortOperators, AggStatePerTransData::sortstates, AggStatePerTransData::transtypeByVal, AggStatePerTransData::transtypeLen, AggStatePerGroupData::transValue, AggStatePerGroupData::transValueIsNull, TupleDescAttr(), tuplesort_begin_datum(), tuplesort_begin_heap(), tuplesort_end(), TUPLESORT_NONE, and work_mem.

Referenced by initialize_aggregates(), and initialize_hash_entry().

◆ initialize_aggregates()

static void initialize_aggregates ( AggState aggstate,
AggStatePerGroup pergroups,
int  numReset 
)
static

Definition at line 667 of file nodeAgg.c.

670{
671 int transno;
672 int numGroupingSets = Max(aggstate->phase->numsets, 1);
673 int setno = 0;
674 int numTrans = aggstate->numtrans;
675 AggStatePerTrans transstates = aggstate->pertrans;
676
677 if (numReset == 0)
678 numReset = numGroupingSets;
679
680 for (setno = 0; setno < numReset; setno++)
681 {
682 AggStatePerGroup pergroup = pergroups[setno];
683
684 select_current_set(aggstate, setno, false);
685
686 for (transno = 0; transno < numTrans; transno++)
687 {
688 AggStatePerTrans pertrans = &transstates[transno];
689 AggStatePerGroup pergroupstate = &pergroup[transno];
690
691 initialize_aggregate(aggstate, pertrans, pergroupstate);
692 }
693 }
694}
static void initialize_aggregate(AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
Definition: nodeAgg.c:580

References initialize_aggregate(), Max, AggStatePerPhaseData::numsets, AggState::numtrans, AggState::pertrans, AggState::phase, and select_current_set().

Referenced by agg_retrieve_direct().

◆ initialize_hash_entry()

static void initialize_hash_entry ( AggState aggstate,
TupleHashTable  hashtable,
TupleHashEntry  entry 
)
static

Definition at line 2137 of file nodeAgg.c.

2139{
2140 AggStatePerGroup pergroup;
2141 int transno;
2142
2143 aggstate->hash_ngroups_current++;
2144 hash_agg_check_limits(aggstate);
2145
2146 /* no need to allocate or initialize per-group state */
2147 if (aggstate->numtrans == 0)
2148 return;
2149
2150 pergroup = (AggStatePerGroup) TupleHashEntryGetAdditional(hashtable, entry);
2151
2152 /*
2153 * Initialize aggregates for new tuple group, lookup_hash_entries()
2154 * already has selected the relevant grouping set.
2155 */
2156 for (transno = 0; transno < aggstate->numtrans; transno++)
2157 {
2158 AggStatePerTrans pertrans = &aggstate->pertrans[transno];
2159 AggStatePerGroup pergroupstate = &pergroup[transno];
2160
2161 initialize_aggregate(aggstate, pertrans, pergroupstate);
2162 }
2163}
static void hash_agg_check_limits(AggState *aggstate)
Definition: nodeAgg.c:1867

References hash_agg_check_limits(), AggState::hash_ngroups_current, initialize_aggregate(), AggState::numtrans, AggState::pertrans, and TupleHashEntryGetAdditional().

Referenced by agg_refill_hash_table(), and lookup_hash_entries().

◆ initialize_phase()

static void initialize_phase ( AggState aggstate,
int  newphase 
)
static

Definition at line 479 of file nodeAgg.c.

480{
481 Assert(newphase <= 1 || newphase == aggstate->current_phase + 1);
482
483 /*
484 * Whatever the previous state, we're now done with whatever input
485 * tuplesort was in use.
486 */
487 if (aggstate->sort_in)
488 {
489 tuplesort_end(aggstate->sort_in);
490 aggstate->sort_in = NULL;
491 }
492
493 if (newphase <= 1)
494 {
495 /*
496 * Discard any existing output tuplesort.
497 */
498 if (aggstate->sort_out)
499 {
500 tuplesort_end(aggstate->sort_out);
501 aggstate->sort_out = NULL;
502 }
503 }
504 else
505 {
506 /*
507 * The old output tuplesort becomes the new input one, and this is the
508 * right time to actually sort it.
509 */
510 aggstate->sort_in = aggstate->sort_out;
511 aggstate->sort_out = NULL;
512 Assert(aggstate->sort_in);
514 }
515
516 /*
517 * If this isn't the last phase, we need to sort appropriately for the
518 * next phase in sequence.
519 */
520 if (newphase > 0 && newphase < aggstate->numphases - 1)
521 {
522 Sort *sortnode = aggstate->phases[newphase + 1].sortnode;
523 PlanState *outerNode = outerPlanState(aggstate);
524 TupleDesc tupDesc = ExecGetResultType(outerNode);
525
526 aggstate->sort_out = tuplesort_begin_heap(tupDesc,
527 sortnode->numCols,
528 sortnode->sortColIdx,
529 sortnode->sortOperators,
530 sortnode->collations,
531 sortnode->nullsFirst,
532 work_mem,
533 NULL, TUPLESORT_NONE);
534 }
535
536 aggstate->current_phase = newphase;
537 aggstate->phase = &aggstate->phases[newphase];
538}
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:496
int numCols
Definition: plannodes.h:1077
void tuplesort_performsort(Tuplesortstate *state)
Definition: tuplesort.c:1363

References Assert(), AggState::current_phase, ExecGetResultType(), Sort::numCols, outerPlanState, AggState::phase, AggState::phases, AggState::sort_in, AggState::sort_out, AggStatePerPhaseData::sortnode, tuplesort_begin_heap(), tuplesort_end(), TUPLESORT_NONE, tuplesort_performsort(), and work_mem.

Referenced by agg_retrieve_direct(), ExecInitAgg(), and ExecReScanAgg().

◆ lookup_hash_entries()

static void lookup_hash_entries ( AggState aggstate)
static

Definition at line 2181 of file nodeAgg.c.

2182{
2183 AggStatePerGroup *pergroup = aggstate->hash_pergroup;
2184 TupleTableSlot *outerslot = aggstate->tmpcontext->ecxt_outertuple;
2185 int setno;
2186
2187 for (setno = 0; setno < aggstate->num_hashes; setno++)
2188 {
2189 AggStatePerHash perhash = &aggstate->perhash[setno];
2190 TupleHashTable hashtable = perhash->hashtable;
2191 TupleTableSlot *hashslot = perhash->hashslot;
2192 TupleHashEntry entry;
2193 uint32 hash;
2194 bool isnew = false;
2195 bool *p_isnew;
2196
2197 /* if hash table already spilled, don't create new entries */
2198 p_isnew = aggstate->hash_spill_mode ? NULL : &isnew;
2199
2200 select_current_set(aggstate, setno, true);
2201 prepare_hash_slot(perhash,
2202 outerslot,
2203 hashslot);
2204
2205 entry = LookupTupleHashEntry(hashtable, hashslot,
2206 p_isnew, &hash);
2207
2208 if (entry != NULL)
2209 {
2210 if (isnew)
2211 initialize_hash_entry(aggstate, hashtable, entry);
2212 pergroup[setno] = TupleHashEntryGetAdditional(hashtable, entry);
2213 }
2214 else
2215 {
2216 HashAggSpill *spill = &aggstate->hash_spills[setno];
2217 TupleTableSlot *slot = aggstate->tmpcontext->ecxt_outertuple;
2218
2219 if (spill->partitions == NULL)
2220 hashagg_spill_init(spill, aggstate->hash_tapeset, 0,
2221 perhash->aggnode->numGroups,
2222 aggstate->hashentrysize);
2223
2224 hashagg_spill_tuple(aggstate, spill, slot, hash);
2225 pergroup[setno] = NULL;
2226 }
2227 }
2228}
TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew, uint32 *hash)
Definition: execGrouping.c:295

References AggStatePerHashData::aggnode, ExprContext::ecxt_outertuple, hash(), AggState::hash_pergroup, AggState::hash_spill_mode, AggState::hash_spills, AggState::hash_tapeset, hashagg_spill_init(), hashagg_spill_tuple(), AggState::hashentrysize, AggStatePerHashData::hashslot, AggStatePerHashData::hashtable, initialize_hash_entry(), LookupTupleHashEntry(), AggState::num_hashes, Agg::numGroups, HashAggSpill::partitions, AggState::perhash, prepare_hash_slot(), select_current_set(), AggState::tmpcontext, and TupleHashEntryGetAdditional().

Referenced by agg_fill_hash_table(), and agg_retrieve_direct().

◆ prepare_hash_slot()

static void prepare_hash_slot ( AggStatePerHash  perhash,
TupleTableSlot inputslot,
TupleTableSlot hashslot 
)
inlinestatic

Definition at line 1203 of file nodeAgg.c.

1206{
1207 int i;
1208
1209 /* transfer just the needed columns into hashslot */
1210 slot_getsomeattrs(inputslot, perhash->largestGrpColIdx);
1211 ExecClearTuple(hashslot);
1212
1213 for (i = 0; i < perhash->numhashGrpCols; i++)
1214 {
1215 int varNumber = perhash->hashGrpColIdxInput[i] - 1;
1216
1217 hashslot->tts_values[i] = inputslot->tts_values[varNumber];
1218 hashslot->tts_isnull[i] = inputslot->tts_isnull[varNumber];
1219 }
1220 ExecStoreVirtualTuple(hashslot);
1221}

References ExecClearTuple(), ExecStoreVirtualTuple(), AggStatePerHashData::hashGrpColIdxInput, i, AggStatePerHashData::largestGrpColIdx, AggStatePerHashData::numhashGrpCols, slot_getsomeattrs(), TupleTableSlot::tts_isnull, and TupleTableSlot::tts_values.

Referenced by agg_refill_hash_table(), and lookup_hash_entries().

◆ prepare_projection_slot()

static void prepare_projection_slot ( AggState aggstate,
TupleTableSlot slot,
int  currentSet 
)
static

Definition at line 1248 of file nodeAgg.c.

1249{
1250 if (aggstate->phase->grouped_cols)
1251 {
1252 Bitmapset *grouped_cols = aggstate->phase->grouped_cols[currentSet];
1253
1254 aggstate->grouped_cols = grouped_cols;
1255
1256 if (TTS_EMPTY(slot))
1257 {
1258 /*
1259 * Force all values to be NULL if working on an empty input tuple
1260 * (i.e. an empty grouping set for which no input rows were
1261 * supplied).
1262 */
1264 }
1265 else if (aggstate->all_grouped_cols)
1266 {
1267 ListCell *lc;
1268
1269 /* all_grouped_cols is arranged in desc order */
1271
1272 foreach(lc, aggstate->all_grouped_cols)
1273 {
1274 int attnum = lfirst_int(lc);
1275
1276 if (!bms_is_member(attnum, grouped_cols))
1277 slot->tts_isnull[attnum - 1] = true;
1278 }
1279 }
1280 }
1281}
TupleTableSlot * ExecStoreAllNullTuple(TupleTableSlot *slot)
Definition: execTuples.c:1765
#define linitial_int(l)
Definition: pg_list.h:179
Bitmapset * grouped_cols
Definition: execnodes.h:2551
#define TTS_EMPTY(slot)
Definition: tuptable.h:96

References AggState::all_grouped_cols, attnum, bms_is_member(), ExecStoreAllNullTuple(), AggStatePerPhaseData::grouped_cols, AggState::grouped_cols, lfirst_int, linitial_int, AggState::phase, slot_getsomeattrs(), TTS_EMPTY, and TupleTableSlot::tts_isnull.

Referenced by agg_retrieve_direct(), and agg_retrieve_hash_table_in_memory().

◆ process_ordered_aggregate_multi()

static void process_ordered_aggregate_multi ( AggState aggstate,
AggStatePerTrans  pertrans,
AggStatePerGroup  pergroupstate 
)
static

Definition at line 948 of file nodeAgg.c.

951{
952 ExprContext *tmpcontext = aggstate->tmpcontext;
953 FunctionCallInfo fcinfo = pertrans->transfn_fcinfo;
954 TupleTableSlot *slot1 = pertrans->sortslot;
955 TupleTableSlot *slot2 = pertrans->uniqslot;
956 int numTransInputs = pertrans->numTransInputs;
957 int numDistinctCols = pertrans->numDistinctCols;
958 Datum newAbbrevVal = (Datum) 0;
959 Datum oldAbbrevVal = (Datum) 0;
960 bool haveOldValue = false;
961 TupleTableSlot *save = aggstate->tmpcontext->ecxt_outertuple;
962 int i;
963
964 tuplesort_performsort(pertrans->sortstates[aggstate->current_set]);
965
966 ExecClearTuple(slot1);
967 if (slot2)
968 ExecClearTuple(slot2);
969
970 while (tuplesort_gettupleslot(pertrans->sortstates[aggstate->current_set],
971 true, true, slot1, &newAbbrevVal))
972 {
974
975 tmpcontext->ecxt_outertuple = slot1;
976 tmpcontext->ecxt_innertuple = slot2;
977
978 if (numDistinctCols == 0 ||
979 !haveOldValue ||
980 newAbbrevVal != oldAbbrevVal ||
981 !ExecQual(pertrans->equalfnMulti, tmpcontext))
982 {
983 /*
984 * Extract the first numTransInputs columns as datums to pass to
985 * the transfn.
986 */
987 slot_getsomeattrs(slot1, numTransInputs);
988
989 /* Load values into fcinfo */
990 /* Start from 1, since the 0th arg will be the transition value */
991 for (i = 0; i < numTransInputs; i++)
992 {
993 fcinfo->args[i + 1].value = slot1->tts_values[i];
994 fcinfo->args[i + 1].isnull = slot1->tts_isnull[i];
995 }
996
997 advance_transition_function(aggstate, pertrans, pergroupstate);
998
999 if (numDistinctCols > 0)
1000 {
1001 /* swap the slot pointers to retain the current tuple */
1002 TupleTableSlot *tmpslot = slot2;
1003
1004 slot2 = slot1;
1005 slot1 = tmpslot;
1006 /* avoid ExecQual() calls by reusing abbreviated keys */
1007 oldAbbrevVal = newAbbrevVal;
1008 haveOldValue = true;
1009 }
1010 }
1011
1012 /* Reset context each time */
1013 ResetExprContext(tmpcontext);
1014
1015 ExecClearTuple(slot1);
1016 }
1017
1018 if (slot2)
1019 ExecClearTuple(slot2);
1020
1021 tuplesort_end(pertrans->sortstates[aggstate->current_set]);
1022 pertrans->sortstates[aggstate->current_set] = NULL;
1023
1024 /* restore previous slot, potentially in use for grouping sets */
1025 tmpcontext->ecxt_outertuple = save;
1026}
static void advance_transition_function(AggState *aggstate, AggStatePerTrans pertrans, AggStatePerGroup pergroupstate)
Definition: nodeAgg.c:708

References advance_transition_function(), FunctionCallInfoBaseData::args, CHECK_FOR_INTERRUPTS, AggState::current_set, ExprContext::ecxt_innertuple, ExprContext::ecxt_outertuple, AggStatePerTransData::equalfnMulti, ExecClearTuple(), ExecQual(), i, NullableDatum::isnull, AggStatePerTransData::numDistinctCols, AggStatePerTransData::numTransInputs, ResetExprContext, slot_getsomeattrs(), AggStatePerTransData::sortslot, AggStatePerTransData::sortstates, AggState::tmpcontext, AggStatePerTransData::transfn_fcinfo, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, tuplesort_end(), tuplesort_gettupleslot(), tuplesort_performsort(), AggStatePerTransData::uniqslot, and NullableDatum::value.

Referenced by finalize_aggregates().

◆ process_ordered_aggregate_single()

static void process_ordered_aggregate_single ( AggState aggstate,
AggStatePerTrans  pertrans,
AggStatePerGroup  pergroupstate 
)
static

Definition at line 847 of file nodeAgg.c.

850{
851 Datum oldVal = (Datum) 0;
852 bool oldIsNull = true;
853 bool haveOldVal = false;
854 MemoryContext workcontext = aggstate->tmpcontext->ecxt_per_tuple_memory;
855 MemoryContext oldContext;
856 bool isDistinct = (pertrans->numDistinctCols > 0);
857 Datum newAbbrevVal = (Datum) 0;
858 Datum oldAbbrevVal = (Datum) 0;
859 FunctionCallInfo fcinfo = pertrans->transfn_fcinfo;
860 Datum *newVal;
861 bool *isNull;
862
863 Assert(pertrans->numDistinctCols < 2);
864
865 tuplesort_performsort(pertrans->sortstates[aggstate->current_set]);
866
867 /* Load the column into argument 1 (arg 0 will be transition value) */
868 newVal = &fcinfo->args[1].value;
869 isNull = &fcinfo->args[1].isnull;
870
871 /*
872 * Note: if input type is pass-by-ref, the datums returned by the sort are
873 * freshly palloc'd in the per-query context, so we must be careful to
874 * pfree them when they are no longer needed.
875 */
876
877 while (tuplesort_getdatum(pertrans->sortstates[aggstate->current_set],
878 true, false, newVal, isNull, &newAbbrevVal))
879 {
880 /*
881 * Clear and select the working context for evaluation of the equality
882 * function and transition function.
883 */
884 MemoryContextReset(workcontext);
885 oldContext = MemoryContextSwitchTo(workcontext);
886
887 /*
888 * If DISTINCT mode, and not distinct from prior, skip it.
889 */
890 if (isDistinct &&
891 haveOldVal &&
892 ((oldIsNull && *isNull) ||
893 (!oldIsNull && !*isNull &&
894 oldAbbrevVal == newAbbrevVal &&
896 pertrans->aggCollation,
897 oldVal, *newVal)))))
898 {
899 MemoryContextSwitchTo(oldContext);
900 continue;
901 }
902 else
903 {
904 advance_transition_function(aggstate, pertrans, pergroupstate);
905
906 MemoryContextSwitchTo(oldContext);
907
908 /*
909 * Forget the old value, if any, and remember the new one for
910 * subsequent equality checks.
911 */
912 if (!pertrans->inputtypeByVal)
913 {
914 if (!oldIsNull)
915 pfree(DatumGetPointer(oldVal));
916 if (!*isNull)
917 oldVal = datumCopy(*newVal, pertrans->inputtypeByVal,
918 pertrans->inputtypeLen);
919 }
920 else
921 oldVal = *newVal;
922 oldAbbrevVal = newAbbrevVal;
923 oldIsNull = *isNull;
924 haveOldVal = true;
925 }
926 }
927
928 if (!oldIsNull && !pertrans->inputtypeByVal)
929 pfree(DatumGetPointer(oldVal));
930
931 tuplesort_end(pertrans->sortstates[aggstate->current_set]);
932 pertrans->sortstates[aggstate->current_set] = NULL;
933}
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149
static bool DatumGetBool(Datum X)
Definition: postgres.h:95
bool tuplesort_getdatum(Tuplesortstate *state, bool forward, bool copy, Datum *val, bool *isNull, Datum *abbrev)

References advance_transition_function(), AggStatePerTransData::aggCollation, FunctionCallInfoBaseData::args, Assert(), AggState::current_set, datumCopy(), DatumGetBool(), DatumGetPointer(), ExprContext::ecxt_per_tuple_memory, AggStatePerTransData::equalfnOne, FunctionCall2Coll(), AggStatePerTransData::inputtypeByVal, AggStatePerTransData::inputtypeLen, NullableDatum::isnull, MemoryContextReset(), MemoryContextSwitchTo(), AggStatePerTransData::numDistinctCols, pfree(), AggStatePerTransData::sortstates, AggState::tmpcontext, AggStatePerTransData::transfn_fcinfo, tuplesort_end(), tuplesort_getdatum(), tuplesort_performsort(), and NullableDatum::value.

Referenced by finalize_aggregates().

◆ project_aggregates()

static TupleTableSlot * project_aggregates ( AggState aggstate)
static

Definition at line 1370 of file nodeAgg.c.

1371{
1372 ExprContext *econtext = aggstate->ss.ps.ps_ExprContext;
1373
1374 /*
1375 * Check the qual (HAVING clause); if the group does not match, ignore it.
1376 */
1377 if (ExecQual(aggstate->ss.ps.qual, econtext))
1378 {
1379 /*
1380 * Form and return projection tuple using the aggregate results and
1381 * the representative input tuple.
1382 */
1383 return ExecProject(aggstate->ss.ps.ps_ProjInfo);
1384 }
1385 else
1386 InstrCountFiltered1(aggstate, 1);
1387
1388 return NULL;
1389}
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:1263
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:505
ProjectionInfo * ps_ProjInfo
Definition: execnodes.h:1199

References ExecProject(), ExecQual(), InstrCountFiltered1, ScanState::ps, PlanState::ps_ExprContext, PlanState::ps_ProjInfo, PlanState::qual, and AggState::ss.

Referenced by agg_retrieve_direct(), and agg_retrieve_hash_table_in_memory().

◆ select_current_set()

static void select_current_set ( AggState aggstate,
int  setno,
bool  is_hash 
)
static

Definition at line 457 of file nodeAgg.c.

458{
459 /*
460 * When changing this, also adapt ExecAggPlainTransByVal() and
461 * ExecAggPlainTransByRef().
462 */
463 if (is_hash)
464 aggstate->curaggcontext = aggstate->hashcontext;
465 else
466 aggstate->curaggcontext = aggstate->aggcontexts[setno];
467
468 aggstate->current_set = setno;
469}

References AggState::aggcontexts, AggState::curaggcontext, AggState::current_set, and AggState::hashcontext.

Referenced by agg_fill_hash_table(), agg_refill_hash_table(), agg_retrieve_direct(), agg_retrieve_hash_table_in_memory(), ExecInitAgg(), ExecReScanAgg(), initialize_aggregates(), and lookup_hash_entries().