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 *tup, Size len)
 
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 2999 of file tuplesort.c.

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

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:2407
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc0(Size size)
Definition: mcxt.c:1346
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:645
bool trace_sort
Definition: tuplesort.c:124
#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 645 of file tuplesort.c.

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

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:1316
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 971 of file tuplesort.c.

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

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 2955 of file tuplesort.c.

2956 {
2957  Size tapesSize;
2958 
2959  Assert(nWorkers > 0);
2960 
2961  /* Make sure that BufFile shared state is MAXALIGN'd */
2962  tapesSize = mul_size(sizeof(TapeShare), nWorkers);
2963  tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
2964 
2965  return tapesSize;
2966 }
#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 2537 of file tuplesort.c.

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

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:1496

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

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

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 2976 of file tuplesort.c.

2977 {
2978  int i;
2979 
2980  Assert(nWorkers > 0);
2981 
2982  SpinLockInit(&shared->mutex);
2983  shared->currentWorker = 0;
2984  shared->workersFinished = 0;
2985  SharedFileSetInit(&shared->fileset, seg);
2986  shared->nTapes = nWorkers;
2987  for (i = 0; i < nWorkers; i++)
2988  {
2989  shared->tapes[i].firstblocknumber = 0L;
2990  }
2991 }
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:372
int workersFinished
Definition: tuplesort.c:360
int nTapes
Definition: tuplesort.c:366
slock_t mutex
Definition: tuplesort.c:349
int currentWorker
Definition: tuplesort.c:359
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 2473 of file tuplesort.c.

2474 {
2475  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2476 
2477  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2478 
2479  switch (state->status)
2480  {
2481  case TSS_SORTEDINMEM:
2482  state->markpos_offset = state->current;
2483  state->markpos_eof = state->eof_reached;
2484  break;
2485  case TSS_SORTEDONTAPE:
2486  LogicalTapeTell(state->result_tape,
2487  &state->markpos_block,
2488  &state->markpos_offset);
2489  state->markpos_eof = state->eof_reached;
2490  break;
2491  default:
2492  elog(ERROR, "invalid tuplesort state");
2493  break;
2494  }
2495 
2496  MemoryContextSwitchTo(oldcontext);
2497 }
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 1804 of file tuplesort.c.

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

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 2581 of file tuplesort.c.

2582 {
2583  switch (m)
2584  {
2586  return "still in progress";
2588  return "top-N heapsort";
2589  case SORT_TYPE_QUICKSORT:
2590  return "quicksort";
2592  return "external sort";
2594  return "external merge";
2595  }
2596 
2597  return "unknown";
2598 }

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 1385 of file tuplesort.c.

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

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 tup,
Size  len 
)

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
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:1189
#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:152
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 1189 of file tuplesort.c.

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

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 2921 of file tuplesort.c.

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

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 2440 of file tuplesort.c.

2441 {
2442  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2443 
2444  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2445 
2446  switch (state->status)
2447  {
2448  case TSS_SORTEDINMEM:
2449  state->current = 0;
2450  state->eof_reached = false;
2451  state->markpos_offset = 0;
2452  state->markpos_eof = false;
2453  break;
2454  case TSS_SORTEDONTAPE:
2455  LogicalTapeRewindForRead(state->result_tape, 0);
2456  state->eof_reached = false;
2457  state->markpos_block = 0L;
2458  state->markpos_offset = 0;
2459  state->markpos_eof = false;
2460  break;
2461  default:
2462  elog(ERROR, "invalid tuplesort state");
2463  break;
2464  }
2465 
2466  MemoryContextSwitchTo(oldcontext);
2467 }
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 1039 of file tuplesort.c.

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

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 2504 of file tuplesort.c.

2505 {
2506  MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2507 
2508  Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2509 
2510  switch (state->status)
2511  {
2512  case TSS_SORTEDINMEM:
2513  state->current = state->markpos_offset;
2514  state->eof_reached = state->markpos_eof;
2515  break;
2516  case TSS_SORTEDONTAPE:
2517  LogicalTapeSeek(state->result_tape,
2518  state->markpos_block,
2519  state->markpos_offset);
2520  state->eof_reached = state->markpos_eof;
2521  break;
2522  default:
2523  elog(ERROR, "invalid tuplesort state");
2524  break;
2525  }
2526 
2527  MemoryContextSwitchTo(oldcontext);
2528 }
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 843 of file tuplesort.c.

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

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

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 2604 of file tuplesort.c.

2605 {
2607  return t == SORT_SPACE_TYPE_DISK ? "Disk" : "Memory";
2608 }

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 891 of file tuplesort.c.

892 {
893  return state->boundUsed;
894 }

Referenced by ExecIncrementalSort().