PostgreSQL Source Code  git master
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/makefuncs.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/logtape.h"
#include "utils/lsyscache.h"
#include "utils/memutils.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   16
 

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 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   16

Definition at line 321 of file nodeAgg.c.

◆ HASHAGG_HLL_BIT_WIDTH

#define HASHAGG_HLL_BIT_WIDTH   5

Definition at line 315 of file nodeAgg.c.

◆ HASHAGG_MAX_PARTITIONS

#define HASHAGG_MAX_PARTITIONS   1024

Definition at line 298 of file nodeAgg.c.

◆ HASHAGG_MIN_PARTITIONS

#define HASHAGG_MIN_PARTITIONS   4

Definition at line 297 of file nodeAgg.c.

◆ HASHAGG_PARTITION_FACTOR

#define HASHAGG_PARTITION_FACTOR   1.50

Definition at line 296 of file nodeAgg.c.

◆ HASHAGG_READ_BUFFER_SIZE

#define HASHAGG_READ_BUFFER_SIZE   BLCKSZ

Definition at line 306 of file nodeAgg.c.

◆ HASHAGG_WRITE_BUFFER_SIZE

#define HASHAGG_WRITE_BUFFER_SIZE   BLCKSZ

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

820 {
821  bool dummynull;
822 
824  aggstate->tmpcontext,
825  &dummynull);
826 }
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:333
ExprState * evaltrans
Definition: nodeAgg.h:291
AggStatePerPhase phase
Definition: execnodes.h:2364
ExprContext * tmpcontext
Definition: execnodes.h:2371

References AggStatePerPhaseData::evaltrans, ExecEvalExprSwitchContext(), 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 707 of file nodeAgg.c.

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

References FunctionCallInfoBaseData::args, AggState::curaggcontext, AggState::curpertrans, datumCopy(), DatumGetPointer(), ExprContext::ecxt_per_tuple_memory, ExecAggTransReparent(), 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 2532 of file nodeAgg.c.

2533 {
2534  TupleTableSlot *outerslot;
2535  ExprContext *tmpcontext = aggstate->tmpcontext;
2536 
2537  /*
2538  * Process each outer-plan tuple, and then fetch the next one, until we
2539  * exhaust the outer plan.
2540  */
2541  for (;;)
2542  {
2543  outerslot = fetch_input_tuple(aggstate);
2544  if (TupIsNull(outerslot))
2545  break;
2546 
2547  /* set up for lookup_hash_entries and advance_aggregates */
2548  tmpcontext->ecxt_outertuple = outerslot;
2549 
2550  /* Find or build hashtable entries */
2551  lookup_hash_entries(aggstate);
2552 
2553  /* Advance the aggregates (or combine functions) */
2554  advance_aggregates(aggstate);
2555 
2556  /*
2557  * Reset per-input-tuple context after each tuple, but note that the
2558  * hash lookups do this too
2559  */
2560  ResetExprContext(aggstate->tmpcontext);
2561  }
2562 
2563  /* finalize spills, if any */
2565 
2566  aggstate->table_filled = true;
2567  /* Initialize to walk the first hash table */
2568  select_current_set(aggstate, 0, true);
2570  &aggstate->perhash[0].hashiter);
2571 }
#define ResetTupleHashIterator(htable, iter)
Definition: execnodes.h:830
#define ResetExprContext(econtext)
Definition: executor.h:529
static void hashagg_finish_initial_spills(AggState *aggstate)
Definition: nodeAgg.c:3051
static TupleTableSlot * fetch_input_tuple(AggState *aggstate)
Definition: nodeAgg.c:548
static void lookup_hash_entries(AggState *aggstate)
Definition: nodeAgg.c:2087
static void advance_aggregates(AggState *aggstate)
Definition: nodeAgg.c:819
static void select_current_set(AggState *aggstate, int setno, bool is_hash)
Definition: nodeAgg.c:456
TupleHashTable hashtable
Definition: nodeAgg.h:311
TupleHashIterator hashiter
Definition: nodeAgg.h:312
bool table_filled
Definition: execnodes.h:2398
AggStatePerHash perhash
Definition: execnodes.h:2421
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:251
#define TupIsNull(slot)
Definition: tuptable.h:300

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

2587 {
2588  HashAggBatch *batch;
2589  AggStatePerHash perhash;
2590  HashAggSpill spill;
2591  LogicalTapeSet *tapeset = aggstate->hash_tapeset;
2592  bool spill_initialized = false;
2593 
2594  if (aggstate->hash_batches == NIL)
2595  return false;
2596 
2597  /* hash_batches is a stack, with the top item at the end of the list */
2598  batch = llast(aggstate->hash_batches);
2599  aggstate->hash_batches = list_delete_last(aggstate->hash_batches);
2600 
2601  hash_agg_set_limits(aggstate->hashentrysize, batch->input_card,
2602  batch->used_bits, &aggstate->hash_mem_limit,
2603  &aggstate->hash_ngroups_limit, NULL);
2604 
2605  /*
2606  * Each batch only processes one grouping set; set the rest to NULL so
2607  * that advance_aggregates() knows to ignore them. We don't touch
2608  * pergroups for sorted grouping sets here, because they will be needed if
2609  * we rescan later. The expressions for sorted grouping sets will not be
2610  * evaluated after we recompile anyway.
2611  */
2612  MemSet(aggstate->hash_pergroup, 0,
2613  sizeof(AggStatePerGroup) * aggstate->num_hashes);
2614 
2615  /* free memory and reset hash tables */
2616  ReScanExprContext(aggstate->hashcontext);
2617  for (int setno = 0; setno < aggstate->num_hashes; setno++)
2618  ResetTupleHashTable(aggstate->perhash[setno].hashtable);
2619 
2620  aggstate->hash_ngroups_current = 0;
2621 
2622  /*
2623  * In AGG_MIXED mode, hash aggregation happens in phase 1 and the output
2624  * happens in phase 0. So, we switch to phase 1 when processing a batch,
2625  * and back to phase 0 after the batch is done.
2626  */
2627  Assert(aggstate->current_phase == 0);
2628  if (aggstate->phase->aggstrategy == AGG_MIXED)
2629  {
2630  aggstate->current_phase = 1;
2631  aggstate->phase = &aggstate->phases[aggstate->current_phase];
2632  }
2633 
2634  select_current_set(aggstate, batch->setno, true);
2635 
2636  perhash = &aggstate->perhash[aggstate->current_set];
2637 
2638  /*
2639  * Spilled tuples are always read back as MinimalTuples, which may be
2640  * different from the outer plan, so recompile the aggregate expressions.
2641  *
2642  * We still need the NULL check, because we are only processing one
2643  * grouping set at a time and the rest will be NULL.
2644  */
2645  hashagg_recompile_expressions(aggstate, true, true);
2646 
2647  for (;;)
2648  {
2649  TupleTableSlot *spillslot = aggstate->hash_spill_rslot;
2650  TupleTableSlot *hashslot = perhash->hashslot;
2651  TupleHashEntry entry;
2652  MinimalTuple tuple;
2653  uint32 hash;
2654  bool isnew = false;
2655  bool *p_isnew = aggstate->hash_spill_mode ? NULL : &isnew;
2656 
2658 
2659  tuple = hashagg_batch_read(batch, &hash);
2660  if (tuple == NULL)
2661  break;
2662 
2663  ExecStoreMinimalTuple(tuple, spillslot, true);
2664  aggstate->tmpcontext->ecxt_outertuple = spillslot;
2665 
2666  prepare_hash_slot(perhash,
2667  aggstate->tmpcontext->ecxt_outertuple,
2668  hashslot);
2669  entry = LookupTupleHashEntryHash(perhash->hashtable, hashslot,
2670  p_isnew, hash);
2671 
2672  if (entry != NULL)
2673  {
2674  if (isnew)
2675  initialize_hash_entry(aggstate, perhash->hashtable, entry);
2676  aggstate->hash_pergroup[batch->setno] = entry->additional;
2677  advance_aggregates(aggstate);
2678  }
2679  else
2680  {
2681  if (!spill_initialized)
2682  {
2683  /*
2684  * Avoid initializing the spill until we actually need it so
2685  * that we don't assign tapes that will never be used.
2686  */
2687  spill_initialized = true;
2688  hashagg_spill_init(&spill, tapeset, batch->used_bits,
2689  batch->input_card, aggstate->hashentrysize);
2690  }
2691  /* no memory for a new group, spill */
2692  hashagg_spill_tuple(aggstate, &spill, spillslot, hash);
2693 
2694  aggstate->hash_pergroup[batch->setno] = NULL;
2695  }
2696 
2697  /*
2698  * Reset per-input-tuple context after each tuple, but note that the
2699  * hash lookups do this too
2700  */
2701  ResetExprContext(aggstate->tmpcontext);
2702  }
2703 
2704  LogicalTapeClose(batch->input_tape);
2705 
2706  /* change back to phase 0 */
2707  aggstate->current_phase = 0;
2708  aggstate->phase = &aggstate->phases[aggstate->current_phase];
2709 
2710  if (spill_initialized)
2711  {
2712  hashagg_spill_finish(aggstate, &spill, batch->setno);
2713  hash_agg_update_metrics(aggstate, true, spill.npartitions);
2714  }
2715  else
2716  hash_agg_update_metrics(aggstate, true, 0);
2717 
2718  aggstate->hash_spill_mode = false;
2719 
2720  /* prepare to walk the first hash table */
2721  select_current_set(aggstate, batch->setno, true);
2722  ResetTupleHashIterator(aggstate->perhash[batch->setno].hashtable,
2723  &aggstate->perhash[batch->setno].hashiter);
2724 
2725  pfree(batch);
2726 
2727  return true;
2728 }
unsigned int uint32
Definition: c.h:442
#define MemSet(start, val, len)
Definition: c.h:953
TupleHashEntry LookupTupleHashEntryHash(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew, uint32 hash)
Definition: execGrouping.c:361
void ResetTupleHashTable(TupleHashTable hashtable)
Definition: execGrouping.c:285
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1446
void ReScanExprContext(ExprContext *econtext)
Definition: execUtils.c:440
Assert(fmt[strlen(fmt) - 1] !='\n')
List * list_delete_last(List *list)
Definition: list.c:956
void LogicalTapeClose(LogicalTape *lt)
Definition: logtape.c:734
void pfree(void *pointer)
Definition: mcxt.c:1306
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static void initialize_hash_entry(AggState *aggstate, TupleHashTable hashtable, TupleHashEntry entry)
Definition: nodeAgg.c:2037
static void hashagg_spill_finish(AggState *aggstate, HashAggSpill *spill, int setno)
Definition: nodeAgg.c:3085
static MinimalTuple hashagg_batch_read(HashAggBatch *batch, uint32 *hashp)
Definition: nodeAgg.c:3002
static void hash_agg_update_metrics(AggState *aggstate, bool from_tape, int npartitions)
Definition: nodeAgg.c:1909
static void hashagg_recompile_expressions(AggState *aggstate, bool minslot, bool nullcheck)
Definition: nodeAgg.c:1733
static void prepare_hash_slot(AggStatePerHash perhash, TupleTableSlot *inputslot, TupleTableSlot *hashslot)
Definition: nodeAgg.c:1197
static Size hashagg_spill_tuple(AggState *aggstate, HashAggSpill *spill, TupleTableSlot *inputslot, uint32 hash)
Definition: nodeAgg.c:2917
static void hashagg_spill_init(HashAggSpill *spill, LogicalTapeSet *tapeset, int used_bits, double input_groups, double hashentrysize)
Definition: nodeAgg.c:2886
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:1790
@ AGG_MIXED
Definition: nodes.h:354
#define llast(l)
Definition: pg_list.h:196
#define NIL
Definition: pg_list.h:66
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:2422
Size hash_mem_limit
Definition: execnodes.h:2410
int current_set
Definition: execnodes.h:2381
struct LogicalTapeSet * hash_tapeset
Definition: execnodes.h:2401
ExprContext * hashcontext
Definition: execnodes.h:2369
uint64 hash_ngroups_limit
Definition: execnodes.h:2411
AggStatePerPhase phases
Definition: execnodes.h:2389
bool hash_spill_mode
Definition: execnodes.h:2408
double hashentrysize
Definition: execnodes.h:2414
uint64 hash_ngroups_current
Definition: execnodes.h:2416
int num_hashes
Definition: execnodes.h:2399
List * hash_batches
Definition: execnodes.h:2406
TupleTableSlot * hash_spill_rslot
Definition: execnodes.h:2404
int current_phase
Definition: execnodes.h:2366
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 TupleHashEntryData::additional, 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_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(), HashAggBatch::input_card, HashAggBatch::input_tape, list_delete_last(), llast, LogicalTapeClose(), LookupTupleHashEntryHash(), 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, and HashAggBatch::used_bits.

Referenced by agg_retrieve_hash_table().

◆ agg_retrieve_direct()

static TupleTableSlot * agg_retrieve_direct ( AggState aggstate)
static

Definition at line 2186 of file nodeAgg.c.

2187 {
2188  Agg *node = aggstate->phase->aggnode;
2189  ExprContext *econtext;
2190  ExprContext *tmpcontext;
2191  AggStatePerAgg peragg;
2192  AggStatePerGroup *pergroups;
2193  TupleTableSlot *outerslot;
2194  TupleTableSlot *firstSlot;
2195  TupleTableSlot *result;
2196  bool hasGroupingSets = aggstate->phase->numsets > 0;
2197  int numGroupingSets = Max(aggstate->phase->numsets, 1);
2198  int currentSet;
2199  int nextSetSize;
2200  int numReset;
2201  int i;
2202 
2203  /*
2204  * get state info from node
2205  *
2206  * econtext is the per-output-tuple expression context
2207  *
2208  * tmpcontext is the per-input-tuple expression context
2209  */
2210  econtext = aggstate->ss.ps.ps_ExprContext;
2211  tmpcontext = aggstate->tmpcontext;
2212 
2213  peragg = aggstate->peragg;
2214  pergroups = aggstate->pergroups;
2215  firstSlot = aggstate->ss.ss_ScanTupleSlot;
2216 
2217  /*
2218  * We loop retrieving groups until we find one matching
2219  * aggstate->ss.ps.qual
2220  *
2221  * For grouping sets, we have the invariant that aggstate->projected_set
2222  * is either -1 (initial call) or the index (starting from 0) in
2223  * gset_lengths for the group we just completed (either by projecting a
2224  * row or by discarding it in the qual).
2225  */
2226  while (!aggstate->agg_done)
2227  {
2228  /*
2229  * Clear the per-output-tuple context for each group, as well as
2230  * aggcontext (which contains any pass-by-ref transvalues of the old
2231  * group). Some aggregate functions store working state in child
2232  * contexts; those now get reset automatically without us needing to
2233  * do anything special.
2234  *
2235  * We use ReScanExprContext not just ResetExprContext because we want
2236  * any registered shutdown callbacks to be called. That allows
2237  * aggregate functions to ensure they've cleaned up any non-memory
2238  * resources.
2239  */
2240  ReScanExprContext(econtext);
2241 
2242  /*
2243  * Determine how many grouping sets need to be reset at this boundary.
2244  */
2245  if (aggstate->projected_set >= 0 &&
2246  aggstate->projected_set < numGroupingSets)
2247  numReset = aggstate->projected_set + 1;
2248  else
2249  numReset = numGroupingSets;
2250 
2251  /*
2252  * numReset can change on a phase boundary, but that's OK; we want to
2253  * reset the contexts used in _this_ phase, and later, after possibly
2254  * changing phase, initialize the right number of aggregates for the
2255  * _new_ phase.
2256  */
2257 
2258  for (i = 0; i < numReset; i++)
2259  {
2260  ReScanExprContext(aggstate->aggcontexts[i]);
2261  }
2262 
2263  /*
2264  * Check if input is complete and there are no more groups to project
2265  * in this phase; move to next phase or mark as done.
2266  */
2267  if (aggstate->input_done == true &&
2268  aggstate->projected_set >= (numGroupingSets - 1))
2269  {
2270  if (aggstate->current_phase < aggstate->numphases - 1)
2271  {
2272  initialize_phase(aggstate, aggstate->current_phase + 1);
2273  aggstate->input_done = false;
2274  aggstate->projected_set = -1;
2275  numGroupingSets = Max(aggstate->phase->numsets, 1);
2276  node = aggstate->phase->aggnode;
2277  numReset = numGroupingSets;
2278  }
2279  else if (aggstate->aggstrategy == AGG_MIXED)
2280  {
2281  /*
2282  * Mixed mode; we've output all the grouped stuff and have
2283  * full hashtables, so switch to outputting those.
2284  */
2285  initialize_phase(aggstate, 0);
2286  aggstate->table_filled = true;
2288  &aggstate->perhash[0].hashiter);
2289  select_current_set(aggstate, 0, true);
2290  return agg_retrieve_hash_table(aggstate);
2291  }
2292  else
2293  {
2294  aggstate->agg_done = true;
2295  break;
2296  }
2297  }
2298 
2299  /*
2300  * Get the number of columns in the next grouping set after the last
2301  * projected one (if any). This is the number of columns to compare to
2302  * see if we reached the boundary of that set too.
2303  */
2304  if (aggstate->projected_set >= 0 &&
2305  aggstate->projected_set < (numGroupingSets - 1))
2306  nextSetSize = aggstate->phase->gset_lengths[aggstate->projected_set + 1];
2307  else
2308  nextSetSize = 0;
2309 
2310  /*----------
2311  * If a subgroup for the current grouping set is present, project it.
2312  *
2313  * We have a new group if:
2314  * - we're out of input but haven't projected all grouping sets
2315  * (checked above)
2316  * OR
2317  * - we already projected a row that wasn't from the last grouping
2318  * set
2319  * AND
2320  * - the next grouping set has at least one grouping column (since
2321  * empty grouping sets project only once input is exhausted)
2322  * AND
2323  * - the previous and pending rows differ on the grouping columns
2324  * of the next grouping set
2325  *----------
2326  */
2327  tmpcontext->ecxt_innertuple = econtext->ecxt_outertuple;
2328  if (aggstate->input_done ||
2329  (node->aggstrategy != AGG_PLAIN &&
2330  aggstate->projected_set != -1 &&
2331  aggstate->projected_set < (numGroupingSets - 1) &&
2332  nextSetSize > 0 &&
2333  !ExecQualAndReset(aggstate->phase->eqfunctions[nextSetSize - 1],
2334  tmpcontext)))
2335  {
2336  aggstate->projected_set += 1;
2337 
2338  Assert(aggstate->projected_set < numGroupingSets);
2339  Assert(nextSetSize > 0 || aggstate->input_done);
2340  }
2341  else
2342  {
2343  /*
2344  * We no longer care what group we just projected, the next
2345  * projection will always be the first (or only) grouping set
2346  * (unless the input proves to be empty).
2347  */
2348  aggstate->projected_set = 0;
2349 
2350  /*
2351  * If we don't already have the first tuple of the new group,
2352  * fetch it from the outer plan.
2353  */
2354  if (aggstate->grp_firstTuple == NULL)
2355  {
2356  outerslot = fetch_input_tuple(aggstate);
2357  if (!TupIsNull(outerslot))
2358  {
2359  /*
2360  * Make a copy of the first input tuple; we will use this
2361  * for comparisons (in group mode) and for projection.
2362  */
2363  aggstate->grp_firstTuple = ExecCopySlotHeapTuple(outerslot);
2364  }
2365  else
2366  {
2367  /* outer plan produced no tuples at all */
2368  if (hasGroupingSets)
2369  {
2370  /*
2371  * If there was no input at all, we need to project
2372  * rows only if there are grouping sets of size 0.
2373  * Note that this implies that there can't be any
2374  * references to ungrouped Vars, which would otherwise
2375  * cause issues with the empty output slot.
2376  *
2377  * XXX: This is no longer true, we currently deal with
2378  * this in finalize_aggregates().
2379  */
2380  aggstate->input_done = true;
2381 
2382  while (aggstate->phase->gset_lengths[aggstate->projected_set] > 0)
2383  {
2384  aggstate->projected_set += 1;
2385  if (aggstate->projected_set >= numGroupingSets)
2386  {
2387  /*
2388  * We can't set agg_done here because we might
2389  * have more phases to do, even though the
2390  * input is empty. So we need to restart the
2391  * whole outer loop.
2392  */
2393  break;
2394  }
2395  }
2396 
2397  if (aggstate->projected_set >= numGroupingSets)
2398  continue;
2399  }
2400  else
2401  {
2402  aggstate->agg_done = true;
2403  /* If we are grouping, we should produce no tuples too */
2404  if (node->aggstrategy != AGG_PLAIN)
2405  return NULL;
2406  }
2407  }
2408  }
2409 
2410  /*
2411  * Initialize working state for a new input tuple group.
2412  */
2413  initialize_aggregates(aggstate, pergroups, numReset);
2414 
2415  if (aggstate->grp_firstTuple != NULL)
2416  {
2417  /*
2418  * Store the copied first input tuple in the tuple table slot
2419  * reserved for it. The tuple will be deleted when it is
2420  * cleared from the slot.
2421  */
2423  firstSlot, true);
2424  aggstate->grp_firstTuple = NULL; /* don't keep two pointers */
2425 
2426  /* set up for first advance_aggregates call */
2427  tmpcontext->ecxt_outertuple = firstSlot;
2428 
2429  /*
2430  * Process each outer-plan tuple, and then fetch the next one,
2431  * until we exhaust the outer plan or cross a group boundary.
2432  */
2433  for (;;)
2434  {
2435  /*
2436  * During phase 1 only of a mixed agg, we need to update
2437  * hashtables as well in advance_aggregates.
2438  */
2439  if (aggstate->aggstrategy == AGG_MIXED &&
2440  aggstate->current_phase == 1)
2441  {
2442  lookup_hash_entries(aggstate);
2443  }
2444 
2445  /* Advance the aggregates (or combine functions) */
2446  advance_aggregates(aggstate);
2447 
2448  /* Reset per-input-tuple context after each tuple */
2449  ResetExprContext(tmpcontext);
2450 
2451  outerslot = fetch_input_tuple(aggstate);
2452  if (TupIsNull(outerslot))
2453  {
2454  /* no more outer-plan tuples available */
2455 
2456  /* if we built hash tables, finalize any spills */
2457  if (aggstate->aggstrategy == AGG_MIXED &&
2458  aggstate->current_phase == 1)
2460 
2461  if (hasGroupingSets)
2462  {
2463  aggstate->input_done = true;
2464  break;
2465  }
2466  else
2467  {
2468  aggstate->agg_done = true;
2469  break;
2470  }
2471  }
2472  /* set up for next advance_aggregates call */
2473  tmpcontext->ecxt_outertuple = outerslot;
2474 
2475  /*
2476  * If we are grouping, check whether we've crossed a group
2477  * boundary.
2478  */
2479  if (node->aggstrategy != AGG_PLAIN)
2480  {
2481  tmpcontext->ecxt_innertuple = firstSlot;
2482  if (!ExecQual(aggstate->phase->eqfunctions[node->numCols - 1],
2483  tmpcontext))
2484  {
2485  aggstate->grp_firstTuple = ExecCopySlotHeapTuple(outerslot);
2486  break;
2487  }
2488  }
2489  }
2490  }
2491 
2492  /*
2493  * Use the representative input tuple for any references to
2494  * non-aggregated input columns in aggregate direct args, the node
2495  * qual, and the tlist. (If we are not grouping, and there are no
2496  * input rows at all, we will come here with an empty firstSlot
2497  * ... but if not grouping, there can't be any references to
2498  * non-aggregated input columns, so no problem.)
2499  */
2500  econtext->ecxt_outertuple = firstSlot;
2501  }
2502 
2503  Assert(aggstate->projected_set >= 0);
2504 
2505  currentSet = aggstate->projected_set;
2506 
2507  prepare_projection_slot(aggstate, econtext->ecxt_outertuple, currentSet);
2508 
2509  select_current_set(aggstate, currentSet, false);
2510 
2511  finalize_aggregates(aggstate,
2512  peragg,
2513  pergroups[currentSet]);
2514 
2515  /*
2516  * If there's no row to project right now, we must continue rather
2517  * than returning a null since there might be more groups.
2518  */
2519  result = project_aggregates(aggstate);
2520  if (result)
2521  return result;
2522  }
2523 
2524  /* No more groups */
2525  return NULL;
2526 }
#define Max(x, y)
Definition: c.h:931
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:398
static bool ExecQualAndReset(ExprState *state, ExprContext *econtext)
Definition: executor.h:425
static TupleTableSlot * project_aggregates(AggState *aggstate)
Definition: nodeAgg.c:1364
static void finalize_aggregates(AggState *aggstate, AggStatePerAgg peraggs, AggStatePerGroup pergroup)
Definition: nodeAgg.c:1287
static void initialize_phase(AggState *aggstate, int newphase)
Definition: nodeAgg.c:478
static void initialize_aggregates(AggState *aggstate, AggStatePerGroup *pergroups, int numReset)
Definition: nodeAgg.c:666
static void prepare_projection_slot(AggState *aggstate, TupleTableSlot *slot, int currentSet)
Definition: nodeAgg.c:1242
static TupleTableSlot * agg_retrieve_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2738
@ AGG_PLAIN
Definition: nodes.h:351
ExprState ** eqfunctions
Definition: nodeAgg.h:286
ScanState ss
Definition: execnodes.h:2358
HeapTuple grp_firstTuple
Definition: execnodes.h:2396
AggStrategy aggstrategy
Definition: execnodes.h:2362
int projected_set
Definition: execnodes.h:2379
bool input_done
Definition: execnodes.h:2377
AggStatePerGroup * pergroups
Definition: execnodes.h:2394
int numphases
Definition: execnodes.h:2365
AggStatePerAgg peragg
Definition: execnodes.h:2367
ExprContext ** aggcontexts
Definition: execnodes.h:2370
bool agg_done
Definition: execnodes.h:2378
Definition: plannodes.h:993
int numCols
Definition: plannodes.h:1003
AggStrategy aggstrategy
Definition: plannodes.h:997
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:249
ExprContext * ps_ExprContext
Definition: execnodes.h:1068
TupleTableSlot * ss_ScanTupleSlot
Definition: execnodes.h:1457
PlanState ps
Definition: execnodes.h:1454
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:460

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

2739 {
2740  TupleTableSlot *result = NULL;
2741 
2742  while (result == NULL)
2743  {
2744  result = agg_retrieve_hash_table_in_memory(aggstate);
2745  if (result == NULL)
2746  {
2747  if (!agg_refill_hash_table(aggstate))
2748  {
2749  aggstate->agg_done = true;
2750  break;
2751  }
2752  }
2753  }
2754 
2755  return result;
2756 }
static bool agg_refill_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2586
static TupleTableSlot * agg_retrieve_hash_table_in_memory(AggState *aggstate)
Definition: nodeAgg.c:2763

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

2764 {
2765  ExprContext *econtext;
2766  AggStatePerAgg peragg;
2767  AggStatePerGroup pergroup;
2768  TupleHashEntryData *entry;
2769  TupleTableSlot *firstSlot;
2770  TupleTableSlot *result;
2771  AggStatePerHash perhash;
2772 
2773  /*
2774  * get state info from node.
2775  *
2776  * econtext is the per-output-tuple expression context.
2777  */
2778  econtext = aggstate->ss.ps.ps_ExprContext;
2779  peragg = aggstate->peragg;
2780  firstSlot = aggstate->ss.ss_ScanTupleSlot;
2781 
2782  /*
2783  * Note that perhash (and therefore anything accessed through it) can
2784  * change inside the loop, as we change between grouping sets.
2785  */
2786  perhash = &aggstate->perhash[aggstate->current_set];
2787 
2788  /*
2789  * We loop retrieving groups until we find one satisfying
2790  * aggstate->ss.ps.qual
2791  */
2792  for (;;)
2793  {
2794  TupleTableSlot *hashslot = perhash->hashslot;
2795  int i;
2796 
2798 
2799  /*
2800  * Find the next entry in the hash table
2801  */
2802  entry = ScanTupleHashTable(perhash->hashtable, &perhash->hashiter);
2803  if (entry == NULL)
2804  {
2805  int nextset = aggstate->current_set + 1;
2806 
2807  if (nextset < aggstate->num_hashes)
2808  {
2809  /*
2810  * Switch to next grouping set, reinitialize, and restart the
2811  * loop.
2812  */
2813  select_current_set(aggstate, nextset, true);
2814 
2815  perhash = &aggstate->perhash[aggstate->current_set];
2816 
2817  ResetTupleHashIterator(perhash->hashtable, &perhash->hashiter);
2818 
2819  continue;
2820  }
2821  else
2822  {
2823  return NULL;
2824  }
2825  }
2826 
2827  /*
2828  * Clear the per-output-tuple context for each group
2829  *
2830  * We intentionally don't use ReScanExprContext here; if any aggs have
2831  * registered shutdown callbacks, they mustn't be called yet, since we
2832  * might not be done with that agg.
2833  */
2834  ResetExprContext(econtext);
2835 
2836  /*
2837  * Transform representative tuple back into one with the right
2838  * columns.
2839  */
2840  ExecStoreMinimalTuple(entry->firstTuple, hashslot, false);
2841  slot_getallattrs(hashslot);
2842 
2843  ExecClearTuple(firstSlot);
2844  memset(firstSlot->tts_isnull, true,
2845  firstSlot->tts_tupleDescriptor->natts * sizeof(bool));
2846 
2847  for (i = 0; i < perhash->numhashGrpCols; i++)
2848  {
2849  int varNumber = perhash->hashGrpColIdxInput[i] - 1;
2850 
2851  firstSlot->tts_values[varNumber] = hashslot->tts_values[i];
2852  firstSlot->tts_isnull[varNumber] = hashslot->tts_isnull[i];
2853  }
2854  ExecStoreVirtualTuple(firstSlot);
2855 
2856  pergroup = (AggStatePerGroup) entry->additional;
2857 
2858  /*
2859  * Use the representative input tuple for any references to
2860  * non-aggregated input columns in the qual and tlist.
2861  */
2862  econtext->ecxt_outertuple = firstSlot;
2863 
2864  prepare_projection_slot(aggstate,
2865  econtext->ecxt_outertuple,
2866  aggstate->current_set);
2867 
2868  finalize_aggregates(aggstate, peragg, pergroup);
2869 
2870  result = project_aggregates(aggstate);
2871  if (result)
2872  return result;
2873  }
2874 
2875  /* No more groups */
2876  return NULL;
2877 }
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1552
#define ScanTupleHashTable(htable, iter)
Definition: execnodes.h:832
struct AggStatePerGroupData * AggStatePerGroup
Definition: execnodes.h:2352
AttrNumber * hashGrpColIdxInput
Definition: nodeAgg.h:319
MinimalTuple firstTuple
Definition: execnodes.h:785
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:124
bool * tts_isnull
Definition: tuptable.h:128
Datum * tts_values
Definition: tuptable.h:126
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:362

References TupleHashEntryData::additional, CHECK_FOR_INTERRUPTS, AggState::current_set, ExprContext::ecxt_outertuple, ExecClearTuple(), ExecStoreMinimalTuple(), ExecStoreVirtualTuple(), finalize_aggregates(), TupleHashEntryData::firstTuple, 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, and TupleTableSlot::tts_values.

Referenced by agg_retrieve_hash_table().

◆ AggCheckCallContext()

int AggCheckCallContext ( FunctionCallInfo  fcinfo,
MemoryContext aggcontext 
)

Definition at line 4509 of file nodeAgg.c.

4510 {
4511  if (fcinfo->context && IsA(fcinfo->context, AggState))
4512  {
4513  if (aggcontext)
4514  {
4515  AggState *aggstate = ((AggState *) fcinfo->context);
4516  ExprContext *cxt = aggstate->curaggcontext;
4517 
4518  *aggcontext = cxt->ecxt_per_tuple_memory;
4519  }
4520  return AGG_CONTEXT_AGGREGATE;
4521  }
4522  if (fcinfo->context && IsA(fcinfo->context, WindowAggState))
4523  {
4524  if (aggcontext)
4525  *aggcontext = ((WindowAggState *) fcinfo->context)->curaggcontext;
4526  return AGG_CONTEXT_WINDOW;
4527  }
4528 
4529  /* this is just to prevent "uninitialized variable" warnings */
4530  if (aggcontext)
4531  *aggcontext = NULL;
4532  return 0;
4533 }
#define AGG_CONTEXT_WINDOW
Definition: fmgr.h:754
#define AGG_CONTEXT_AGGREGATE
Definition: fmgr.h:753
#define IsA(nodeptr, _type_)
Definition: nodes.h:168
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_finalfn(), array_agg_array_transfn(), array_agg_finalfn(), 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(), json_agg_finalfn(), json_agg_transfn(), json_object_agg_finalfn(), json_object_agg_transfn(), jsonb_agg_finalfn(), jsonb_agg_transfn(), jsonb_object_agg_finalfn(), jsonb_object_agg_transfn(), makeBoolAggState(), 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(), and string_agg_finalfn().

◆ AggGetAggref()

Aggref* AggGetAggref ( FunctionCallInfo  fcinfo)

Definition at line 4553 of file nodeAgg.c.

4554 {
4555  if (fcinfo->context && IsA(fcinfo->context, AggState))
4556  {
4557  AggState *aggstate = (AggState *) fcinfo->context;
4558  AggStatePerAgg curperagg;
4559  AggStatePerTrans curpertrans;
4560 
4561  /* check curperagg (valid when in a final function) */
4562  curperagg = aggstate->curperagg;
4563 
4564  if (curperagg)
4565  return curperagg->aggref;
4566 
4567  /* check curpertrans (valid when in a transition function) */
4568  curpertrans = aggstate->curpertrans;
4569 
4570  if (curpertrans)
4571  return curpertrans->aggref;
4572  }
4573  return NULL;
4574 }
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Aggref * aggref
Definition: nodeAgg.h:44
AggStatePerAgg curperagg
Definition: execnodes.h:2374

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

4588 {
4589  if (fcinfo->context && IsA(fcinfo->context, AggState))
4590  {
4591  AggState *aggstate = (AggState *) fcinfo->context;
4592 
4593  return aggstate->tmpcontext->ecxt_per_tuple_memory;
4594  }
4595  return NULL;
4596 }

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

◆ AggRegisterCallback()

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

Definition at line 4652 of file nodeAgg.c.

4655 {
4656  if (fcinfo->context && IsA(fcinfo->context, AggState))
4657  {
4658  AggState *aggstate = (AggState *) fcinfo->context;
4659  ExprContext *cxt = aggstate->curaggcontext;
4660 
4661  RegisterExprContextCallback(cxt, func, arg);
4662 
4663  return;
4664  }
4665  elog(ERROR, "aggregate function cannot register a callback in this context");
4666 }
#define ERROR
Definition: elog.h:35
void RegisterExprContextCallback(ExprContext *econtext, ExprContextCallbackFunction function, Datum arg)
Definition: execUtils.c:927
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 4613 of file nodeAgg.c.

4614 {
4615  if (fcinfo->context && IsA(fcinfo->context, AggState))
4616  {
4617  AggState *aggstate = (AggState *) fcinfo->context;
4618  AggStatePerAgg curperagg;
4619  AggStatePerTrans curpertrans;
4620 
4621  /* check curperagg (valid when in a final function) */
4622  curperagg = aggstate->curperagg;
4623 
4624  if (curperagg)
4625  return aggstate->pertrans[curperagg->transno].aggshared;
4626 
4627  /* check curpertrans (valid when in a transition function) */
4628  curpertrans = aggstate->curpertrans;
4629 
4630  if (curpertrans)
4631  return curpertrans->aggshared;
4632  }
4633  return true;
4634 }
AggStatePerTrans pertrans
Definition: execnodes.h:2368

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

1497 {
1498  AggStatePerHash perhash = &aggstate->perhash[setno];
1499  MemoryContext metacxt = aggstate->hash_metacxt;
1500  MemoryContext hashcxt = aggstate->hashcontext->ecxt_per_tuple_memory;
1501  MemoryContext tmpcxt = aggstate->tmpcontext->ecxt_per_tuple_memory;
1502  Size additionalsize;
1503 
1504  Assert(aggstate->aggstrategy == AGG_HASHED ||
1505  aggstate->aggstrategy == AGG_MIXED);
1506 
1507  /*
1508  * Used to make sure initial hash table allocation does not exceed
1509  * hash_mem. Note that the estimate does not include space for
1510  * pass-by-reference transition data values, nor for the representative
1511  * tuple of each group.
1512  */
1513  additionalsize = aggstate->numtrans * sizeof(AggStatePerGroupData);
1514 
1515  perhash->hashtable = BuildTupleHashTableExt(&aggstate->ss.ps,
1516  perhash->hashslot->tts_tupleDescriptor,
1517  perhash->numCols,
1518  perhash->hashGrpColIdxHash,
1519  perhash->eqfuncoids,
1520  perhash->hashfunctions,
1521  perhash->aggnode->grpCollations,
1522  nbuckets,
1523  additionalsize,
1524  metacxt,
1525  hashcxt,
1526  tmpcxt,
1527  DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit));
1528 }
size_t Size
Definition: c.h:541
TupleHashTable BuildTupleHashTableExt(PlanState *parent, TupleDesc inputDesc, 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:154
struct AggStatePerGroupData AggStatePerGroupData
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:383
@ AGG_HASHED
Definition: nodes.h:353
FmgrInfo * hashfunctions
Definition: nodeAgg.h:314
AttrNumber * hashGrpColIdxHash
Definition: nodeAgg.h:320
MemoryContext hash_metacxt
Definition: execnodes.h:2400
int numtrans
Definition: execnodes.h:2361
AggSplit aggsplit
Definition: execnodes.h:2363

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

Referenced by build_hash_tables().

◆ build_hash_tables()

static void build_hash_tables ( AggState aggstate)
static

Definition at line 1461 of file nodeAgg.c.

1462 {
1463  int setno;
1464 
1465  for (setno = 0; setno < aggstate->num_hashes; ++setno)
1466  {
1467  AggStatePerHash perhash = &aggstate->perhash[setno];
1468  long nbuckets;
1469  Size memory;
1470 
1471  if (perhash->hashtable != NULL)
1472  {
1473  ResetTupleHashTable(perhash->hashtable);
1474  continue;
1475  }
1476 
1477  Assert(perhash->aggnode->numGroups > 0);
1478 
1479  memory = aggstate->hash_mem_limit / aggstate->num_hashes;
1480 
1481  /* choose reasonable number of buckets per hashtable */
1482  nbuckets = hash_choose_num_buckets(aggstate->hashentrysize,
1483  perhash->aggnode->numGroups,
1484  memory);
1485 
1486  build_hash_table(aggstate, setno, nbuckets);
1487  }
1488 
1489  aggstate->hash_ngroups_current = 0;
1490 }
static long hash_choose_num_buckets(double hashentrysize, long ngroups, Size memory)
Definition: nodeAgg.c:1958
static void build_hash_table(AggState *aggstate, int setno, long nbuckets)
Definition: nodeAgg.c:1496
long numGroups
Definition: plannodes.h:1013

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

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

4033 {
4034  int numGroupingSets = Max(aggstate->maxsets, 1);
4035  Expr *transfnexpr;
4036  int numTransArgs;
4037  Expr *serialfnexpr = NULL;
4038  Expr *deserialfnexpr = NULL;
4039  ListCell *lc;
4040  int numInputs;
4041  int numDirectArgs;
4042  List *sortlist;
4043  int numSortCols;
4044  int numDistinctCols;
4045  int i;
4046 
4047  /* Begin filling in the pertrans data */
4048  pertrans->aggref = aggref;
4049  pertrans->aggshared = false;
4050  pertrans->aggCollation = aggref->inputcollid;
4051  pertrans->transfn_oid = transfn_oid;
4052  pertrans->serialfn_oid = aggserialfn;
4053  pertrans->deserialfn_oid = aggdeserialfn;
4054  pertrans->initValue = initValue;
4055  pertrans->initValueIsNull = initValueIsNull;
4056 
4057  /* Count the "direct" arguments, if any */
4058  numDirectArgs = list_length(aggref->aggdirectargs);
4059 
4060  /* Count the number of aggregated input columns */
4061  pertrans->numInputs = numInputs = list_length(aggref->args);
4062 
4063  pertrans->aggtranstype = aggtranstype;
4064 
4065  /* account for the current transition state */
4066  numTransArgs = pertrans->numTransInputs + 1;
4067 
4068  /*
4069  * Set up infrastructure for calling the transfn. Note that invtrans is
4070  * not needed here.
4071  */
4072  build_aggregate_transfn_expr(inputTypes,
4073  numArguments,
4074  numDirectArgs,
4075  aggref->aggvariadic,
4076  aggtranstype,
4077  aggref->inputcollid,
4078  transfn_oid,
4079  InvalidOid,
4080  &transfnexpr,
4081  NULL);
4082 
4083  fmgr_info(transfn_oid, &pertrans->transfn);
4084  fmgr_info_set_expr((Node *) transfnexpr, &pertrans->transfn);
4085 
4086  pertrans->transfn_fcinfo =
4089  &pertrans->transfn,
4090  numTransArgs,
4091  pertrans->aggCollation,
4092  (void *) aggstate, NULL);
4093 
4094  /* get info about the state value's datatype */
4095  get_typlenbyval(aggtranstype,
4096  &pertrans->transtypeLen,
4097  &pertrans->transtypeByVal);
4098 
4099  if (OidIsValid(aggserialfn))
4100  {
4101  build_aggregate_serialfn_expr(aggserialfn,
4102  &serialfnexpr);
4103  fmgr_info(aggserialfn, &pertrans->serialfn);
4104  fmgr_info_set_expr((Node *) serialfnexpr, &pertrans->serialfn);
4105 
4106  pertrans->serialfn_fcinfo =
4109  &pertrans->serialfn,
4110  1,
4111  InvalidOid,
4112  (void *) aggstate, NULL);
4113  }
4114 
4115  if (OidIsValid(aggdeserialfn))
4116  {
4117  build_aggregate_deserialfn_expr(aggdeserialfn,
4118  &deserialfnexpr);
4119  fmgr_info(aggdeserialfn, &pertrans->deserialfn);
4120  fmgr_info_set_expr((Node *) deserialfnexpr, &pertrans->deserialfn);
4121 
4122  pertrans->deserialfn_fcinfo =
4125  &pertrans->deserialfn,
4126  2,
4127  InvalidOid,
4128  (void *) aggstate, NULL);
4129  }
4130 
4131  /*
4132  * If we're doing either DISTINCT or ORDER BY for a plain agg, then we
4133  * have a list of SortGroupClause nodes; fish out the data in them and
4134  * stick them into arrays. We ignore ORDER BY for an ordered-set agg,
4135  * however; the agg's transfn and finalfn are responsible for that.
4136  *
4137  * When the planner has set the aggpresorted flag, the input to the
4138  * aggregate is already correctly sorted. For ORDER BY aggregates we can
4139  * simply treat these as normal aggregates. For presorted DISTINCT
4140  * aggregates an extra step must be added to remove duplicate consecutive
4141  * inputs.
4142  *
4143  * Note that by construction, if there is a DISTINCT clause then the ORDER
4144  * BY clause is a prefix of it (see transformDistinctClause).
4145  */
4146  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
4147  {
4148  sortlist = NIL;
4149  numSortCols = numDistinctCols = 0;
4150  pertrans->aggsortrequired = false;
4151  }
4152  else if (aggref->aggpresorted && aggref->aggdistinct == NIL)
4153  {
4154  sortlist = NIL;
4155  numSortCols = numDistinctCols = 0;
4156  pertrans->aggsortrequired = false;
4157  }
4158  else if (aggref->aggdistinct)
4159  {
4160  sortlist = aggref->aggdistinct;
4161  numSortCols = numDistinctCols = list_length(sortlist);
4162  Assert(numSortCols >= list_length(aggref->aggorder));
4163  pertrans->aggsortrequired = !aggref->aggpresorted;
4164  }
4165  else
4166  {
4167  sortlist = aggref->aggorder;
4168  numSortCols = list_length(sortlist);
4169  numDistinctCols = 0;
4170  pertrans->aggsortrequired = (numSortCols > 0);
4171  }
4172 
4173  pertrans->numSortCols = numSortCols;
4174  pertrans->numDistinctCols = numDistinctCols;
4175 
4176  /*
4177  * If we have either sorting or filtering to do, create a tupledesc and
4178  * slot corresponding to the aggregated inputs (including sort
4179  * expressions) of the agg.
4180  */
4181  if (numSortCols > 0 || aggref->aggfilter)
4182  {
4183  pertrans->sortdesc = ExecTypeFromTL(aggref->args);
4184  pertrans->sortslot =
4185  ExecInitExtraTupleSlot(estate, pertrans->sortdesc,
4187  }
4188 
4189  if (numSortCols > 0)
4190  {
4191  /*
4192  * We don't implement DISTINCT or ORDER BY aggs in the HASHED case
4193  * (yet)
4194  */
4195  Assert(aggstate->aggstrategy != AGG_HASHED && aggstate->aggstrategy != AGG_MIXED);
4196 
4197  /* ORDER BY aggregates are not supported with partial aggregation */
4198  Assert(!DO_AGGSPLIT_COMBINE(aggstate->aggsplit));
4199 
4200  /* If we have only one input, we need its len/byval info. */
4201  if (numInputs == 1)
4202  {
4203  get_typlenbyval(inputTypes[numDirectArgs],
4204  &pertrans->inputtypeLen,
4205  &pertrans->inputtypeByVal);
4206  }
4207  else if (numDistinctCols > 0)
4208  {
4209  /* we will need an extra slot to store prior values */
4210  pertrans->uniqslot =
4211  ExecInitExtraTupleSlot(estate, pertrans->sortdesc,
4213  }
4214 
4215  /* Extract the sort information for use later */
4216  pertrans->sortColIdx =
4217  (AttrNumber *) palloc(numSortCols * sizeof(AttrNumber));
4218  pertrans->sortOperators =
4219  (Oid *) palloc(numSortCols * sizeof(Oid));
4220  pertrans->sortCollations =
4221  (Oid *) palloc(numSortCols * sizeof(Oid));
4222  pertrans->sortNullsFirst =
4223  (bool *) palloc(numSortCols * sizeof(bool));
4224 
4225  i = 0;
4226  foreach(lc, sortlist)
4227  {
4228  SortGroupClause *sortcl = (SortGroupClause *) lfirst(lc);
4229  TargetEntry *tle = get_sortgroupclause_tle(sortcl, aggref->args);
4230 
4231  /* the parser should have made sure of this */
4232  Assert(OidIsValid(sortcl->sortop));
4233 
4234  pertrans->sortColIdx[i] = tle->resno;
4235  pertrans->sortOperators[i] = sortcl->sortop;
4236  pertrans->sortCollations[i] = exprCollation((Node *) tle->expr);
4237  pertrans->sortNullsFirst[i] = sortcl->nulls_first;
4238  i++;
4239  }
4240  Assert(i == numSortCols);
4241  }
4242 
4243  if (aggref->aggdistinct)
4244  {
4245  Oid *ops;
4246 
4247  Assert(numArguments > 0);
4248  Assert(list_length(aggref->aggdistinct) == numDistinctCols);
4249 
4250  ops = palloc(numDistinctCols * sizeof(Oid));
4251 
4252  i = 0;
4253  foreach(lc, aggref->aggdistinct)
4254  ops[i++] = ((SortGroupClause *) lfirst(lc))->eqop;
4255 
4256  /* lookup / build the necessary comparators */
4257  if (numDistinctCols == 1)
4258  fmgr_info(get_opcode(ops[0]), &pertrans->equalfnOne);
4259  else
4260  pertrans->equalfnMulti =
4261  execTuplesMatchPrepare(pertrans->sortdesc,
4262  numDistinctCols,
4263  pertrans->sortColIdx,
4264  ops,
4265  pertrans->sortCollations,
4266  &aggstate->ss.ps);
4267  pfree(ops);
4268  }
4269 
4270  pertrans->sortstates = (Tuplesortstate **)
4271  palloc0(sizeof(Tuplesortstate *) * numGroupingSets);
4272 }
int16 AttrNumber
Definition: attnum.h:21
#define OidIsValid(objectId)
Definition: c.h:711
ExprState * execTuplesMatchPrepare(TupleDesc desc, int numCols, const AttrNumber *keyColIdx, const Oid *eqOperators, const Oid *collations, PlanState *parent)
Definition: execGrouping.c:59
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1831
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleDesc ExecTypeFromTL(List *targetList)
Definition: execTuples.c:1938
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#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:677
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2209
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1267
void * palloc0(Size size)
Definition: mcxt.c:1230
void * palloc(Size size)
Definition: mcxt.c:1199
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:764
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:382
void build_aggregate_deserialfn_expr(Oid deserialfn_oid, Expr **deserialfnexpr)
Definition: parse_agg.c:2060
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:1976
void build_aggregate_serialfn_expr(Oid serialfn_oid, Expr **serialfnexpr)
Definition: parse_agg.c:2037
#define lfirst(lc)
Definition: pg_list.h:170
static int list_length(const List *l)
Definition: pg_list.h:150
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
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:2388
List * aggdistinct
Definition: primnodes.h:403
List * aggdirectargs
Definition: primnodes.h:394
bool aggvariadic
Definition: primnodes.h:415
char aggkind
Definition: primnodes.h:418
List * args
Definition: primnodes.h:397
Expr * aggfilter
Definition: primnodes.h:406
Oid inputcollid
Definition: primnodes.h:382
List * aggorder
Definition: primnodes.h:400
Definition: pg_list.h:52
Definition: nodes.h:118
Expr * expr
Definition: primnodes.h:1555
AttrNumber resno
Definition: primnodes.h:1556
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::aggkind, Aggref::aggorder, AggStatePerTransData::aggref, AggStatePerTransData::aggshared, AggStatePerTransData::aggsortrequired, AggState::aggsplit, AggState::aggstrategy, AggStatePerTransData::aggtranstype, Aggref::aggvariadic, 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, Aggref::inputcollid, 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 2150 of file nodeAgg.c.

2151 {
2152  AggState *node = castNode(AggState, pstate);
2153  TupleTableSlot *result = NULL;
2154 
2156 
2157  if (!node->agg_done)
2158  {
2159  /* Dispatch based on strategy */
2160  switch (node->phase->aggstrategy)
2161  {
2162  case AGG_HASHED:
2163  if (!node->table_filled)
2164  agg_fill_hash_table(node);
2165  /* FALLTHROUGH */
2166  case AGG_MIXED:
2167  result = agg_retrieve_hash_table(node);
2168  break;
2169  case AGG_PLAIN:
2170  case AGG_SORTED:
2171  result = agg_retrieve_direct(node);
2172  break;
2173  }
2174 
2175  if (!TupIsNull(result))
2176  return result;
2177  }
2178 
2179  return NULL;
2180 }
static void agg_fill_hash_table(AggState *aggstate)
Definition: nodeAgg.c:2532
static TupleTableSlot * agg_retrieve_direct(AggState *aggstate)
Definition: nodeAgg.c:2186
@ AGG_SORTED
Definition: nodes.h:352
#define castNode(_type_, nodeptr)
Definition: nodes.h:186

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

4682 {
4683  Size size;
4684 
4685  /* don't need this if not instrumenting or no workers */
4686  if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4687  return;
4688 
4689  size = mul_size(pcxt->nworkers, sizeof(AggregateInstrumentation));
4690  size = add_size(size, offsetof(SharedAggInfo, sinstrument));
4691  shm_toc_estimate_chunk(&pcxt->estimator, size);
4692  shm_toc_estimate_keys(&pcxt->estimator, 1);
4693 }
#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:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
shm_toc_estimator estimator
Definition: parallel.h:42
Instrumentation * instrument
Definition: execnodes.h:1039

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

4703 {
4704  Size size;
4705 
4706  /* don't need this if not instrumenting or no workers */
4707  if (!node->ss.ps.instrument || pcxt->nworkers == 0)
4708  return;
4709 
4710  size = offsetof(SharedAggInfo, sinstrument)
4711  + pcxt->nworkers * sizeof(AggregateInstrumentation);
4712  node->shared_info = shm_toc_allocate(pcxt->toc, size);
4713  /* ensure any unfilled slots will contain zeroes */
4714  memset(node->shared_info, 0, size);
4715  node->shared_info->num_workers = pcxt->nworkers;
4716  shm_toc_insert(pcxt->toc, node->ss.ps.plan->plan_node_id,
4717  node->shared_info);
4718 }
struct AggregateInstrumentation AggregateInstrumentation
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
SharedAggInfo * shared_info
Definition: execnodes.h:2430
shm_toc * toc
Definition: parallel.h:45
Plan * plan
Definition: execnodes.h:1029
int plan_node_id
Definition: plannodes.h:152

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

4728 {
4729  node->shared_info =
4730  shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
4731 }
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 4740 of file nodeAgg.c.

4741 {
4742  Size size;
4743  SharedAggInfo *si;
4744 
4745  if (node->shared_info == NULL)
4746  return;
4747 
4748  size = offsetof(SharedAggInfo, sinstrument)
4750  si = palloc(size);
4751  memcpy(si, node->shared_info, size);
4752  node->shared_info = si;
4753 }

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

Referenced by ExecParallelRetrieveInstrumentation().

◆ ExecEndAgg()

void ExecEndAgg ( AggState node)

Definition at line 4292 of file nodeAgg.c.

4293 {
4295  int transno;
4296  int numGroupingSets = Max(node->maxsets, 1);
4297  int setno;
4298 
4299  /*
4300  * When ending a parallel worker, copy the statistics gathered by the
4301  * worker back into shared memory so that it can be picked up by the main
4302  * process to report in EXPLAIN ANALYZE.
4303  */
4304  if (node->shared_info && IsParallelWorker())
4305  {
4307 
4308  Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
4311  si->hash_disk_used = node->hash_disk_used;
4312  si->hash_mem_peak = node->hash_mem_peak;
4313  }
4314 
4315  /* Make sure we have closed any open tuplesorts */
4316 
4317  if (node->sort_in)
4318  tuplesort_end(node->sort_in);
4319  if (node->sort_out)
4320  tuplesort_end(node->sort_out);
4321 
4323 
4324  if (node->hash_metacxt != NULL)
4325  {
4327  node->hash_metacxt = NULL;
4328  }
4329 
4330  for (transno = 0; transno < node->numtrans; transno++)
4331  {
4332  AggStatePerTrans pertrans = &node->pertrans[transno];
4333 
4334  for (setno = 0; setno < numGroupingSets; setno++)
4335  {
4336  if (pertrans->sortstates[setno])
4337  tuplesort_end(pertrans->sortstates[setno]);
4338  }
4339  }
4340 
4341  /* And ensure any agg shutdown callbacks have been called */
4342  for (setno = 0; setno < numGroupingSets; setno++)
4343  ReScanExprContext(node->aggcontexts[setno]);
4344  if (node->hashcontext)
4346 
4347  /*
4348  * We don't actually free any ExprContexts here (see comment in
4349  * ExecFreeExprContext), just unlinking the output one from the plan node
4350  * suffices.
4351  */
4352  ExecFreeExprContext(&node->ss.ps);
4353 
4354  /* clean up tuple table */
4356 
4357  outerPlan = outerPlanState(node);
4359 }
int ParallelWorkerNumber
Definition: parallel.c:113
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:557
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:652
#define outerPlanState(node)
Definition: execnodes.h:1125
#define IsParallelWorker()
Definition: parallel.h:61
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
static void hashagg_reset_spill_state(AggState *aggstate)
Definition: nodeAgg.c:3125
#define outerPlan(node)
Definition: plannodes.h:183
Tuplesortstate * sort_out
Definition: execnodes.h:2391
uint64 hash_disk_used
Definition: execnodes.h:2418
Size hash_mem_peak
Definition: execnodes.h:2415
int hash_batches_used
Definition: execnodes.h:2419
Tuplesortstate * sort_in
Definition: execnodes.h:2390
AggregateInstrumentation sinstrument[FLEXIBLE_ARRAY_MEMBER]
Definition: execnodes.h:2334
void tuplesort_end(Tuplesortstate *state)
Definition: tuplesort.c:972

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

Referenced by ExecEndNode().

◆ ExecInitAgg()

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

Definition at line 3165 of file nodeAgg.c.

3166 {
3167  AggState *aggstate;
3168  AggStatePerAgg peraggs;
3169  AggStatePerTrans pertransstates;
3170  AggStatePerGroup *pergroups;
3171  Plan *outerPlan;
3172  ExprContext *econtext;
3173  TupleDesc scanDesc;
3174  int max_aggno;
3175  int max_transno;
3176  int numaggrefs;
3177  int numaggs;
3178  int numtrans;
3179  int phase;
3180  int phaseidx;
3181  ListCell *l;
3182  Bitmapset *all_grouped_cols = NULL;
3183  int numGroupingSets = 1;
3184  int numPhases;
3185  int numHashes;
3186  int i = 0;
3187  int j = 0;
3188  bool use_hashing = (node->aggstrategy == AGG_HASHED ||
3189  node->aggstrategy == AGG_MIXED);
3190 
3191  /* check for unsupported flags */
3192  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
3193 
3194  /*
3195  * create state structure
3196  */
3197  aggstate = makeNode(AggState);
3198  aggstate->ss.ps.plan = (Plan *) node;
3199  aggstate->ss.ps.state = estate;
3200  aggstate->ss.ps.ExecProcNode = ExecAgg;
3201 
3202  aggstate->aggs = NIL;
3203  aggstate->numaggs = 0;
3204  aggstate->numtrans = 0;
3205  aggstate->aggstrategy = node->aggstrategy;
3206  aggstate->aggsplit = node->aggsplit;
3207  aggstate->maxsets = 0;
3208  aggstate->projected_set = -1;
3209  aggstate->current_set = 0;
3210  aggstate->peragg = NULL;
3211  aggstate->pertrans = NULL;
3212  aggstate->curperagg = NULL;
3213  aggstate->curpertrans = NULL;
3214  aggstate->input_done = false;
3215  aggstate->agg_done = false;
3216  aggstate->pergroups = NULL;
3217  aggstate->grp_firstTuple = NULL;
3218  aggstate->sort_in = NULL;
3219  aggstate->sort_out = NULL;
3220 
3221  /*
3222  * phases[0] always exists, but is dummy in sorted/plain mode
3223  */
3224  numPhases = (use_hashing ? 1 : 2);
3225  numHashes = (use_hashing ? 1 : 0);
3226 
3227  /*
3228  * Calculate the maximum number of grouping sets in any phase; this
3229  * determines the size of some allocations. Also calculate the number of
3230  * phases, since all hashed/mixed nodes contribute to only a single phase.
3231  */
3232  if (node->groupingSets)
3233  {
3234  numGroupingSets = list_length(node->groupingSets);
3235 
3236  foreach(l, node->chain)
3237  {
3238  Agg *agg = lfirst(l);
3239 
3240  numGroupingSets = Max(numGroupingSets,
3241  list_length(agg->groupingSets));
3242 
3243  /*
3244  * additional AGG_HASHED aggs become part of phase 0, but all
3245  * others add an extra phase.
3246  */
3247  if (agg->aggstrategy != AGG_HASHED)
3248  ++numPhases;
3249  else
3250  ++numHashes;
3251  }
3252  }
3253 
3254  aggstate->maxsets = numGroupingSets;
3255  aggstate->numphases = numPhases;
3256 
3257  aggstate->aggcontexts = (ExprContext **)
3258  palloc0(sizeof(ExprContext *) * numGroupingSets);
3259 
3260  /*
3261  * Create expression contexts. We need three or more, one for
3262  * per-input-tuple processing, one for per-output-tuple processing, one
3263  * for all the hashtables, and one for each grouping set. The per-tuple
3264  * memory context of the per-grouping-set ExprContexts (aggcontexts)
3265  * replaces the standalone memory context formerly used to hold transition
3266  * values. We cheat a little by using ExecAssignExprContext() to build
3267  * all of them.
3268  *
3269  * NOTE: the details of what is stored in aggcontexts and what is stored
3270  * in the regular per-query memory context are driven by a simple
3271  * decision: we want to reset the aggcontext at group boundaries (if not
3272  * hashing) and in ExecReScanAgg to recover no-longer-wanted space.
3273  */
3274  ExecAssignExprContext(estate, &aggstate->ss.ps);
3275  aggstate->tmpcontext = aggstate->ss.ps.ps_ExprContext;
3276 
3277  for (i = 0; i < numGroupingSets; ++i)
3278  {
3279  ExecAssignExprContext(estate, &aggstate->ss.ps);
3280  aggstate->aggcontexts[i] = aggstate->ss.ps.ps_ExprContext;
3281  }
3282 
3283  if (use_hashing)
3284  aggstate->hashcontext = CreateWorkExprContext(estate);
3285 
3286  ExecAssignExprContext(estate, &aggstate->ss.ps);
3287 
3288  /*
3289  * Initialize child nodes.
3290  *
3291  * If we are doing a hashed aggregation then the child plan does not need
3292  * to handle REWIND efficiently; see ExecReScanAgg.
3293  */
3294  if (node->aggstrategy == AGG_HASHED)
3295  eflags &= ~EXEC_FLAG_REWIND;
3296  outerPlan = outerPlan(node);
3297  outerPlanState(aggstate) = ExecInitNode(outerPlan, estate, eflags);
3298 
3299  /*
3300  * initialize source tuple type.
3301  */
3302  aggstate->ss.ps.outerops =
3304  &aggstate->ss.ps.outeropsfixed);
3305  aggstate->ss.ps.outeropsset = true;
3306 
3307  ExecCreateScanSlotFromOuterPlan(estate, &aggstate->ss,
3308  aggstate->ss.ps.outerops);
3309  scanDesc = aggstate->ss.ss_ScanTupleSlot->tts_tupleDescriptor;
3310 
3311  /*
3312  * If there are more than two phases (including a potential dummy phase
3313  * 0), input will be resorted using tuplesort. Need a slot for that.
3314  */
3315  if (numPhases > 2)
3316  {
3317  aggstate->sort_slot = ExecInitExtraTupleSlot(estate, scanDesc,
3319 
3320  /*
3321  * The output of the tuplesort, and the output from the outer child
3322  * might not use the same type of slot. In most cases the child will
3323  * be a Sort, and thus return a TTSOpsMinimalTuple type slot - but the
3324  * input can also be presorted due an index, in which case it could be
3325  * a different type of slot.
3326  *
3327  * XXX: For efficiency it would be good to instead/additionally
3328  * generate expressions with corresponding settings of outerops* for
3329  * the individual phases - deforming is often a bottleneck for
3330  * aggregations with lots of rows per group. If there's multiple
3331  * sorts, we know that all but the first use TTSOpsMinimalTuple (via
3332  * the nodeAgg.c internal tuplesort).
3333  */
3334  if (aggstate->ss.ps.outeropsfixed &&
3335  aggstate->ss.ps.outerops != &TTSOpsMinimalTuple)
3336  aggstate->ss.ps.outeropsfixed = false;
3337  }
3338 
3339  /*
3340  * Initialize result type, slot and projection.
3341  */
3343  ExecAssignProjectionInfo(&aggstate->ss.ps, NULL);
3344 
3345  /*
3346  * initialize child expressions
3347  *
3348  * We expect the parser to have checked that no aggs contain other agg
3349  * calls in their arguments (and just to be sure, we verify it again while
3350  * initializing the plan node). This would make no sense under SQL
3351  * semantics, and it's forbidden by the spec. Because it is true, we
3352  * don't need to worry about evaluating the aggs in any particular order.
3353  *
3354  * Note: execExpr.c finds Aggrefs for us, and adds them to aggstate->aggs.
3355  * Aggrefs in the qual are found here; Aggrefs in the targetlist are found
3356  * during ExecAssignProjectionInfo, above.
3357  */
3358  aggstate->ss.ps.qual =
3359  ExecInitQual(node->plan.qual, (PlanState *) aggstate);
3360 
3361  /*
3362  * We should now have found all Aggrefs in the targetlist and quals.
3363  */
3364  numaggrefs = list_length(aggstate->aggs);
3365  max_aggno = -1;
3366  max_transno = -1;
3367  foreach(l, aggstate->aggs)
3368  {
3369  Aggref *aggref = (Aggref *) lfirst(l);
3370 
3371  max_aggno = Max(max_aggno, aggref->aggno);
3372  max_transno = Max(max_transno, aggref->aggtransno);
3373  }
3374  numaggs = max_aggno + 1;
3375  numtrans = max_transno + 1;
3376 
3377  /*
3378  * For each phase, prepare grouping set data and fmgr lookup data for
3379  * compare functions. Accumulate all_grouped_cols in passing.
3380  */
3381  aggstate->phases = palloc0(numPhases * sizeof(AggStatePerPhaseData));
3382 
3383  aggstate->num_hashes = numHashes;
3384  if (numHashes)
3385  {
3386  aggstate->perhash = palloc0(sizeof(AggStatePerHashData) * numHashes);
3387  aggstate->phases[0].numsets = 0;
3388  aggstate->phases[0].gset_lengths = palloc(numHashes * sizeof(int));
3389  aggstate->phases[0].grouped_cols = palloc(numHashes * sizeof(Bitmapset *));
3390  }
3391 
3392  phase = 0;
3393  for (phaseidx = 0; phaseidx <= list_length(node->chain); ++phaseidx)
3394  {
3395  Agg *aggnode;
3396  Sort *sortnode;
3397 
3398  if (phaseidx > 0)
3399  {
3400  aggnode = list_nth_node(Agg, node->chain, phaseidx - 1);
3401  sortnode = castNode(Sort, outerPlan(aggnode));
3402  }
3403  else
3404  {
3405  aggnode = node;
3406  sortnode = NULL;
3407  }
3408 
3409  Assert(phase <= 1 || sortnode);
3410 
3411  if (aggnode->aggstrategy == AGG_HASHED
3412  || aggnode->aggstrategy == AGG_MIXED)
3413  {
3414  AggStatePerPhase phasedata = &aggstate->phases[0];
3415  AggStatePerHash perhash;
3416  Bitmapset *cols = NULL;
3417 
3418  Assert(phase == 0);
3419  i = phasedata->numsets++;
3420  perhash = &aggstate->perhash[i];
3421 
3422  /* phase 0 always points to the "real" Agg in the hash case */
3423  phasedata->aggnode = node;
3424  phasedata->aggstrategy = node->aggstrategy;
3425 
3426  /* but the actual Agg node representing this hash is saved here */
3427  perhash->aggnode = aggnode;
3428 
3429  phasedata->gset_lengths[i] = perhash->numCols = aggnode->numCols;
3430 
3431  for (j = 0; j < aggnode->numCols; ++j)
3432  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3433 
3434  phasedata->grouped_cols[i] = cols;
3435 
3436  all_grouped_cols = bms_add_members(all_grouped_cols, cols);
3437  continue;
3438  }
3439  else
3440  {
3441  AggStatePerPhase phasedata = &aggstate->phases[++phase];
3442  int num_sets;
3443 
3444  phasedata->numsets = num_sets = list_length(aggnode->groupingSets);
3445 
3446  if (num_sets)
3447  {
3448  phasedata->gset_lengths = palloc(num_sets * sizeof(int));
3449  phasedata->grouped_cols = palloc(num_sets * sizeof(Bitmapset *));
3450 
3451  i = 0;
3452  foreach(l, aggnode->groupingSets)
3453  {
3454  int current_length = list_length(lfirst(l));
3455  Bitmapset *cols = NULL;
3456 
3457  /* planner forces this to be correct */
3458  for (j = 0; j < current_length; ++j)
3459  cols = bms_add_member(cols, aggnode->grpColIdx[j]);
3460 
3461  phasedata->grouped_cols[i] = cols;
3462  phasedata->gset_lengths[i] = current_length;
3463 
3464  ++i;
3465  }
3466 
3467  all_grouped_cols = bms_add_members(all_grouped_cols,
3468  phasedata->grouped_cols[0]);
3469  }
3470  else
3471  {
3472  Assert(phaseidx == 0);
3473 
3474  phasedata->gset_lengths = NULL;
3475  phasedata->grouped_cols = NULL;
3476  }
3477 
3478  /*
3479  * If we are grouping, precompute fmgr lookup data for inner loop.
3480  */
3481  if (aggnode->aggstrategy == AGG_SORTED)
3482  {
3483  Assert(aggnode->numCols > 0);
3484 
3485  /*
3486  * Build a separate function for each subset of columns that
3487  * need to be compared.
3488  */
3489  phasedata->eqfunctions =
3490  (ExprState **) palloc0(aggnode->numCols * sizeof(ExprState *));
3491 
3492  /* for each grouping set */
3493  for (int k = 0; k < phasedata->numsets; k++)
3494  {
3495  int length = phasedata->gset_lengths[k];
3496 
3497  if (phasedata->eqfunctions[length - 1] != NULL)
3498  continue;
3499 
3500  phasedata->eqfunctions[length - 1] =
3501  execTuplesMatchPrepare(scanDesc,
3502  length,
3503  aggnode->grpColIdx,
3504  aggnode->grpOperators,
3505  aggnode->grpCollations,
3506  (PlanState *) aggstate);
3507  }
3508 
3509  /* and for all grouped columns, unless already computed */
3510  if (phasedata->eqfunctions[aggnode->numCols - 1] == NULL)
3511  {
3512  phasedata->eqfunctions[aggnode->numCols - 1] =
3513  execTuplesMatchPrepare(scanDesc,
3514  aggnode->numCols,
3515  aggnode->grpColIdx,
3516  aggnode->grpOperators,
3517  aggnode->grpCollations,
3518  (PlanState *) aggstate);
3519  }
3520  }
3521 
3522  phasedata->aggnode = aggnode;
3523  phasedata->aggstrategy = aggnode->aggstrategy;
3524  phasedata->sortnode = sortnode;
3525  }
3526  }
3527 
3528  /*
3529  * Convert all_grouped_cols to a descending-order list.
3530  */
3531  i = -1;
3532  while ((i = bms_next_member(all_grouped_cols, i)) >= 0)
3533  aggstate->all_grouped_cols = lcons_int(i, aggstate->all_grouped_cols);
3534 
3535  /*
3536  * Set up aggregate-result storage in the output expr context, and also
3537  * allocate my private per-agg working storage
3538  */
3539  econtext = aggstate->ss.ps.ps_ExprContext;
3540  econtext->ecxt_aggvalues = (Datum *) palloc0(sizeof(Datum) * numaggs);
3541  econtext->ecxt_aggnulls = (bool *) palloc0(sizeof(bool) * numaggs);
3542 
3543  peraggs = (AggStatePerAgg) palloc0(sizeof(AggStatePerAggData) * numaggs);
3544  pertransstates = (AggStatePerTrans) palloc0(sizeof(AggStatePerTransData) * numtrans);
3545 
3546  aggstate->peragg = peraggs;
3547  aggstate->pertrans = pertransstates;
3548 
3549 
3550  aggstate->all_pergroups =
3552  * (numGroupingSets + numHashes));
3553  pergroups = aggstate->all_pergroups;
3554 
3555  if (node->aggstrategy != AGG_HASHED)
3556  {
3557  for (i = 0; i < numGroupingSets; i++)
3558  {
3559  pergroups[i] = (AggStatePerGroup) palloc0(sizeof(AggStatePerGroupData)
3560  * numaggs);
3561  }
3562 
3563  aggstate->pergroups = pergroups;
3564  pergroups += numGroupingSets;
3565  }
3566 
3567  /*
3568  * Hashing can only appear in the initial phase.
3569  */
3570  if (use_hashing)
3571  {
3572  Plan *outerplan = outerPlan(node);
3573  uint64 totalGroups = 0;
3574 
3575  aggstate->hash_metacxt = AllocSetContextCreate(aggstate->ss.ps.state->es_query_cxt,
3576  "HashAgg meta context",
3578  aggstate->hash_spill_rslot = ExecInitExtraTupleSlot(estate, scanDesc,
3580  aggstate->hash_spill_wslot = ExecInitExtraTupleSlot(estate, scanDesc,
3581  &TTSOpsVirtual);
3582 
3583  /* this is an array of pointers, not structures */
3584  aggstate->hash_pergroup = pergroups;
3585 
3586  aggstate->hashentrysize = hash_agg_entry_size(aggstate->numtrans,
3587  outerplan->plan_width,
3588  node->transitionSpace);
3589 
3590  /*
3591  * Consider all of the grouping sets together when setting the limits
3592  * and estimating the number of partitions. This can be inaccurate
3593  * when there is more than one grouping set, but should still be
3594  * reasonable.
3595  */
3596  for (int k = 0; k < aggstate->num_hashes; k++)
3597  totalGroups += aggstate->perhash[k].aggnode->numGroups;
3598 
3599  hash_agg_set_limits(aggstate->hashentrysize, totalGroups, 0,
3600  &aggstate->hash_mem_limit,
3601  &aggstate->hash_ngroups_limit,
3602  &aggstate->hash_planned_partitions);
3603  find_hash_columns(aggstate);
3604 
3605  /* Skip massive memory allocation if we are just doing EXPLAIN */
3606  if (!(eflags & EXEC_FLAG_EXPLAIN_ONLY))
3607  build_hash_tables(aggstate);
3608 
3609  aggstate->table_filled = false;
3610 
3611  /* Initialize this to 1, meaning nothing spilled, yet */
3612  aggstate->hash_batches_used = 1;
3613  }
3614 
3615  /*
3616  * Initialize current phase-dependent values to initial phase. The initial
3617  * phase is 1 (first sort pass) for all strategies that use sorting (if
3618  * hashing is being done too, then phase 0 is processed last); but if only
3619  * hashing is being done, then phase 0 is all there is.
3620  */
3621  if (node->aggstrategy == AGG_HASHED)
3622  {
3623  aggstate->current_phase = 0;
3624  initialize_phase(aggstate, 0);
3625  select_current_set(aggstate, 0, true);
3626  }
3627  else
3628  {
3629  aggstate->current_phase = 1;
3630  initialize_phase(aggstate, 1);
3631  select_current_set(aggstate, 0, false);
3632  }
3633 
3634  /*
3635  * Perform lookups of aggregate function info, and initialize the
3636  * unchanging fields of the per-agg and per-trans data.
3637  */
3638  foreach(l, aggstate->aggs)
3639  {
3640  Aggref *aggref = lfirst(l);
3641  AggStatePerAgg peragg;
3642  AggStatePerTrans pertrans;
3643  Oid aggTransFnInputTypes[FUNC_MAX_ARGS];
3644  int numAggTransFnArgs;
3645  int numDirectArgs;
3646  HeapTuple aggTuple;
3647  Form_pg_aggregate aggform;
3648  AclResult aclresult;
3649  Oid finalfn_oid;
3650  Oid serialfn_oid,
3651  deserialfn_oid;
3652  Oid aggOwner;
3653  Expr *finalfnexpr;
3654  Oid aggtranstype;
3655 
3656  /* Planner should have assigned aggregate to correct level */
3657  Assert(aggref->agglevelsup == 0);
3658  /* ... and the split mode should match */
3659  Assert(aggref->aggsplit == aggstate->aggsplit);
3660 
3661  peragg = &peraggs[aggref->aggno];
3662 
3663  /* Check if we initialized the state for this aggregate already. */
3664  if (peragg->aggref != NULL)
3665  continue;
3666 
3667  peragg->aggref = aggref;
3668  peragg->transno = aggref->aggtransno;
3669 
3670  /* Fetch the pg_aggregate row */
3671  aggTuple = SearchSysCache1(AGGFNOID,
3672  ObjectIdGetDatum(aggref->aggfnoid));
3673  if (!HeapTupleIsValid(aggTuple))
3674  elog(ERROR, "cache lookup failed for aggregate %u",
3675  aggref->aggfnoid);
3676  aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
3677 
3678  /* Check permission to call aggregate function */
3679  aclresult = object_aclcheck(ProcedureRelationId, aggref->aggfnoid, GetUserId(),
3680  ACL_EXECUTE);
3681  if (aclresult != ACLCHECK_OK)
3682  aclcheck_error(aclresult, OBJECT_AGGREGATE,
3683  get_func_name(aggref->aggfnoid));
3685 
3686  /* planner recorded transition state type in the Aggref itself */
3687  aggtranstype = aggref->aggtranstype;
3688  Assert(OidIsValid(aggtranstype));
3689 
3690  /* Final function only required if we're finalizing the aggregates */
3691  if (DO_AGGSPLIT_SKIPFINAL(aggstate->aggsplit))
3692  peragg->finalfn_oid = finalfn_oid = InvalidOid;
3693  else
3694  peragg->finalfn_oid = finalfn_oid = aggform->aggfinalfn;
3695 
3696  serialfn_oid = InvalidOid;
3697  deserialfn_oid = InvalidOid;
3698 
3699  /*
3700  * Check if serialization/deserialization is required. We only do it
3701  * for aggregates that have transtype INTERNAL.
3702  */
3703  if (aggtranstype == INTERNALOID)
3704  {
3705  /*
3706  * The planner should only have generated a serialize agg node if
3707  * every aggregate with an INTERNAL state has a serialization
3708  * function. Verify that.
3709  */
3710  if (DO_AGGSPLIT_SERIALIZE(aggstate->aggsplit))
3711  {
3712  /* serialization only valid when not running finalfn */
3714 
3715  if (!OidIsValid(aggform->aggserialfn))
3716  elog(ERROR, "serialfunc not provided for serialization aggregation");
3717  serialfn_oid = aggform->aggserialfn;
3718  }
3719 
3720  /* Likewise for deserialization functions */
3721  if (DO_AGGSPLIT_DESERIALIZE(aggstate->aggsplit))
3722  {
3723  /* deserialization only valid when combining states */
3724  Assert(DO_AGGSPLIT_COMBINE(aggstate->aggsplit));
3725 
3726  if (!OidIsValid(aggform->aggdeserialfn))
3727  elog(ERROR, "deserialfunc not provided for deserialization aggregation");
3728  deserialfn_oid = aggform->aggdeserialfn;
3729  }
3730  }
3731 
3732  /* Check that aggregate owner has permission to call component fns */
3733  {
3734  HeapTuple procTuple;
3735 
3736  procTuple = SearchSysCache1(PROCOID,
3737  ObjectIdGetDatum(aggref->aggfnoid));
3738  if (!HeapTupleIsValid(procTuple))
3739  elog(ERROR, "cache lookup failed for function %u",
3740  aggref->aggfnoid);
3741  aggOwner = ((Form_pg_proc) GETSTRUCT(procTuple))->proowner;
3742  ReleaseSysCache(procTuple);
3743 
3744  if (OidIsValid(finalfn_oid))
3745  {
3746  aclresult = object_aclcheck(ProcedureRelationId, finalfn_oid, aggOwner,
3747  ACL_EXECUTE);
3748  if (aclresult != ACLCHECK_OK)
3749  aclcheck_error(aclresult, OBJECT_FUNCTION,
3750  get_func_name(finalfn_oid));
3751  InvokeFunctionExecuteHook(finalfn_oid);
3752  }
3753  if (OidIsValid(serialfn_oid))
3754  {
3755  aclresult = object_aclcheck(ProcedureRelationId, serialfn_oid, aggOwner,
3756  ACL_EXECUTE);
3757  if (aclresult != ACLCHECK_OK)
3758  aclcheck_error(aclresult, OBJECT_FUNCTION,
3759  get_func_name(serialfn_oid));
3760  InvokeFunctionExecuteHook(serialfn_oid);
3761  }
3762  if (OidIsValid(deserialfn_oid))
3763  {
3764  aclresult = object_aclcheck(ProcedureRelationId, deserialfn_oid, aggOwner,
3765  ACL_EXECUTE);
3766  if (aclresult != ACLCHECK_OK)
3767  aclcheck_error(aclresult, OBJECT_FUNCTION,
3768  get_func_name(deserialfn_oid));
3769  InvokeFunctionExecuteHook(deserialfn_oid);
3770  }
3771  }
3772 
3773  /*
3774  * Get actual datatypes of the (nominal) aggregate inputs. These
3775  * could be different from the agg's declared input types, when the
3776  * agg accepts ANY or a polymorphic type.
3777  */
3778  numAggTransFnArgs = get_aggregate_argtypes(aggref,
3779  aggTransFnInputTypes);
3780 
3781  /* Count the "direct" arguments, if any */
3782  numDirectArgs = list_length(aggref->aggdirectargs);
3783 
3784  /* Detect how many arguments to pass to the finalfn */
3785  if (aggform->aggfinalextra)
3786  peragg->numFinalArgs = numAggTransFnArgs + 1;
3787  else
3788  peragg->numFinalArgs = numDirectArgs + 1;
3789 
3790  /* Initialize any direct-argument expressions */
3791  peragg->aggdirectargs = ExecInitExprList(aggref->aggdirectargs,
3792  (PlanState *) aggstate);
3793 
3794  /*
3795  * build expression trees using actual argument & result types for the
3796  * finalfn, if it exists and is required.
3797  */
3798  if (OidIsValid(finalfn_oid))
3799  {
3800  build_aggregate_finalfn_expr(aggTransFnInputTypes,
3801  peragg->numFinalArgs,
3802  aggtranstype,
3803  aggref->aggtype,
3804  aggref->inputcollid,
3805  finalfn_oid,
3806  &finalfnexpr);
3807  fmgr_info(finalfn_oid, &peragg->finalfn);
3808  fmgr_info_set_expr((Node *) finalfnexpr, &peragg->finalfn);
3809  }
3810 
3811  /* get info about the output value's datatype */
3812  get_typlenbyval(aggref->aggtype,
3813  &peragg->resulttypeLen,
3814  &peragg->resulttypeByVal);
3815 
3816  /*
3817  * Build working state for invoking the transition function, if we
3818  * haven't done it already.
3819  */
3820  pertrans = &pertransstates[aggref->aggtransno];
3821  if (pertrans->aggref == NULL)
3822  {
3823  Datum textInitVal;
3824  Datum initValue;
3825  bool initValueIsNull;
3826  Oid transfn_oid;
3827 
3828  /*
3829  * If this aggregation is performing state combines, then instead
3830  * of using the transition function, we'll use the combine
3831  * function.
3832  */
3833  if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3834  {
3835  transfn_oid = aggform->aggcombinefn;
3836 
3837  /* If not set then the planner messed up */
3838  if (!OidIsValid(transfn_oid))
3839  elog(ERROR, "combinefn not set for aggregate function");
3840  }
3841  else
3842  transfn_oid = aggform->aggtransfn;
3843 
3844  aclresult = object_aclcheck(ProcedureRelationId, transfn_oid, aggOwner, ACL_EXECUTE);
3845  if (aclresult != ACLCHECK_OK)
3846  aclcheck_error(aclresult, OBJECT_FUNCTION,
3847  get_func_name(transfn_oid));
3848  InvokeFunctionExecuteHook(transfn_oid);
3849 
3850  /*
3851  * initval is potentially null, so don't try to access it as a
3852  * struct field. Must do it the hard way with SysCacheGetAttr.
3853  */
3854  textInitVal = SysCacheGetAttr(AGGFNOID, aggTuple,
3855  Anum_pg_aggregate_agginitval,
3856  &initValueIsNull);
3857  if (initValueIsNull)
3858  initValue = (Datum) 0;
3859  else
3860  initValue = GetAggInitVal(textInitVal, aggtranstype);
3861 
3862  if (DO_AGGSPLIT_COMBINE(aggstate->aggsplit))
3863  {
3864  Oid combineFnInputTypes[] = {aggtranstype,
3865  aggtranstype};
3866 
3867  /*
3868  * When combining there's only one input, the to-be-combined
3869  * transition value. The transition value is not counted
3870  * here.
3871  */
3872  pertrans->numTransInputs = 1;
3873 
3874  /* aggcombinefn always has two arguments of aggtranstype */
3875  build_pertrans_for_aggref(pertrans, aggstate, estate,
3876  aggref, transfn_oid, aggtranstype,
3877  serialfn_oid, deserialfn_oid,
3878  initValue, initValueIsNull,
3879  combineFnInputTypes, 2);
3880 
3881  /*
3882  * Ensure that a combine function to combine INTERNAL states
3883  * is not strict. This should have been checked during CREATE
3884  * AGGREGATE, but the strict property could have been changed
3885  * since then.
3886  */
3887  if (pertrans->transfn.fn_strict && aggtranstype == INTERNALOID)
3888  ereport(ERROR,
3889  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
3890  errmsg("combine function with transition type %s must not be declared STRICT",
3891  format_type_be(aggtranstype))));
3892  }
3893  else
3894  {
3895  /* Detect how many arguments to pass to the transfn */
3896  if (AGGKIND_IS_ORDERED_SET(aggref->aggkind))
3897  pertrans->numTransInputs = list_length(aggref->args);
3898  else
3899  pertrans->numTransInputs = numAggTransFnArgs;
3900 
3901  build_pertrans_for_aggref(pertrans, aggstate, estate,
3902  aggref, transfn_oid, aggtranstype,
3903  serialfn_oid, deserialfn_oid,
3904  initValue, initValueIsNull,
3905  aggTransFnInputTypes,
3906  numAggTransFnArgs);
3907 
3908  /*
3909  * If the transfn is strict and the initval is NULL, make sure
3910  * input type and transtype are the same (or at least
3911  * binary-compatible), so that it's OK to use the first
3912  * aggregated input value as the initial transValue. This
3913  * should have been checked at agg definition time, but we
3914  * must check again in case the transfn's strictness property
3915  * has been changed.
3916  */
3917  if (pertrans->transfn.fn_strict && pertrans->initValueIsNull)
3918  {
3919  if (numAggTransFnArgs <= numDirectArgs ||
3920  !IsBinaryCoercible(aggTransFnInputTypes[numDirectArgs],
3921  aggtranstype))
3922  ereport(ERROR,
3923  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
3924  errmsg("aggregate %u needs to have compatible input type and transition type",
3925  aggref->aggfnoid)));
3926  }
3927  }
3928  }
3929  else
3930  pertrans->aggshared = true;
3931  ReleaseSysCache(aggTuple);
3932  }
3933 
3934  /*
3935  * Update aggstate->numaggs to be the number of unique aggregates found.
3936  * Also set numstates to the number of unique transition states found.
3937  */
3938  aggstate->numaggs = numaggs;
3939  aggstate->numtrans = numtrans;
3940 
3941  /*
3942  * Last, check whether any more aggregates got added onto the node while
3943  * we processed the expressions for the aggregate arguments (including not
3944  * only the regular arguments and FILTER expressions handled immediately
3945  * above, but any direct arguments we might've handled earlier). If so,
3946  * we have nested aggregate functions, which is semantically nonsensical,
3947  * so complain. (This should have been caught by the parser, so we don't
3948  * need to work hard on a helpful error message; but we defend against it
3949  * here anyway, just to be sure.)
3950  */
3951  if (numaggrefs != list_length(aggstate->aggs))
3952  ereport(ERROR,
3953  (errcode(ERRCODE_GROUPING_ERROR),
3954  errmsg("aggregate function calls cannot be nested")));
3955 
3956  /*
3957  * Build expressions doing all the transition work at once. We build a
3958  * different one for each phase, as the number of transition function
3959  * invocation can differ between phases. Note this'll work both for
3960  * transition and combination functions (although there'll only be one
3961  * phase in the latter case).
3962  */
3963  for (phaseidx = 0; phaseidx < aggstate->numphases; phaseidx++)
3964  {
3965  AggStatePerPhase phase = &aggstate->phases[phaseidx];
3966  bool dohash = false;
3967  bool dosort = false;
3968 
3969  /* phase 0 doesn't necessarily exist */
3970  if (!phase->aggnode)
3971  continue;
3972 
3973  if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 1)
3974  {
3975  /*
3976  * Phase one, and only phase one, in a mixed agg performs both
3977  * sorting and aggregation.
3978  */
3979  dohash = true;
3980  dosort = true;
3981  }
3982  else if (aggstate->aggstrategy == AGG_MIXED && phaseidx == 0)
3983  {
3984  /*
3985  * No need to compute a transition function for an AGG_MIXED phase
3986  * 0 - the contents of the hashtables will have been computed
3987  * during phase 1.
3988  */
3989  continue;
3990  }
3991  else if (phase->aggstrategy == AGG_PLAIN ||
3992  phase->aggstrategy == AGG_SORTED)
3993  {
3994  dohash = false;
3995  dosort = true;
3996  }
3997  else if (phase->aggstrategy == AGG_HASHED)
3998  {
3999  dohash = true;
4000  dosort = false;
4001  }
4002  else
4003  Assert(false);
4004 
4005  phase->evaltrans = ExecBuildAggTrans(aggstate, phase, dosort, dohash,
4006  false);
4007 
4008  /* cache compiled expression for outer slot without NULL check */
4009  phase->evaltrans_cache[0][0] = phase->evaltrans;
4010  }
4011 
4012  return aggstate;
4013 }
AclResult
Definition: acl.h:183
@ ACLCHECK_OK
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3485
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:4598
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1047
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:796
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ereport(elevel,...)
Definition: elog.h:145
List * ExecInitExprList(List *nodes, PlanState *parent)
Definition: execExpr.c:319
ExprState * ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase, bool doSort, bool doHash, bool nullcheck)
Definition: execExpr.c:3263
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:210
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:142
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
void ExecInitResultTupleSlotTL(PlanState *planstate, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1799
ExprContext * CreateWorkExprContext(EState *estate)
Definition: execUtils.c:318
const TupleTableSlotOps * ExecGetResultSlotOps(PlanState *planstate, bool *isfixed)
Definition: execUtils.c:501
void ExecCreateScanSlotFromOuterPlan(EState *estate, ScanState *scanstate, const TupleTableSlotOps *tts_ops)
Definition: execUtils.c:684
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:482
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:537
struct AggStatePerTransData * AggStatePerTrans
Definition: execnodes.h:2351
struct AggStatePerAggData * AggStatePerAgg
Definition: execnodes.h:2350
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
#define EXEC_FLAG_REWIND
Definition: executor.h:57
#define EXEC_FLAG_EXPLAIN_ONLY
Definition: executor.h:56
#define EXEC_FLAG_MARK
Definition: executor.h:59
char * format_type_be(Oid type_oid)
Definition: format_type.c:339
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
int j
Definition: isn.c:74
List * lcons_int(int datum, List *list)
Definition: list.c:512
char * get_func_name(Oid funcid)
Definition: lsyscache.c:1590
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Oid GetUserId(void)
Definition: miscinit.c:497
static void find_hash_columns(AggState *aggstate)
Definition: nodeAgg.c:1556
static Datum GetAggInitVal(Datum textInitVal, Oid transtype)
Definition: nodeAgg.c:4276
static TupleTableSlot * ExecAgg(PlanState *pstate)
Definition: nodeAgg.c:2150
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1686
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:4026
static void build_hash_tables(AggState *aggstate)
Definition: nodeAgg.c:1461
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:385
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:384
#define makeNode(_type_)
Definition: nodes.h:165
#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:2084
int get_aggregate_argtypes(Aggref *aggref, Oid *inputTypes)
Definition: parse_agg.c:1890
bool IsBinaryCoercible(Oid srctype, Oid targettype)
@ OBJECT_AGGREGATE
Definition: parsenodes.h:1863
@ OBJECT_FUNCTION
Definition: parsenodes.h:1881
#define ACL_EXECUTE
Definition: parsenodes.h:90
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:325
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
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:2427
List * aggs
Definition: execnodes.h:2359
int hash_planned_partitions
Definition: execnodes.h:2412
List * all_grouped_cols
Definition: execnodes.h:2383
TupleTableSlot * hash_spill_wslot
Definition: execnodes.h:2405
TupleTableSlot * sort_slot
Definition: execnodes.h:2392
int numaggs
Definition: execnodes.h:2360
AggSplit aggsplit
Definition: plannodes.h:1000
List * chain
Definition: plannodes.h:1027
List * groupingSets
Definition: plannodes.h:1024
Plan plan
Definition: plannodes.h:994
uint64 transitionSpace
Definition: plannodes.h:1016
Oid aggfnoid
Definition: primnodes.h:373
int aggtransno
Definition: primnodes.h:433
Index agglevelsup
Definition: primnodes.h:424
Oid aggtype
Definition: primnodes.h:376
AggSplit aggsplit
Definition: primnodes.h:427
int aggno
Definition: primnodes.h:430
MemoryContext es_query_cxt
Definition: execnodes.h:655
Datum * ecxt_aggvalues
Definition: execnodes.h:266
bool * ecxt_aggnulls
Definition: execnodes.h:268
bool outeropsset
Definition: execnodes.h:1112
const TupleTableSlotOps * outerops
Definition: execnodes.h:1104
ExprState * qual
Definition: execnodes.h:1050
bool outeropsfixed
Definition: execnodes.h:1108
EState * state
Definition: execnodes.h:1031
ExecProcNodeMtd ExecProcNode
Definition: execnodes.h:1035
List * qual
Definition: plannodes.h:154
int plan_width
Definition: plannodes.h:136
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
@ AGGFNOID
Definition: syscache.h:34
@ PROCOID
Definition: syscache.h:79

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, AGGFNOID, Aggref::aggkind, Aggref::agglevelsup, Aggref::aggno, AggStatePerPhaseData::aggnode, AggStatePerHashData::aggnode, AggStatePerTransData::aggref, AggStatePerAggData::aggref, AggState::aggs, AggStatePerTransData::aggshared, AggState::aggsplit, Agg::aggsplit, Aggref::aggsplit, AggStatePerPhaseData::aggstrategy, AggState::aggstrategy, Agg::aggstrategy, Aggref::aggtransno, Aggref::aggtype, AggState::all_grouped_cols, AggState::all_pergroups, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, 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, CreateWorkExprContext(), 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, EState::es_query_cxt, AggStatePerPhaseData::evaltrans, AggStatePerPhaseData::evaltrans_cache, EXEC_FLAG_BACKWARD, EXEC_FLAG_EXPLAIN_ONLY, EXEC_FLAG_MARK, EXEC_FLAG_REWIND, 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, AggState::hash_mem_limit, AggState::hash_metacxt, AggState::hash_ngroups_limit, AggState::hash_pergroup, AggState::hash_planned_partitions, AggState::hash_spill_rslot, AggState::hash_spill_wslot, AggState::hashcontext, AggState::hashentrysize, HeapTupleIsValid, i, initialize_phase(), initValue(), AggStatePerTransData::initValueIsNull, AggState::input_done, Aggref::inputcollid, 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, PROCOID, 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 4362 of file nodeAgg.c.

4363 {
4364  ExprContext *econtext = node->ss.ps.ps_ExprContext;
4366  Agg *aggnode = (Agg *) node->ss.ps.plan;
4367  int transno;
4368  int numGroupingSets = Max(node->maxsets, 1);
4369  int setno;
4370 
4371  node->agg_done = false;
4372 
4373  if (node->aggstrategy == AGG_HASHED)
4374  {
4375  /*
4376  * In the hashed case, if we haven't yet built the hash table then we
4377  * can just return; nothing done yet, so nothing to undo. If subnode's
4378  * chgParam is not NULL then it will be re-scanned by ExecProcNode,
4379  * else no reason to re-scan it at all.
4380  */
4381  if (!node->table_filled)
4382  return;
4383 
4384  /*
4385  * If we do have the hash table, and it never spilled, and the subplan
4386  * does not have any parameter changes, and none of our own parameter
4387  * changes affect input expressions of the aggregated functions, then
4388  * we can just rescan the existing hash table; no need to build it
4389  * again.
4390  */
4391  if (outerPlan->chgParam == NULL && !node->hash_ever_spilled &&
4392  !bms_overlap(node->ss.ps.chgParam, aggnode->aggParams))
4393  {
4395  &node->perhash[0].hashiter);
4396  select_current_set(node, 0, true);
4397  return;
4398  }
4399  }
4400 
4401  /* Make sure we have closed any open tuplesorts */
4402  for (transno = 0; transno < node->numtrans; transno++)
4403  {
4404  for (setno = 0; setno < numGroupingSets; setno++)
4405  {
4406  AggStatePerTrans pertrans = &node->pertrans[transno];
4407 
4408  if (pertrans->sortstates[setno])
4409  {
4410  tuplesort_end(pertrans->sortstates[setno]);
4411  pertrans->sortstates[setno] = NULL;
4412  }
4413  }
4414  }
4415 
4416  /*
4417  * We don't need to ReScanExprContext the output tuple context here;
4418  * ExecReScan already did it. But we do need to reset our per-grouping-set
4419  * contexts, which may have transvalues stored in them. (We use rescan
4420  * rather than just reset because transfns may have registered callbacks
4421  * that need to be run now.) For the AGG_HASHED case, see below.
4422  */
4423 
4424  for (setno = 0; setno < numGroupingSets; setno++)
4425  {
4426  ReScanExprContext(node->aggcontexts[setno]);
4427  }
4428 
4429  /* Release first tuple of group, if we have made a copy */
4430  if (node->grp_firstTuple != NULL)
4431  {
4433  node->grp_firstTuple = NULL;
4434  }
4436 
4437  /* Forget current agg values */
4438  MemSet(econtext->ecxt_aggvalues, 0, sizeof(Datum) * node->numaggs);
4439  MemSet(econtext->ecxt_aggnulls, 0, sizeof(bool) * node->numaggs);
4440 
4441  /*
4442  * With AGG_HASHED/MIXED, the hash table is allocated in a sub-context of
4443  * the hashcontext. This used to be an issue, but now, resetting a context
4444  * automatically deletes sub-contexts too.
4445  */
4446  if (node->aggstrategy == AGG_HASHED || node->aggstrategy == AGG_MIXED)
4447  {
4449 
4450  node->hash_ever_spilled = false;
4451  node->hash_spill_mode = false;
4452  node->hash_ngroups_current = 0;
4453 
4455  /* Rebuild an empty hash table */
4456  build_hash_tables(node);
4457  node->table_filled = false;
4458  /* iterator will be reset when the table is filled */
4459 
4460  hashagg_recompile_expressions(node, false, false);
4461  }
4462 
4463  if (node->aggstrategy != AGG_HASHED)
4464  {
4465  /*
4466  * Reset the per-group state (in particular, mark transvalues null)
4467  */
4468  for (setno = 0; setno < numGroupingSets; setno++)
4469  {
4470  MemSet(node->pergroups[setno], 0,
4471  sizeof(AggStatePerGroupData) * node->numaggs);
4472  }
4473 
4474  /* reset to phase 1 */
4475  initialize_phase(node, 1);
4476 
4477  node->input_done = false;
4478  node->projected_set = -1;
4479  }
4480 
4481  if (outerPlan->chgParam == NULL)
4483 }
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:495
void ExecReScan(PlanState *node)
Definition: execAmi.c:78
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
bool hash_ever_spilled
Definition: execnodes.h:2407
Bitmapset * aggParams
Definition: plannodes.h:1019
Bitmapset * chgParam
Definition: execnodes.h:1061

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

Referenced by ExecReScan().

◆ fetch_input_tuple()

static TupleTableSlot * fetch_input_tuple ( AggState aggstate)
static

Definition at line 548 of file nodeAgg.c.

549 {
550  TupleTableSlot *slot;
551 
552  if (aggstate->sort_in)
553  {
554  /* make sure we check for interrupts in either path through here */
556  if (!tuplesort_gettupleslot(aggstate->sort_in, true, false,
557  aggstate->sort_slot, NULL))
558  return NULL;
559  slot = aggstate->sort_slot;
560  }
561  else
562  slot = ExecProcNode(outerPlanState(aggstate));
563 
564  if (!TupIsNull(slot) && aggstate->sort_out)
565  tuplesort_puttupleslot(aggstate->sort_out, slot);
566 
567  return slot;
568 }
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:254
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 1048 of file nodeAgg.c.

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

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

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

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

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

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

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

1414 {
1415  if (node == NULL)
1416  return false;
1417  if (IsA(node, Var))
1418  {
1419  Var *var = (Var *) node;
1420 
1421  /* setrefs.c should have set the varno to OUTER_VAR */
1422  Assert(var->varno == OUTER_VAR);
1423  Assert(var->varlevelsup == 0);
1424  if (context->is_aggref)
1425  context->aggregated = bms_add_member(context->aggregated,
1426  var->varattno);
1427  else
1428  context->unaggregated = bms_add_member(context->unaggregated,
1429  var->varattno);
1430  return false;
1431  }
1432  if (IsA(node, Aggref))
1433  {
1434  Assert(!context->is_aggref);
1435  context->is_aggref = true;
1436  expression_tree_walker(node, find_cols_walker, (void *) context);
1437  context->is_aggref = false;
1438  return false;
1439  }
1441  (void *) context);
1442 }
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:151
#define OUTER_VAR
Definition: primnodes.h:194
Bitmapset * aggregated
Definition: nodeAgg.c:364
Bitmapset * unaggregated
Definition: nodeAgg.c:365
Definition: primnodes.h:205
AttrNumber varattno
Definition: primnodes.h:217
int varno
Definition: primnodes.h:212
Index varlevelsup
Definition: primnodes.h:230

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

Referenced by find_cols().

◆ find_hash_columns()

static void find_hash_columns ( AggState aggstate)
static

Definition at line 1556 of file nodeAgg.c.

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

References AggStatePerHashData::aggnode, AggState::all_cols_needed, AggState::all_grouped_cols, attnum, bms_add_member(), bms_copy(), bms_del_member(), bms_first_member(), bms_free(), bms_is_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 4276 of file nodeAgg.c.

4277 {
4278  Oid typinput,
4279  typioparam;
4280  char *strInitVal;
4281  Datum initVal;
4282 
4283  getTypeInputInfo(transtype, &typinput, &typioparam);
4284  strInitVal = TextDatumGetCString(textInitVal);
4285  initVal = OidInputFunctionCall(typinput, strInitVal,
4286  typioparam, -1);
4287  pfree(strInitVal);
4288  return initVal;
4289 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1630
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2832

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

1849 {
1850  uint64 ngroups = aggstate->hash_ngroups_current;
1851  Size meta_mem = MemoryContextMemAllocated(aggstate->hash_metacxt,
1852  true);
1854  true);
1855 
1856  /*
1857  * Don't spill unless there's at least one group in the hash table so we
1858  * can be sure to make progress even in edge cases.
1859  */
1860  if (aggstate->hash_ngroups_current > 0 &&
1861  (meta_mem + hashkey_mem > aggstate->hash_mem_limit ||
1862  ngroups > aggstate->hash_ngroups_limit))
1863  {
1864  hash_agg_enter_spill_mode(aggstate);
1865  }
1866 }
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:644
static void hash_agg_enter_spill_mode(AggState *aggstate)
Definition: nodeAgg.c:1874

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::hashcontext, 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 1874 of file nodeAgg.c.

1875 {
1876  aggstate->hash_spill_mode = true;
1877  hashagg_recompile_expressions(aggstate, aggstate->table_filled, true);
1878 
1879  if (!aggstate->hash_ever_spilled)
1880  {
1881  Assert(aggstate->hash_tapeset == NULL);
1882  Assert(aggstate->hash_spills == NULL);
1883 
1884  aggstate->hash_ever_spilled = true;
1885 
1886  aggstate->hash_tapeset = LogicalTapeSetCreate(true, NULL, -1);
1887 
1888  aggstate->hash_spills = palloc(sizeof(HashAggSpill) * aggstate->num_hashes);
1889 
1890  for (int setno = 0; setno < aggstate->num_hashes; setno++)
1891  {
1892  AggStatePerHash perhash = &aggstate->perhash[setno];
1893  HashAggSpill *spill = &aggstate->hash_spills[setno];
1894 
1895  hashagg_spill_init(spill, aggstate->hash_tapeset, 0,
1896  perhash->aggnode->numGroups,
1897  aggstate->hashentrysize);
1898  }
1899  }
1900 }
LogicalTapeSet * LogicalTapeSetCreate(bool preallocate, SharedFileSet *fileset, int worker)
Definition: logtape.c:557
struct HashAggSpill * hash_spills
Definition: execnodes.h:2402

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

1687 {
1688  Size tupleChunkSize;
1689  Size pergroupChunkSize;
1690  Size transitionChunkSize;
1691  Size tupleSize = (MAXALIGN(SizeofMinimalTupleHeader) +
1692  tupleWidth);
1693  Size pergroupSize = numTrans * sizeof(AggStatePerGroupData);
1694 
1695  tupleChunkSize = CHUNKHDRSZ + tupleSize;
1696 
1697  if (pergroupSize > 0)
1698  pergroupChunkSize = CHUNKHDRSZ + pergroupSize;
1699  else
1700  pergroupChunkSize = 0;
1701 
1702  if (transitionSpace > 0)
1703  transitionChunkSize = CHUNKHDRSZ + transitionSpace;
1704  else
1705  transitionChunkSize = 0;
1706 
1707  return
1708  sizeof(TupleHashEntryData) +
1709  tupleChunkSize +
1710  pergroupChunkSize +
1711  transitionChunkSize;
1712 }
#define MAXALIGN(LEN)
Definition: c.h:747
struct TupleHashEntryData TupleHashEntryData
#define SizeofMinimalTupleHeader
Definition: htup_details.h:643
#define CHUNKHDRSZ
Definition: nodeAgg.c:321

References CHUNKHDRSZ, MAXALIGN, and SizeofMinimalTupleHeader.

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

1793 {
1794  int npartitions;
1795  Size partition_mem;
1796  Size hash_mem_limit = get_hash_memory_limit();
1797 
1798  /* if not expected to spill, use all of hash_mem */
1799  if (input_groups * hashentrysize <= hash_mem_limit)
1800  {
1801  if (num_partitions != NULL)
1802  *num_partitions = 0;
1803  *mem_limit = hash_mem_limit;
1804  *ngroups_limit = hash_mem_limit / hashentrysize;
1805  return;
1806  }
1807 
1808  /*
1809  * Calculate expected memory requirements for spilling, which is the size
1810  * of the buffers needed for all the tapes that need to be open at once.
1811  * Then, subtract that from the memory available for holding hash tables.
1812  */
1813  npartitions = hash_choose_num_partitions(input_groups,
1814  hashentrysize,
1815  used_bits,
1816  NULL);
1817  if (num_partitions != NULL)
1818  *num_partitions = npartitions;
1819 
1820  partition_mem =
1822  HASHAGG_WRITE_BUFFER_SIZE * npartitions;
1823 
1824  /*
1825  * Don't set the limit below 3/4 of hash_mem. In that case, we are at the
1826  * minimum number of partitions, so we aren't going to dramatically exceed
1827  * work mem anyway.
1828  */
1829  if (hash_mem_limit > 4 * partition_mem)
1830  *mem_limit = hash_mem_limit - partition_mem;
1831  else
1832  *mem_limit = hash_mem_limit * 0.75;
1833 
1834  if (*mem_limit > hashentrysize)
1835  *ngroups_limit = *mem_limit / hashentrysize;
1836  else
1837  *ngroups_limit = 1;
1838 }
#define HASHAGG_READ_BUFFER_SIZE
Definition: nodeAgg.c:306
#define HASHAGG_WRITE_BUFFER_SIZE
Definition: nodeAgg.c:307
static int hash_choose_num_partitions(double input_groups, double hashentrysize, int used_bits, int *log2_npartitions)
Definition: nodeAgg.c:1983
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3390

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

1910 {
1911  Size meta_mem;
1912  Size hashkey_mem;
1913  Size buffer_mem;
1914  Size total_mem;
1915 
1916  if (aggstate->aggstrategy != AGG_MIXED &&
1917  aggstate->aggstrategy != AGG_HASHED)
1918  return;
1919 
1920  /* memory for the hash table itself */
1921  meta_mem = MemoryContextMemAllocated(aggstate->hash_metacxt, true);
1922 
1923  /* memory for the group keys and transition states */
1924  hashkey_mem = MemoryContextMemAllocated(aggstate->hashcontext->ecxt_per_tuple_memory, true);
1925 
1926  /* memory for read/write tape buffers, if spilled */
1927  buffer_mem = npartitions * HASHAGG_WRITE_BUFFER_SIZE;
1928  if (from_tape)
1929  buffer_mem += HASHAGG_READ_BUFFER_SIZE;
1930 
1931  /* update peak mem */
1932  total_mem = meta_mem + hashkey_mem + buffer_mem;
1933  if (total_mem > aggstate->hash_mem_peak)
1934  aggstate->hash_mem_peak = total_mem;
1935 
1936  /* update disk usage */
1937  if (aggstate->hash_tapeset != NULL)
1938  {
1939  uint64 disk_used = LogicalTapeSetBlocks(aggstate->hash_tapeset) * (BLCKSZ / 1024);
1940 
1941  if (aggstate->hash_disk_used < disk_used)
1942  aggstate->hash_disk_used = disk_used;
1943  }
1944 
1945  /* update hashentrysize estimate based on contents */
1946  if (aggstate->hash_ngroups_current > 0)
1947  {
1948  aggstate->hashentrysize =
1949  sizeof(TupleHashEntryData) +
1950  (hashkey_mem / (double) aggstate->hash_ngroups_current);
1951  }
1952 }
long LogicalTapeSetBlocks(LogicalTapeSet *lts)
Definition: logtape.c:1184

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_tapeset, HASHAGG_READ_BUFFER_SIZE, HASHAGG_WRITE_BUFFER_SIZE, AggState::hashcontext, AggState::hashentrysize, LogicalTapeSetBlocks(), and MemoryContextMemAllocated().

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

1959 {
1960  long max_nbuckets;
1961  long nbuckets = ngroups;
1962 
1963  max_nbuckets = memory / hashentrysize;
1964 
1965  /*
1966  * Underestimating is better than overestimating. Too many buckets crowd
1967  * out space for group keys and transition state values.
1968  */
1969  max_nbuckets >>= 1;
1970 
1971  if (nbuckets > max_nbuckets)
1972  nbuckets = max_nbuckets;
1973 
1974  return Max(nbuckets, 1);
1975 }

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

1985 {
1986  Size hash_mem_limit = get_hash_memory_limit();
1987  double partition_limit;
1988  double mem_wanted;
1989  double dpartitions;
1990  int npartitions;
1991  int partition_bits;
1992 
1993  /*
1994  * Avoid creating so many partitions that the memory requirements of the
1995  * open partition files are greater than 1/4 of hash_mem.
1996  */
1997  partition_limit =
1998  (hash_mem_limit * 0.25 - HASHAGG_READ_BUFFER_SIZE) /
2000 
2001  mem_wanted = HASHAGG_PARTITION_FACTOR * input_groups * hashentrysize;
2002 
2003  /* make enough partitions so that each one is likely to fit in memory */
2004  dpartitions = 1 + (mem_wanted / hash_mem_limit);
2005 
2006  if (dpartitions > partition_limit)
2007  dpartitions = partition_limit;
2008 
2009  if (dpartitions < HASHAGG_MIN_PARTITIONS)
2010  dpartitions = HASHAGG_MIN_PARTITIONS;
2011  if (dpartitions > HASHAGG_MAX_PARTITIONS)
2012  dpartitions = HASHAGG_MAX_PARTITIONS;
2013 
2014  /* HASHAGG_MAX_PARTITIONS limit makes this safe */
2015  npartitions = (int) dpartitions;
2016 
2017  /* ceil(log2(npartitions)) */
2018  partition_bits = my_log2(npartitions);
2019 
2020  /* make sure that we don't exhaust the hash bits */
2021  if (partition_bits + used_bits >= 32)
2022  partition_bits = 32 - used_bits;
2023 
2024  if (log2_npartitions != NULL)
2025  *log2_npartitions = partition_bits;
2026 
2027  /* number of partitions will be a power of two */
2028  npartitions = 1 << partition_bits;
2029 
2030  return npartitions;
2031 }
int my_log2(long num)
Definition: dynahash.c:1760
#define HASHAGG_MAX_PARTITIONS
Definition: nodeAgg.c:298
#define HASHAGG_MIN_PARTITIONS
Definition: nodeAgg.c:297
#define HASHAGG_PARTITION_FACTOR
Definition: nodeAgg.c:296

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

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

2985 {
2986  HashAggBatch *batch = palloc0(sizeof(HashAggBatch));
2987 
2988  batch->setno = setno;
2989  batch->used_bits = used_bits;
2990  batch->input_tape = input_tape;
2991  batch->input_tuples = input_tuples;
2992  batch->input_card = input_card;
2993 
2994  return batch;
2995 }
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 3002 of file nodeAgg.c.

3003 {
3004  LogicalTape *tape = batch->input_tape;
3005  MinimalTuple tuple;
3006  uint32 t_len;
3007  size_t nread;
3008  uint32 hash;
3009 
3010  nread = LogicalTapeRead(tape, &hash, sizeof(uint32));
3011  if (nread == 0)
3012  return NULL;
3013  if (nread != sizeof(uint32))
3014  ereport(ERROR,
3016  errmsg("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3017  tape, sizeof(uint32), nread)));
3018  if (hashp != NULL)
3019  *hashp = hash;
3020 
3021  nread = LogicalTapeRead(tape, &t_len, sizeof(t_len));
3022  if (nread != sizeof(uint32))
3023  ereport(ERROR,
3025  errmsg("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3026  tape, sizeof(uint32), nread)));
3027 
3028  tuple = (MinimalTuple) palloc(t_len);
3029  tuple->t_len = t_len;
3030 
3031  nread = LogicalTapeRead(tape,
3032  (void *) ((char *) tuple + sizeof(uint32)),
3033  t_len - sizeof(uint32));
3034  if (nread != t_len - sizeof(uint32))
3035  ereport(ERROR,
3037  errmsg("unexpected EOF for tape %p: requested %zu bytes, read %zu bytes",
3038  tape, t_len - sizeof(uint32), nread)));
3039 
3040  return tuple;
3041 }
int errcode_for_file_access(void)
Definition: elog.c:718
MinimalTupleData * MinimalTuple
Definition: htup.h:27
size_t LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:929

References ereport, errcode_for_file_access(), errmsg(), 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 3051 of file nodeAgg.c.

3052 {
3053  int setno;
3054  int total_npartitions = 0;
3055 
3056  if (aggstate->hash_spills != NULL)
3057  {
3058  for (setno = 0; setno < aggstate->num_hashes; setno++)
3059  {
3060  HashAggSpill *spill = &aggstate->hash_spills[setno];
3061 
3062  total_npartitions += spill->npartitions;
3063  hashagg_spill_finish(aggstate, spill, setno);
3064  }
3065 
3066  /*
3067  * We're not processing tuples from outer plan any more; only
3068  * processing batches of spilled tuples. The initial spill structures
3069  * are no longer needed.
3070  */
3071  pfree(aggstate->hash_spills);
3072  aggstate->hash_spills = NULL;
3073  }
3074 
3075  hash_agg_update_metrics(aggstate, false, total_npartitions);
3076  aggstate->hash_spill_mode = false;
3077 }

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

1734 {
1735  AggStatePerPhase phase;
1736  int i = minslot ? 1 : 0;
1737  int j = nullcheck ? 1 : 0;
1738 
1739  Assert(aggstate->aggstrategy == AGG_HASHED ||
1740  aggstate->aggstrategy == AGG_MIXED);
1741 
1742  if (aggstate->aggstrategy == AGG_HASHED)
1743  phase = &aggstate->phases[0];
1744  else /* AGG_MIXED */
1745  phase = &aggstate->phases[1];
1746 
1747  if (phase->evaltrans_cache[i][j] == NULL)
1748  {
1749  const TupleTableSlotOps *outerops = aggstate->ss.ps.outerops;
1750  bool outerfixed = aggstate->ss.ps.outeropsfixed;
1751  bool dohash = true;
1752  bool dosort = false;
1753 
1754  /*
1755  * If minslot is true, that means we are processing a spilled batch
1756  * (inside agg_refill_hash_table()), and we must not advance the
1757  * sorted grouping sets.
1758  */
1759  if (aggstate->aggstrategy == AGG_MIXED && !minslot)
1760  dosort = true;
1761 
1762  /* temporarily change the outerops while compiling the expression */
1763  if (minslot)
1764  {
1765  aggstate->ss.ps.outerops = &TTSOpsMinimalTuple;
1766  aggstate->ss.ps.outeropsfixed = true;
1767  }
1768 
1769  phase->evaltrans_cache[i][j] = ExecBuildAggTrans(aggstate, phase,
1770  dosort, dohash,
1771  nullcheck);
1772 
1773  /* change back */
1774  aggstate->ss.ps.outerops = outerops;
1775  aggstate->ss.ps.outeropsfixed = outerfixed;
1776  }
1777 
1778  phase->evaltrans = phase->evaltrans_cache[i][j];
1779 }

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

3126 {
3127  /* free spills from initial pass */
3128  if (aggstate->hash_spills != NULL)
3129  {
3130  int setno;
3131 
3132  for (setno = 0; setno < aggstate->num_hashes; setno++)
3133  {
3134  HashAggSpill *spill = &aggstate->hash_spills[setno];
3135 
3136  pfree(spill->ntuples);
3137  pfree(spill->partitions);
3138  }
3139  pfree(aggstate->hash_spills);
3140  aggstate->hash_spills = NULL;
3141  }
3142 
3143  /* free batches */
3144  list_free_deep(aggstate->hash_batches);
3145  aggstate->hash_batches = NIL;
3146 
3147  /* close tape set */
3148  if (aggstate->hash_tapeset != NULL)
3149  {
3150  LogicalTapeSetClose(aggstate->hash_tapeset);
3151  aggstate->hash_tapeset = NULL;
3152  }
3153 }
void list_free_deep(List *list)
Definition: list.c:1559
void LogicalTapeSetClose(LogicalTapeSet *lts)
Definition: logtape.c:668
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 3085 of file nodeAgg.c.

3086 {
3087  int i;
3088  int used_bits = 32 - spill->shift;
3089 
3090  if (spill->npartitions == 0)
3091  return; /* didn't spill */
3092 
3093  for (i = 0; i < spill->npartitions; i++)
3094  {
3095  LogicalTape *tape = spill->partitions[i];
3096  HashAggBatch *new_batch;
3097  double cardinality;
3098 
3099  /* if the partition is empty, don't create a new batch of work */
3100  if (spill->ntuples[i] == 0)
3101  continue;
3102 
3103  cardinality = estimateHyperLogLog(&spill->hll_card[i]);
3104  freeHyperLogLog(&spill->hll_card[i]);
3105 
3106  /* rewinding frees the buffer while not in use */
3108 
3109  new_batch = hashagg_batch_new(tape, setno,
3110  spill->ntuples[i], cardinality,
3111  used_bits);
3112  aggstate->hash_batches = lappend(aggstate->hash_batches, new_batch);
3113  aggstate->hash_batches_used++;
3114  }
3115 
3116  pfree(spill->ntuples);
3117  pfree(spill->hll_card);
3118  pfree(spill->partitions);
3119 }
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:847
static HashAggBatch * hashagg_batch_new(LogicalTape *input_tape, int setno, int64 input_tuples, double input_card, int used_bits)
Definition: nodeAgg.c:2983
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 2886 of file nodeAgg.c.

2888 {
2889  int npartitions;
2890  int partition_bits;
2891 
2892  npartitions = hash_choose_num_partitions(input_groups, hashentrysize,
2893  used_bits, &partition_bits);
2894 
2895  spill->partitions = palloc0(sizeof(LogicalTape *) * npartitions);
2896  spill->ntuples = palloc0(sizeof(int64) * npartitions);
2897  spill->hll_card = palloc0(sizeof(hyperLogLogState) * npartitions);
2898 
2899  for (int i = 0; i < npartitions; i++)
2900  spill->partitions[i] = LogicalTapeCreate(tapeset);
2901 
2902  spill->shift = 32 - used_bits - partition_bits;
2903  spill->mask = (npartitions - 1) << spill->shift;
2904  spill->npartitions = npartitions;
2905 
2906  for (int i = 0; i < npartitions; i++)
2908 }
void initHyperLogLog(hyperLogLogState *cState, uint8 bwidth)
Definition: hyperloglog.c:66
LogicalTape * LogicalTapeCreate(LogicalTapeSet *lts)
Definition: logtape.c:681
#define HASHAGG_HLL_BIT_WIDTH
Definition: nodeAgg.c:315
uint32 mask
Definition: nodeAgg.c:337

References hash_choose_num_partitions(), HASHAGG_HLL_BIT_WIDTH, HashAggSpill::hll_card, i, initHyperLogLog(), 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 2917 of file nodeAgg.c.

2919 {
2920  TupleTableSlot *spillslot;
2921  int partition;
2922  MinimalTuple tuple;
2923  LogicalTape *tape;
2924  int total_written = 0;
2925  bool shouldFree;
2926 
2927  Assert(spill->partitions != NULL);
2928 
2929  /* spill only attributes that we actually need */
2930  if (!aggstate->all_cols_needed)
2931  {
2932  spillslot = aggstate->hash_spill_wslot;
2933  slot_getsomeattrs(inputslot, aggstate->max_colno_needed);
2934  ExecClearTuple(spillslot);
2935  for (int i = 0; i < spillslot->tts_tupleDescriptor->natts; i++)
2936  {
2937  if (bms_is_member(i + 1, aggstate->colnos_needed))
2938  {
2939  spillslot->tts_values[i] = inputslot->tts_values[i];
2940  spillslot->tts_isnull[i] = inputslot->tts_isnull[i];
2941  }
2942  else
2943  spillslot->tts_isnull[i] = true;
2944  }
2945  ExecStoreVirtualTuple(spillslot);
2946  }
2947  else
2948  spillslot = inputslot;
2949 
2950  tuple = ExecFetchSlotMinimalTuple(spillslot, &shouldFree);
2951 
2952  partition = (hash & spill->mask) >> spill->shift;
2953  spill->ntuples[partition]++;
2954 
2955  /*
2956  * All hash values destined for a given partition have some bits in
2957  * common, which causes bad HLL cardinality estimates. Hash the hash to
2958  * get a more uniform distribution.
2959  */
2960  addHyperLogLog(&spill->hll_card[partition], hash_bytes_uint32(hash));
2961 
2962  tape = spill->partitions[partition];
2963 
2964  LogicalTapeWrite(tape, (void *) &hash, sizeof(uint32));
2965  total_written += sizeof(uint32);
2966 
2967  LogicalTapeWrite(tape, (void *) tuple, tuple->t_len);
2968  total_written += tuple->t_len;
2969 
2970  if (shouldFree)
2971  pfree(tuple);
2972 
2973  return total_written;
2974 }
MinimalTuple ExecFetchSlotMinimalTuple(TupleTableSlot *slot, bool *shouldFree)
Definition: execTuples.c:1692
uint32 hash_bytes_uint32(uint32 k)
Definition: hashfn.c:610
void addHyperLogLog(hyperLogLogState *cState, uint32 hash)
Definition: hyperloglog.c:167
void LogicalTapeWrite(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:762
static void slot_getsomeattrs(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:349

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

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

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

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

2039 {
2040  AggStatePerGroup pergroup;
2041  int transno;
2042 
2043  aggstate->hash_ngroups_current++;
2044  hash_agg_check_limits(aggstate);
2045 
2046  /* no need to allocate or initialize per-group state */
2047  if (aggstate->numtrans == 0)
2048  return;
2049 
2050  pergroup = (AggStatePerGroup)
2051  MemoryContextAlloc(hashtable->tablecxt,
2052  sizeof(AggStatePerGroupData) * aggstate->numtrans);
2053 
2054  entry->additional = pergroup;
2055 
2056  /*
2057  * Initialize aggregates for new tuple group, lookup_hash_entries()
2058  * already has selected the relevant grouping set.
2059  */
2060  for (transno = 0; transno < aggstate->numtrans; transno++)
2061  {
2062  AggStatePerTrans pertrans = &aggstate->pertrans[transno];
2063  AggStatePerGroup pergroupstate = &pergroup[transno];
2064 
2065  initialize_aggregate(aggstate, pertrans, pergroupstate);
2066  }
2067 }
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
static void hash_agg_check_limits(AggState *aggstate)
Definition: nodeAgg.c:1848
MemoryContext tablecxt
Definition: execnodes.h:807

References TupleHashEntryData::additional, hash_agg_check_limits(), AggState::hash_ngroups_current, initialize_aggregate(), MemoryContextAlloc(), AggState::numtrans, AggState::pertrans, and TupleHashTableData::tablecxt.

Referenced by agg_refill_hash_table(), and lookup_hash_entries().

◆ initialize_phase()

static void initialize_phase ( AggState aggstate,
int  newphase 
)
static

Definition at line 478 of file nodeAgg.c.

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

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

2088 {
2089  AggStatePerGroup *pergroup = aggstate->hash_pergroup;
2090  TupleTableSlot *outerslot = aggstate->tmpcontext->ecxt_outertuple;
2091  int setno;
2092 
2093  for (setno = 0; setno < aggstate->num_hashes; setno++)
2094  {
2095  AggStatePerHash perhash = &aggstate->perhash[setno];
2096  TupleHashTable hashtable = perhash->hashtable;
2097  TupleTableSlot *hashslot = perhash->hashslot;
2098  TupleHashEntry entry;
2099  uint32 hash;
2100  bool isnew = false;
2101  bool *p_isnew;
2102 
2103  /* if hash table already spilled, don't create new entries */
2104  p_isnew = aggstate->hash_spill_mode ? NULL : &isnew;
2105 
2106  select_current_set(aggstate, setno, true);
2107  prepare_hash_slot(perhash,
2108  outerslot,
2109  hashslot);
2110 
2111  entry = LookupTupleHashEntry(hashtable, hashslot,
2112  p_isnew, &hash);
2113 
2114  if (entry != NULL)
2115  {
2116  if (isnew)
2117  initialize_hash_entry(aggstate, hashtable, entry);
2118  pergroup[setno] = entry->additional;
2119  }
2120  else
2121  {
2122  HashAggSpill *spill = &aggstate->hash_spills[setno];
2123  TupleTableSlot *slot = aggstate->tmpcontext->ecxt_outertuple;
2124 
2125  if (spill->partitions == NULL)
2126  hashagg_spill_init(spill, aggstate->hash_tapeset, 0,
2127  perhash->aggnode->numGroups,
2128  aggstate->hashentrysize);
2129 
2130  hashagg_spill_tuple(aggstate, spill, slot, hash);
2131  pergroup[setno] = NULL;
2132  }
2133  }
2134 }
TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew, uint32 *hash)
Definition: execGrouping.c:306

References TupleHashEntryData::additional, 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(), and AggState::tmpcontext.

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

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

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

1243 {
1244  if (aggstate->phase->grouped_cols)
1245  {
1246  Bitmapset *grouped_cols = aggstate->phase->grouped_cols[currentSet];
1247 
1248  aggstate->grouped_cols = grouped_cols;
1249 
1250  if (TTS_EMPTY(slot))
1251  {
1252  /*
1253  * Force all values to be NULL if working on an empty input tuple
1254  * (i.e. an empty grouping set for which no input rows were
1255  * supplied).
1256  */
1257  ExecStoreAllNullTuple(slot);
1258  }
1259  else if (aggstate->all_grouped_cols)
1260  {
1261  ListCell *lc;
1262 
1263  /* all_grouped_cols is arranged in desc order */
1265 
1266  foreach(lc, aggstate->all_grouped_cols)
1267  {
1268  int attnum = lfirst_int(lc);
1269 
1270  if (!bms_is_member(attnum, grouped_cols))
1271  slot->tts_isnull[attnum - 1] = true;
1272  }
1273