PostgreSQL Source Code  git master
tuplesort.h File Reference
#include "access/brin_tuple.h"
#include "access/itup.h"
#include "executor/tuptable.h"
#include "storage/dsm.h"
#include "utils/logtape.h"
#include "utils/relcache.h"
#include "utils/sortsupport.h"
Include dependency graph for tuplesort.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  SortCoordinateData
 
struct  TuplesortInstrumentation
 
struct  SortTuple
 
struct  TuplesortPublic
 

Macros

#define NUM_TUPLESORTMETHODS   4
 
#define TUPLESORT_NONE   0
 
#define TUPLESORT_RANDOMACCESS   (1 << 0)
 
#define TUPLESORT_ALLOWBOUNDED   (1 << 1)
 
#define TupleSortUseBumpTupleCxt(opt)   (((opt) & TUPLESORT_ALLOWBOUNDED) == 0)
 
#define PARALLEL_SORT(coordinate)
 
#define TuplesortstateGetPublic(state)   ((TuplesortPublic *) state)
 
#define LogicalTapeReadExact(tape, ptr, len)
 

Typedefs

typedef struct Tuplesortstate Tuplesortstate
 
typedef struct Sharedsort Sharedsort
 
typedef struct SortCoordinateData SortCoordinateData
 
typedef struct SortCoordinateDataSortCoordinate
 
typedef struct TuplesortInstrumentation TuplesortInstrumentation
 
typedef int(* SortTupleComparator) (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 

Enumerations

enum  TuplesortMethod {
  SORT_TYPE_STILL_IN_PROGRESS = 0 , SORT_TYPE_TOP_N_HEAPSORT = 1 << 0 , SORT_TYPE_QUICKSORT = 1 << 1 , SORT_TYPE_EXTERNAL_SORT = 1 << 2 ,
  SORT_TYPE_EXTERNAL_MERGE = 1 << 3
}
 
enum  TuplesortSpaceType { SORT_SPACE_TYPE_DISK , SORT_SPACE_TYPE_MEMORY }
 

Functions

Tuplesortstatetuplesort_begin_common (int workMem, SortCoordinate coordinate, int sortopt)
 
void tuplesort_set_bound (Tuplesortstate *state, int64 bound)
 
bool tuplesort_used_bound (Tuplesortstate *state)
 
void tuplesort_puttuple_common (Tuplesortstate *state, SortTuple *tuple, bool useAbbrev, Size tuplen)
 
void tuplesort_performsort (Tuplesortstate *state)
 
bool tuplesort_gettuple_common (Tuplesortstate *state, bool forward, SortTuple *stup)
 
bool tuplesort_skiptuples (Tuplesortstate *state, int64 ntuples, bool forward)
 
void tuplesort_end (Tuplesortstate *state)
 
void tuplesort_reset (Tuplesortstate *state)
 
void tuplesort_get_stats (Tuplesortstate *state, TuplesortInstrumentation *stats)
 
const char * tuplesort_method_name (TuplesortMethod m)
 
const char * tuplesort_space_type_name (TuplesortSpaceType t)
 
int tuplesort_merge_order (int64 allowedMem)
 
Size tuplesort_estimate_shared (int nWorkers)
 
void tuplesort_initialize_shared (Sharedsort *shared, int nWorkers, dsm_segment *seg)
 
void tuplesort_attach_shared (Sharedsort *shared, dsm_segment *seg)
 
void tuplesort_rescan (Tuplesortstate *state)
 
void tuplesort_markpos (Tuplesortstate *state)
 
void tuplesort_restorepos (Tuplesortstate *state)
 
void * tuplesort_readtup_alloc (Tuplesortstate *state, Size tuplen)
 
Tuplesortstatetuplesort_begin_heap (TupleDesc tupDesc, int nkeys, AttrNumber *attNums, Oid *sortOperators, Oid *sortCollations, bool *nullsFirstFlags, int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_cluster (TupleDesc tupDesc, Relation indexRel, int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_index_btree (Relation heapRel, Relation indexRel, bool enforceUnique, bool uniqueNullsNotDistinct, int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_index_hash (Relation heapRel, Relation indexRel, uint32 high_mask, uint32 low_mask, uint32 max_buckets, int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_index_gist (Relation heapRel, Relation indexRel, int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_index_brin (int workMem, SortCoordinate coordinate, int sortopt)
 
Tuplesortstatetuplesort_begin_datum (Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, int sortopt)
 
void tuplesort_puttupleslot (Tuplesortstate *state, TupleTableSlot *slot)
 
void tuplesort_putheaptuple (Tuplesortstate *state, HeapTuple tup)
 
void tuplesort_putindextuplevalues (Tuplesortstate *state, Relation rel, ItemPointer self, const Datum *values, const bool *isnull)
 
void tuplesort_putbrintuple (Tuplesortstate *state, BrinTuple *tuple, Size size)
 
void tuplesort_putdatum (Tuplesortstate *state, Datum val, bool isNull)
 
bool tuplesort_gettupleslot (Tuplesortstate *state, bool forward, bool copy, TupleTableSlot *slot, Datum *abbrev)
 
HeapTuple tuplesort_getheaptuple (Tuplesortstate *state, bool forward)
 
IndexTuple tuplesort_getindextuple (Tuplesortstate *state, bool forward)
 
BrinTupletuplesort_getbrintuple (Tuplesortstate *state, Size *len, bool forward)
 
bool tuplesort_getdatum (Tuplesortstate *state, bool forward, bool copy, Datum *val, bool *isNull, Datum *abbrev)
 

Macro Definition Documentation

◆ LogicalTapeReadExact

#define LogicalTapeReadExact (   tape,
  ptr,
  len 
)
Value:
do { \
if (LogicalTapeRead(tape, ptr, len) != (size_t) (len)) \
elog(ERROR, "unexpected end of data"); \
} while(0)
#define ERROR
Definition: elog.h:39
size_t LogicalTapeRead(LogicalTape *lt, void *ptr, size_t size)
Definition: logtape.c:928
const void size_t len

Definition at line 262 of file tuplesort.h.

◆ NUM_TUPLESORTMETHODS

#define NUM_TUPLESORTMETHODS   4

Definition at line 84 of file tuplesort.h.

◆ PARALLEL_SORT

#define PARALLEL_SORT (   coordinate)
Value:
(coordinate == NULL || \
(coordinate)->sharedsort == NULL ? 0 : \
(coordinate)->isWorker ? 1 : 2)

Definition at line 255 of file tuplesort.h.

◆ TUPLESORT_ALLOWBOUNDED

#define TUPLESORT_ALLOWBOUNDED   (1 << 1)

Definition at line 99 of file tuplesort.h.

◆ TUPLESORT_NONE

#define TUPLESORT_NONE   0

Definition at line 93 of file tuplesort.h.

◆ TUPLESORT_RANDOMACCESS

#define TUPLESORT_RANDOMACCESS   (1 << 0)

Definition at line 96 of file tuplesort.h.

◆ TuplesortstateGetPublic

#define TuplesortstateGetPublic (   state)    ((TuplesortPublic *) state)

Definition at line 259 of file tuplesort.h.

◆ TupleSortUseBumpTupleCxt

#define TupleSortUseBumpTupleCxt (   opt)    (((opt) & TUPLESORT_ALLOWBOUNDED) == 0)

Definition at line 108 of file tuplesort.h.

Typedef Documentation

◆ Sharedsort

typedef struct Sharedsort Sharedsort

Definition at line 1 of file tuplesort.h.

◆ SortCoordinate

Definition at line 61 of file tuplesort.h.

◆ SortCoordinateData

◆ SortTupleComparator

typedef int(* SortTupleComparator) (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)

Definition at line 155 of file tuplesort.h.

◆ TuplesortInstrumentation

◆ Tuplesortstate

Definition at line 1 of file tuplesort.h.

Enumeration Type Documentation

◆ TuplesortMethod

Enumerator
SORT_TYPE_STILL_IN_PROGRESS 
SORT_TYPE_TOP_N_HEAPSORT 
SORT_TYPE_QUICKSORT 
SORT_TYPE_EXTERNAL_SORT 
SORT_TYPE_EXTERNAL_MERGE 

Definition at line 75 of file tuplesort.h.

76 {
78  SORT_TYPE_TOP_N_HEAPSORT = 1 << 0,
79  SORT_TYPE_QUICKSORT = 1 << 1,
80  SORT_TYPE_EXTERNAL_SORT = 1 << 2,
81  SORT_TYPE_EXTERNAL_MERGE = 1 << 3,
TuplesortMethod
Definition: tuplesort.h:76
@ SORT_TYPE_EXTERNAL_SORT
Definition: tuplesort.h:80
@ SORT_TYPE_TOP_N_HEAPSORT
Definition: tuplesort.h:78
@ SORT_TYPE_QUICKSORT
Definition: tuplesort.h:79
@ SORT_TYPE_STILL_IN_PROGRESS
Definition: tuplesort.h:77
@ SORT_TYPE_EXTERNAL_MERGE
Definition: tuplesort.h:81

◆ TuplesortSpaceType

Enumerator
SORT_SPACE_TYPE_DISK 
SORT_SPACE_TYPE_MEMORY 

Definition at line 86 of file tuplesort.h.

87 {
TuplesortSpaceType
Definition: tuplesort.h:87
@ SORT_SPACE_TYPE_DISK
Definition: tuplesort.h:88
@ SORT_SPACE_TYPE_MEMORY
Definition: tuplesort.h:89

Function Documentation

◆ tuplesort_attach_shared()

void tuplesort_attach_shared ( Sharedsort shared,
dsm_segment seg 
)

Definition at line 3000 of file tuplesort.c.

3001 {
3002  /* Attach to SharedFileSet */
3003  SharedFileSetAttach(&shared->fileset, seg);
3004 }
void SharedFileSetAttach(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:56
SharedFileSet fileset
Definition: tuplesort.c:364

References Sharedsort::fileset, and SharedFileSetAttach().

Referenced by _brin_parallel_build_main(), and _bt_parallel_build_main().

◆ tuplesort_begin_cluster()

Tuplesortstate* tuplesort_begin_cluster ( TupleDesc  tupDesc,
Relation  indexRel,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 243 of file tuplesortvariants.c.

247 {
248  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
249  sortopt);
251  BTScanInsert indexScanKey;
252  MemoryContext oldcontext;
254  int i;
255 
256  Assert(indexRel->rd_rel->relam == BTREE_AM_OID);
257 
258  oldcontext = MemoryContextSwitchTo(base->maincontext);
260 
261 #ifdef TRACE_SORT
262  if (trace_sort)
263  elog(LOG,
264  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
266  workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
267 #endif
268 
270 
271  TRACE_POSTGRESQL_SORT_START(CLUSTER_SORT,
272  false, /* no unique check */
273  base->nKeys,
274  workMem,
275  sortopt & TUPLESORT_RANDOMACCESS,
276  PARALLEL_SORT(coordinate));
277 
281  base->writetup = writetup_cluster;
282  base->readtup = readtup_cluster;
284  base->arg = arg;
285 
286  arg->indexInfo = BuildIndexInfo(indexRel);
287 
288  /*
289  * If we don't have a simple leading attribute, we don't currently
290  * initialize datum1, so disable optimizations that require it.
291  */
292  if (arg->indexInfo->ii_IndexAttrNumbers[0] == 0)
293  base->haveDatum1 = false;
294  else
295  base->haveDatum1 = true;
296 
297  arg->tupDesc = tupDesc; /* assume we need not copy tupDesc */
298 
299  indexScanKey = _bt_mkscankey(indexRel, NULL);
300 
301  if (arg->indexInfo->ii_Expressions != NULL)
302  {
303  TupleTableSlot *slot;
304  ExprContext *econtext;
305 
306  /*
307  * We will need to use FormIndexDatum to evaluate the index
308  * expressions. To do that, we need an EState, as well as a
309  * TupleTableSlot to put the table tuples into. The econtext's
310  * scantuple has to point to that slot, too.
311  */
312  arg->estate = CreateExecutorState();
313  slot = MakeSingleTupleTableSlot(tupDesc, &TTSOpsHeapTuple);
314  econtext = GetPerTupleExprContext(arg->estate);
315  econtext->ecxt_scantuple = slot;
316  }
317 
318  /* Prepare SortSupport data for each column */
319  base->sortKeys = (SortSupport) palloc0(base->nKeys *
320  sizeof(SortSupportData));
321 
322  for (i = 0; i < base->nKeys; i++)
323  {
324  SortSupport sortKey = base->sortKeys + i;
325  ScanKey scanKey = indexScanKey->scankeys + i;
326  int16 strategy;
327 
328  sortKey->ssup_cxt = CurrentMemoryContext;
329  sortKey->ssup_collation = scanKey->sk_collation;
330  sortKey->ssup_nulls_first =
331  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
332  sortKey->ssup_attno = scanKey->sk_attno;
333  /* Convey if abbreviation optimization is applicable in principle */
334  sortKey->abbreviate = (i == 0 && base->haveDatum1);
335 
336  Assert(sortKey->ssup_attno != 0);
337 
338  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
340 
341  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
342  }
343 
344  pfree(indexScanKey);
345 
346  MemoryContextSwitchTo(oldcontext);
347 
348  return state;
349 }
signed short int16
Definition: c.h:493
#define Assert(condition)
Definition: c.h:858
#define LOG
Definition: elog.h:31
#define elog(elevel,...)
Definition: elog.h:224
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1325
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:550
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2404
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc0(Size size)
Definition: mcxt.c:1347
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1128
#define SK_BT_DESC
Definition: nbtree.h:1127
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:129
void * arg
MemoryContextSwitchTo(old_ctx)
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:511
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:524
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:161
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define BTLessStrategyNumber
Definition: stratnum.h:29
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:793
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:255
Form_pg_class rd_rel
Definition: rel.h:111
int sk_flags
Definition: skey.h:66
Oid sk_collation
Definition: skey.h:70
AttrNumber sk_attno
Definition: skey.h:67
AttrNumber ssup_attno
Definition: sortsupport.h:81
bool ssup_nulls_first
Definition: sortsupport.h:75
MemoryContext ssup_cxt
Definition: sortsupport.h:66
MemoryContext maincontext
Definition: tuplesort.h:218
void(* writetup)(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
Definition: tuplesort.h:194
void(* removeabbrev)(Tuplesortstate *state, SortTuple *stups, int count)
Definition: tuplesort.h:187
void(* freestate)(Tuplesortstate *state)
Definition: tuplesort.h:212
void(* readtup)(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
Definition: tuplesort.h:203
SortTupleComparator comparetup
Definition: tuplesort.h:174
SortSupport sortKeys
Definition: tuplesort.h:235
SortTupleComparator comparetup_tiebreak
Definition: tuplesort.h:181
Definition: regguts.h:323
Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, int sortopt)
Definition: tuplesort.c:646
bool trace_sort
Definition: tuplesort.c:125
#define PARALLEL_SORT(coordinate)
Definition: tuplesort.h:255
#define TUPLESORT_RANDOMACCESS
Definition: tuplesort.h:96
#define TuplesortstateGetPublic(state)
Definition: tuplesort.h:259
static int comparetup_cluster_tiebreak(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void readtup_cluster(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int tuplen)
#define CLUSTER_SORT
static void freestate_cluster(Tuplesortstate *state)
static int comparetup_cluster(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void writetup_cluster(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
static void removeabbrev_cluster(Tuplesortstate *state, SortTuple *stups, int count)

References _bt_mkscankey(), SortSupportData::abbreviate, arg, TuplesortPublic::arg, Assert, BTGreaterStrategyNumber, BTLessStrategyNumber, BuildIndexInfo(), CLUSTER_SORT, TuplesortPublic::comparetup, comparetup_cluster(), comparetup_cluster_tiebreak(), TuplesortPublic::comparetup_tiebreak, CreateExecutorState(), CurrentMemoryContext, ExprContext::ecxt_scantuple, elog, TuplesortPublic::freestate, freestate_cluster(), GetPerTupleExprContext, TuplesortPublic::haveDatum1, i, IndexRelationGetNumberOfKeyAttributes, LOG, TuplesortPublic::maincontext, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), TuplesortPublic::nKeys, palloc0(), PARALLEL_SORT, pfree(), PrepareSortSupportFromIndexRel(), RelationData::rd_rel, TuplesortPublic::readtup, readtup_cluster(), RelationGetNumberOfAttributes, TuplesortPublic::removeabbrev, removeabbrev_cluster(), BTScanInsertData::scankeys, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, TuplesortPublic::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, TTSOpsHeapTuple, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_cluster().

Referenced by heapam_relation_copy_for_cluster().

◆ tuplesort_begin_common()

Tuplesortstate* tuplesort_begin_common ( int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 646 of file tuplesort.c.

647 {
649  MemoryContext maincontext;
650  MemoryContext sortcontext;
651  MemoryContext oldcontext;
652 
653  /* See leader_takeover_tapes() remarks on random access support */
654  if (coordinate && (sortopt & TUPLESORT_RANDOMACCESS))
655  elog(ERROR, "random access disallowed under parallel sort");
656 
657  /*
658  * Memory context surviving tuplesort_reset. This memory context holds
659  * data which is useful to keep while sorting multiple similar batches.
660  */
662  "TupleSort main",
664 
665  /*
666  * Create a working memory context for one sort operation. The content of
667  * this context is deleted by tuplesort_reset.
668  */
669  sortcontext = AllocSetContextCreate(maincontext,
670  "TupleSort sort",
672 
673  /*
674  * Additionally a working memory context for tuples is setup in
675  * tuplesort_begin_batch.
676  */
677 
678  /*
679  * Make the Tuplesortstate within the per-sortstate context. This way, we
680  * don't need a separate pfree() operation for it at shutdown.
681  */
682  oldcontext = MemoryContextSwitchTo(maincontext);
683 
685 
686 #ifdef TRACE_SORT
687  if (trace_sort)
688  pg_rusage_init(&state->ru_start);
689 #endif
690 
691  state->base.sortopt = sortopt;
692  state->base.tuples = true;
693  state->abbrevNext = 10;
694 
695  /*
696  * workMem is forced to be at least 64KB, the current minimum valid value
697  * for the work_mem GUC. This is a defense against parallel sort callers
698  * that divide out memory among many workers in a way that leaves each
699  * with very little memory.
700  */
701  state->allowedMem = Max(workMem, 64) * (int64) 1024;
702  state->base.sortcontext = sortcontext;
703  state->base.maincontext = maincontext;
704 
705  /*
706  * Initial size of array must be more than ALLOCSET_SEPARATE_THRESHOLD;
707  * see comments in grow_memtuples().
708  */
709  state->memtupsize = INITIAL_MEMTUPSIZE;
710  state->memtuples = NULL;
711 
712  /*
713  * After all of the other non-parallel-related state, we setup all of the
714  * state needed for each batch.
715  */
717 
718  /*
719  * Initialize parallel-related state based on coordination information
720  * from caller
721  */
722  if (!coordinate)
723  {
724  /* Serial sort */
725  state->shared = NULL;
726  state->worker = -1;
727  state->nParticipants = -1;
728  }
729  else if (coordinate->isWorker)
730  {
731  /* Parallel worker produces exactly one final run from all input */
732  state->shared = coordinate->sharedsort;
733  state->worker = worker_get_identifier(state);
734  state->nParticipants = -1;
735  }
736  else
737  {
738  /* Parallel leader state only used for final merge */
739  state->shared = coordinate->sharedsort;
740  state->worker = -1;
741  state->nParticipants = coordinate->nParticipants;
742  Assert(state->nParticipants >= 1);
743  }
744 
745  MemoryContextSwitchTo(oldcontext);
746 
747  return state;
748 }
#define Max(x, y)
Definition: c.h:998
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
Sharedsort * sharedsort
Definition: tuplesort.h:58
#define INITIAL_MEMTUPSIZE
Definition: tuplesort.c:120
static int worker_get_identifier(Tuplesortstate *state)
Definition: tuplesort.c:3020
static void tuplesort_begin_batch(Tuplesortstate *state)
Definition: tuplesort.c:758

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, CurrentMemoryContext, elog, ERROR, INITIAL_MEMTUPSIZE, SortCoordinateData::isWorker, Max, MemoryContextSwitchTo(), SortCoordinateData::nParticipants, palloc0(), pg_rusage_init(), SortCoordinateData::sharedsort, trace_sort, tuplesort_begin_batch(), TUPLESORT_RANDOMACCESS, and worker_get_identifier().

Referenced by tuplesort_begin_cluster(), tuplesort_begin_datum(), tuplesort_begin_heap(), tuplesort_begin_index_brin(), tuplesort_begin_index_btree(), tuplesort_begin_index_gist(), and tuplesort_begin_index_hash().

◆ tuplesort_begin_datum()

Tuplesortstate* tuplesort_begin_datum ( Oid  datumType,
Oid  sortOperator,
Oid  sortCollation,
bool  nullsFirstFlag,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 584 of file tuplesortvariants.c.

587 {
588  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
589  sortopt);
592  MemoryContext oldcontext;
593  int16 typlen;
594  bool typbyval;
595 
596  oldcontext = MemoryContextSwitchTo(base->maincontext);
598 
599 #ifdef TRACE_SORT
600  if (trace_sort)
601  elog(LOG,
602  "begin datum sort: workMem = %d, randomAccess = %c",
603  workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
604 #endif
605 
606  base->nKeys = 1; /* always a one-column sort */
607 
608  TRACE_POSTGRESQL_SORT_START(DATUM_SORT,
609  false, /* no unique check */
610  1,
611  workMem,
612  sortopt & TUPLESORT_RANDOMACCESS,
613  PARALLEL_SORT(coordinate));
614 
618  base->writetup = writetup_datum;
619  base->readtup = readtup_datum;
620  base->haveDatum1 = true;
621  base->arg = arg;
622 
623  arg->datumType = datumType;
624 
625  /* lookup necessary attributes of the datum type */
626  get_typlenbyval(datumType, &typlen, &typbyval);
627  arg->datumTypeLen = typlen;
628  base->tuples = !typbyval;
629 
630  /* Prepare SortSupport data */
631  base->sortKeys = (SortSupport) palloc0(sizeof(SortSupportData));
632 
634  base->sortKeys->ssup_collation = sortCollation;
635  base->sortKeys->ssup_nulls_first = nullsFirstFlag;
636 
637  /*
638  * Abbreviation is possible here only for by-reference types. In theory,
639  * a pass-by-value datatype could have an abbreviated form that is cheaper
640  * to compare. In a tuple sort, we could support that, because we can
641  * always extract the original datum from the tuple as needed. Here, we
642  * can't, because a datum sort only stores a single copy of the datum; the
643  * "tuple" field of each SortTuple is NULL.
644  */
645  base->sortKeys->abbreviate = !typbyval;
646 
647  PrepareSortSupportFromOrderingOp(sortOperator, base->sortKeys);
648 
649  /*
650  * The "onlyKey" optimization cannot be used with abbreviated keys, since
651  * tie-breaker comparisons may be required. Typically, the optimization
652  * is only of value to pass-by-value types anyway, whereas abbreviated
653  * keys are typically only of value to pass-by-reference types.
654  */
655  if (!base->sortKeys->abbrev_converter)
656  base->onlyKey = base->sortKeys;
657 
658  MemoryContextSwitchTo(oldcontext);
659 
660  return state;
661 }
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2251
void * palloc(Size size)
Definition: mcxt.c:1317
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:134
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
SortSupport onlyKey
Definition: tuplesort.h:245
static void removeabbrev_datum(Tuplesortstate *state, SortTuple *stups, int count)
static int comparetup_datum(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static int comparetup_datum_tiebreak(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void readtup_datum(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
static void writetup_datum(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
#define DATUM_SORT

References SortSupportData::abbrev_converter, SortSupportData::abbreviate, arg, TuplesortPublic::arg, TuplesortPublic::comparetup, comparetup_datum(), comparetup_datum_tiebreak(), TuplesortPublic::comparetup_tiebreak, CurrentMemoryContext, DATUM_SORT, elog, get_typlenbyval(), TuplesortPublic::haveDatum1, LOG, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, TuplesortPublic::onlyKey, palloc(), palloc0(), PARALLEL_SORT, PrepareSortSupportFromOrderingOp(), TuplesortPublic::readtup, readtup_datum(), TuplesortPublic::removeabbrev, removeabbrev_datum(), TuplesortPublic::sortKeys, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, TuplesortPublic::tuples, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_datum().

Referenced by ExecSort(), initialize_aggregate(), ordered_set_startup(), and validate_index().

◆ tuplesort_begin_heap()

Tuplesortstate* tuplesort_begin_heap ( TupleDesc  tupDesc,
int  nkeys,
AttrNumber attNums,
Oid sortOperators,
Oid sortCollations,
bool nullsFirstFlags,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 168 of file tuplesortvariants.c.

173 {
174  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
175  sortopt);
177  MemoryContext oldcontext;
178  int i;
179 
180  oldcontext = MemoryContextSwitchTo(base->maincontext);
181 
182  Assert(nkeys > 0);
183 
184 #ifdef TRACE_SORT
185  if (trace_sort)
186  elog(LOG,
187  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
188  nkeys, workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
189 #endif
190 
191  base->nKeys = nkeys;
192 
193  TRACE_POSTGRESQL_SORT_START(HEAP_SORT,
194  false, /* no unique check */
195  nkeys,
196  workMem,
197  sortopt & TUPLESORT_RANDOMACCESS,
198  PARALLEL_SORT(coordinate));
199 
201  base->comparetup = comparetup_heap;
203  base->writetup = writetup_heap;
204  base->readtup = readtup_heap;
205  base->haveDatum1 = true;
206  base->arg = tupDesc; /* assume we need not copy tupDesc */
207 
208  /* Prepare SortSupport data for each column */
209  base->sortKeys = (SortSupport) palloc0(nkeys * sizeof(SortSupportData));
210 
211  for (i = 0; i < nkeys; i++)
212  {
213  SortSupport sortKey = base->sortKeys + i;
214 
215  Assert(attNums[i] != 0);
216  Assert(sortOperators[i] != 0);
217 
218  sortKey->ssup_cxt = CurrentMemoryContext;
219  sortKey->ssup_collation = sortCollations[i];
220  sortKey->ssup_nulls_first = nullsFirstFlags[i];
221  sortKey->ssup_attno = attNums[i];
222  /* Convey if abbreviation optimization is applicable in principle */
223  sortKey->abbreviate = (i == 0 && base->haveDatum1);
224 
225  PrepareSortSupportFromOrderingOp(sortOperators[i], sortKey);
226  }
227 
228  /*
229  * The "onlyKey" optimization cannot be used with abbreviated keys, since
230  * tie-breaker comparisons may be required. Typically, the optimization
231  * is only of value to pass-by-value types anyway, whereas abbreviated
232  * keys are typically only of value to pass-by-reference types.
233  */
234  if (nkeys == 1 && !base->sortKeys->abbrev_converter)
235  base->onlyKey = base->sortKeys;
236 
237  MemoryContextSwitchTo(oldcontext);
238 
239  return state;
240 }
static void readtup_heap(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
static int comparetup_heap(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void writetup_heap(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
static int comparetup_heap_tiebreak(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void removeabbrev_heap(Tuplesortstate *state, SortTuple *stups, int count)
#define HEAP_SORT

References SortSupportData::abbrev_converter, SortSupportData::abbreviate, TuplesortPublic::arg, Assert, TuplesortPublic::comparetup, comparetup_heap(), comparetup_heap_tiebreak(), TuplesortPublic::comparetup_tiebreak, CurrentMemoryContext, elog, TuplesortPublic::haveDatum1, HEAP_SORT, i, LOG, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, TuplesortPublic::onlyKey, palloc0(), PARALLEL_SORT, PrepareSortSupportFromOrderingOp(), TuplesortPublic::readtup, readtup_heap(), TuplesortPublic::removeabbrev, removeabbrev_heap(), TuplesortPublic::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_heap().

Referenced by ExecIncrementalSort(), ExecSort(), initialize_aggregate(), initialize_phase(), ordered_set_startup(), and switchToPresortedPrefixMode().

◆ tuplesort_begin_index_brin()

Tuplesortstate* tuplesort_begin_index_brin ( int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 555 of file tuplesortvariants.c.

558 {
559  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
560  sortopt);
562 
563 #ifdef TRACE_SORT
564  if (trace_sort)
565  elog(LOG,
566  "begin index sort: workMem = %d, randomAccess = %c",
567  workMem,
568  sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
569 #endif
570 
571  base->nKeys = 1; /* Only one sort column, the block number */
572 
576  base->readtup = readtup_index_brin;
577  base->haveDatum1 = true;
578  base->arg = NULL;
579 
580  return state;
581 }
static void writetup_index_brin(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
static void removeabbrev_index_brin(Tuplesortstate *state, SortTuple *stups, int count)
static void readtup_index_brin(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
static int comparetup_index_brin(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)

References TuplesortPublic::arg, TuplesortPublic::comparetup, comparetup_index_brin(), elog, TuplesortPublic::haveDatum1, LOG, TuplesortPublic::nKeys, TuplesortPublic::readtup, readtup_index_brin(), TuplesortPublic::removeabbrev, removeabbrev_index_brin(), trace_sort, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_index_brin().

Referenced by _brin_parallel_scan_and_build(), and brinbuild().

◆ tuplesort_begin_index_btree()

Tuplesortstate* tuplesort_begin_index_btree ( Relation  heapRel,
Relation  indexRel,
bool  enforceUnique,
bool  uniqueNullsNotDistinct,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 352 of file tuplesortvariants.c.

359 {
360  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
361  sortopt);
363  BTScanInsert indexScanKey;
365  MemoryContext oldcontext;
366  int i;
367 
368  oldcontext = MemoryContextSwitchTo(base->maincontext);
370 
371 #ifdef TRACE_SORT
372  if (trace_sort)
373  elog(LOG,
374  "begin index sort: unique = %c, workMem = %d, randomAccess = %c",
375  enforceUnique ? 't' : 'f',
376  workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
377 #endif
378 
380 
381  TRACE_POSTGRESQL_SORT_START(INDEX_SORT,
382  enforceUnique,
383  base->nKeys,
384  workMem,
385  sortopt & TUPLESORT_RANDOMACCESS,
386  PARALLEL_SORT(coordinate));
387 
391  base->writetup = writetup_index;
392  base->readtup = readtup_index;
393  base->haveDatum1 = true;
394  base->arg = arg;
395 
396  arg->index.heapRel = heapRel;
397  arg->index.indexRel = indexRel;
398  arg->enforceUnique = enforceUnique;
399  arg->uniqueNullsNotDistinct = uniqueNullsNotDistinct;
400 
401  indexScanKey = _bt_mkscankey(indexRel, NULL);
402 
403  /* Prepare SortSupport data for each column */
404  base->sortKeys = (SortSupport) palloc0(base->nKeys *
405  sizeof(SortSupportData));
406 
407  for (i = 0; i < base->nKeys; i++)
408  {
409  SortSupport sortKey = base->sortKeys + i;
410  ScanKey scanKey = indexScanKey->scankeys + i;
411  int16 strategy;
412 
413  sortKey->ssup_cxt = CurrentMemoryContext;
414  sortKey->ssup_collation = scanKey->sk_collation;
415  sortKey->ssup_nulls_first =
416  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
417  sortKey->ssup_attno = scanKey->sk_attno;
418  /* Convey if abbreviation optimization is applicable in principle */
419  sortKey->abbreviate = (i == 0 && base->haveDatum1);
420 
421  Assert(sortKey->ssup_attno != 0);
422 
423  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
425 
426  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
427  }
428 
429  pfree(indexScanKey);
430 
431  MemoryContextSwitchTo(oldcontext);
432 
433  return state;
434 }
static int comparetup_index_btree_tiebreak(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static int comparetup_index_btree(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static void readtup_index(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
static void removeabbrev_index(Tuplesortstate *state, SortTuple *stups, int count)
#define INDEX_SORT
static void writetup_index(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)

References _bt_mkscankey(), SortSupportData::abbreviate, arg, TuplesortPublic::arg, Assert, BTGreaterStrategyNumber, BTLessStrategyNumber, TuplesortPublic::comparetup, comparetup_index_btree(), comparetup_index_btree_tiebreak(), TuplesortPublic::comparetup_tiebreak, CurrentMemoryContext, elog, TuplesortPublic::haveDatum1, i, INDEX_SORT, IndexRelationGetNumberOfKeyAttributes, LOG, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, palloc(), palloc0(), PARALLEL_SORT, pfree(), PrepareSortSupportFromIndexRel(), TuplesortPublic::readtup, readtup_index(), TuplesortPublic::removeabbrev, removeabbrev_index(), BTScanInsertData::scankeys, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, TuplesortPublic::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_index().

Referenced by _bt_parallel_scan_and_sort(), and _bt_spools_heapscan().

◆ tuplesort_begin_index_gist()

Tuplesortstate* tuplesort_begin_index_gist ( Relation  heapRel,
Relation  indexRel,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 490 of file tuplesortvariants.c.

495 {
496  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
497  sortopt);
499  MemoryContext oldcontext;
501  int i;
502 
503  oldcontext = MemoryContextSwitchTo(base->maincontext);
505 
506 #ifdef TRACE_SORT
507  if (trace_sort)
508  elog(LOG,
509  "begin index sort: workMem = %d, randomAccess = %c",
510  workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
511 #endif
512 
514 
518  base->writetup = writetup_index;
519  base->readtup = readtup_index;
520  base->haveDatum1 = true;
521  base->arg = arg;
522 
523  arg->index.heapRel = heapRel;
524  arg->index.indexRel = indexRel;
525  arg->enforceUnique = false;
526  arg->uniqueNullsNotDistinct = false;
527 
528  /* Prepare SortSupport data for each column */
529  base->sortKeys = (SortSupport) palloc0(base->nKeys *
530  sizeof(SortSupportData));
531 
532  for (i = 0; i < base->nKeys; i++)
533  {
534  SortSupport sortKey = base->sortKeys + i;
535 
536  sortKey->ssup_cxt = CurrentMemoryContext;
537  sortKey->ssup_collation = indexRel->rd_indcollation[i];
538  sortKey->ssup_nulls_first = false;
539  sortKey->ssup_attno = i + 1;
540  /* Convey if abbreviation optimization is applicable in principle */
541  sortKey->abbreviate = (i == 0 && base->haveDatum1);
542 
543  Assert(sortKey->ssup_attno != 0);
544 
545  /* Look for a sort support function */
546  PrepareSortSupportFromGistIndexRel(indexRel, sortKey);
547  }
548 
549  MemoryContextSwitchTo(oldcontext);
550 
551  return state;
552 }
void PrepareSortSupportFromGistIndexRel(Relation indexRel, SortSupport ssup)
Definition: sortsupport.c:188
Oid * rd_indcollation
Definition: rel.h:217

References SortSupportData::abbreviate, arg, TuplesortPublic::arg, Assert, TuplesortPublic::comparetup, comparetup_index_btree(), comparetup_index_btree_tiebreak(), TuplesortPublic::comparetup_tiebreak, CurrentMemoryContext, elog, TuplesortPublic::haveDatum1, i, IndexRelationGetNumberOfKeyAttributes, LOG, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, palloc(), palloc0(), PrepareSortSupportFromGistIndexRel(), RelationData::rd_indcollation, TuplesortPublic::readtup, readtup_index(), TuplesortPublic::removeabbrev, removeabbrev_index(), TuplesortPublic::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_index().

Referenced by gistbuild().

◆ tuplesort_begin_index_hash()

Tuplesortstate* tuplesort_begin_index_hash ( Relation  heapRel,
Relation  indexRel,
uint32  high_mask,
uint32  low_mask,
uint32  max_buckets,
int  workMem,
SortCoordinate  coordinate,
int  sortopt 
)

Definition at line 437 of file tuplesortvariants.c.

445 {
446  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
447  sortopt);
449  MemoryContext oldcontext;
451 
452  oldcontext = MemoryContextSwitchTo(base->maincontext);
454 
455 #ifdef TRACE_SORT
456  if (trace_sort)
457  elog(LOG,
458  "begin index sort: high_mask = 0x%x, low_mask = 0x%x, "
459  "max_buckets = 0x%x, workMem = %d, randomAccess = %c",
460  high_mask,
461  low_mask,
462  max_buckets,
463  workMem,
464  sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
465 #endif
466 
467  base->nKeys = 1; /* Only one sort column, the hash code */
468 
472  base->writetup = writetup_index;
473  base->readtup = readtup_index;
474  base->haveDatum1 = true;
475  base->arg = arg;
476 
477  arg->index.heapRel = heapRel;
478  arg->index.indexRel = indexRel;
479 
480  arg->high_mask = high_mask;
481  arg->low_mask = low_mask;
482  arg->max_buckets = max_buckets;
483 
484  MemoryContextSwitchTo(oldcontext);
485 
486  return state;
487 }
static int comparetup_index_hash(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
static int comparetup_index_hash_tiebreak(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)

References arg, TuplesortPublic::arg, TuplesortPublic::comparetup, comparetup_index_hash(), comparetup_index_hash_tiebreak(), TuplesortPublic::comparetup_tiebreak, elog, TuplesortPublic::haveDatum1, LOG, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, palloc(), TuplesortPublic::readtup, readtup_index(), TuplesortPublic::removeabbrev, removeabbrev_index(), trace_sort, tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TuplesortPublic::writetup, and writetup_index().

Referenced by _h_spoolinit().

◆ tuplesort_end()

void tuplesort_end ( Tuplesortstate state)

Definition at line 972 of file tuplesort.c.

973 {
975 
976  /*
977  * Free the main memory context, including the Tuplesortstate struct
978  * itself.
979  */
980  MemoryContextDelete(state->base.maincontext);
981 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
static void tuplesort_free(Tuplesortstate *state)
Definition: tuplesort.c:903

References MemoryContextDelete(), and tuplesort_free().

Referenced by _brin_parallel_merge(), _brin_parallel_scan_and_build(), _bt_parallel_scan_and_sort(), _bt_spooldestroy(), _h_spooldestroy(), ExecEndAgg(), ExecEndIncrementalSort(), ExecEndSort(), ExecReScanAgg(), ExecReScanSort(), gistbuild(), heapam_relation_copy_for_cluster(), initialize_aggregate(), initialize_phase(), ordered_set_shutdown(), process_ordered_aggregate_multi(), process_ordered_aggregate_single(), and validate_index().

◆ tuplesort_estimate_shared()

Size tuplesort_estimate_shared ( int  nWorkers)

Definition at line 2956 of file tuplesort.c.

2957 {
2958  Size tapesSize;
2959 
2960  Assert(nWorkers > 0);
2961 
2962  /* Make sure that BufFile shared state is MAXALIGN'd */
2963  tapesSize = mul_size(sizeof(TapeShare), nWorkers);
2964  tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
2965 
2966  return tapesSize;
2967 }
#define MAXALIGN(LEN)
Definition: c.h:811
size_t Size
Definition: c.h:605
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510

References add_size(), Assert, MAXALIGN, and mul_size().

Referenced by _brin_begin_parallel(), and _bt_begin_parallel().

◆ tuplesort_get_stats()

void tuplesort_get_stats ( Tuplesortstate state,
TuplesortInstrumentation stats 
)

Definition at line 2538 of file tuplesort.c.

2540 {
2541  /*
2542  * Note: it might seem we should provide both memory and disk usage for a
2543  * disk-based sort. However, the current code doesn't track memory space
2544  * accurately once we have begun to return tuples to the caller (since we
2545  * don't account for pfree's the caller is expected to do), so we cannot
2546  * rely on availMem in a disk sort. This does not seem worth the overhead
2547  * to fix. Is it worth creating an API for the memory context code to
2548  * tell us how much is actually used in sortcontext?
2549  */
2551 
2552  if (state->isMaxSpaceDisk)
2554  else
2556  stats->spaceUsed = (state->maxSpace + 1023) / 1024;
2557 
2558  switch (state->maxSpaceStatus)
2559  {
2560  case TSS_SORTEDINMEM:
2561  if (state->boundUsed)
2563  else
2565  break;
2566  case TSS_SORTEDONTAPE:
2568  break;
2569  case TSS_FINALMERGE:
2571  break;
2572  default:
2574  break;
2575  }
2576 }
TuplesortMethod sortMethod
Definition: tuplesort.h:112
TuplesortSpaceType spaceType
Definition: tuplesort.h:113
@ TSS_SORTEDONTAPE
Definition: tuplesort.c:162
@ TSS_SORTEDINMEM
Definition: tuplesort.c:161
@ TSS_FINALMERGE
Definition: tuplesort.c:163
static void tuplesort_updatemax(Tuplesortstate *state)
Definition: tuplesort.c:989

References SORT_SPACE_TYPE_DISK, SORT_SPACE_TYPE_MEMORY, SORT_TYPE_EXTERNAL_MERGE, SORT_TYPE_EXTERNAL_SORT, SORT_TYPE_QUICKSORT, SORT_TYPE_STILL_IN_PROGRESS, SORT_TYPE_TOP_N_HEAPSORT, TuplesortInstrumentation::sortMethod, TuplesortInstrumentation::spaceType, TuplesortInstrumentation::spaceUsed, TSS_FINALMERGE, TSS_SORTEDINMEM, TSS_SORTEDONTAPE, and tuplesort_updatemax().

Referenced by ExecSort(), instrumentSortedGroup(), and show_sort_info().

◆ tuplesort_getbrintuple()

BrinTuple* tuplesort_getbrintuple ( Tuplesortstate state,
Size len,
bool  forward 
)

Definition at line 970 of file tuplesortvariants.c.

971 {
973  MemoryContext oldcontext = MemoryContextSwitchTo(base->sortcontext);
974  SortTuple stup;
975  BrinSortTuple *btup;
976 
977  if (!tuplesort_gettuple_common(state, forward, &stup))
978  stup.tuple = NULL;
979 
980  MemoryContextSwitchTo(oldcontext);
981 
982  if (!stup.tuple)
983  return NULL;
984 
985  btup = (BrinSortTuple *) stup.tuple;
986 
987  *len = btup->tuplen;
988 
989  return &btup->tuple;
990 }
void * tuple
Definition: tuplesort.h:149
MemoryContext sortcontext
Definition: tuplesort.h:220
bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup)
Definition: tuplesort.c:1497

References len, MemoryContextSwitchTo(), TuplesortPublic::sortcontext, BrinSortTuple::tuple, SortTuple::tuple, BrinSortTuple::tuplen, tuplesort_gettuple_common(), and TuplesortstateGetPublic.

Referenced by _brin_parallel_merge().

◆ tuplesort_getdatum()

bool tuplesort_getdatum ( Tuplesortstate state,
bool  forward,
bool  copy,
Datum val,
bool isNull,
Datum abbrev 
)

Definition at line 1018 of file tuplesortvariants.c.

1020 {
1022  MemoryContext oldcontext = MemoryContextSwitchTo(base->sortcontext);
1024  SortTuple stup;
1025 
1026  if (!tuplesort_gettuple_common(state, forward, &stup))
1027  {
1028  MemoryContextSwitchTo(oldcontext);
1029  return false;
1030  }
1031 
1032  /* Ensure we copy into caller's memory context */
1033  MemoryContextSwitchTo(oldcontext);
1034 
1035  /* Record abbreviated key for caller */
1036  if (base->sortKeys->abbrev_converter && abbrev)
1037  *abbrev = stup.datum1;
1038 
1039  if (stup.isnull1 || !base->tuples)
1040  {
1041  *val = stup.datum1;
1042  *isNull = stup.isnull1;
1043  }
1044  else
1045  {
1046  /* use stup.tuple because stup.datum1 may be an abbreviation */
1047  if (copy)
1048  *val = datumCopy(PointerGetDatum(stup.tuple), false,
1049  arg->datumTypeLen);
1050  else
1051  *val = PointerGetDatum(stup.tuple);
1052  *isNull = false;
1053  }
1054 
1055  return true;
1056 }
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
long val
Definition: informix.c:670
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322

References SortSupportData::abbrev_converter, arg, TuplesortPublic::arg, datumCopy(), if(), MemoryContextSwitchTo(), PointerGetDatum(), TuplesortPublic::sortcontext, TuplesortPublic::sortKeys, TuplesortPublic::tuples, tuplesort_gettuple_common(), TuplesortstateGetPublic, and val.

Referenced by ExecSort(), heapam_index_validate_scan(), mode_final(), percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), percentile_disc_multi_final(), and process_ordered_aggregate_single().

◆ tuplesort_getheaptuple()

HeapTuple tuplesort_getheaptuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 928 of file tuplesortvariants.c.

929 {
931  MemoryContext oldcontext = MemoryContextSwitchTo(base->sortcontext);
932  SortTuple stup;
933 
934  if (!tuplesort_gettuple_common(state, forward, &stup))
935  stup.tuple = NULL;
936 
937  MemoryContextSwitchTo(oldcontext);
938 
939  return stup.tuple;
940 }

References MemoryContextSwitchTo(), TuplesortPublic::sortcontext, SortTuple::tuple, tuplesort_gettuple_common(), and TuplesortstateGetPublic.

Referenced by heapam_relation_copy_for_cluster().

◆ tuplesort_getindextuple()

IndexTuple tuplesort_getindextuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 949 of file tuplesortvariants.c.

950 {
952  MemoryContext oldcontext = MemoryContextSwitchTo(base->sortcontext);
953  SortTuple stup;
954 
955  if (!tuplesort_gettuple_common(state, forward, &stup))
956  stup.tuple = NULL;
957 
958  MemoryContextSwitchTo(oldcontext);
959 
960  return (IndexTuple) stup.tuple;
961 }

References MemoryContextSwitchTo(), TuplesortPublic::sortcontext, SortTuple::tuple, tuplesort_gettuple_common(), and TuplesortstateGetPublic.

Referenced by _bt_load(), _h_indexbuild(), and gist_indexsortbuild().

◆ tuplesort_gettuple_common()

bool tuplesort_gettuple_common ( Tuplesortstate state,
bool  forward,
SortTuple stup 
)

Definition at line 1497 of file tuplesort.c.

1499 {
1500  unsigned int tuplen;
1501  size_t nmoved;
1502 
1503  Assert(!WORKER(state));
1504 
1505  switch (state->status)
1506  {
1507  case TSS_SORTEDINMEM:
1508  Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
1509  Assert(!state->slabAllocatorUsed);
1510  if (forward)
1511  {
1512  if (state->current < state->memtupcount)
1513  {
1514  *stup = state->memtuples[state->current++];
1515  return true;
1516  }
1517  state->eof_reached = true;
1518 
1519  /*
1520  * Complain if caller tries to retrieve more tuples than
1521  * originally asked for in a bounded sort. This is because
1522  * returning EOF here might be the wrong thing.
1523  */
1524  if (state->bounded && state->current >= state->bound)
1525  elog(ERROR, "retrieved too many tuples in a bounded sort");
1526 
1527  return false;
1528  }
1529  else
1530  {
1531  if (state->current <= 0)
1532  return false;
1533 
1534  /*
1535  * if all tuples are fetched already then we return last
1536  * tuple, else - tuple before last returned.
1537  */
1538  if (state->eof_reached)
1539  state->eof_reached = false;
1540  else
1541  {
1542  state->current--; /* last returned tuple */
1543  if (state->current <= 0)
1544  return false;
1545  }
1546  *stup = state->memtuples[state->current - 1];
1547  return true;
1548  }
1549  break;
1550 
1551  case TSS_SORTEDONTAPE:
1552  Assert(forward || state->base.sortopt & TUPLESORT_RANDOMACCESS);
1553  Assert(state->slabAllocatorUsed);
1554 
1555  /*
1556  * The slot that held the tuple that we returned in previous
1557  * gettuple call can now be reused.
1558  */
1559  if (state->lastReturnedTuple)
1560  {
1561  RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
1562  state->lastReturnedTuple = NULL;
1563  }
1564 
1565  if (forward)
1566  {
1567  if (state->eof_reached)
1568  return false;
1569 
1570  if ((tuplen = getlen(state->result_tape, true)) != 0)
1571  {
1572  READTUP(state, stup, state->result_tape, tuplen);
1573 
1574  /*
1575  * Remember the tuple we return, so that we can recycle
1576  * its memory on next call. (This can be NULL, in the
1577  * !state->tuples case).
1578  */
1579  state->lastReturnedTuple = stup->tuple;
1580 
1581  return true;
1582  }
1583  else
1584  {
1585  state->eof_reached = true;
1586  return false;
1587  }
1588  }
1589 
1590  /*
1591  * Backward.
1592  *
1593  * if all tuples are fetched already then we return last tuple,
1594  * else - tuple before last returned.
1595  */
1596  if (state->eof_reached)
1597  {
1598  /*
1599  * Seek position is pointing just past the zero tuplen at the
1600  * end of file; back up to fetch last tuple's ending length
1601  * word. If seek fails we must have a completely empty file.
1602  */
1603  nmoved = LogicalTapeBackspace(state->result_tape,
1604  2 * sizeof(unsigned int));
1605  if (nmoved == 0)
1606  return false;
1607  else if (nmoved != 2 * sizeof(unsigned int))
1608  elog(ERROR, "unexpected tape position");
1609  state->eof_reached = false;
1610  }
1611  else
1612  {
1613  /*
1614  * Back up and fetch previously-returned tuple's ending length
1615  * word. If seek fails, assume we are at start of file.
1616  */
1617  nmoved = LogicalTapeBackspace(state->result_tape,
1618  sizeof(unsigned int));
1619  if (nmoved == 0)
1620  return false;
1621  else if (nmoved != sizeof(unsigned int))
1622  elog(ERROR, "unexpected tape position");
1623  tuplen = getlen(state->result_tape, false);
1624 
1625  /*
1626  * Back up to get ending length word of tuple before it.
1627  */
1628  nmoved = LogicalTapeBackspace(state->result_tape,
1629  tuplen + 2 * sizeof(unsigned int));
1630  if (nmoved == tuplen + sizeof(unsigned int))
1631  {
1632  /*
1633  * We backed up over the previous tuple, but there was no
1634  * ending length word before it. That means that the prev
1635  * tuple is the first tuple in the file. It is now the
1636  * next to read in forward direction (not obviously right,
1637  * but that is what in-memory case does).
1638  */
1639  return false;
1640  }
1641  else if (nmoved != tuplen + 2 * sizeof(unsigned int))
1642  elog(ERROR, "bogus tuple length in backward scan");
1643  }
1644 
1645  tuplen = getlen(state->result_tape, false);
1646 
1647  /*
1648  * Now we have the length of the prior tuple, back up and read it.
1649  * Note: READTUP expects we are positioned after the initial
1650  * length word of the tuple, so back up to that point.
1651  */
1652  nmoved = LogicalTapeBackspace(state->result_tape,
1653  tuplen);
1654  if (nmoved != tuplen)
1655  elog(ERROR, "bogus tuple length in backward scan");
1656  READTUP(state, stup, state->result_tape, tuplen);
1657 
1658  /*
1659  * Remember the tuple we return, so that we can recycle its memory
1660  * on next call. (This can be NULL, in the Datum case).
1661  */
1662  state->lastReturnedTuple = stup->tuple;
1663 
1664  return true;
1665 
1666  case TSS_FINALMERGE:
1667  Assert(forward);
1668  /* We are managing memory ourselves, with the slab allocator. */
1669  Assert(state->slabAllocatorUsed);
1670 
1671  /*
1672  * The slab slot holding the tuple that we returned in previous
1673  * gettuple call can now be reused.
1674  */
1675  if (state->lastReturnedTuple)
1676  {
1677  RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
1678  state->lastReturnedTuple = NULL;
1679  }
1680 
1681  /*
1682  * This code should match the inner loop of mergeonerun().
1683  */
1684  if (state->memtupcount > 0)
1685  {
1686  int srcTapeIndex = state->memtuples[0].srctape;
1687  LogicalTape *srcTape = state->inputTapes[srcTapeIndex];
1688  SortTuple newtup;
1689 
1690  *stup = state->memtuples[0];
1691 
1692  /*
1693  * Remember the tuple we return, so that we can recycle its
1694  * memory on next call. (This can be NULL, in the Datum case).
1695  */
1696  state->lastReturnedTuple = stup->tuple;
1697 
1698  /*
1699  * Pull next tuple from tape, and replace the returned tuple
1700  * at top of the heap with it.
1701  */
1702  if (!mergereadnext(state, srcTape, &newtup))
1703  {
1704  /*
1705  * If no more data, we've reached end of run on this tape.
1706  * Remove the top node from the heap.
1707  */
1709  state->nInputRuns--;
1710 
1711  /*
1712  * Close the tape. It'd go away at the end of the sort
1713  * anyway, but better to release the memory early.
1714  */
1715  LogicalTapeClose(srcTape);
1716  return true;
1717  }
1718  newtup.srctape = srcTapeIndex;
1720  return true;
1721  }
1722  return false;
1723 
1724  default:
1725  elog(ERROR, "invalid tuplesort state");
1726  return false; /* keep compiler quiet */
1727  }
1728 }
size_t LogicalTapeBackspace(LogicalTape *lt, size_t size)
Definition: logtape.c:1062
void LogicalTapeClose(LogicalTape *lt)
Definition: logtape.c:733
int srctape
Definition: tuplesort.h:152
static void tuplesort_heap_delete_top(Tuplesortstate *state)
Definition: tuplesort.c:2813
static unsigned int getlen(LogicalTape *tape, bool eofOK)
Definition: tuplesort.c:2895
#define READTUP(state, stup, tape, len)
Definition: tuplesort.c:402
#define WORKER(state)
Definition: tuplesort.c:408
static bool mergereadnext(Tuplesortstate *state, LogicalTape *srcTape, SortTuple *stup)
Definition: tuplesort.c:2321
#define RELEASE_SLAB_SLOT(state, tuple)
Definition: tuplesort.c:387
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:2837

References Assert, elog, ERROR, getlen(), LogicalTapeBackspace(), LogicalTapeClose(), mergereadnext(), READTUP, RELEASE_SLAB_SLOT, SortTuple::srctape, TSS_FINALMERGE, TSS_SORTEDINMEM, TSS_SORTEDONTAPE, SortTuple::tuple, tuplesort_heap_delete_top(), tuplesort_heap_replace_top(), TUPLESORT_RANDOMACCESS, and WORKER.

Referenced by tuplesort_getbrintuple(), tuplesort_getdatum(), tuplesort_getheaptuple(), tuplesort_getindextuple(), tuplesort_gettupleslot(), and tuplesort_skiptuples().

◆ tuplesort_gettupleslot()

bool tuplesort_gettupleslot ( Tuplesortstate state,
bool  forward,
bool  copy,
TupleTableSlot slot,
Datum abbrev 
)

Definition at line 890 of file tuplesortvariants.c.

892 {
894  MemoryContext oldcontext = MemoryContextSwitchTo(base->sortcontext);
895  SortTuple stup;
896 
897  if (!tuplesort_gettuple_common(state, forward, &stup))
898  stup.tuple = NULL;
899 
900  MemoryContextSwitchTo(oldcontext);
901 
902  if (stup.tuple)
903  {
904  /* Record abbreviated key for caller */
905  if (base->sortKeys->abbrev_converter && abbrev)
906  *abbrev = stup.datum1;
907 
908  if (copy)
910 
911  ExecStoreMinimalTuple((MinimalTuple) stup.tuple, slot, copy);
912  return true;
913  }
914  else
915  {
916  ExecClearTuple(slot);
917  return false;
918  }
919 }
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1533
MinimalTuple heap_copy_minimal_tuple(MinimalTuple mtup)
Definition: heaptuple.c:1535
Datum datum1
Definition: tuplesort.h:150
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454

References SortSupportData::abbrev_converter, SortTuple::datum1, ExecClearTuple(), ExecStoreMinimalTuple(), heap_copy_minimal_tuple(), MemoryContextSwitchTo(), TuplesortPublic::sortcontext, TuplesortPublic::sortKeys, SortTuple::tuple, tuplesort_gettuple_common(), and TuplesortstateGetPublic.

Referenced by ExecIncrementalSort(), ExecSort(), fetch_input_tuple(), hypothetical_dense_rank_final(), hypothetical_rank_common(), process_ordered_aggregate_multi(), and switchToPresortedPrefixMode().

◆ tuplesort_initialize_shared()

void tuplesort_initialize_shared ( Sharedsort shared,
int  nWorkers,
dsm_segment seg 
)

Definition at line 2977 of file tuplesort.c.

2978 {
2979  int i;
2980 
2981  Assert(nWorkers > 0);
2982 
2983  SpinLockInit(&shared->mutex);
2984  shared->currentWorker = 0;
2985  shared->workersFinished = 0;
2986  SharedFileSetInit(&shared->fileset, seg);
2987  shared->nTapes = nWorkers;
2988  for (i = 0; i < nWorkers; i++)
2989  {
2990  shared->tapes[i].firstblocknumber = 0L;
2991  }
2992 }
void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:38
#define SpinLockInit(lock)
Definition: spin.h:60
TapeShare tapes[FLEXIBLE_ARRAY_MEMBER]
Definition: tuplesort.c:373
int workersFinished
Definition: tuplesort.c:361
int nTapes
Definition: tuplesort.c:367
slock_t mutex
Definition: tuplesort.c:350
int currentWorker
Definition: tuplesort.c:360
int64 firstblocknumber
Definition: logtape.h:54

References Assert, Sharedsort::currentWorker, Sharedsort::fileset, TapeShare::firstblocknumber, i, Sharedsort::mutex, Sharedsort::nTapes, SharedFileSetInit(), SpinLockInit, Sharedsort::tapes, and Sharedsort::workersFinished.

Referenced by _brin_begin_parallel(), and _bt_begin_parallel().

◆ tuplesort_markpos()

void tuplesort_markpos ( Tuplesortstate state)

Definition at line 2474 of file tuplesort.c.

2475 {
2476  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2477 
2478  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2479 
2480  switch (state->status)
2481  {
2482  case TSS_SORTEDINMEM:
2483  state->markpos_offset = state->current;
2484  state->markpos_eof = state->eof_reached;
2485  break;
2486  case TSS_SORTEDONTAPE:
2487  LogicalTapeTell(state->result_tape,
2488  &state->markpos_block,
2489  &state->markpos_offset);
2490  state->markpos_eof = state->eof_reached;
2491  break;
2492  default:
2493  elog(ERROR, "invalid tuplesort state");
2494  break;
2495  }
2496 
2497  MemoryContextSwitchTo(oldcontext);
2498 }
void LogicalTapeTell(LogicalTape *lt, int64 *blocknum, int *offset)
Definition: logtape.c:1162

References Assert, elog, ERROR, LogicalTapeTell(), MemoryContextSwitchTo(), TSS_SORTEDINMEM, TSS_SORTEDONTAPE, and TUPLESORT_RANDOMACCESS.

Referenced by ExecSortMarkPos().

◆ tuplesort_merge_order()

int tuplesort_merge_order ( int64  allowedMem)

Definition at line 1805 of file tuplesort.c.

1806 {
1807  int mOrder;
1808 
1809  /*----------
1810  * In the merge phase, we need buffer space for each input and output tape.
1811  * Each pass in the balanced merge algorithm reads from M input tapes, and
1812  * writes to N output tapes. Each tape consumes TAPE_BUFFER_OVERHEAD bytes
1813  * of memory. In addition to that, we want MERGE_BUFFER_SIZE workspace per
1814  * input tape.
1815  *
1816  * totalMem = M * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE) +
1817  * N * TAPE_BUFFER_OVERHEAD
1818  *
1819  * Except for the last and next-to-last merge passes, where there can be
1820  * fewer tapes left to process, M = N. We choose M so that we have the
1821  * desired amount of memory available for the input buffers
1822  * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE), given the total memory
1823  * available for the tape buffers (allowedMem).
1824  *
1825  * Note: you might be thinking we need to account for the memtuples[]
1826  * array in this calculation, but we effectively treat that as part of the
1827  * MERGE_BUFFER_SIZE workspace.
1828  *----------
1829  */
1830  mOrder = allowedMem /
1832 
1833  /*
1834  * Even in minimum memory, use at least a MINORDER merge. On the other
1835  * hand, even when we have lots of memory, do not use more than a MAXORDER
1836  * merge. Tapes are pretty cheap, but they're not entirely free. Each
1837  * additional tape reduces the amount of memory available to build runs,
1838  * which in turn can cause the same sort to need more runs, which makes
1839  * merging slower even if it can still be done in a single pass. Also,
1840  * high order merges are quite slow due to CPU cache effects; it can be
1841  * faster to pay the I/O cost of a multi-pass merge than to perform a
1842  * single merge pass across many hundreds of tapes.
1843  */
1844  mOrder = Max(mOrder, MINORDER);
1845  mOrder = Min(mOrder, MAXORDER);
1846 
1847  return mOrder;
1848 }
#define Min(x, y)
Definition: c.h:1004
#define TAPE_BUFFER_OVERHEAD
Definition: tuplesort.c:180
#define MAXORDER
Definition: tuplesort.c:179
#define MERGE_BUFFER_SIZE
Definition: tuplesort.c:181
#define MINORDER
Definition: tuplesort.c:178

References Max, MAXORDER, MERGE_BUFFER_SIZE, Min, MINORDER, and TAPE_BUFFER_OVERHEAD.

Referenced by cost_tuplesort(), and inittapes().

◆ tuplesort_method_name()

const char* tuplesort_method_name ( TuplesortMethod  m)

Definition at line 2582 of file tuplesort.c.

2583 {
2584  switch (m)
2585  {
2587  return "still in progress";
2589  return "top-N heapsort";
2590  case SORT_TYPE_QUICKSORT:
2591  return "quicksort";
2593  return "external sort";
2595  return "external merge";
2596  }
2597 
2598  return "unknown";
2599 }

References SORT_TYPE_EXTERNAL_MERGE, SORT_TYPE_EXTERNAL_SORT, SORT_TYPE_QUICKSORT, SORT_TYPE_STILL_IN_PROGRESS, and SORT_TYPE_TOP_N_HEAPSORT.

Referenced by show_incremental_sort_group_info(), and show_sort_info().

◆ tuplesort_performsort()

void tuplesort_performsort ( Tuplesortstate state)

Definition at line 1386 of file tuplesort.c.

1387 {
1388  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1389 
1390 #ifdef TRACE_SORT
1391  if (trace_sort)
1392  elog(LOG, "performsort of worker %d starting: %s",
1393  state->worker, pg_rusage_show(&state->ru_start));
1394 #endif
1395 
1396  switch (state->status)
1397  {
1398  case TSS_INITIAL:
1399 
1400  /*
1401  * We were able to accumulate all the tuples within the allowed
1402  * amount of memory, or leader to take over worker tapes
1403  */
1404  if (SERIAL(state))
1405  {
1406  /* Just qsort 'em and we're done */
1408  state->status = TSS_SORTEDINMEM;
1409  }
1410  else if (WORKER(state))
1411  {
1412  /*
1413  * Parallel workers must still dump out tuples to tape. No
1414  * merge is required to produce single output run, though.
1415  */
1416  inittapes(state, false);
1417  dumptuples(state, true);
1419  state->status = TSS_SORTEDONTAPE;
1420  }
1421  else
1422  {
1423  /*
1424  * Leader will take over worker tapes and merge worker runs.
1425  * Note that mergeruns sets the correct state->status.
1426  */
1428  mergeruns(state);
1429  }
1430  state->current = 0;
1431  state->eof_reached = false;
1432  state->markpos_block = 0L;
1433  state->markpos_offset = 0;
1434  state->markpos_eof = false;
1435  break;
1436 
1437  case TSS_BOUNDED:
1438 
1439  /*
1440  * We were able to accumulate all the tuples required for output
1441  * in memory, using a heap to eliminate excess tuples. Now we
1442  * have to transform the heap to a properly-sorted array. Note
1443  * that sort_bounded_heap sets the correct state->status.
1444  */
1446  state->current = 0;
1447  state->eof_reached = false;
1448  state->markpos_offset = 0;
1449  state->markpos_eof = false;
1450  break;
1451 
1452  case TSS_BUILDRUNS:
1453 
1454  /*
1455  * Finish tape-based sort. First, flush all tuples remaining in
1456  * memory out to tape; then merge until we have a single remaining
1457  * run (or, if !randomAccess and !WORKER(), one run per tape).
1458  * Note that mergeruns sets the correct state->status.
1459  */
1460  dumptuples(state, true);
1461  mergeruns(state);
1462  state->eof_reached = false;
1463  state->markpos_block = 0L;
1464  state->markpos_offset = 0;
1465  state->markpos_eof = false;
1466  break;
1467 
1468  default:
1469  elog(ERROR, "invalid tuplesort state");
1470  break;
1471  }
1472 
1473 #ifdef TRACE_SORT
1474  if (trace_sort)
1475  {
1476  if (state->status == TSS_FINALMERGE)
1477  elog(LOG, "performsort of worker %d done (except %d-way final merge): %s",
1478  state->worker, state->nInputTapes,
1479  pg_rusage_show(&state->ru_start));
1480  else
1481  elog(LOG, "performsort of worker %d done: %s",
1482  state->worker, pg_rusage_show(&state->ru_start));
1483  }
1484 #endif
1485 
1486  MemoryContextSwitchTo(oldcontext);
1487 }
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define SERIAL(state)
Definition: tuplesort.c:407
static void sort_bounded_heap(Tuplesortstate *state)
Definition: tuplesort.c:2675
@ TSS_INITIAL
Definition: tuplesort.c:158
@ TSS_BUILDRUNS
Definition: tuplesort.c:160
@ TSS_BOUNDED
Definition: tuplesort.c:159
static void leader_takeover_tapes(Tuplesortstate *state)
Definition: tuplesort.c:3108
static void tuplesort_sort_memtuples(Tuplesortstate *state)
Definition: tuplesort.c:2715
static void inittapes(Tuplesortstate *state, bool mergeruns)
Definition: tuplesort.c:1892
static void worker_nomergeruns(Tuplesortstate *state)
Definition: tuplesort.c:3086
static void mergeruns(Tuplesortstate *state)
Definition: tuplesort.c:2046
static void dumptuples(Tuplesortstate *state, bool alltuples)
Definition: tuplesort.c:2340

References dumptuples(), elog, ERROR, inittapes(), leader_takeover_tapes(), LOG, MemoryContextSwitchTo(), mergeruns(), pg_rusage_show(), SERIAL, sort_bounded_heap(), trace_sort, TSS_BOUNDED, TSS_BUILDRUNS, TSS_FINALMERGE, TSS_INITIAL, TSS_SORTEDINMEM, TSS_SORTEDONTAPE, tuplesort_sort_memtuples(), WORKER, and worker_nomergeruns().

Referenced by _brin_parallel_merge(), _brin_parallel_scan_and_build(), _bt_leafbuild(), _bt_parallel_scan_and_sort(), _h_indexbuild(), ExecIncrementalSort(), ExecSort(), gistbuild(), heapam_relation_copy_for_cluster(), hypothetical_dense_rank_final(), hypothetical_rank_common(), initialize_phase(), mode_final(), percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), percentile_disc_multi_final(), process_ordered_aggregate_multi(), process_ordered_aggregate_single(), switchToPresortedPrefixMode(), and validate_index().

◆ tuplesort_putbrintuple()

void tuplesort_putbrintuple ( Tuplesortstate state,
BrinTuple tuple,
Size  size 
)

Definition at line 788 of file tuplesortvariants.c.

789 {
790  SortTuple stup;
791  BrinSortTuple *bstup;
794  Size tuplen;
795 
796  /* allocate space for the whole BRIN sort tuple */
797  bstup = palloc(BRINSORTTUPLE_SIZE(size));
798 
799  bstup->tuplen = size;
800  memcpy(&bstup->tuple, tuple, size);
801 
802  stup.tuple = bstup;
803  stup.datum1 = tuple->bt_blkno;
804  stup.isnull1 = false;
805 
806  /* GetMemoryChunkSpace is not supported for bump contexts */
808  tuplen = MAXALIGN(BRINSORTTUPLE_SIZE(size));
809  else
810  tuplen = GetMemoryChunkSpace(bstup);
811 
813  base->sortKeys &&
814  base->sortKeys->abbrev_converter &&
815  !stup.isnull1, tuplen);
816 
817  MemoryContextSwitchTo(oldcontext);
818 }
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:721
static pg_noinline void Size size
Definition: slab.c:607
BlockNumber bt_blkno
Definition: brin_tuple.h:66
bool isnull1
Definition: tuplesort.h:151
MemoryContext tuplecontext
Definition: tuplesort.h:221
void tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple, bool useAbbrev, Size tuplen)
Definition: tuplesort.c:1190
#define TupleSortUseBumpTupleCxt(opt)
Definition: tuplesort.h:108
#define BRINSORTTUPLE_SIZE(len)

References SortSupportData::abbrev_converter, BRINSORTTUPLE_SIZE, BrinTuple::bt_blkno, SortTuple::datum1, GetMemoryChunkSpace(), SortTuple::isnull1, MAXALIGN, MemoryContextSwitchTo(), palloc(), size, TuplesortPublic::sortKeys, TuplesortPublic::sortopt, BrinSortTuple::tuple, SortTuple::tuple, TuplesortPublic::tuplecontext, BrinSortTuple::tuplen, tuplesort_puttuple_common(), TuplesortstateGetPublic, and TupleSortUseBumpTupleCxt.

Referenced by form_and_spill_tuple().

◆ tuplesort_putdatum()

void tuplesort_putdatum ( Tuplesortstate state,
Datum  val,
bool  isNull 
)

Definition at line 826 of file tuplesortvariants.c.

827 {
831  SortTuple stup;
832 
833  /*
834  * Pass-by-value types or null values are just stored directly in
835  * stup.datum1 (and stup.tuple is not used and set to NULL).
836  *
837  * Non-null pass-by-reference values need to be copied into memory we
838  * control, and possibly abbreviated. The copied value is pointed to by
839  * stup.tuple and is treated as the canonical copy (e.g. to return via
840  * tuplesort_getdatum or when writing to tape); stup.datum1 gets the
841  * abbreviated value if abbreviation is happening, otherwise it's
842  * identical to stup.tuple.
843  */
844 
845  if (isNull || !base->tuples)
846  {
847  /*
848  * Set datum1 to zeroed representation for NULLs (to be consistent,
849  * and to support cheap inequality tests for NULL abbreviated keys).
850  */
851  stup.datum1 = !isNull ? val : (Datum) 0;
852  stup.isnull1 = isNull;
853  stup.tuple = NULL; /* no separate storage */
854  }
855  else
856  {
857  stup.isnull1 = false;
858  stup.datum1 = datumCopy(val, false, arg->datumTypeLen);
859  stup.tuple = DatumGetPointer(stup.datum1);
860  }
861 
863  base->tuples &&
864  base->sortKeys->abbrev_converter && !isNull, 0);
865 
866  MemoryContextSwitchTo(oldcontext);
867 }
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312

References SortSupportData::abbrev_converter, arg, TuplesortPublic::arg, datumCopy(), DatumGetPointer(), if(), MemoryContextSwitchTo(), TuplesortPublic::sortKeys, TuplesortPublic::tuplecontext, TuplesortPublic::tuples, tuplesort_puttuple_common(), TuplesortstateGetPublic, and val.

Referenced by ExecEvalAggOrderedTransDatum(), ExecSort(), ordered_set_transition(), and validate_index_callback().

◆ tuplesort_putheaptuple()

void tuplesort_putheaptuple ( Tuplesortstate state,
HeapTuple  tup 
)

Definition at line 709 of file tuplesortvariants.c.

710 {
711  SortTuple stup;
715  Size tuplen;
716 
717  /* copy the tuple into sort storage */
718  tup = heap_copytuple(tup);
719  stup.tuple = (void *) tup;
720 
721  /*
722  * set up first-column key value, and potentially abbreviate, if it's a
723  * simple column
724  */
725  if (base->haveDatum1)
726  {
727  stup.datum1 = heap_getattr(tup,
728  arg->indexInfo->ii_IndexAttrNumbers[0],
729  arg->tupDesc,
730  &stup.isnull1);
731  }
732 
733  /* GetMemoryChunkSpace is not supported for bump contexts */
735  tuplen = MAXALIGN(HEAPTUPLESIZE + tup->t_len);
736  else
737  tuplen = GetMemoryChunkSpace(tup);
738 
740  base->haveDatum1 &&
741  base->sortKeys->abbrev_converter &&
742  !stup.isnull1, tuplen);
743 
744  MemoryContextSwitchTo(oldcontext);
745 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:776
#define HEAPTUPLESIZE
Definition: htup.h:73
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
uint32 t_len
Definition: htup.h:64

References SortSupportData::abbrev_converter, arg, TuplesortPublic::arg, SortTuple::datum1, GetMemoryChunkSpace(), TuplesortPublic::haveDatum1, heap_copytuple(), heap_getattr(), HEAPTUPLESIZE, SortTuple::isnull1, MAXALIGN, MemoryContextSwitchTo(), TuplesortPublic::sortKeys, TuplesortPublic::sortopt, HeapTupleData::t_len, SortTuple::tuple, TuplesortPublic::tuplecontext, tuplesort_puttuple_common(), TuplesortstateGetPublic, and TupleSortUseBumpTupleCxt.

Referenced by heapam_relation_copy_for_cluster().

◆ tuplesort_putindextuplevalues()

void tuplesort_putindextuplevalues ( Tuplesortstate state,
Relation  rel,
ItemPointer  self,
const Datum values,
const bool isnull 
)

Definition at line 752 of file tuplesortvariants.c.

755 {
756  SortTuple stup;
757  IndexTuple tuple;
760  Size tuplen;
761 
763  isnull, base->tuplecontext);
764  tuple = ((IndexTuple) stup.tuple);
765  tuple->t_tid = *self;
766  /* set up first-column key value */
767  stup.datum1 = index_getattr(tuple,
768  1,
769  RelationGetDescr(arg->indexRel),
770  &stup.isnull1);
771 
772  /* GetMemoryChunkSpace is not supported for bump contexts */
774  tuplen = MAXALIGN(tuple->t_info & INDEX_SIZE_MASK);
775  else
776  tuplen = GetMemoryChunkSpace(tuple);
777 
779  base->sortKeys &&
780  base->sortKeys->abbrev_converter &&
781  !stup.isnull1, tuplen);
782 }
static Datum values[MAXATTR]
Definition: bootstrap.c:150
IndexTuple index_form_tuple_context(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull, MemoryContext context)
Definition: indextuple.c:65
IndexTupleData * IndexTuple
Definition: itup.h:53
static Datum index_getattr(IndexTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: itup.h:117
#define INDEX_SIZE_MASK
Definition: itup.h:65
#define RelationGetDescr(relation)
Definition: rel.h:531
ItemPointerData t_tid
Definition: itup.h:37
unsigned short t_info
Definition: itup.h:49

References SortSupportData::abbrev_converter, arg, TuplesortPublic::arg, SortTuple::datum1, GetMemoryChunkSpace(), index_form_tuple_context(), index_getattr(), INDEX_SIZE_MASK, SortTuple::isnull1, MAXALIGN, RelationGetDescr, TuplesortPublic::sortKeys, TuplesortPublic::sortopt, IndexTupleData::t_info, IndexTupleData::t_tid, SortTuple::tuple, TuplesortPublic::tuplecontext, tuplesort_puttuple_common(), TuplesortstateGetPublic, TupleSortUseBumpTupleCxt, and values.

Referenced by _bt_spool(), _h_spool(), and gistSortedBuildCallback().

◆ tuplesort_puttuple_common()

void tuplesort_puttuple_common ( Tuplesortstate state,
SortTuple tuple,
bool  useAbbrev,
Size  tuplen 
)

Definition at line 1190 of file tuplesort.c.

1192 {
1193  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1194 
1195  Assert(!LEADER(state));
1196 
1197  /* account for the memory used for this tuple */
1198  USEMEM(state, tuplen);
1199  state->tupleMem += tuplen;
1200 
1201  if (!useAbbrev)
1202  {
1203  /*
1204  * Leave ordinary Datum representation, or NULL value. If there is a
1205  * converter it won't expect NULL values, and cost model is not
1206  * required to account for NULL, so in that case we avoid calling
1207  * converter and just set datum1 to zeroed representation (to be
1208  * consistent, and to support cheap inequality tests for NULL
1209  * abbreviated keys).
1210  */
1211  }
1212  else if (!consider_abort_common(state))
1213  {
1214  /* Store abbreviated key representation */
1215  tuple->datum1 = state->base.sortKeys->abbrev_converter(tuple->datum1,
1216  state->base.sortKeys);
1217  }
1218  else
1219  {
1220  /*
1221  * Set state to be consistent with never trying abbreviation.
1222  *
1223  * Alter datum1 representation in already-copied tuples, so as to
1224  * ensure a consistent representation (current tuple was just
1225  * handled). It does not matter if some dumped tuples are already
1226  * sorted on tape, since serialized tuples lack abbreviated keys
1227  * (TSS_BUILDRUNS state prevents control reaching here in any case).
1228  */
1229  REMOVEABBREV(state, state->memtuples, state->memtupcount);
1230  }
1231 
1232  switch (state->status)
1233  {
1234  case TSS_INITIAL:
1235 
1236  /*
1237  * Save the tuple into the unsorted array. First, grow the array
1238  * as needed. Note that we try to grow the array when there is
1239  * still one free slot remaining --- if we fail, there'll still be
1240  * room to store the incoming tuple, and then we'll switch to
1241  * tape-based operation.
1242  */
1243  if (state->memtupcount >= state->memtupsize - 1)
1244  {
1245  (void) grow_memtuples(state);
1246  Assert(state->memtupcount < state->memtupsize);
1247  }
1248  state->memtuples[state->memtupcount++] = *tuple;
1249 
1250  /*
1251  * Check if it's time to switch over to a bounded heapsort. We do
1252  * so if the input tuple count exceeds twice the desired tuple
1253  * count (this is a heuristic for where heapsort becomes cheaper
1254  * than a quicksort), or if we've just filled workMem and have
1255  * enough tuples to meet the bound.
1256  *
1257  * Note that once we enter TSS_BOUNDED state we will always try to
1258  * complete the sort that way. In the worst case, if later input
1259  * tuples are larger than earlier ones, this might cause us to
1260  * exceed workMem significantly.
1261  */
1262  if (state->bounded &&
1263  (state->memtupcount > state->bound * 2 ||
1264  (state->memtupcount > state->bound && LACKMEM(state))))
1265  {
1266 #ifdef TRACE_SORT
1267  if (trace_sort)
1268  elog(LOG, "switching to bounded heapsort at %d tuples: %s",
1269  state->memtupcount,
1270  pg_rusage_show(&state->ru_start));
1271 #endif
1273  MemoryContextSwitchTo(oldcontext);
1274  return;
1275  }
1276 
1277  /*
1278  * Done if we still fit in available memory and have array slots.
1279  */
1280  if (state->memtupcount < state->memtupsize && !LACKMEM(state))
1281  {
1282  MemoryContextSwitchTo(oldcontext);
1283  return;
1284  }
1285 
1286  /*
1287  * Nope; time to switch to tape-based operation.
1288  */
1289  inittapes(state, true);
1290 
1291  /*
1292  * Dump all tuples.
1293  */
1294  dumptuples(state, false);
1295  break;
1296 
1297  case TSS_BOUNDED:
1298 
1299  /*
1300  * We don't want to grow the array here, so check whether the new
1301  * tuple can be discarded before putting it in. This should be a
1302  * good speed optimization, too, since when there are many more
1303  * input tuples than the bound, most input tuples can be discarded
1304  * with just this one comparison. Note that because we currently
1305  * have the sort direction reversed, we must check for <= not >=.
1306  */
1307  if (COMPARETUP(state, tuple, &state->memtuples[0]) <= 0)
1308  {
1309  /* new tuple <= top of the heap, so we can discard it */
1310  free_sort_tuple(state, tuple);
1312  }
1313  else
1314  {
1315  /* discard top of heap, replacing it with the new tuple */
1316  free_sort_tuple(state, &state->memtuples[0]);
1318  }
1319  break;
1320 
1321  case TSS_BUILDRUNS:
1322 
1323  /*
1324  * Save the tuple into the unsorted array (there must be space)
1325  */
1326  state->memtuples[state->memtupcount++] = *tuple;
1327 
1328  /*
1329  * If we are over the memory limit, dump all tuples.
1330  */
1331  dumptuples(state, false);
1332  break;
1333 
1334  default:
1335  elog(ERROR, "invalid tuplesort state");
1336  break;
1337  }
1338  MemoryContextSwitchTo(oldcontext);
1339 }
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define COMPARETUP(state, a, b)
Definition: tuplesort.c:400
static void free_sort_tuple(Tuplesortstate *state, SortTuple *stup)
Definition: tuplesort.c:3167
#define REMOVEABBREV(state, stup, count)
Definition: tuplesort.c:399
#define LACKMEM(state)
Definition: tuplesort.c:404
#define USEMEM(state, amt)
Definition: tuplesort.c:405
static bool grow_memtuples(Tuplesortstate *state)
Definition: tuplesort.c:1073
static void make_bounded_heap(Tuplesortstate *state)
Definition: tuplesort.c:2626
#define LEADER(state)
Definition: tuplesort.c:409
static bool consider_abort_common(Tuplesortstate *state)
Definition: tuplesort.c:1342

References Assert, CHECK_FOR_INTERRUPTS, COMPARETUP, consider_abort_common(), SortTuple::datum1, dumptuples(), elog, ERROR, free_sort_tuple(), grow_memtuples(), inittapes(), LACKMEM, LEADER, LOG, make_bounded_heap(), MemoryContextSwitchTo(), pg_rusage_show(), REMOVEABBREV, trace_sort, TSS_BOUNDED, TSS_BUILDRUNS, TSS_INITIAL, tuplesort_heap_replace_top(), and USEMEM.

Referenced by tuplesort_putbrintuple(), tuplesort_putdatum(), tuplesort_putheaptuple(), tuplesort_putindextuplevalues(), and tuplesort_puttupleslot().

◆ tuplesort_puttupleslot()

void tuplesort_puttupleslot ( Tuplesortstate state,
TupleTableSlot slot 
)

Definition at line 669 of file tuplesortvariants.c.

670 {
673  TupleDesc tupDesc = (TupleDesc) base->arg;
674  SortTuple stup;
675  MinimalTuple tuple;
676  HeapTupleData htup;
677  Size tuplen;
678 
679  /* copy the tuple into sort storage */
680  tuple = ExecCopySlotMinimalTuple(slot);
681  stup.tuple = (void *) tuple;
682  /* set up first-column key value */
683  htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
684  htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
685  stup.datum1 = heap_getattr(&htup,
686  base->sortKeys[0].ssup_attno,
687  tupDesc,
688  &stup.isnull1);
689 
690  /* GetMemoryChunkSpace is not supported for bump contexts */
692  tuplen = MAXALIGN(tuple->t_len);
693  else
694  tuplen = GetMemoryChunkSpace(tuple);
695 
697  base->sortKeys->abbrev_converter &&
698  !stup.isnull1, tuplen);
699 
700  MemoryContextSwitchTo(oldcontext);
701 }
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:617
struct TupleDescData * TupleDesc
Definition: tupdesc.h:89
static MinimalTuple ExecCopySlotMinimalTuple(TupleTableSlot *slot)
Definition: tuptable.h:492

References SortSupportData::abbrev_converter, TuplesortPublic::arg, ExecCopySlotMinimalTuple(), GetMemoryChunkSpace(), heap_getattr(), MAXALIGN, MemoryContextSwitchTo(), MINIMAL_TUPLE_OFFSET, TuplesortPublic::sortKeys, TuplesortPublic::sortopt, SortSupportData::ssup_attno, MinimalTupleData::t_len, TuplesortPublic::tuplecontext, tuplesort_puttuple_common(), TuplesortstateGetPublic, and TupleSortUseBumpTupleCxt.

Referenced by ExecEvalAggOrderedTransTuple(), ExecIncrementalSort(), ExecSort(), fetch_input_tuple(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ordered_set_transition_multi(), and switchToPresortedPrefixMode().

◆ tuplesort_readtup_alloc()

void* tuplesort_readtup_alloc ( Tuplesortstate state,
Size  tuplen 
)

Definition at line 2922 of file tuplesort.c.

2923 {
2924  SlabSlot *buf;
2925 
2926  /*
2927  * We pre-allocate enough slots in the slab arena that we should never run
2928  * out.
2929  */
2930  Assert(state->slabFreeHead);
2931 
2932  if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
2933  return MemoryContextAlloc(state->base.sortcontext, tuplen);
2934  else
2935  {
2936  buf = state->slabFreeHead;
2937  /* Reuse this slot */
2938  state->slabFreeHead = buf->nextfree;
2939 
2940  return buf;
2941  }
2942 }
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1181
static char * buf
Definition: pg_test_fsync.c:73
#define SLAB_SLOT_SIZE
Definition: tuplesort.c:144

References Assert, buf, MemoryContextAlloc(), and SLAB_SLOT_SIZE.

Referenced by readtup_cluster(), readtup_datum(), readtup_heap(), readtup_index(), and readtup_index_brin().

◆ tuplesort_rescan()

void tuplesort_rescan ( Tuplesortstate state)

Definition at line 2441 of file tuplesort.c.

2442 {
2443  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2444 
2445  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2446 
2447  switch (state->status)
2448  {
2449  case TSS_SORTEDINMEM:
2450  state->current = 0;
2451  state->eof_reached = false;
2452  state->markpos_offset = 0;
2453  state->markpos_eof = false;
2454  break;
2455  case TSS_SORTEDONTAPE:
2456  LogicalTapeRewindForRead(state->result_tape, 0);
2457  state->eof_reached = false;
2458  state->markpos_block = 0L;
2459  state->markpos_offset = 0;
2460  state->markpos_eof = false;
2461  break;
2462  default:
2463  elog(ERROR, "invalid tuplesort state");
2464  break;
2465  }
2466 
2467  MemoryContextSwitchTo(oldcontext);
2468 }
void LogicalTapeRewindForRead(LogicalTape *lt, size_t buffer_size)
Definition: logtape.c:846

References Assert, elog, ERROR, LogicalTapeRewindForRead(), MemoryContextSwitchTo(), TSS_SORTEDINMEM, TSS_SORTEDONTAPE, and TUPLESORT_RANDOMACCESS.

Referenced by ExecReScanSort(), mode_final(), percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), and percentile_disc_multi_final().

◆ tuplesort_reset()

void tuplesort_reset ( Tuplesortstate state)

Definition at line 1040 of file tuplesort.c.

1041 {
1044 
1045  /*
1046  * After we've freed up per-batch memory, re-setup all of the state common
1047  * to both the first batch and any subsequent batch.
1048  */
1050 
1051  state->lastReturnedTuple = NULL;
1052  state->slabMemoryBegin = NULL;
1053  state->slabMemoryEnd = NULL;
1054  state->slabFreeHead = NULL;
1055 }

References tuplesort_begin_batch(), tuplesort_free(), and tuplesort_updatemax().

Referenced by ExecIncrementalSort(), ExecReScanIncrementalSort(), and switchToPresortedPrefixMode().

◆ tuplesort_restorepos()

void tuplesort_restorepos ( Tuplesortstate state)

Definition at line 2505 of file tuplesort.c.

2506 {
2507  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2508 
2509  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2510 
2511  switch (state->status)
2512  {
2513  case TSS_SORTEDINMEM:
2514  state->current = state->markpos_offset;
2515  state->eof_reached = state->markpos_eof;
2516  break;
2517  case TSS_SORTEDONTAPE:
2518  LogicalTapeSeek(state->result_tape,
2519  state->markpos_block,
2520  state->markpos_offset);
2521  state->eof_reached = state->markpos_eof;
2522  break;
2523  default:
2524  elog(ERROR, "invalid tuplesort state");
2525  break;
2526  }
2527 
2528  MemoryContextSwitchTo(oldcontext);
2529 }
void LogicalTapeSeek(LogicalTape *lt, int64 blocknum, int offset)
Definition: logtape.c:1133

References Assert, elog, ERROR, LogicalTapeSeek(), MemoryContextSwitchTo(), TSS_SORTEDINMEM, TSS_SORTEDONTAPE, and TUPLESORT_RANDOMACCESS.

Referenced by ExecSortRestrPos().

◆ tuplesort_set_bound()

void tuplesort_set_bound ( Tuplesortstate state,
int64  bound 
)

Definition at line 844 of file tuplesort.c.

845 {
846  /* Assert we're called before loading any tuples */
847  Assert(state->status == TSS_INITIAL && state->memtupcount == 0);
848  /* Assert we allow bounded sorts */
849  Assert(state->base.sortopt & TUPLESORT_ALLOWBOUNDED);
850  /* Can't set the bound twice, either */
851  Assert(!state->bounded);
852  /* Also, this shouldn't be called in a parallel worker */
853  Assert(!WORKER(state));
854 
855  /* Parallel leader allows but ignores hint */
856  if (LEADER(state))
857  return;
858 
859 #ifdef DEBUG_BOUNDED_SORT
860  /* Honor GUC setting that disables the feature (for easy testing) */
861  if (!optimize_bounded_sort)
862  return;
863 #endif
864 
865  /* We want to be able to compute bound * 2, so limit the setting */
866  if (bound > (int64) (INT_MAX / 2))
867  return;
868 
869  state->bounded = true;
870  state->bound = (int) bound;
871 
872  /*
873  * Bounded sorts are not an effective target for abbreviated key
874  * optimization. Disable by setting state to be consistent with no
875  * abbreviation support.
876  */
877  state->base.sortKeys->abbrev_converter = NULL;
878  if (state->base.sortKeys->abbrev_full_comparator)
879  state->base.sortKeys->comparator = state->base.sortKeys->abbrev_full_comparator;
880 
881  /* Not strictly necessary, but be tidy */
882  state->base.sortKeys->abbrev_abort = NULL;
883  state->base.sortKeys->abbrev_full_comparator = NULL;
884 }
#define TUPLESORT_ALLOWBOUNDED
Definition: tuplesort.h:99

References Assert, LEADER, TSS_INITIAL, TUPLESORT_ALLOWBOUNDED, and WORKER.

Referenced by ExecIncrementalSort(), ExecSort(), and switchToPresortedPrefixMode().

◆ tuplesort_skiptuples()

bool tuplesort_skiptuples ( Tuplesortstate state,
int64  ntuples,
bool  forward 
)

Definition at line 1737 of file tuplesort.c.

1738 {
1739  MemoryContext oldcontext;
1740 
1741  /*
1742  * We don't actually support backwards skip yet, because no callers need
1743  * it. The API is designed to allow for that later, though.
1744  */
1745  Assert(forward);
1746  Assert(ntuples >= 0);
1747  Assert(!WORKER(state));
1748 
1749  switch (state->status)
1750  {
1751  case TSS_SORTEDINMEM:
1752  if (state->memtupcount - state->current >= ntuples)
1753  {
1754  state->current += ntuples;
1755  return true;
1756  }
1757  state->current = state->memtupcount;
1758  state->eof_reached = true;
1759 
1760  /*
1761  * Complain if caller tries to retrieve more tuples than
1762  * originally asked for in a bounded sort. This is because
1763  * returning EOF here might be the wrong thing.
1764  */
1765  if (state->bounded && state->current >= state->bound)
1766  elog(ERROR, "retrieved too many tuples in a bounded sort");
1767 
1768  return false;
1769 
1770  case TSS_SORTEDONTAPE:
1771  case TSS_FINALMERGE:
1772 
1773  /*
1774  * We could probably optimize these cases better, but for now it's
1775  * not worth the trouble.
1776  */
1777  oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1778  while (ntuples-- > 0)
1779  {
1780  SortTuple stup;
1781 
1782  if (!tuplesort_gettuple_common(state, forward, &stup))
1783  {
1784  MemoryContextSwitchTo(oldcontext);
1785  return false;
1786  }
1788  }
1789  MemoryContextSwitchTo(oldcontext);
1790  return true;
1791 
1792  default:
1793  elog(ERROR, "invalid tuplesort state");
1794  return false; /* keep compiler quiet */
1795  }
1796 }

References Assert, CHECK_FOR_INTERRUPTS, elog, ERROR, MemoryContextSwitchTo(), TSS_FINALMERGE, TSS_SORTEDINMEM, TSS_SORTEDONTAPE, tuplesort_gettuple_common(), and WORKER.

Referenced by percentile_cont_final_common(), percentile_cont_multi_final_common(), percentile_disc_final(), and percentile_disc_multi_final().

◆ tuplesort_space_type_name()

const char* tuplesort_space_type_name ( TuplesortSpaceType  t)

Definition at line 2605 of file tuplesort.c.

2606 {
2608  return t == SORT_SPACE_TYPE_DISK ? "Disk" : "Memory";
2609 }

References Assert, SORT_SPACE_TYPE_DISK, and SORT_SPACE_TYPE_MEMORY.

Referenced by show_incremental_sort_group_info(), and show_sort_info().

◆ tuplesort_used_bound()

bool tuplesort_used_bound ( Tuplesortstate state)

Definition at line 892 of file tuplesort.c.

893 {
894  return state->boundUsed;
895 }

Referenced by ExecIncrementalSort().