Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

PostgreSQL Source Code git master
tuplesort.h File Reference
#include "access/brin_tuple.h"
#include "access/gin_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_index_gin (Relation heapRel, Relation indexRel, 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_putgintuple (Tuplesortstate *state, GinTuple *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)
 
GinTupletuplesort_getgintuple (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 263 of file tuplesort.h.

◆ NUM_TUPLESORTMETHODS

#define NUM_TUPLESORTMETHODS   4

Definition at line 85 of file tuplesort.h.

◆ PARALLEL_SORT

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

Definition at line 256 of file tuplesort.h.

◆ TUPLESORT_ALLOWBOUNDED

#define TUPLESORT_ALLOWBOUNDED   (1 << 1)

Definition at line 100 of file tuplesort.h.

◆ TUPLESORT_NONE

#define TUPLESORT_NONE   0

Definition at line 94 of file tuplesort.h.

◆ TUPLESORT_RANDOMACCESS

#define TUPLESORT_RANDOMACCESS   (1 << 0)

Definition at line 97 of file tuplesort.h.

◆ TuplesortstateGetPublic

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

Definition at line 260 of file tuplesort.h.

◆ TupleSortUseBumpTupleCxt

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

Definition at line 109 of file tuplesort.h.

Typedef Documentation

◆ Sharedsort

typedef struct Sharedsort Sharedsort

Definition at line 39 of file tuplesort.h.

◆ SortCoordinate

Definition at line 62 of file tuplesort.h.

◆ SortCoordinateData

◆ SortTupleComparator

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

Definition at line 156 of file tuplesort.h.

◆ TuplesortInstrumentation

◆ Tuplesortstate

Definition at line 38 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 76 of file tuplesort.h.

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

◆ TuplesortSpaceType

Enumerator
SORT_SPACE_TYPE_DISK 
SORT_SPACE_TYPE_MEMORY 

Definition at line 87 of file tuplesort.h.

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

Function Documentation

◆ tuplesort_attach_shared()

void tuplesort_attach_shared ( Sharedsort shared,
dsm_segment seg 
)

Definition at line 2955 of file tuplesort.c.

2956{
2957 /* Attach to SharedFileSet */
2958 SharedFileSetAttach(&shared->fileset, seg);
2959}
void SharedFileSetAttach(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:56
SharedFileSet fileset
Definition: tuplesort.c:360

References Sharedsort::fileset, and SharedFileSetAttach().

Referenced by _brin_parallel_build_main(), _bt_parallel_build_main(), and _gin_parallel_build_main().

◆ tuplesort_begin_cluster()

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

Definition at line 252 of file tuplesortvariants.c.

256{
257 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
258 sortopt);
260 BTScanInsert indexScanKey;
261 MemoryContext oldcontext;
263 int i;
264
265 Assert(indexRel->rd_rel->relam == BTREE_AM_OID);
266
267 oldcontext = MemoryContextSwitchTo(base->maincontext);
269
270 if (trace_sort)
271 elog(LOG,
272 "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
274 workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
275
277
278 TRACE_POSTGRESQL_SORT_START(CLUSTER_SORT,
279 false, /* no unique check */
280 base->nKeys,
281 workMem,
282 sortopt & TUPLESORT_RANDOMACCESS,
283 PARALLEL_SORT(coordinate));
284
289 base->readtup = readtup_cluster;
291 base->arg = arg;
292
293 arg->indexInfo = BuildIndexInfo(indexRel);
294
295 /*
296 * If we don't have a simple leading attribute, we don't currently
297 * initialize datum1, so disable optimizations that require it.
298 */
299 if (arg->indexInfo->ii_IndexAttrNumbers[0] == 0)
300 base->haveDatum1 = false;
301 else
302 base->haveDatum1 = true;
303
304 arg->tupDesc = tupDesc; /* assume we need not copy tupDesc */
305
306 indexScanKey = _bt_mkscankey(indexRel, NULL);
307
308 if (arg->indexInfo->ii_Expressions != NULL)
309 {
310 TupleTableSlot *slot;
311 ExprContext *econtext;
312
313 /*
314 * We will need to use FormIndexDatum to evaluate the index
315 * expressions. To do that, we need an EState, as well as a
316 * TupleTableSlot to put the table tuples into. The econtext's
317 * scantuple has to point to that slot, too.
318 */
319 arg->estate = CreateExecutorState();
321 econtext = GetPerTupleExprContext(arg->estate);
322 econtext->ecxt_scantuple = slot;
323 }
324
325 /* Prepare SortSupport data for each column */
326 base->sortKeys = (SortSupport) palloc0(base->nKeys *
327 sizeof(SortSupportData));
328
329 for (i = 0; i < base->nKeys; i++)
330 {
331 SortSupport sortKey = base->sortKeys + i;
332 ScanKey scanKey = indexScanKey->scankeys + i;
333 bool reverse;
334
336 sortKey->ssup_collation = scanKey->sk_collation;
337 sortKey->ssup_nulls_first =
338 (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
339 sortKey->ssup_attno = scanKey->sk_attno;
340 /* Convey if abbreviation optimization is applicable in principle */
341 sortKey->abbreviate = (i == 0 && base->haveDatum1);
342
343 Assert(sortKey->ssup_attno != 0);
344
345 reverse = (scanKey->sk_flags & SK_BT_DESC) != 0;
346
347 PrepareSortSupportFromIndexRel(indexRel, reverse, sortKey);
348 }
349
350 pfree(indexScanKey);
351
352 MemoryContextSwitchTo(oldcontext);
353
354 return state;
355}
#define LOG
Definition: elog.h:31
#define elog(elevel,...)
Definition: elog.h:226
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1427
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:85
EState * CreateExecutorState(void)
Definition: execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition: executor.h:653
Assert(PointerIsAligned(start, uint64))
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2428
int i
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
MemoryContext CurrentMemoryContext
Definition: mcxt.c:160
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1147
#define SK_BT_DESC
Definition: nbtree.h:1146
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:97
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void * arg
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:520
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:533
void PrepareSortSupportFromIndexRel(Relation indexRel, bool reverse, SortSupport ssup)
Definition: sortsupport.c:161
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:803
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:273
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:219
void(* writetup)(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
Definition: tuplesort.h:195
void(* removeabbrev)(Tuplesortstate *state, SortTuple *stups, int count)
Definition: tuplesort.h:188
void(* freestate)(Tuplesortstate *state)
Definition: tuplesort.h:213
void(* readtup)(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
Definition: tuplesort.h:204
SortTupleComparator comparetup
Definition: tuplesort.h:175
SortSupport sortKeys
Definition: tuplesort.h:236
SortTupleComparator comparetup_tiebreak
Definition: tuplesort.h:182
Definition: regguts.h:323
Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, int sortopt)
Definition: tuplesort.c:638
bool trace_sort
Definition: tuplesort.c:124
#define PARALLEL_SORT(coordinate)
Definition: tuplesort.h:256
#define TUPLESORT_RANDOMACCESS
Definition: tuplesort.h:97
#define TuplesortstateGetPublic(state)
Definition: tuplesort.h:260
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(), 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 638 of file tuplesort.c.

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

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_gin(), 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 652 of file tuplesortvariants.c.

655{
656 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
657 sortopt);
660 MemoryContext oldcontext;
661 int16 typlen;
662 bool typbyval;
663
664 oldcontext = MemoryContextSwitchTo(base->maincontext);
666
667 if (trace_sort)
668 elog(LOG,
669 "begin datum sort: workMem = %d, randomAccess = %c",
670 workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
671
672 base->nKeys = 1; /* always a one-column sort */
673
674 TRACE_POSTGRESQL_SORT_START(DATUM_SORT,
675 false, /* no unique check */
676 1,
677 workMem,
678 sortopt & TUPLESORT_RANDOMACCESS,
679 PARALLEL_SORT(coordinate));
680
684 base->writetup = writetup_datum;
685 base->readtup = readtup_datum;
686 base->haveDatum1 = true;
687 base->arg = arg;
688
689 arg->datumType = datumType;
690
691 /* lookup necessary attributes of the datum type */
692 get_typlenbyval(datumType, &typlen, &typbyval);
693 arg->datumTypeLen = typlen;
694 base->tuples = !typbyval;
695
696 /* Prepare SortSupport data */
697 base->sortKeys = (SortSupport) palloc0(sizeof(SortSupportData));
698
700 base->sortKeys->ssup_collation = sortCollation;
701 base->sortKeys->ssup_nulls_first = nullsFirstFlag;
702
703 /*
704 * Abbreviation is possible here only for by-reference types. In theory,
705 * a pass-by-value datatype could have an abbreviated form that is cheaper
706 * to compare. In a tuple sort, we could support that, because we can
707 * always extract the original datum from the tuple as needed. Here, we
708 * can't, because a datum sort only stores a single copy of the datum; the
709 * "tuple" field of each SortTuple is NULL.
710 */
711 base->sortKeys->abbreviate = !typbyval;
712
713 PrepareSortSupportFromOrderingOp(sortOperator, base->sortKeys);
714
715 /*
716 * The "onlyKey" optimization cannot be used with abbreviated keys, since
717 * tie-breaker comparisons may be required. Typically, the optimization
718 * is only of value to pass-by-value types anyway, whereas abbreviated
719 * keys are typically only of value to pass-by-reference types.
720 */
721 if (!base->sortKeys->abbrev_converter)
722 base->onlyKey = base->sortKeys;
723
724 MemoryContextSwitchTo(oldcontext);
725
726 return state;
727}
int16_t int16
Definition: c.h:534
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2418
void * palloc(Size size)
Definition: mcxt.c:1365
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:246
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 array_sort_internal(), 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 179 of file tuplesortvariants.c.

184{
185 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
186 sortopt);
188 MemoryContext oldcontext;
189 int i;
190
191 oldcontext = MemoryContextSwitchTo(base->maincontext);
192
193 Assert(nkeys > 0);
194
195 if (trace_sort)
196 elog(LOG,
197 "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
198 nkeys, workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
199
200 base->nKeys = nkeys;
201
202 TRACE_POSTGRESQL_SORT_START(HEAP_SORT,
203 false, /* no unique check */
204 nkeys,
205 workMem,
206 sortopt & TUPLESORT_RANDOMACCESS,
207 PARALLEL_SORT(coordinate));
208
212 base->writetup = writetup_heap;
213 base->readtup = readtup_heap;
214 base->haveDatum1 = true;
215 base->arg = tupDesc; /* assume we need not copy tupDesc */
216
217 /* Prepare SortSupport data for each column */
218 base->sortKeys = (SortSupport) palloc0(nkeys * sizeof(SortSupportData));
219
220 for (i = 0; i < nkeys; i++)
221 {
222 SortSupport sortKey = base->sortKeys + i;
223
224 Assert(attNums[i] != 0);
225 Assert(sortOperators[i] != 0);
226
228 sortKey->ssup_collation = sortCollations[i];
229 sortKey->ssup_nulls_first = nullsFirstFlags[i];
230 sortKey->ssup_attno = attNums[i];
231 /* Convey if abbreviation optimization is applicable in principle */
232 sortKey->abbreviate = (i == 0 && base->haveDatum1);
233
234 PrepareSortSupportFromOrderingOp(sortOperators[i], sortKey);
235 }
236
237 /*
238 * The "onlyKey" optimization cannot be used with abbreviated keys, since
239 * tie-breaker comparisons may be required. Typically, the optimization
240 * is only of value to pass-by-value types anyway, whereas abbreviated
241 * keys are typically only of value to pass-by-reference types.
242 */
243 if (nkeys == 1 && !base->sortKeys->abbrev_converter)
244 base->onlyKey = base->sortKeys;
245
246 MemoryContextSwitchTo(oldcontext);
247
248 return state;
249}
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 554 of file tuplesortvariants.c.

557{
558 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
559 sortopt);
561
562 if (trace_sort)
563 elog(LOG,
564 "begin index sort: workMem = %d, randomAccess = %c",
565 workMem,
566 sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
567
568 base->nKeys = 1; /* Only one sort column, the block number */
569
574 base->haveDatum1 = true;
575 base->arg = NULL;
576
577 return state;
578}
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 358 of file tuplesortvariants.c.

365{
366 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
367 sortopt);
369 BTScanInsert indexScanKey;
371 MemoryContext oldcontext;
372 int i;
373
374 oldcontext = MemoryContextSwitchTo(base->maincontext);
376
377 if (trace_sort)
378 elog(LOG,
379 "begin index sort: unique = %c, workMem = %d, randomAccess = %c",
380 enforceUnique ? 't' : 'f',
381 workMem, sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
382
384
385 TRACE_POSTGRESQL_SORT_START(INDEX_SORT,
386 enforceUnique,
387 base->nKeys,
388 workMem,
389 sortopt & TUPLESORT_RANDOMACCESS,
390 PARALLEL_SORT(coordinate));
391
395 base->writetup = writetup_index;
396 base->readtup = readtup_index;
397 base->haveDatum1 = true;
398 base->arg = arg;
399
400 arg->index.heapRel = heapRel;
401 arg->index.indexRel = indexRel;
402 arg->enforceUnique = enforceUnique;
403 arg->uniqueNullsNotDistinct = uniqueNullsNotDistinct;
404
405 indexScanKey = _bt_mkscankey(indexRel, NULL);
406
407 /* Prepare SortSupport data for each column */
408 base->sortKeys = (SortSupport) palloc0(base->nKeys *
409 sizeof(SortSupportData));
410
411 for (i = 0; i < base->nKeys; i++)
412 {
413 SortSupport sortKey = base->sortKeys + i;
414 ScanKey scanKey = indexScanKey->scankeys + i;
415 bool reverse;
416
418 sortKey->ssup_collation = scanKey->sk_collation;
419 sortKey->ssup_nulls_first =
420 (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
421 sortKey->ssup_attno = scanKey->sk_attno;
422 /* Convey if abbreviation optimization is applicable in principle */
423 sortKey->abbreviate = (i == 0 && base->haveDatum1);
424
425 Assert(sortKey->ssup_attno != 0);
426
427 reverse = (scanKey->sk_flags & SK_BT_DESC) != 0;
428
429 PrepareSortSupportFromIndexRel(indexRel, reverse, sortKey);
430 }
431
432 pfree(indexScanKey);
433
434 MemoryContextSwitchTo(oldcontext);
435
436 return state;
437}
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(), 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_gin()

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

Definition at line 581 of file tuplesortvariants.c.

585{
586 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
587 sortopt);
589 MemoryContext oldcontext;
590 int i;
591 TupleDesc desc = RelationGetDescr(indexRel);
592
593 oldcontext = MemoryContextSwitchTo(base->maincontext);
594
595#ifdef TRACE_SORT
596 if (trace_sort)
597 elog(LOG,
598 "begin index sort: workMem = %d, randomAccess = %c",
599 workMem,
600 sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
601#endif
602
603 /*
604 * Multi-column GIN indexes expand the row into a separate index entry for
605 * attribute, and that's what we write into the tuplesort. But we still
606 * need to initialize sortsupport for all the attributes.
607 */
609
610 /* Prepare SortSupport data for each column */
611 base->sortKeys = (SortSupport) palloc0(base->nKeys *
612 sizeof(SortSupportData));
613
614 for (i = 0; i < base->nKeys; i++)
615 {
616 SortSupport sortKey = base->sortKeys + i;
617 Form_pg_attribute att = TupleDescAttr(desc, i);
618 TypeCacheEntry *typentry;
619
621 sortKey->ssup_collation = indexRel->rd_indcollation[i];
622 sortKey->ssup_nulls_first = false;
623 sortKey->ssup_attno = i + 1;
624 sortKey->abbreviate = false;
625
626 Assert(sortKey->ssup_attno != 0);
627
628 if (!OidIsValid(sortKey->ssup_collation))
629 sortKey->ssup_collation = DEFAULT_COLLATION_OID;
630
631 /*
632 * Look for a ordering for the index key data type, and then the sort
633 * support function.
634 */
635 typentry = lookup_type_cache(att->atttypid, TYPECACHE_LT_OPR);
636 PrepareSortSupportFromOrderingOp(typentry->lt_opr, sortKey);
637 }
638
643 base->haveDatum1 = false;
644 base->arg = NULL;
645
646 MemoryContextSwitchTo(oldcontext);
647
648 return state;
649}
#define OidIsValid(objectId)
Definition: c.h:775
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:202
#define RelationGetDescr(relation)
Definition: rel.h:540
Oid * rd_indcollation
Definition: rel.h:217
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:160
static void writetup_index_gin(Tuplesortstate *state, LogicalTape *tape, SortTuple *stup)
static void readtup_index_gin(Tuplesortstate *state, SortTuple *stup, LogicalTape *tape, unsigned int len)
static void removeabbrev_index_gin(Tuplesortstate *state, SortTuple *stups, int count)
static int comparetup_index_gin(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition: typcache.c:386
#define TYPECACHE_LT_OPR
Definition: typcache.h:139

References SortSupportData::abbreviate, TuplesortPublic::arg, Assert(), TuplesortPublic::comparetup, comparetup_index_gin(), CurrentMemoryContext, elog, TuplesortPublic::haveDatum1, i, IndexRelationGetNumberOfKeyAttributes, LOG, lookup_type_cache(), TypeCacheEntry::lt_opr, TuplesortPublic::maincontext, MemoryContextSwitchTo(), TuplesortPublic::nKeys, OidIsValid, palloc0(), PrepareSortSupportFromOrderingOp(), RelationData::rd_indcollation, TuplesortPublic::readtup, readtup_index_gin(), RelationGetDescr, TuplesortPublic::removeabbrev, removeabbrev_index_gin(), TuplesortPublic::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, TupleDescAttr(), tuplesort_begin_common(), TUPLESORT_RANDOMACCESS, TuplesortstateGetPublic, TYPECACHE_LT_OPR, TuplesortPublic::writetup, and writetup_index_gin().

Referenced by _gin_parallel_scan_and_build(), and ginbuild().

◆ tuplesort_begin_index_gist()

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

Definition at line 491 of file tuplesortvariants.c.

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

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 440 of file tuplesortvariants.c.

448{
449 Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
450 sortopt);
452 MemoryContext oldcontext;
454
455 oldcontext = MemoryContextSwitchTo(base->maincontext);
457
458 if (trace_sort)
459 elog(LOG,
460 "begin index sort: high_mask = 0x%x, low_mask = 0x%x, "
461 "max_buckets = 0x%x, workMem = %d, randomAccess = %c",
462 high_mask,
463 low_mask,
464 max_buckets,
465 workMem,
466 sortopt & TUPLESORT_RANDOMACCESS ? 't' : 'f');
467
468 base->nKeys = 1; /* Only one sort column, the hash code */
469
473 base->writetup = writetup_index;
474 base->readtup = readtup_index;
475 base->haveDatum1 = true;
476 base->arg = arg;
477
478 arg->index.heapRel = heapRel;
479 arg->index.indexRel = indexRel;
480
481 arg->high_mask = high_mask;
482 arg->low_mask = low_mask;
483 arg->max_buckets = max_buckets;
484
485 MemoryContextSwitchTo(oldcontext);
486
487 return state;
488}
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()

◆ tuplesort_estimate_shared()

Size tuplesort_estimate_shared ( int  nWorkers)

Definition at line 2911 of file tuplesort.c.

2912{
2913 Size tapesSize;
2914
2915 Assert(nWorkers > 0);
2916
2917 /* Make sure that BufFile shared state is MAXALIGN'd */
2918 tapesSize = mul_size(sizeof(TapeShare), nWorkers);
2919 tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
2920
2921 return tapesSize;
2922}
#define MAXALIGN(LEN)
Definition: c.h:811
size_t Size
Definition: c.h:611
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(), _bt_begin_parallel(), and _gin_begin_parallel().

◆ tuplesort_get_stats()

void tuplesort_get_stats ( Tuplesortstate state,
TuplesortInstrumentation stats 
)

Definition at line 2495 of file tuplesort.c.

2497{
2498 /*
2499 * Note: it might seem we should provide both memory and disk usage for a
2500 * disk-based sort. However, the current code doesn't track memory space
2501 * accurately once we have begun to return tuples to the caller (since we
2502 * don't account for pfree's the caller is expected to do), so we cannot
2503 * rely on availMem in a disk sort. This does not seem worth the overhead
2504 * to fix. Is it worth creating an API for the memory context code to
2505 * tell us how much is actually used in sortcontext?
2506 */
2508
2509 if (state->isMaxSpaceDisk)
2511 else
2513 stats->spaceUsed = (state->maxSpace + 1023) / 1024;
2514
2515 switch (state->maxSpaceStatus)
2516 {
2517 case TSS_SORTEDINMEM:
2518 if (state->boundUsed)
2520 else
2522 break;
2523 case TSS_SORTEDONTAPE:
2525 break;
2526 case TSS_FINALMERGE:
2528 break;
2529 default:
2531 break;
2532 }
2533}
TuplesortMethod sortMethod
Definition: tuplesort.h:113
TuplesortSpaceType spaceType
Definition: tuplesort.h:114
@ TSS_SORTEDONTAPE
Definition: tuplesort.c:160
@ TSS_SORTEDINMEM
Definition: tuplesort.c:159
@ TSS_FINALMERGE
Definition: tuplesort.c:161
static void tuplesort_updatemax(Tuplesortstate *state)
Definition: tuplesort.c:964

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 1067 of file tuplesortvariants.c.

1068{
1071 SortTuple stup;
1072 BrinSortTuple *btup;
1073
1074 if (!tuplesort_gettuple_common(state, forward, &stup))
1075 stup.tuple = NULL;
1076
1077 MemoryContextSwitchTo(oldcontext);
1078
1079 if (!stup.tuple)
1080 return NULL;
1081
1082 btup = (BrinSortTuple *) stup.tuple;
1083
1084 *len = btup->tuplen;
1085
1086 return &btup->tuple;
1087}
void * tuple
Definition: tuplesort.h:150
MemoryContext sortcontext
Definition: tuplesort.h:221
bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup)
Definition: tuplesort.c:1466

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 1138 of file tuplesortvariants.c.

1140{
1144 SortTuple stup;
1145
1146 if (!tuplesort_gettuple_common(state, forward, &stup))
1147 {
1148 MemoryContextSwitchTo(oldcontext);
1149 return false;
1150 }
1151
1152 /* Ensure we copy into caller's memory context */
1153 MemoryContextSwitchTo(oldcontext);
1154
1155 /* Record abbreviated key for caller */
1156 if (base->sortKeys->abbrev_converter && abbrev)
1157 *abbrev = stup.datum1;
1158
1159 if (stup.isnull1 || !base->tuples)
1160 {
1161 *val = stup.datum1;
1162 *isNull = stup.isnull1;
1163 }
1164 else
1165 {
1166 /* use stup.tuple because stup.datum1 may be an abbreviation */
1167 if (copy)
1168 *val = datumCopy(PointerGetDatum(stup.tuple), false,
1169 arg->datumTypeLen);
1170 else
1171 *val = PointerGetDatum(stup.tuple);
1172 *isNull = false;
1173 }
1174
1175 return true;
1176}
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
long val
Definition: informix.c:689
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332

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 array_sort_internal(), 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_getgintuple()

GinTuple * tuplesort_getgintuple ( Tuplesortstate state,
Size len,
bool  forward 
)

Definition at line 1090 of file tuplesortvariants.c.

1091{
1094 SortTuple stup;
1095 GinTuple *tup;
1096
1097 if (!tuplesort_gettuple_common(state, forward, &stup))
1098 stup.tuple = NULL;
1099
1100 MemoryContextSwitchTo(oldcontext);
1101
1102 if (!stup.tuple)
1103 return NULL;
1104
1105 tup = (GinTuple *) stup.tuple;
1106
1107 *len = tup->tuplen;
1108
1109 return tup;
1110}
int tuplen
Definition: gin_tuple.h:24

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

Referenced by _gin_parallel_merge(), and _gin_process_worker_data().

◆ tuplesort_getheaptuple()

HeapTuple tuplesort_getheaptuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 1025 of file tuplesortvariants.c.

1026{
1029 SortTuple stup;
1030
1031 if (!tuplesort_gettuple_common(state, forward, &stup))
1032 stup.tuple = NULL;
1033
1034 MemoryContextSwitchTo(oldcontext);
1035
1036 return stup.tuple;
1037}

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 1046 of file tuplesortvariants.c.

1047{
1050 SortTuple stup;
1051
1052 if (!tuplesort_gettuple_common(state, forward, &stup))
1053 stup.tuple = NULL;
1054
1055 MemoryContextSwitchTo(oldcontext);
1056
1057 return (IndexTuple) stup.tuple;
1058}

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

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

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_getgintuple(), 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 987 of file tuplesortvariants.c.

989{
992 SortTuple stup;
993
994 if (!tuplesort_gettuple_common(state, forward, &stup))
995 stup.tuple = NULL;
996
997 MemoryContextSwitchTo(oldcontext);
998
999 if (stup.tuple)
1000 {
1001 /* Record abbreviated key for caller */
1002 if (base->sortKeys->abbrev_converter && abbrev)
1003 *abbrev = stup.datum1;
1004
1005 if (copy)
1007
1008 ExecStoreMinimalTuple((MinimalTuple) stup.tuple, slot, copy);
1009 return true;
1010 }
1011 else
1012 {
1013 ExecClearTuple(slot);
1014 return false;
1015 }
1016}
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1635
MinimalTuple heap_copy_minimal_tuple(MinimalTuple mtup, Size extra)
Definition: heaptuple.c:1542
Datum datum1
Definition: tuplesort.h:151
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:458

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

2933{
2934 int i;
2935
2936 Assert(nWorkers > 0);
2937
2938 SpinLockInit(&shared->mutex);
2939 shared->currentWorker = 0;
2940 shared->workersFinished = 0;
2941 SharedFileSetInit(&shared->fileset, seg);
2942 shared->nTapes = nWorkers;
2943 for (i = 0; i < nWorkers; i++)
2944 {
2945 shared->tapes[i].firstblocknumber = 0L;
2946 }
2947}
void SharedFileSetInit(SharedFileSet *fileset, dsm_segment *seg)
Definition: sharedfileset.c:38
#define SpinLockInit(lock)
Definition: spin.h:57
TapeShare tapes[FLEXIBLE_ARRAY_MEMBER]
Definition: tuplesort.c:369
int workersFinished
Definition: tuplesort.c:357
int nTapes
Definition: tuplesort.c:363
slock_t mutex
Definition: tuplesort.c:346
int currentWorker
Definition: tuplesort.c:356
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(), _bt_begin_parallel(), and _gin_begin_parallel().

◆ tuplesort_markpos()

void tuplesort_markpos ( Tuplesortstate state)

Definition at line 2431 of file tuplesort.c.

2432{
2433 MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2434
2435 Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2436
2437 switch (state->status)
2438 {
2439 case TSS_SORTEDINMEM:
2440 state->markpos_offset = state->current;
2441 state->markpos_eof = state->eof_reached;
2442 break;
2443 case TSS_SORTEDONTAPE:
2444 LogicalTapeTell(state->result_tape,
2445 &state->markpos_block,
2446 &state->markpos_offset);
2447 state->markpos_eof = state->eof_reached;
2448 break;
2449 default:
2450 elog(ERROR, "invalid tuplesort state");
2451 break;
2452 }
2453
2454 MemoryContextSwitchTo(oldcontext);
2455}
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 1774 of file tuplesort.c.

1775{
1776 int mOrder;
1777
1778 /*----------
1779 * In the merge phase, we need buffer space for each input and output tape.
1780 * Each pass in the balanced merge algorithm reads from M input tapes, and
1781 * writes to N output tapes. Each tape consumes TAPE_BUFFER_OVERHEAD bytes
1782 * of memory. In addition to that, we want MERGE_BUFFER_SIZE workspace per
1783 * input tape.
1784 *
1785 * totalMem = M * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE) +
1786 * N * TAPE_BUFFER_OVERHEAD
1787 *
1788 * Except for the last and next-to-last merge passes, where there can be
1789 * fewer tapes left to process, M = N. We choose M so that we have the
1790 * desired amount of memory available for the input buffers
1791 * (TAPE_BUFFER_OVERHEAD + MERGE_BUFFER_SIZE), given the total memory
1792 * available for the tape buffers (allowedMem).
1793 *
1794 * Note: you might be thinking we need to account for the memtuples[]
1795 * array in this calculation, but we effectively treat that as part of the
1796 * MERGE_BUFFER_SIZE workspace.
1797 *----------
1798 */
1799 mOrder = allowedMem /
1801
1802 /*
1803 * Even in minimum memory, use at least a MINORDER merge. On the other
1804 * hand, even when we have lots of memory, do not use more than a MAXORDER
1805 * merge. Tapes are pretty cheap, but they're not entirely free. Each
1806 * additional tape reduces the amount of memory available to build runs,
1807 * which in turn can cause the same sort to need more runs, which makes
1808 * merging slower even if it can still be done in a single pass. Also,
1809 * high order merges are quite slow due to CPU cache effects; it can be
1810 * faster to pay the I/O cost of a multi-pass merge than to perform a
1811 * single merge pass across many hundreds of tapes.
1812 */
1813 mOrder = Max(mOrder, MINORDER);
1814 mOrder = Min(mOrder, MAXORDER);
1815
1816 return mOrder;
1817}
#define Min(x, y)
Definition: c.h:1004
#define TAPE_BUFFER_OVERHEAD
Definition: tuplesort.c:178
#define MAXORDER
Definition: tuplesort.c:177
#define MERGE_BUFFER_SIZE
Definition: tuplesort.c:179
#define MINORDER
Definition: tuplesort.c:176

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

2540{
2541 switch (m)
2542 {
2544 return "still in progress";
2546 return "top-N heapsort";
2548 return "quicksort";
2550 return "external sort";
2552 return "external merge";
2553 }
2554
2555 return "unknown";
2556}

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

1360{
1361 MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1362
1363 if (trace_sort)
1364 elog(LOG, "performsort of worker %d starting: %s",
1365 state->worker, pg_rusage_show(&state->ru_start));
1366
1367 switch (state->status)
1368 {
1369 case TSS_INITIAL:
1370
1371 /*
1372 * We were able to accumulate all the tuples within the allowed
1373 * amount of memory, or leader to take over worker tapes
1374 */
1375 if (SERIAL(state))
1376 {
1377 /* Just qsort 'em and we're done */
1379 state->status = TSS_SORTEDINMEM;
1380 }
1381 else if (WORKER(state))
1382 {
1383 /*
1384 * Parallel workers must still dump out tuples to tape. No
1385 * merge is required to produce single output run, though.
1386 */
1387 inittapes(state, false);
1388 dumptuples(state, true);
1390 state->status = TSS_SORTEDONTAPE;
1391 }
1392 else
1393 {
1394 /*
1395 * Leader will take over worker tapes and merge worker runs.
1396 * Note that mergeruns sets the correct state->status.
1397 */
1400 }
1401 state->current = 0;
1402 state->eof_reached = false;
1403 state->markpos_block = 0L;
1404 state->markpos_offset = 0;
1405 state->markpos_eof = false;
1406 break;
1407
1408 case TSS_BOUNDED:
1409
1410 /*
1411 * We were able to accumulate all the tuples required for output
1412 * in memory, using a heap to eliminate excess tuples. Now we
1413 * have to transform the heap to a properly-sorted array. Note
1414 * that sort_bounded_heap sets the correct state->status.
1415 */
1417 state->current = 0;
1418 state->eof_reached = false;
1419 state->markpos_offset = 0;
1420 state->markpos_eof = false;
1421 break;
1422
1423 case TSS_BUILDRUNS:
1424
1425 /*
1426 * Finish tape-based sort. First, flush all tuples remaining in
1427 * memory out to tape; then merge until we have a single remaining
1428 * run (or, if !randomAccess and !WORKER(), one run per tape).
1429 * Note that mergeruns sets the correct state->status.
1430 */
1431 dumptuples(state, true);
1433 state->eof_reached = false;
1434 state->markpos_block = 0L;
1435 state->markpos_offset = 0;
1436 state->markpos_eof = false;
1437 break;
1438
1439 default:
1440 elog(ERROR, "invalid tuplesort state");
1441 break;
1442 }
1443
1444 if (trace_sort)
1445 {
1446 if (state->status == TSS_FINALMERGE)
1447 elog(LOG, "performsort of worker %d done (except %d-way final merge): %s",
1448 state->worker, state->nInputTapes,
1449 pg_rusage_show(&state->ru_start));
1450 else
1451 elog(LOG, "performsort of worker %d done: %s",
1452 state->worker, pg_rusage_show(&state->ru_start));
1453 }
1454
1455 MemoryContextSwitchTo(oldcontext);
1456}
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define SERIAL(state)
Definition: tuplesort.c:403
static void sort_bounded_heap(Tuplesortstate *state)
Definition: tuplesort.c:2632
@ TSS_INITIAL
Definition: tuplesort.c:156
@ TSS_BUILDRUNS
Definition: tuplesort.c:158
@ TSS_BOUNDED
Definition: tuplesort.c:157
static void leader_takeover_tapes(Tuplesortstate *state)
Definition: tuplesort.c:3063
static void tuplesort_sort_memtuples(Tuplesortstate *state)
Definition: tuplesort.c:2672
static void inittapes(Tuplesortstate *state, bool mergeruns)
Definition: tuplesort.c:1861
static void worker_nomergeruns(Tuplesortstate *state)
Definition: tuplesort.c:3041
static void mergeruns(Tuplesortstate *state)
Definition: tuplesort.c:2013
static void dumptuples(Tuplesortstate *state, bool alltuples)
Definition: tuplesort.c:2303

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(), _gin_parallel_merge(), _gin_parallel_scan_and_build(), _gin_process_worker_data(), _h_indexbuild(), array_sort_internal(), 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 854 of file tuplesortvariants.c.

855{
856 SortTuple stup;
857 BrinSortTuple *bstup;
860 Size tuplen;
861
862 /* allocate space for the whole BRIN sort tuple */
863 bstup = palloc(BRINSORTTUPLE_SIZE(size));
864
865 bstup->tuplen = size;
866 memcpy(&bstup->tuple, tuple, size);
867
868 stup.tuple = bstup;
869 stup.datum1 = UInt32GetDatum(tuple->bt_blkno);
870 stup.isnull1 = false;
871
872 /* GetMemoryChunkSpace is not supported for bump contexts */
874 tuplen = MAXALIGN(BRINSORTTUPLE_SIZE(size));
875 else
876 tuplen = GetMemoryChunkSpace(bstup);
877
879 base->sortKeys &&
880 base->sortKeys->abbrev_converter &&
881 !stup.isnull1, tuplen);
882
883 MemoryContextSwitchTo(oldcontext);
884}
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:767
static Datum UInt32GetDatum(uint32 X)
Definition: postgres.h:242
BlockNumber bt_blkno
Definition: brin_tuple.h:66
bool isnull1
Definition: tuplesort.h:152
MemoryContext tuplecontext
Definition: tuplesort.h:222
void tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple, bool useAbbrev, Size tuplen)
Definition: tuplesort.c:1165
#define TupleSortUseBumpTupleCxt(opt)
Definition: tuplesort.h:109
#define BRINSORTTUPLE_SIZE(len)

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

Referenced by form_and_spill_tuple().

◆ tuplesort_putdatum()

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

Definition at line 923 of file tuplesortvariants.c.

924{
928 SortTuple stup;
929
930 /*
931 * Pass-by-value types or null values are just stored directly in
932 * stup.datum1 (and stup.tuple is not used and set to NULL).
933 *
934 * Non-null pass-by-reference values need to be copied into memory we
935 * control, and possibly abbreviated. The copied value is pointed to by
936 * stup.tuple and is treated as the canonical copy (e.g. to return via
937 * tuplesort_getdatum or when writing to tape); stup.datum1 gets the
938 * abbreviated value if abbreviation is happening, otherwise it's
939 * identical to stup.tuple.
940 */
941
942 if (isNull || !base->tuples)
943 {
944 /*
945 * Set datum1 to zeroed representation for NULLs (to be consistent,
946 * and to support cheap inequality tests for NULL abbreviated keys).
947 */
948 stup.datum1 = !isNull ? val : (Datum) 0;
949 stup.isnull1 = isNull;
950 stup.tuple = NULL; /* no separate storage */
951 }
952 else
953 {
954 stup.isnull1 = false;
955 stup.datum1 = datumCopy(val, false, arg->datumTypeLen);
956 stup.tuple = DatumGetPointer(stup.datum1);
957 }
958
960 base->tuples &&
961 base->sortKeys->abbrev_converter && !isNull, 0);
962
963 MemoryContextSwitchTo(oldcontext);
964}
uint64_t Datum
Definition: postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:322

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 array_sort_internal(), ExecEvalAggOrderedTransDatum(), ExecSort(), ordered_set_transition(), and validate_index_callback().

◆ tuplesort_putgintuple()

void tuplesort_putgintuple ( Tuplesortstate state,
GinTuple tuple,
Size  size 
)

Definition at line 887 of file tuplesortvariants.c.

888{
889 SortTuple stup;
890 GinTuple *ctup;
893 Size tuplen;
894
895 /* copy the GinTuple into the right memory context */
896 ctup = palloc(size);
897 memcpy(ctup, tuple, size);
898
899 stup.tuple = ctup;
900 stup.datum1 = (Datum) 0;
901 stup.isnull1 = false;
902
903 /* GetMemoryChunkSpace is not supported for bump contexts */
905 tuplen = MAXALIGN(size);
906 else
907 tuplen = GetMemoryChunkSpace(ctup);
908
910 base->sortKeys &&
911 base->sortKeys->abbrev_converter &&
912 !stup.isnull1, tuplen);
913
914 MemoryContextSwitchTo(oldcontext);
915}

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

Referenced by _gin_process_worker_data(), and ginFlushBuildState().

◆ tuplesort_putheaptuple()

void tuplesort_putheaptuple ( Tuplesortstate state,
HeapTuple  tup 
)

Definition at line 775 of file tuplesortvariants.c.

776{
777 SortTuple stup;
781 Size tuplen;
782
783 /* copy the tuple into sort storage */
784 tup = heap_copytuple(tup);
785 stup.tuple = tup;
786
787 /*
788 * set up first-column key value, and potentially abbreviate, if it's a
789 * simple column
790 */
791 if (base->haveDatum1)
792 {
793 stup.datum1 = heap_getattr(tup,
794 arg->indexInfo->ii_IndexAttrNumbers[0],
795 arg->tupDesc,
796 &stup.isnull1);
797 }
798
799 /* GetMemoryChunkSpace is not supported for bump contexts */
801 tuplen = MAXALIGN(HEAPTUPLESIZE + tup->t_len);
802 else
803 tuplen = GetMemoryChunkSpace(tup);
804
806 base->haveDatum1 &&
807 base->sortKeys->abbrev_converter &&
808 !stup.isnull1, tuplen);
809
810 MemoryContextSwitchTo(oldcontext);
811}
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:778
#define HEAPTUPLESIZE
Definition: htup.h:73
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:904
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 818 of file tuplesortvariants.c.

821{
822 SortTuple stup;
823 IndexTuple tuple;
826 Size tuplen;
827
829 isnull, base->tuplecontext);
830 tuple = ((IndexTuple) stup.tuple);
831 tuple->t_tid = *self;
832 /* set up first-column key value */
833 stup.datum1 = index_getattr(tuple,
834 1,
835 RelationGetDescr(arg->indexRel),
836 &stup.isnull1);
837
838 /* GetMemoryChunkSpace is not supported for bump contexts */
840 tuplen = MAXALIGN(tuple->t_info & INDEX_SIZE_MASK);
841 else
842 tuplen = GetMemoryChunkSpace(tuple);
843
845 base->sortKeys &&
846 base->sortKeys->abbrev_converter &&
847 !stup.isnull1, tuplen);
848}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
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:131
#define INDEX_SIZE_MASK
Definition: itup.h:65
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 1165 of file tuplesort.c.

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

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_putgintuple(), tuplesort_putheaptuple(), tuplesort_putindextuplevalues(), and tuplesort_puttupleslot().

◆ tuplesort_puttupleslot()

void tuplesort_puttupleslot ( Tuplesortstate state,
TupleTableSlot slot 
)

Definition at line 735 of file tuplesortvariants.c.

736{
739 TupleDesc tupDesc = (TupleDesc) base->arg;
740 SortTuple stup;
741 MinimalTuple tuple;
742 HeapTupleData htup;
743 Size tuplen;
744
745 /* copy the tuple into sort storage */
746 tuple = ExecCopySlotMinimalTuple(slot);
747 stup.tuple = tuple;
748 /* set up first-column key value */
749 htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
750 htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
751 stup.datum1 = heap_getattr(&htup,
752 base->sortKeys[0].ssup_attno,
753 tupDesc,
754 &stup.isnull1);
755
756 /* GetMemoryChunkSpace is not supported for bump contexts */
758 tuplen = MAXALIGN(tuple->t_len);
759 else
760 tuplen = GetMemoryChunkSpace(tuple);
761
763 base->sortKeys->abbrev_converter &&
764 !stup.isnull1, tuplen);
765
766 MemoryContextSwitchTo(oldcontext);
767}
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:669
struct TupleDescData * TupleDesc
Definition: tupdesc.h:145
static MinimalTuple ExecCopySlotMinimalTuple(TupleTableSlot *slot)
Definition: tuptable.h:496

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

2878{
2879 SlabSlot *buf;
2880
2881 /*
2882 * We pre-allocate enough slots in the slab arena that we should never run
2883 * out.
2884 */
2885 Assert(state->slabFreeHead);
2886
2887 if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
2888 return MemoryContextAlloc(state->base.sortcontext, tuplen);
2889 else
2890 {
2891 buf = state->slabFreeHead;
2892 /* Reuse this slot */
2893 state->slabFreeHead = buf->nextfree;
2894
2895 return buf;
2896 }
2897}
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1229
static char * buf
Definition: pg_test_fsync.c:72
#define SLAB_SLOT_SIZE
Definition: tuplesort.c:142

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

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

◆ tuplesort_rescan()

void tuplesort_rescan ( Tuplesortstate state)

Definition at line 2398 of file tuplesort.c.

2399{
2400 MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2401
2402 Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2403
2404 switch (state->status)
2405 {
2406 case TSS_SORTEDINMEM:
2407 state->current = 0;
2408 state->eof_reached = false;
2409 state->markpos_offset = 0;
2410 state->markpos_eof = false;
2411 break;
2412 case TSS_SORTEDONTAPE:
2413 LogicalTapeRewindForRead(state->result_tape, 0);
2414 state->eof_reached = false;
2415 state->markpos_block = 0L;
2416 state->markpos_offset = 0;
2417 state->markpos_eof = false;
2418 break;
2419 default:
2420 elog(ERROR, "invalid tuplesort state");
2421 break;
2422 }
2423
2424 MemoryContextSwitchTo(oldcontext);
2425}
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 1015 of file tuplesort.c.

1016{
1019
1020 /*
1021 * After we've freed up per-batch memory, re-setup all of the state common
1022 * to both the first batch and any subsequent batch.
1023 */
1025
1026 state->lastReturnedTuple = NULL;
1027 state->slabMemoryBegin = NULL;
1028 state->slabMemoryEnd = NULL;
1029 state->slabFreeHead = NULL;
1030}

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

2463{
2464 MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
2465
2466 Assert(state->base.sortopt & TUPLESORT_RANDOMACCESS);
2467
2468 switch (state->status)
2469 {
2470 case TSS_SORTEDINMEM:
2471 state->current = state->markpos_offset;
2472 state->eof_reached = state->markpos_eof;
2473 break;
2474 case TSS_SORTEDONTAPE:
2475 LogicalTapeSeek(state->result_tape,
2476 state->markpos_block,
2477 state->markpos_offset);
2478 state->eof_reached = state->markpos_eof;
2479 break;
2480 default:
2481 elog(ERROR, "invalid tuplesort state");
2482 break;
2483 }
2484
2485 MemoryContextSwitchTo(oldcontext);
2486}
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 834 of file tuplesort.c.

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

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

1707{
1708 MemoryContext oldcontext;
1709
1710 /*
1711 * We don't actually support backwards skip yet, because no callers need
1712 * it. The API is designed to allow for that later, though.
1713 */
1714 Assert(forward);
1715 Assert(ntuples >= 0);
1716 Assert(!WORKER(state));
1717
1718 switch (state->status)
1719 {
1720 case TSS_SORTEDINMEM:
1721 if (state->memtupcount - state->current >= ntuples)
1722 {
1723 state->current += ntuples;
1724 return true;
1725 }
1726 state->current = state->memtupcount;
1727 state->eof_reached = true;
1728
1729 /*
1730 * Complain if caller tries to retrieve more tuples than
1731 * originally asked for in a bounded sort. This is because
1732 * returning EOF here might be the wrong thing.
1733 */
1734 if (state->bounded && state->current >= state->bound)
1735 elog(ERROR, "retrieved too many tuples in a bounded sort");
1736
1737 return false;
1738
1739 case TSS_SORTEDONTAPE:
1740 case TSS_FINALMERGE:
1741
1742 /*
1743 * We could probably optimize these cases better, but for now it's
1744 * not worth the trouble.
1745 */
1746 oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
1747 while (ntuples-- > 0)
1748 {
1749 SortTuple stup;
1750
1751 if (!tuplesort_gettuple_common(state, forward, &stup))
1752 {
1753 MemoryContextSwitchTo(oldcontext);
1754 return false;
1755 }
1757 }
1758 MemoryContextSwitchTo(oldcontext);
1759 return true;
1760
1761 default:
1762 elog(ERROR, "invalid tuplesort state");
1763 return false; /* keep compiler quiet */
1764 }
1765}

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

2563{
2565 return t == SORT_SPACE_TYPE_DISK ? "Disk" : "Memory";
2566}

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

883{
884 return state->boundUsed;
885}

Referenced by ExecIncrementalSort().