PostgreSQL Source Code  git master
tuplesort.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/hash.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "commands/tablespace.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "utils/datum.h"
#include "utils/logtape.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/rel.h"
#include "utils/sortsupport.h"
#include "utils/tuplesort.h"
#include "qsort_tuple.c"
Include dependency graph for tuplesort.c:

Go to the source code of this file.

Data Structures

struct  SortTuple
 
union  SlabSlot
 
struct  Tuplesortstate
 
struct  Sharedsort
 

Macros

#define HEAP_SORT   0
 
#define INDEX_SORT   1
 
#define DATUM_SORT   2
 
#define CLUSTER_SORT   3
 
#define PARALLEL_SORT(state)
 
#define INITIAL_MEMTUPSIZE
 
#define SLAB_SLOT_SIZE   1024
 
#define MINORDER   6 /* minimum merge order */
 
#define MAXORDER   500 /* maximum merge order */
 
#define TAPE_BUFFER_OVERHEAD   BLCKSZ
 
#define MERGE_BUFFER_SIZE   (BLCKSZ * 32)
 
#define IS_SLAB_SLOT(state, tuple)
 
#define RELEASE_SLAB_SLOT(state, tuple)
 
#define COMPARETUP(state, a, b)   ((*(state)->comparetup) (a, b, state))
 
#define COPYTUP(state, stup, tup)   ((*(state)->copytup) (state, stup, tup))
 
#define WRITETUP(state, tape, stup)   ((*(state)->writetup) (state, tape, stup))
 
#define READTUP(state, stup, tape, len)   ((*(state)->readtup) (state, stup, tape, len))
 
#define LACKMEM(state)   ((state)->availMem < 0 && !(state)->slabAllocatorUsed)
 
#define USEMEM(state, amt)   ((state)->availMem -= (amt))
 
#define FREEMEM(state, amt)   ((state)->availMem += (amt))
 
#define SERIAL(state)   ((state)->shared == NULL)
 
#define WORKER(state)   ((state)->shared && (state)->worker != -1)
 
#define LEADER(state)   ((state)->shared && (state)->worker == -1)
 
#define LogicalTapeReadExact(tapeset, tapenum, ptr, len)
 

Typedefs

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

Enumerations

enum  TupSortStatus {
  TSS_INITIAL, TSS_BOUNDED, TSS_BUILDRUNS, TSS_SORTEDINMEM,
  TSS_SORTEDONTAPE, TSS_FINALMERGE
}
 

Functions

static Tuplesortstatetuplesort_begin_common (int workMem, SortCoordinate coordinate, bool randomAccess)
 
static void tuplesort_begin_batch (Tuplesortstate *state)
 
static void puttuple_common (Tuplesortstate *state, SortTuple *tuple)
 
static bool consider_abort_common (Tuplesortstate *state)
 
static void inittapes (Tuplesortstate *state, bool mergeruns)
 
static void inittapestate (Tuplesortstate *state, int maxTapes)
 
static void selectnewtape (Tuplesortstate *state)
 
static void init_slab_allocator (Tuplesortstate *state, int numSlots)
 
static void mergeruns (Tuplesortstate *state)
 
static void mergeonerun (Tuplesortstate *state)
 
static void beginmerge (Tuplesortstate *state)
 
static bool mergereadnext (Tuplesortstate *state, int srcTape, SortTuple *stup)
 
static void dumptuples (Tuplesortstate *state, bool alltuples)
 
static void make_bounded_heap (Tuplesortstate *state)
 
static void sort_bounded_heap (Tuplesortstate *state)
 
static void tuplesort_sort_memtuples (Tuplesortstate *state)
 
static void tuplesort_heap_insert (Tuplesortstate *state, SortTuple *tuple)
 
static void tuplesort_heap_replace_top (Tuplesortstate *state, SortTuple *tuple)
 
static void tuplesort_heap_delete_top (Tuplesortstate *state)
 
static void reversedirection (Tuplesortstate *state)
 
static unsigned int getlen (Tuplesortstate *state, int tapenum, bool eofOK)
 
static void markrunend (Tuplesortstate *state, int tapenum)
 
static void * readtup_alloc (Tuplesortstate *state, Size tuplen)
 
static int comparetup_heap (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 
static void copytup_heap (Tuplesortstate *state, SortTuple *stup, void *tup)
 
static void writetup_heap (Tuplesortstate *state, int tapenum, SortTuple *stup)
 
static void readtup_heap (Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
 
static int comparetup_cluster (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 
static void copytup_cluster (Tuplesortstate *state, SortTuple *stup, void *tup)
 
static void writetup_cluster (Tuplesortstate *state, int tapenum, SortTuple *stup)
 
static void readtup_cluster (Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
 
static int comparetup_index_btree (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 
static int comparetup_index_hash (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 
static void copytup_index (Tuplesortstate *state, SortTuple *stup, void *tup)
 
static void writetup_index (Tuplesortstate *state, int tapenum, SortTuple *stup)
 
static void readtup_index (Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
 
static int comparetup_datum (const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
 
static void copytup_datum (Tuplesortstate *state, SortTuple *stup, void *tup)
 
static void writetup_datum (Tuplesortstate *state, int tapenum, SortTuple *stup)
 
static void readtup_datum (Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
 
static int worker_get_identifier (Tuplesortstate *state)
 
static void worker_freeze_result_tape (Tuplesortstate *state)
 
static void worker_nomergeruns (Tuplesortstate *state)
 
static void leader_takeover_tapes (Tuplesortstate *state)
 
static void free_sort_tuple (Tuplesortstate *state, SortTuple *stup)
 
static void tuplesort_free (Tuplesortstate *state)
 
static void tuplesort_updatemax (Tuplesortstate *state)
 
Tuplesortstatetuplesort_begin_heap (TupleDesc tupDesc, int nkeys, AttrNumber *attNums, Oid *sortOperators, Oid *sortCollations, bool *nullsFirstFlags, int workMem, SortCoordinate coordinate, bool randomAccess)
 
Tuplesortstatetuplesort_begin_cluster (TupleDesc tupDesc, Relation indexRel, int workMem, SortCoordinate coordinate, bool randomAccess)
 
Tuplesortstatetuplesort_begin_index_btree (Relation heapRel, Relation indexRel, bool enforceUnique, int workMem, SortCoordinate coordinate, bool randomAccess)
 
Tuplesortstatetuplesort_begin_index_hash (Relation heapRel, Relation indexRel, uint32 high_mask, uint32 low_mask, uint32 max_buckets, int workMem, SortCoordinate coordinate, bool randomAccess)
 
Tuplesortstatetuplesort_begin_index_gist (Relation heapRel, Relation indexRel, int workMem, SortCoordinate coordinate, bool randomAccess)
 
Tuplesortstatetuplesort_begin_datum (Oid datumType, Oid sortOperator, Oid sortCollation, bool nullsFirstFlag, int workMem, SortCoordinate coordinate, bool randomAccess)
 
void tuplesort_set_bound (Tuplesortstate *state, int64 bound)
 
bool tuplesort_used_bound (Tuplesortstate *state)
 
void tuplesort_end (Tuplesortstate *state)
 
void tuplesort_reset (Tuplesortstate *state)
 
static bool grow_memtuples (Tuplesortstate *state)
 
void tuplesort_puttupleslot (Tuplesortstate *state, TupleTableSlot *slot)
 
void tuplesort_putheaptuple (Tuplesortstate *state, HeapTuple tup)
 
void tuplesort_putindextuplevalues (Tuplesortstate *state, Relation rel, ItemPointer self, Datum *values, bool *isnull)
 
void tuplesort_putdatum (Tuplesortstate *state, Datum val, bool isNull)
 
void tuplesort_performsort (Tuplesortstate *state)
 
static bool tuplesort_gettuple_common (Tuplesortstate *state, bool forward, SortTuple *stup)
 
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)
 
bool tuplesort_getdatum (Tuplesortstate *state, bool forward, Datum *val, bool *isNull, Datum *abbrev)
 
bool tuplesort_skiptuples (Tuplesortstate *state, int64 ntuples, bool forward)
 
int tuplesort_merge_order (int64 allowedMem)
 
void tuplesort_rescan (Tuplesortstate *state)
 
void tuplesort_markpos (Tuplesortstate *state)
 
void tuplesort_restorepos (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)
 
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)
 

Variables

bool trace_sort = false
 

Macro Definition Documentation

◆ CLUSTER_SORT

#define CLUSTER_SORT   3

Definition at line 122 of file tuplesort.c.

Referenced by tuplesort_begin_cluster().

◆ COMPARETUP

#define COMPARETUP (   state,
  a,
 
)    ((*(state)->comparetup) (a, b, state))

◆ COPYTUP

#define COPYTUP (   state,
  stup,
  tup 
)    ((*(state)->copytup) (state, stup, tup))

Definition at line 542 of file tuplesort.c.

Referenced by tuplesort_putheaptuple(), and tuplesort_puttupleslot().

◆ DATUM_SORT

#define DATUM_SORT   2

Definition at line 121 of file tuplesort.c.

Referenced by tuplesort_begin_datum().

◆ FREEMEM

#define FREEMEM (   state,
  amt 
)    ((state)->availMem += (amt))

◆ HEAP_SORT

#define HEAP_SORT   0

Definition at line 119 of file tuplesort.c.

Referenced by tuplesort_begin_heap().

◆ INDEX_SORT

#define INDEX_SORT   1

Definition at line 120 of file tuplesort.c.

Referenced by tuplesort_begin_index_btree().

◆ INITIAL_MEMTUPSIZE

#define INITIAL_MEMTUPSIZE
Value:
Max(1024, \
#define ALLOCSET_SEPARATE_THRESHOLD
Definition: memutils.h:219
#define Max(x, y)
Definition: c.h:922

Definition at line 135 of file tuplesort.c.

Referenced by tuplesort_begin_batch(), and tuplesort_begin_common().

◆ IS_SLAB_SLOT

#define IS_SLAB_SLOT (   state,
  tuple 
)
Value:
((char *) (tuple) >= (state)->slabMemoryBegin && \
(char *) (tuple) < (state)->slabMemoryEnd)
Definition: regguts.h:298

Definition at line 521 of file tuplesort.c.

◆ LACKMEM

#define LACKMEM (   state)    ((state)->availMem < 0 && !(state)->slabAllocatorUsed)

Definition at line 545 of file tuplesort.c.

Referenced by dumptuples(), grow_memtuples(), puttuple_common(), and tuplesort_begin_batch().

◆ LEADER

#define LEADER (   state)    ((state)->shared && (state)->worker == -1)

◆ LogicalTapeReadExact

#define LogicalTapeReadExact (   tapeset,
  tapenum,
  ptr,
  len 
)
Value:
do { \
if (LogicalTapeRead(tapeset, tapenum, ptr, len) != (size_t) (len)) \
elog(ERROR, "unexpected end of data"); \
} while(0)
size_t LogicalTapeRead(LogicalTapeSet *lts, int tapenum, void *ptr, size_t size)
Definition: logtape.c:977
#define ERROR
Definition: elog.h:43

Definition at line 602 of file tuplesort.c.

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

◆ MAXORDER

#define MAXORDER   500 /* maximum merge order */

Definition at line 230 of file tuplesort.c.

Referenced by tuplesort_merge_order().

◆ MERGE_BUFFER_SIZE

#define MERGE_BUFFER_SIZE   (BLCKSZ * 32)

Definition at line 232 of file tuplesort.c.

Referenced by tuplesort_merge_order().

◆ MINORDER

#define MINORDER   6 /* minimum merge order */

Definition at line 229 of file tuplesort.c.

Referenced by inittapes(), and tuplesort_merge_order().

◆ PARALLEL_SORT

#define PARALLEL_SORT (   state)
Value:
((state)->shared == NULL ? 0 : \
(state)->worker >= 0 ? 1 : 2)
Definition: regguts.h:298

Definition at line 125 of file tuplesort.c.

Referenced by tuplesort_begin_cluster(), tuplesort_begin_datum(), tuplesort_begin_heap(), and tuplesort_begin_index_btree().

◆ READTUP

#define READTUP (   state,
  stup,
  tape,
  len 
)    ((*(state)->readtup) (state, stup, tape, len))

Definition at line 544 of file tuplesort.c.

Referenced by mergereadnext(), and tuplesort_gettuple_common().

◆ RELEASE_SLAB_SLOT

#define RELEASE_SLAB_SLOT (   state,
  tuple 
)
Value:
do { \
SlabSlot *buf = (SlabSlot *) tuple; \
\
if (IS_SLAB_SLOT((state), buf)) \
{ \
buf->nextfree = (state)->slabFreeHead; \
(state)->slabFreeHead = buf; \
pfree(buf); \
} while(0)
void pfree(void *pointer)
Definition: mcxt.c:1057
static char * buf
Definition: pg_test_fsync.c:68
Definition: regguts.h:298
#define IS_SLAB_SLOT(state, tuple)
Definition: tuplesort.c:521

Definition at line 529 of file tuplesort.c.

Referenced by mergeonerun(), and tuplesort_gettuple_common().

◆ SERIAL

#define SERIAL (   state)    ((state)->shared == NULL)

◆ SLAB_SLOT_SIZE

#define SLAB_SLOT_SIZE   1024

Definition at line 196 of file tuplesort.c.

Referenced by init_slab_allocator(), and readtup_alloc().

◆ TAPE_BUFFER_OVERHEAD

#define TAPE_BUFFER_OVERHEAD   BLCKSZ

Definition at line 231 of file tuplesort.c.

Referenced by inittapestate(), mergeruns(), and tuplesort_merge_order().

◆ USEMEM

#define USEMEM (   state,
  amt 
)    ((state)->availMem -= (amt))

◆ WORKER

◆ WRITETUP

#define WRITETUP (   state,
  tape,
  stup 
)    ((*(state)->writetup) (state, tape, stup))

Definition at line 543 of file tuplesort.c.

Referenced by dumptuples(), and mergeonerun().

Typedef Documentation

◆ SlabSlot

typedef union SlabSlot SlabSlot

◆ SortTupleComparator

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

Definition at line 234 of file tuplesort.c.

Enumeration Type Documentation

◆ TupSortStatus

Enumerator
TSS_INITIAL 
TSS_BOUNDED 
TSS_BUILDRUNS 
TSS_SORTEDINMEM 
TSS_SORTEDONTAPE 
TSS_FINALMERGE 

Definition at line 208 of file tuplesort.c.

209 {
210  TSS_INITIAL, /* Loading tuples; still within memory limit */
211  TSS_BOUNDED, /* Loading tuples into bounded-size heap */
212  TSS_BUILDRUNS, /* Loading tuples; writing to tape */
213  TSS_SORTEDINMEM, /* Sort completed entirely in memory */
214  TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */
215  TSS_FINALMERGE /* Performing final merge on-the-fly */
216 } TupSortStatus;
TupSortStatus
Definition: tuplesort.c:208

Function Documentation

◆ beginmerge()

static void beginmerge ( Tuplesortstate state)
static

Definition at line 3082 of file tuplesort.c.

References Tuplesortstate::activeTapes, Assert, Tuplesortstate::maxTapes, Tuplesortstate::memtupcount, Tuplesortstate::mergeactive, mergereadnext(), SortTuple::srctape, Tuplesortstate::tapeRange, Tuplesortstate::tp_dummy, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, and tuplesort_heap_insert().

Referenced by mergeonerun(), and mergeruns().

3083 {
3084  int activeTapes;
3085  int tapenum;
3086  int srcTape;
3087 
3088  /* Heap should be empty here */
3089  Assert(state->memtupcount == 0);
3090 
3091  /* Adjust run counts and mark the active tapes */
3092  memset(state->mergeactive, 0,
3093  state->maxTapes * sizeof(*state->mergeactive));
3094  activeTapes = 0;
3095  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
3096  {
3097  if (state->tp_dummy[tapenum] > 0)
3098  state->tp_dummy[tapenum]--;
3099  else
3100  {
3101  Assert(state->tp_runs[tapenum] > 0);
3102  state->tp_runs[tapenum]--;
3103  srcTape = state->tp_tapenum[tapenum];
3104  state->mergeactive[srcTape] = true;
3105  activeTapes++;
3106  }
3107  }
3108  Assert(activeTapes > 0);
3109  state->activeTapes = activeTapes;
3110 
3111  /* Load the merge heap with the first tuple from each input tape */
3112  for (srcTape = 0; srcTape < state->maxTapes; srcTape++)
3113  {
3114  SortTuple tup;
3115 
3116  if (mergereadnext(state, srcTape, &tup))
3117  {
3118  tup.srctape = srcTape;
3119  tuplesort_heap_insert(state, &tup);
3120  }
3121  }
3122 }
static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3564
static bool mergereadnext(Tuplesortstate *state, int srcTape, SortTuple *stup)
Definition: tuplesort.c:3130
#define Assert(condition)
Definition: c.h:746
int srctape
Definition: tuplesort.c:182
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
bool * mergeactive
Definition: tuplesort.c:376

◆ comparetup_cluster()

static int comparetup_cluster ( const SortTuple a,
const SortTuple b,
Tuplesortstate state 
)
static

Definition at line 3935 of file tuplesort.c.

References SortSupportData::abbrev_converter, ApplySortAbbrevFullComparator(), ApplySortComparator(), compare(), SortTuple::datum1, Tuplesortstate::estate, ExecStoreHeapTuple(), FormIndexDatum(), GetPerTupleExprContext, heap_getattr, IndexInfo::ii_Expressions, IndexInfo::ii_IndexAttrNumbers, INDEX_MAX_KEYS, Tuplesortstate::indexInfo, SortTuple::isnull1, Tuplesortstate::nKeys, ResetPerTupleExprContext, Tuplesortstate::sortKeys, Tuplesortstate::tupDesc, and SortTuple::tuple.

Referenced by tuplesort_begin_cluster().

3937 {
3938  SortSupport sortKey = state->sortKeys;
3939  HeapTuple ltup;
3940  HeapTuple rtup;
3941  TupleDesc tupDesc;
3942  int nkey;
3943  int32 compare;
3944  Datum datum1,
3945  datum2;
3946  bool isnull1,
3947  isnull2;
3948  AttrNumber leading = state->indexInfo->ii_IndexAttrNumbers[0];
3949 
3950  /* Be prepared to compare additional sort keys */
3951  ltup = (HeapTuple) a->tuple;
3952  rtup = (HeapTuple) b->tuple;
3953  tupDesc = state->tupDesc;
3954 
3955  /* Compare the leading sort key, if it's simple */
3956  if (leading != 0)
3957  {
3958  compare = ApplySortComparator(a->datum1, a->isnull1,
3959  b->datum1, b->isnull1,
3960  sortKey);
3961  if (compare != 0)
3962  return compare;
3963 
3964  if (sortKey->abbrev_converter)
3965  {
3966  datum1 = heap_getattr(ltup, leading, tupDesc, &isnull1);
3967  datum2 = heap_getattr(rtup, leading, tupDesc, &isnull2);
3968 
3969  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
3970  datum2, isnull2,
3971  sortKey);
3972  }
3973  if (compare != 0 || state->nKeys == 1)
3974  return compare;
3975  /* Compare additional columns the hard way */
3976  sortKey++;
3977  nkey = 1;
3978  }
3979  else
3980  {
3981  /* Must compare all keys the hard way */
3982  nkey = 0;
3983  }
3984 
3985  if (state->indexInfo->ii_Expressions == NULL)
3986  {
3987  /* If not expression index, just compare the proper heap attrs */
3988 
3989  for (; nkey < state->nKeys; nkey++, sortKey++)
3990  {
3991  AttrNumber attno = state->indexInfo->ii_IndexAttrNumbers[nkey];
3992 
3993  datum1 = heap_getattr(ltup, attno, tupDesc, &isnull1);
3994  datum2 = heap_getattr(rtup, attno, tupDesc, &isnull2);
3995 
3996  compare = ApplySortComparator(datum1, isnull1,
3997  datum2, isnull2,
3998  sortKey);
3999  if (compare != 0)
4000  return compare;
4001  }
4002  }
4003  else
4004  {
4005  /*
4006  * In the expression index case, compute the whole index tuple and
4007  * then compare values. It would perhaps be faster to compute only as
4008  * many columns as we need to compare, but that would require
4009  * duplicating all the logic in FormIndexDatum.
4010  */
4011  Datum l_index_values[INDEX_MAX_KEYS];
4012  bool l_index_isnull[INDEX_MAX_KEYS];
4013  Datum r_index_values[INDEX_MAX_KEYS];
4014  bool r_index_isnull[INDEX_MAX_KEYS];
4015  TupleTableSlot *ecxt_scantuple;
4016 
4017  /* Reset context each time to prevent memory leakage */
4019 
4020  ecxt_scantuple = GetPerTupleExprContext(state->estate)->ecxt_scantuple;
4021 
4022  ExecStoreHeapTuple(ltup, ecxt_scantuple, false);
4023  FormIndexDatum(state->indexInfo, ecxt_scantuple, state->estate,
4024  l_index_values, l_index_isnull);
4025 
4026  ExecStoreHeapTuple(rtup, ecxt_scantuple, false);
4027  FormIndexDatum(state->indexInfo, ecxt_scantuple, state->estate,
4028  r_index_values, r_index_isnull);
4029 
4030  for (; nkey < state->nKeys; nkey++, sortKey++)
4031  {
4032  compare = ApplySortComparator(l_index_values[nkey],
4033  l_index_isnull[nkey],
4034  r_index_values[nkey],
4035  r_index_isnull[nkey],
4036  sortKey);
4037  if (compare != 0)
4038  return compare;
4039  }
4040  }
4041 
4042  return 0;
4043 }
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2585
HeapTupleData * HeapTuple
Definition: htup.h:71
#define ResetPerTupleExprContext(estate)
Definition: executor.h:515
EState * estate
Definition: tuplesort.c:452
SortSupport sortKeys
Definition: tuplesort.c:430
Datum datum1
Definition: tuplesort.c:180
bool isnull1
Definition: tuplesort.c:181
signed int int32
Definition: c.h:363
#define GetPerTupleExprContext(estate)
Definition: executor.h:506
void * tuple
Definition: tuplesort.c:179
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
IndexInfo * indexInfo
Definition: tuplesort.c:451
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
List * ii_Expressions
Definition: execnodes.h:160
#define INDEX_MAX_KEYS
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
int16 AttrNumber
Definition: attnum.h:21
TupleTableSlot * ExecStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1322
TupleDesc tupDesc
Definition: tuplesort.c:429
static int ApplySortAbbrevFullComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:238

◆ comparetup_datum()

static int comparetup_datum ( const SortTuple a,
const SortTuple b,
Tuplesortstate state 
)
static

Definition at line 4422 of file tuplesort.c.

References SortSupportData::abbrev_converter, ApplySortAbbrevFullComparator(), ApplySortComparator(), compare(), SortTuple::datum1, SortTuple::isnull1, PointerGetDatum, Tuplesortstate::sortKeys, and SortTuple::tuple.

Referenced by tuplesort_begin_datum().

4423 {
4424  int compare;
4425 
4426  compare = ApplySortComparator(a->datum1, a->isnull1,
4427  b->datum1, b->isnull1,
4428  state->sortKeys);
4429  if (compare != 0)
4430  return compare;
4431 
4432  /* if we have abbreviations, then "tuple" has the original value */
4433 
4434  if (state->sortKeys->abbrev_converter)
4436  PointerGetDatum(b->tuple), b->isnull1,
4437  state->sortKeys);
4438 
4439  return compare;
4440 }
#define PointerGetDatum(X)
Definition: postgres.h:556
SortSupport sortKeys
Definition: tuplesort.c:430
Datum datum1
Definition: tuplesort.c:180
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
static int ApplySortAbbrevFullComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:238

◆ comparetup_heap()

static int comparetup_heap ( const SortTuple a,
const SortTuple b,
Tuplesortstate state 
)
static

Definition at line 3736 of file tuplesort.c.

References SortSupportData::abbrev_converter, ApplySortAbbrevFullComparator(), ApplySortComparator(), compare(), SortTuple::datum1, heap_getattr, SortTuple::isnull1, MINIMAL_TUPLE_OFFSET, Tuplesortstate::nKeys, Tuplesortstate::sortKeys, SortSupportData::ssup_attno, HeapTupleData::t_data, HeapTupleData::t_len, Tuplesortstate::tupDesc, and SortTuple::tuple.

Referenced by tuplesort_begin_heap().

3737 {
3738  SortSupport sortKey = state->sortKeys;
3739  HeapTupleData ltup;
3740  HeapTupleData rtup;
3741  TupleDesc tupDesc;
3742  int nkey;
3743  int32 compare;
3744  AttrNumber attno;
3745  Datum datum1,
3746  datum2;
3747  bool isnull1,
3748  isnull2;
3749 
3750 
3751  /* Compare the leading sort key */
3752  compare = ApplySortComparator(a->datum1, a->isnull1,
3753  b->datum1, b->isnull1,
3754  sortKey);
3755  if (compare != 0)
3756  return compare;
3757 
3758  /* Compare additional sort keys */
3759  ltup.t_len = ((MinimalTuple) a->tuple)->t_len + MINIMAL_TUPLE_OFFSET;
3760  ltup.t_data = (HeapTupleHeader) ((char *) a->tuple - MINIMAL_TUPLE_OFFSET);
3761  rtup.t_len = ((MinimalTuple) b->tuple)->t_len + MINIMAL_TUPLE_OFFSET;
3762  rtup.t_data = (HeapTupleHeader) ((char *) b->tuple - MINIMAL_TUPLE_OFFSET);
3763  tupDesc = state->tupDesc;
3764 
3765  if (sortKey->abbrev_converter)
3766  {
3767  attno = sortKey->ssup_attno;
3768 
3769  datum1 = heap_getattr(&ltup, attno, tupDesc, &isnull1);
3770  datum2 = heap_getattr(&rtup, attno, tupDesc, &isnull2);
3771 
3772  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
3773  datum2, isnull2,
3774  sortKey);
3775  if (compare != 0)
3776  return compare;
3777  }
3778 
3779  sortKey++;
3780  for (nkey = 1; nkey < state->nKeys; nkey++, sortKey++)
3781  {
3782  attno = sortKey->ssup_attno;
3783 
3784  datum1 = heap_getattr(&ltup, attno, tupDesc, &isnull1);
3785  datum2 = heap_getattr(&rtup, attno, tupDesc, &isnull2);
3786 
3787  compare = ApplySortComparator(datum1, isnull1,
3788  datum2, isnull2,
3789  sortKey);
3790  if (compare != 0)
3791  return compare;
3792  }
3793 
3794  return 0;
3795 }
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
SortSupport sortKeys
Definition: tuplesort.c:430
Datum datum1
Definition: tuplesort.c:180
bool isnull1
Definition: tuplesort.c:181
signed int int32
Definition: c.h:363
HeapTupleHeader t_data
Definition: htup.h:68
void * tuple
Definition: tuplesort.c:179
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
uint32 t_len
Definition: htup.h:64
MinimalTupleData * MinimalTuple
Definition: htup.h:27
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:619
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
int16 AttrNumber
Definition: attnum.h:21
TupleDesc tupDesc
Definition: tuplesort.c:429
static int ApplySortAbbrevFullComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:238

◆ comparetup_index_btree()

static int comparetup_index_btree ( const SortTuple a,
const SortTuple b,
Tuplesortstate state 
)
static

Definition at line 4181 of file tuplesort.c.

References SortSupportData::abbrev_converter, ApplySortAbbrevFullComparator(), ApplySortComparator(), Assert, BuildIndexValueDescription(), compare(), SortTuple::datum1, Tuplesortstate::enforceUnique, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), Tuplesortstate::heapRel, index_deform_tuple(), index_getattr, INDEX_MAX_KEYS, Tuplesortstate::indexRel, SortTuple::isnull1, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, Tuplesortstate::nKeys, RelationGetDescr, RelationGetRelationName, Tuplesortstate::sortKeys, IndexTupleData::t_tid, SortTuple::tuple, and values.

Referenced by tuplesort_begin_index_btree(), and tuplesort_begin_index_gist().

4183 {
4184  /*
4185  * This is similar to comparetup_heap(), but expects index tuples. There
4186  * is also special handling for enforcing uniqueness, and special
4187  * treatment for equal keys at the end.
4188  */
4189  SortSupport sortKey = state->sortKeys;
4190  IndexTuple tuple1;
4191  IndexTuple tuple2;
4192  int keysz;
4193  TupleDesc tupDes;
4194  bool equal_hasnull = false;
4195  int nkey;
4196  int32 compare;
4197  Datum datum1,
4198  datum2;
4199  bool isnull1,
4200  isnull2;
4201 
4202 
4203  /* Compare the leading sort key */
4204  compare = ApplySortComparator(a->datum1, a->isnull1,
4205  b->datum1, b->isnull1,
4206  sortKey);
4207  if (compare != 0)
4208  return compare;
4209 
4210  /* Compare additional sort keys */
4211  tuple1 = (IndexTuple) a->tuple;
4212  tuple2 = (IndexTuple) b->tuple;
4213  keysz = state->nKeys;
4214  tupDes = RelationGetDescr(state->indexRel);
4215 
4216  if (sortKey->abbrev_converter)
4217  {
4218  datum1 = index_getattr(tuple1, 1, tupDes, &isnull1);
4219  datum2 = index_getattr(tuple2, 1, tupDes, &isnull2);
4220 
4221  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
4222  datum2, isnull2,
4223  sortKey);
4224  if (compare != 0)
4225  return compare;
4226  }
4227 
4228  /* they are equal, so we only need to examine one null flag */
4229  if (a->isnull1)
4230  equal_hasnull = true;
4231 
4232  sortKey++;
4233  for (nkey = 2; nkey <= keysz; nkey++, sortKey++)
4234  {
4235  datum1 = index_getattr(tuple1, nkey, tupDes, &isnull1);
4236  datum2 = index_getattr(tuple2, nkey, tupDes, &isnull2);
4237 
4238  compare = ApplySortComparator(datum1, isnull1,
4239  datum2, isnull2,
4240  sortKey);
4241  if (compare != 0)
4242  return compare; /* done when we find unequal attributes */
4243 
4244  /* they are equal, so we only need to examine one null flag */
4245  if (isnull1)
4246  equal_hasnull = true;
4247  }
4248 
4249  /*
4250  * If btree has asked us to enforce uniqueness, complain if two equal
4251  * tuples are detected (unless there was at least one NULL field).
4252  *
4253  * It is sufficient to make the test here, because if two tuples are equal
4254  * they *must* get compared at some stage of the sort --- otherwise the
4255  * sort algorithm wouldn't have checked whether one must appear before the
4256  * other.
4257  */
4258  if (state->enforceUnique && !equal_hasnull)
4259  {
4261  bool isnull[INDEX_MAX_KEYS];
4262  char *key_desc;
4263 
4264  /*
4265  * Some rather brain-dead implementations of qsort (such as the one in
4266  * QNX 4) will sometimes call the comparison routine to compare a
4267  * value to itself, but we always use our own implementation, which
4268  * does not.
4269  */
4270  Assert(tuple1 != tuple2);
4271 
4272  index_deform_tuple(tuple1, tupDes, values, isnull);
4273 
4274  key_desc = BuildIndexValueDescription(state->indexRel, values, isnull);
4275 
4276  ereport(ERROR,
4277  (errcode(ERRCODE_UNIQUE_VIOLATION),
4278  errmsg("could not create unique index \"%s\"",
4280  key_desc ? errdetail("Key %s is duplicated.", key_desc) :
4281  errdetail("Duplicate keys exist."),
4282  errtableconstraint(state->heapRel,
4283  RelationGetRelationName(state->indexRel))));
4284  }
4285 
4286  /*
4287  * If key values are equal, we sort on ItemPointer. This is required for
4288  * btree indexes, since heap TID is treated as an implicit last key
4289  * attribute in order to ensure that all keys in the index are physically
4290  * unique.
4291  */
4292  {
4293  BlockNumber blk1 = ItemPointerGetBlockNumber(&tuple1->t_tid);
4294  BlockNumber blk2 = ItemPointerGetBlockNumber(&tuple2->t_tid);
4295 
4296  if (blk1 != blk2)
4297  return (blk1 < blk2) ? -1 : 1;
4298  }
4299  {
4302 
4303  if (pos1 != pos2)
4304  return (pos1 < pos2) ? -1 : 1;
4305  }
4306 
4307  /* ItemPointer values should never be equal */
4308  Assert(false);
4309 
4310  return 0;
4311 }
Relation heapRel
Definition: tuplesort.c:458
#define RelationGetDescr(relation)
Definition: rel.h:482
SortSupport sortKeys
Definition: tuplesort.c:430
ItemPointerData t_tid
Definition: itup.h:37
Datum datum1
Definition: tuplesort.c:180
int errcode(int sqlerrcode)
Definition: elog.c:610
uint32 BlockNumber
Definition: block.h:31
bool isnull1
Definition: tuplesort.c:181
signed int int32
Definition: c.h:363
uint16 OffsetNumber
Definition: off.h:24
void * tuple
Definition: tuplesort.c:179
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5551
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
#define ERROR
Definition: elog.h:43
IndexTupleData * IndexTuple
Definition: itup.h:53
int errdetail(const char *fmt,...)
Definition: elog.c:954
#define RelationGetRelationName(relation)
Definition: rel.h:490
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
void index_deform_tuple(IndexTuple tup, TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:434
Relation indexRel
Definition: tuplesort.c:459
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
bool enforceUnique
Definition: tuplesort.c:462
#define INDEX_MAX_KEYS
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * BuildIndexValueDescription(Relation indexRelation, Datum *values, bool *isnull)
Definition: genam.c:177
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200
static int ApplySortAbbrevFullComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:238

◆ comparetup_index_hash()

static int comparetup_index_hash ( const SortTuple a,
const SortTuple b,
Tuplesortstate state 
)
static

Definition at line 4314 of file tuplesort.c.

References _hash_hashkey2bucket(), Assert, SortTuple::datum1, DatumGetUInt32, Tuplesortstate::high_mask, SortTuple::isnull1, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, Tuplesortstate::low_mask, Tuplesortstate::max_buckets, IndexTupleData::t_tid, and SortTuple::tuple.

Referenced by tuplesort_begin_index_hash().

4316 {
4317  Bucket bucket1;
4318  Bucket bucket2;
4319  IndexTuple tuple1;
4320  IndexTuple tuple2;
4321 
4322  /*
4323  * Fetch hash keys and mask off bits we don't want to sort by. We know
4324  * that the first column of the index tuple is the hash key.
4325  */
4326  Assert(!a->isnull1);
4328  state->max_buckets, state->high_mask,
4329  state->low_mask);
4330  Assert(!b->isnull1);
4332  state->max_buckets, state->high_mask,
4333  state->low_mask);
4334  if (bucket1 > bucket2)
4335  return 1;
4336  else if (bucket1 < bucket2)
4337  return -1;
4338 
4339  /*
4340  * If hash values are equal, we sort on ItemPointer. This does not affect
4341  * validity of the finished index, but it may be useful to have index
4342  * scans in physical order.
4343  */
4344  tuple1 = (IndexTuple) a->tuple;
4345  tuple2 = (IndexTuple) b->tuple;
4346 
4347  {
4348  BlockNumber blk1 = ItemPointerGetBlockNumber(&tuple1->t_tid);
4349  BlockNumber blk2 = ItemPointerGetBlockNumber(&tuple2->t_tid);
4350 
4351  if (blk1 != blk2)
4352  return (blk1 < blk2) ? -1 : 1;
4353  }
4354  {
4357 
4358  if (pos1 != pos2)
4359  return (pos1 < pos2) ? -1 : 1;
4360  }
4361 
4362  /* ItemPointer values should never be equal */
4363  Assert(false);
4364 
4365  return 0;
4366 }
#define DatumGetUInt32(X)
Definition: postgres.h:486
Bucket _hash_hashkey2bucket(uint32 hashkey, uint32 maxbucket, uint32 highmask, uint32 lowmask)
Definition: hashutil.c:126
ItemPointerData t_tid
Definition: itup.h:37
Datum datum1
Definition: tuplesort.c:180
uint32 BlockNumber
Definition: block.h:31
bool isnull1
Definition: tuplesort.c:181
uint16 OffsetNumber
Definition: off.h:24
uint32 Bucket
Definition: hash.h:35
void * tuple
Definition: tuplesort.c:179
uint32 high_mask
Definition: tuplesort.c:465
IndexTupleData * IndexTuple
Definition: itup.h:53
#define Assert(condition)
Definition: c.h:746
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
uint32 max_buckets
Definition: tuplesort.c:467
uint32 low_mask
Definition: tuplesort.c:466
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ consider_abort_common()

static bool consider_abort_common ( Tuplesortstate state)
static

Definition at line 1977 of file tuplesort.c.

References SortSupportData::abbrev_abort, SortSupportData::abbrev_converter, SortSupportData::abbrev_full_comparator, Tuplesortstate::abbrevNext, Assert, SortSupportData::comparator, Tuplesortstate::memtupcount, Tuplesortstate::sortKeys, Tuplesortstate::status, and TSS_INITIAL.

Referenced by copytup_cluster(), copytup_heap(), tuplesort_putdatum(), and tuplesort_putindextuplevalues().

1978 {
1979  Assert(state->sortKeys[0].abbrev_converter != NULL);
1980  Assert(state->sortKeys[0].abbrev_abort != NULL);
1981  Assert(state->sortKeys[0].abbrev_full_comparator != NULL);
1982 
1983  /*
1984  * Check effectiveness of abbreviation optimization. Consider aborting
1985  * when still within memory limit.
1986  */
1987  if (state->status == TSS_INITIAL &&
1988  state->memtupcount >= state->abbrevNext)
1989  {
1990  state->abbrevNext *= 2;
1991 
1992  /*
1993  * Check opclass-supplied abbreviation abort routine. It may indicate
1994  * that abbreviation should not proceed.
1995  */
1996  if (!state->sortKeys->abbrev_abort(state->memtupcount,
1997  state->sortKeys))
1998  return false;
1999 
2000  /*
2001  * Finally, restore authoritative comparator, and indicate that
2002  * abbreviation is not in play by setting abbrev_converter to NULL
2003  */
2004  state->sortKeys[0].comparator = state->sortKeys[0].abbrev_full_comparator;
2005  state->sortKeys[0].abbrev_converter = NULL;
2006  /* Not strictly necessary, but be tidy */
2007  state->sortKeys[0].abbrev_abort = NULL;
2008  state->sortKeys[0].abbrev_full_comparator = NULL;
2009 
2010  /* Give up - expect original pass-by-value representation */
2011  return true;
2012  }
2013 
2014  return false;
2015 }
TupSortStatus status
Definition: tuplesort.c:242
int64 abbrevNext
Definition: tuplesort.c:444
SortSupport sortKeys
Definition: tuplesort.c:430
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:106
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:191
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
#define Assert(condition)
Definition: c.h:746
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
Definition: sortsupport.h:182

◆ copytup_cluster()

static void copytup_cluster ( Tuplesortstate state,
SortTuple stup,
void *  tup 
)
static

Definition at line 4046 of file tuplesort.c.

References SortSupportData::abbrev_converter, consider_abort_common(), SortTuple::datum1, GetMemoryChunkSpace(), heap_copytuple(), heap_getattr, i, IndexInfo::ii_IndexAttrNumbers, Tuplesortstate::indexInfo, SortTuple::isnull1, MemoryContextSwitchTo(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, Tuplesortstate::sortKeys, Tuplesortstate::tupDesc, SortTuple::tuple, Tuplesortstate::tuplecontext, and USEMEM.

Referenced by tuplesort_begin_cluster().

4047 {
4048  HeapTuple tuple = (HeapTuple) tup;
4049  Datum original;
4050  MemoryContext oldcontext = MemoryContextSwitchTo(state->tuplecontext);
4051 
4052  /* copy the tuple into sort storage */
4053  tuple = heap_copytuple(tuple);
4054  stup->tuple = (void *) tuple;
4055  USEMEM(state, GetMemoryChunkSpace(tuple));
4056 
4057  MemoryContextSwitchTo(oldcontext);
4058 
4059  /*
4060  * set up first-column key value, and potentially abbreviate, if it's a
4061  * simple column
4062  */
4063  if (state->indexInfo->ii_IndexAttrNumbers[0] == 0)
4064  return;
4065 
4066  original = heap_getattr(tuple,
4067  state->indexInfo->ii_IndexAttrNumbers[0],
4068  state->tupDesc,
4069  &stup->isnull1);
4070 
4071  if (!state->sortKeys->abbrev_converter || stup->isnull1)
4072  {
4073  /*
4074  * Store ordinary Datum representation, or NULL value. If there is a
4075  * converter it won't expect NULL values, and cost model is not
4076  * required to account for NULL, so in that case we avoid calling
4077  * converter and just set datum1 to zeroed representation (to be
4078  * consistent, and to support cheap inequality tests for NULL
4079  * abbreviated keys).
4080  */
4081  stup->datum1 = original;
4082  }
4083  else if (!consider_abort_common(state))
4084  {
4085  /* Store abbreviated key representation */
4086  stup->datum1 = state->sortKeys->abbrev_converter(original,
4087  state->sortKeys);
4088  }
4089  else
4090  {
4091  /* Abort abbreviation */
4092  int i;
4093 
4094  stup->datum1 = original;
4095 
4096  /*
4097  * Set state to be consistent with never trying abbreviation.
4098  *
4099  * Alter datum1 representation in already-copied tuples, so as to
4100  * ensure a consistent representation (current tuple was just
4101  * handled). It does not matter if some dumped tuples are already
4102  * sorted on tape, since serialized tuples lack abbreviated keys
4103  * (TSS_BUILDRUNS state prevents control reaching here in any case).
4104  */
4105  for (i = 0; i < state->memtupcount; i++)
4106  {
4107  SortTuple *mtup = &state->memtuples[i];
4108 
4109  tuple = (HeapTuple) mtup->tuple;
4110  mtup->datum1 = heap_getattr(tuple,
4111  state->indexInfo->ii_IndexAttrNumbers[0],
4112  state->tupDesc,
4113  &mtup->isnull1);
4114  }
4115  }
4116 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
HeapTupleData * HeapTuple
Definition: htup.h:71
SortSupport sortKeys
Definition: tuplesort.c:430
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Datum datum1
Definition: tuplesort.c:180
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
static bool consider_abort_common(Tuplesortstate *state)
Definition: tuplesort.c:1977
IndexInfo * indexInfo
Definition: tuplesort.c:451
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
MemoryContext tuplecontext
Definition: tuplesort.c:263
#define USEMEM(state, amt)
Definition: tuplesort.c:546
int i
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
TupleDesc tupDesc
Definition: tuplesort.c:429
SortTuple * memtuples
Definition: tuplesort.c:311

◆ copytup_datum()

static void copytup_datum ( Tuplesortstate state,
SortTuple stup,
void *  tup 
)
static

Definition at line 4443 of file tuplesort.c.

References elog, and ERROR.

Referenced by tuplesort_begin_datum().

4444 {
4445  /* Not currently needed */
4446  elog(ERROR, "copytup_datum() should not be called");
4447 }
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214

◆ copytup_heap()

static void copytup_heap ( Tuplesortstate state,
SortTuple stup,
void *  tup 
)
static

Definition at line 3798 of file tuplesort.c.

References SortSupportData::abbrev_converter, consider_abort_common(), SortTuple::datum1, ExecCopySlotMinimalTuple(), GetMemoryChunkSpace(), heap_getattr, i, SortTuple::isnull1, MemoryContextSwitchTo(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, MINIMAL_TUPLE_OFFSET, Tuplesortstate::sortKeys, SortSupportData::ssup_attno, HeapTupleData::t_data, HeapTupleData::t_len, MinimalTupleData::t_len, Tuplesortstate::tupDesc, SortTuple::tuple, Tuplesortstate::tuplecontext, and USEMEM.

Referenced by tuplesort_begin_heap().

3799 {
3800  /*
3801  * We expect the passed "tup" to be a TupleTableSlot, and form a
3802  * MinimalTuple using the exported interface for that.
3803  */
3804  TupleTableSlot *slot = (TupleTableSlot *) tup;
3805  Datum original;
3806  MinimalTuple tuple;
3807  HeapTupleData htup;
3808  MemoryContext oldcontext = MemoryContextSwitchTo(state->tuplecontext);
3809 
3810  /* copy the tuple into sort storage */
3811  tuple = ExecCopySlotMinimalTuple(slot);
3812  stup->tuple = (void *) tuple;
3813  USEMEM(state, GetMemoryChunkSpace(tuple));
3814  /* set up first-column key value */
3815  htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
3816  htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
3817  original = heap_getattr(&htup,
3818  state->sortKeys[0].ssup_attno,
3819  state->tupDesc,
3820  &stup->isnull1);
3821 
3822  MemoryContextSwitchTo(oldcontext);
3823 
3824  if (!state->sortKeys->abbrev_converter || stup->isnull1)
3825  {
3826  /*
3827  * Store ordinary Datum representation, or NULL value. If there is a
3828  * converter it won't expect NULL values, and cost model is not
3829  * required to account for NULL, so in that case we avoid calling
3830  * converter and just set datum1 to zeroed representation (to be
3831  * consistent, and to support cheap inequality tests for NULL
3832  * abbreviated keys).
3833  */
3834  stup->datum1 = original;
3835  }
3836  else if (!consider_abort_common(state))
3837  {
3838  /* Store abbreviated key representation */
3839  stup->datum1 = state->sortKeys->abbrev_converter(original,
3840  state->sortKeys);
3841  }
3842  else
3843  {
3844  /* Abort abbreviation */
3845  int i;
3846 
3847  stup->datum1 = original;
3848 
3849  /*
3850  * Set state to be consistent with never trying abbreviation.
3851  *
3852  * Alter datum1 representation in already-copied tuples, so as to
3853  * ensure a consistent representation (current tuple was just
3854  * handled). It does not matter if some dumped tuples are already
3855  * sorted on tape, since serialized tuples lack abbreviated keys
3856  * (TSS_BUILDRUNS state prevents control reaching here in any case).
3857  */
3858  for (i = 0; i < state->memtupcount; i++)
3859  {
3860  SortTuple *mtup = &state->memtuples[i];
3861 
3862  htup.t_len = ((MinimalTuple) mtup->tuple)->t_len +
3864  htup.t_data = (HeapTupleHeader) ((char *) mtup->tuple -
3866 
3867  mtup->datum1 = heap_getattr(&htup,
3868  state->sortKeys[0].ssup_attno,
3869  state->tupDesc,
3870  &mtup->isnull1);
3871  }
3872  }
3873 }
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
SortSupport sortKeys
Definition: tuplesort.c:430
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Datum datum1
Definition: tuplesort.c:180
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
bool isnull1
Definition: tuplesort.c:181
HeapTupleHeader t_data
Definition: htup.h:68
void * tuple
Definition: tuplesort.c:179
static bool consider_abort_common(Tuplesortstate *state)
Definition: tuplesort.c:1977
uint32 t_len
Definition: htup.h:64
static MinimalTuple ExecCopySlotMinimalTuple(TupleTableSlot *slot)
Definition: tuptable.h:463
MinimalTupleData * MinimalTuple
Definition: htup.h:27
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
uintptr_t Datum
Definition: postgres.h:367
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:619
MemoryContext tuplecontext
Definition: tuplesort.c:263
#define USEMEM(state, amt)
Definition: tuplesort.c:546
int i
TupleDesc tupDesc
Definition: tuplesort.c:429
SortTuple * memtuples
Definition: tuplesort.c:311

◆ copytup_index()

static void copytup_index ( Tuplesortstate state,
SortTuple stup,
void *  tup 
)
static

Definition at line 4369 of file tuplesort.c.

References elog, and ERROR.

Referenced by tuplesort_begin_index_btree(), tuplesort_begin_index_gist(), and tuplesort_begin_index_hash().

4370 {
4371  /* Not currently needed */
4372  elog(ERROR, "copytup_index() should not be called");
4373 }
#define ERROR
Definition: elog.h:43
#define elog(elevel,...)
Definition: elog.h:214

◆ dumptuples()

static void dumptuples ( Tuplesortstate state,
bool  alltuples 
)
static

Definition at line 3155 of file tuplesort.c.

References Assert, Tuplesortstate::currentRun, Tuplesortstate::destTape, elog, ereport, errcode(), errmsg(), ERROR, i, LACKMEM, LOG, markrunend(), MemoryContextReset(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, Tuplesortstate::memtupsize, pg_rusage_show(), Tuplesortstate::ru_start, selectnewtape(), Tuplesortstate::status, Tuplesortstate::tp_dummy, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, trace_sort, TSS_BUILDRUNS, Tuplesortstate::tuplecontext, tuplesort_sort_memtuples(), Tuplesortstate::worker, and WRITETUP.

Referenced by puttuple_common(), and tuplesort_performsort().

3156 {
3157  int memtupwrite;
3158  int i;
3159 
3160  /*
3161  * Nothing to do if we still fit in available memory and have array slots,
3162  * unless this is the final call during initial run generation.
3163  */
3164  if (state->memtupcount < state->memtupsize && !LACKMEM(state) &&
3165  !alltuples)
3166  return;
3167 
3168  /*
3169  * Final call might require no sorting, in rare cases where we just so
3170  * happen to have previously LACKMEM()'d at the point where exactly all
3171  * remaining tuples are loaded into memory, just before input was
3172  * exhausted.
3173  *
3174  * In general, short final runs are quite possible. Rather than allowing
3175  * a special case where there was a superfluous selectnewtape() call (i.e.
3176  * a call with no subsequent run actually written to destTape), we prefer
3177  * to write out a 0 tuple run.
3178  *
3179  * mergereadnext() is prepared for 0 tuple runs, and will reliably mark
3180  * the tape inactive for the merge when called from beginmerge(). This
3181  * case is therefore similar to the case where mergeonerun() finds a dummy
3182  * run for the tape, and so doesn't need to merge a run from the tape (or
3183  * conceptually "merges" the dummy run, if you prefer). According to
3184  * Knuth, Algorithm D "isn't strictly optimal" in its method of
3185  * distribution and dummy run assignment; this edge case seems very
3186  * unlikely to make that appreciably worse.
3187  */
3188  Assert(state->status == TSS_BUILDRUNS);
3189 
3190  /*
3191  * It seems unlikely that this limit will ever be exceeded, but take no
3192  * chances
3193  */
3194  if (state->currentRun == INT_MAX)
3195  ereport(ERROR,
3196  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3197  errmsg("cannot have more than %d runs for an external sort",
3198  INT_MAX)));
3199 
3200  state->currentRun++;
3201 
3202 #ifdef TRACE_SORT
3203  if (trace_sort)
3204  elog(LOG, "worker %d starting quicksort of run %d: %s",
3205  state->worker, state->currentRun,
3206  pg_rusage_show(&state->ru_start));
3207 #endif
3208 
3209  /*
3210  * Sort all tuples accumulated within the allowed amount of memory for
3211  * this run using quicksort
3212  */
3213  tuplesort_sort_memtuples(state);
3214 
3215 #ifdef TRACE_SORT
3216  if (trace_sort)
3217  elog(LOG, "worker %d finished quicksort of run %d: %s",
3218  state->worker, state->currentRun,
3219  pg_rusage_show(&state->ru_start));
3220 #endif
3221 
3222  memtupwrite = state->memtupcount;
3223  for (i = 0; i < memtupwrite; i++)
3224  {
3225  WRITETUP(state, state->tp_tapenum[state->destTape],
3226  &state->memtuples[i]);
3227  state->memtupcount--;
3228  }
3229 
3230  /*
3231  * Reset tuple memory. We've freed all of the tuples that we previously
3232  * allocated. It's important to avoid fragmentation when there is a stark
3233  * change in the sizes of incoming tuples. Fragmentation due to
3234  * AllocSetFree's bucketing by size class might be particularly bad if
3235  * this step wasn't taken.
3236  */
3238 
3239  markrunend(state, state->tp_tapenum[state->destTape]);
3240  state->tp_runs[state->destTape]++;
3241  state->tp_dummy[state->destTape]--; /* per Alg D step D2 */
3242 
3243 #ifdef TRACE_SORT
3244  if (trace_sort)
3245  elog(LOG, "worker %d finished writing run %d to tape %d: %s",
3246  state->worker, state->currentRun, state->destTape,
3247  pg_rusage_show(&state->ru_start));
3248 #endif
3249 
3250  if (!alltuples)
3251  selectnewtape(state);
3252 }
TupSortStatus status
Definition: tuplesort.c:242
PGRUsage ru_start
Definition: tuplesort.c:481
int errcode(int sqlerrcode)
Definition: elog.c:610
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
static void markrunend(Tuplesortstate *state, int tapenum)
Definition: tuplesort.c:3694
#define ERROR
Definition: elog.h:43
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
static void selectnewtape(Tuplesortstate *state)
Definition: tuplesort.c:2724
#define WRITETUP(state, tape, stup)
Definition: tuplesort.c:543
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
static void tuplesort_sort_memtuples(Tuplesortstate *state)
Definition: tuplesort.c:3536
int * tp_dummy
Definition: tuplesort.c:387
MemoryContext tuplecontext
Definition: tuplesort.c:263
int errmsg(const char *fmt,...)
Definition: elog.c:821
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:214
int i
#define LACKMEM(state)
Definition: tuplesort.c:545
SortTuple * memtuples
Definition: tuplesort.c:311

◆ free_sort_tuple()

static void free_sort_tuple ( Tuplesortstate state,
SortTuple stup 
)
static

Definition at line 4755 of file tuplesort.c.

References FREEMEM, GetMemoryChunkSpace(), pfree(), and SortTuple::tuple.

Referenced by make_bounded_heap(), and puttuple_common().

4756 {
4757  FREEMEM(state, GetMemoryChunkSpace(stup->tuple));
4758  pfree(stup->tuple);
4759 }
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
void * tuple
Definition: tuplesort.c:179
void pfree(void *pointer)
Definition: mcxt.c:1057
#define FREEMEM(state, amt)
Definition: tuplesort.c:547

◆ getlen()

static unsigned int getlen ( Tuplesortstate state,
int  tapenum,
bool  eofOK 
)
static

Definition at line 3681 of file tuplesort.c.

References elog, ERROR, LogicalTapeRead(), and Tuplesortstate::tapeset.

Referenced by mergereadnext(), and tuplesort_gettuple_common().

3682 {
3683  unsigned int len;
3684 
3685  if (LogicalTapeRead(state->tapeset, tapenum,
3686  &len, sizeof(len)) != sizeof(len))
3687  elog(ERROR, "unexpected end of tape");
3688  if (len == 0 && !eofOK)
3689  elog(ERROR, "unexpected end of data");
3690  return len;
3691 }
size_t LogicalTapeRead(LogicalTapeSet *lts, int tapenum, void *ptr, size_t size)
Definition: logtape.c:977
#define ERROR
Definition: elog.h:43
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
#define elog(elevel,...)
Definition: elog.h:214

◆ grow_memtuples()

static bool grow_memtuples ( Tuplesortstate state)
static

Definition at line 1546 of file tuplesort.c.

References Tuplesortstate::allowedMem, Tuplesortstate::availMem, elog, ERROR, FREEMEM, GetMemoryChunkSpace(), Tuplesortstate::growmemtuples, LACKMEM, MaxAllocHugeSize, Tuplesortstate::memtuples, Tuplesortstate::memtupsize, repalloc_huge(), and USEMEM.

Referenced by puttuple_common().

1547 {
1548  int newmemtupsize;
1549  int memtupsize = state->memtupsize;
1550  int64 memNowUsed = state->allowedMem - state->availMem;
1551 
1552  /* Forget it if we've already maxed out memtuples, per comment above */
1553  if (!state->growmemtuples)
1554  return false;
1555 
1556  /* Select new value of memtupsize */
1557  if (memNowUsed <= state->availMem)
1558  {
1559  /*
1560  * We've used no more than half of allowedMem; double our usage,
1561  * clamping at INT_MAX tuples.
1562  */
1563  if (memtupsize < INT_MAX / 2)
1564  newmemtupsize = memtupsize * 2;
1565  else
1566  {
1567  newmemtupsize = INT_MAX;
1568  state->growmemtuples = false;
1569  }
1570  }
1571  else
1572  {
1573  /*
1574  * This will be the last increment of memtupsize. Abandon doubling
1575  * strategy and instead increase as much as we safely can.
1576  *
1577  * To stay within allowedMem, we can't increase memtupsize by more
1578  * than availMem / sizeof(SortTuple) elements. In practice, we want
1579  * to increase it by considerably less, because we need to leave some
1580  * space for the tuples to which the new array slots will refer. We
1581  * assume the new tuples will be about the same size as the tuples
1582  * we've already seen, and thus we can extrapolate from the space
1583  * consumption so far to estimate an appropriate new size for the
1584  * memtuples array. The optimal value might be higher or lower than
1585  * this estimate, but it's hard to know that in advance. We again
1586  * clamp at INT_MAX tuples.
1587  *
1588  * This calculation is safe against enlarging the array so much that
1589  * LACKMEM becomes true, because the memory currently used includes
1590  * the present array; thus, there would be enough allowedMem for the
1591  * new array elements even if no other memory were currently used.
1592  *
1593  * We do the arithmetic in float8, because otherwise the product of
1594  * memtupsize and allowedMem could overflow. Any inaccuracy in the
1595  * result should be insignificant; but even if we computed a
1596  * completely insane result, the checks below will prevent anything
1597  * really bad from happening.
1598  */
1599  double grow_ratio;
1600 
1601  grow_ratio = (double) state->allowedMem / (double) memNowUsed;
1602  if (memtupsize * grow_ratio < INT_MAX)
1603  newmemtupsize = (int) (memtupsize * grow_ratio);
1604  else
1605  newmemtupsize = INT_MAX;
1606 
1607  /* We won't make any further enlargement attempts */
1608  state->growmemtuples = false;
1609  }
1610 
1611  /* Must enlarge array by at least one element, else report failure */
1612  if (newmemtupsize <= memtupsize)
1613  goto noalloc;
1614 
1615  /*
1616  * On a 32-bit machine, allowedMem could exceed MaxAllocHugeSize. Clamp
1617  * to ensure our request won't be rejected. Note that we can easily
1618  * exhaust address space before facing this outcome. (This is presently
1619  * impossible due to guc.c's MAX_KILOBYTES limitation on work_mem, but
1620  * don't rely on that at this distance.)
1621  */
1622  if ((Size) newmemtupsize >= MaxAllocHugeSize / sizeof(SortTuple))
1623  {
1624  newmemtupsize = (int) (MaxAllocHugeSize / sizeof(SortTuple));
1625  state->growmemtuples = false; /* can't grow any more */
1626  }
1627 
1628  /*
1629  * We need to be sure that we do not cause LACKMEM to become true, else
1630  * the space management algorithm will go nuts. The code above should
1631  * never generate a dangerous request, but to be safe, check explicitly
1632  * that the array growth fits within availMem. (We could still cause
1633  * LACKMEM if the memory chunk overhead associated with the memtuples
1634  * array were to increase. That shouldn't happen because we chose the
1635  * initial array size large enough to ensure that palloc will be treating
1636  * both old and new arrays as separate chunks. But we'll check LACKMEM
1637  * explicitly below just in case.)
1638  */
1639  if (state->availMem < (int64) ((newmemtupsize - memtupsize) * sizeof(SortTuple)))
1640  goto noalloc;
1641 
1642  /* OK, do it */
1643  FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
1644  state->memtupsize = newmemtupsize;
1645  state->memtuples = (SortTuple *)
1646  repalloc_huge(state->memtuples,
1647  state->memtupsize * sizeof(SortTuple));
1648  USEMEM(state, GetMemoryChunkSpace(state->memtuples));
1649  if (LACKMEM(state))
1650  elog(ERROR, "unexpected out-of-memory situation in tuplesort");
1651  return true;
1652 
1653 noalloc:
1654  /* If for any reason we didn't realloc, shut off future attempts */
1655  state->growmemtuples = false;
1656  return false;
1657 }
int64 availMem
Definition: tuplesort.c:250
bool growmemtuples
Definition: tuplesort.c:314
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
#define MaxAllocHugeSize
Definition: memutils.h:44
#define ERROR
Definition: elog.h:43
#define FREEMEM(state, amt)
Definition: tuplesort.c:547
int64 allowedMem
Definition: tuplesort.c:251
size_t Size
Definition: c.h:474
void * repalloc_huge(void *pointer, Size size)
Definition: mcxt.c:1140
#define USEMEM(state, amt)
Definition: tuplesort.c:546
#define elog(elevel,...)
Definition: elog.h:214
#define LACKMEM(state)
Definition: tuplesort.c:545
SortTuple * memtuples
Definition: tuplesort.c:311

◆ init_slab_allocator()

static void init_slab_allocator ( Tuplesortstate state,
int  numSlots 
)
static

Definition at line 2756 of file tuplesort.c.

References i, palloc(), SLAB_SLOT_SIZE, Tuplesortstate::slabAllocatorUsed, Tuplesortstate::slabFreeHead, Tuplesortstate::slabMemoryBegin, Tuplesortstate::slabMemoryEnd, and USEMEM.

Referenced by mergeruns().

2757 {
2758  if (numSlots > 0)
2759  {
2760  char *p;
2761  int i;
2762 
2763  state->slabMemoryBegin = palloc(numSlots * SLAB_SLOT_SIZE);
2764  state->slabMemoryEnd = state->slabMemoryBegin +
2765  numSlots * SLAB_SLOT_SIZE;
2766  state->slabFreeHead = (SlabSlot *) state->slabMemoryBegin;
2767  USEMEM(state, numSlots * SLAB_SLOT_SIZE);
2768 
2769  p = state->slabMemoryBegin;
2770  for (i = 0; i < numSlots - 1; i++)
2771  {
2772  ((SlabSlot *) p)->nextfree = (SlabSlot *) (p + SLAB_SLOT_SIZE);
2773  p += SLAB_SLOT_SIZE;
2774  }
2775  ((SlabSlot *) p)->nextfree = NULL;
2776  }
2777  else
2778  {
2779  state->slabMemoryBegin = state->slabMemoryEnd = NULL;
2780  state->slabFreeHead = NULL;
2781  }
2782  state->slabAllocatorUsed = true;
2783 }
char * slabMemoryEnd
Definition: tuplesort.c:346
#define SLAB_SLOT_SIZE
Definition: tuplesort.c:196
char * slabMemoryBegin
Definition: tuplesort.c:345
bool slabAllocatorUsed
Definition: tuplesort.c:343
void * palloc(Size size)
Definition: mcxt.c:950
#define USEMEM(state, amt)
Definition: tuplesort.c:546
int i
SlabSlot * slabFreeHead
Definition: tuplesort.c:347

◆ inittapes()

static void inittapes ( Tuplesortstate state,
bool  mergeruns 
)
static

Definition at line 2623 of file tuplesort.c.

References Tuplesortstate::allowedMem, Assert, Tuplesortstate::currentRun, Tuplesortstate::destTape, elog, Sharedsort::fileset, inittapestate(), LEADER, Tuplesortstate::Level, LOG, LogicalTapeSetCreate(), MINORDER, pg_rusage_show(), Tuplesortstate::ru_start, Tuplesortstate::shared, Tuplesortstate::status, Tuplesortstate::tapeRange, Tuplesortstate::tapeset, Tuplesortstate::tp_dummy, Tuplesortstate::tp_fib, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, trace_sort, TSS_BUILDRUNS, tuplesort_merge_order(), Tuplesortstate::worker, and WORKER.

Referenced by puttuple_common(), and tuplesort_performsort().

2624 {
2625  int maxTapes,
2626  j;
2627 
2628  Assert(!LEADER(state));
2629 
2630  if (mergeruns)
2631  {
2632  /* Compute number of tapes to use: merge order plus 1 */
2633  maxTapes = tuplesort_merge_order(state->allowedMem) + 1;
2634  }
2635  else
2636  {
2637  /* Workers can sometimes produce single run, output without merge */
2638  Assert(WORKER(state));
2639  maxTapes = MINORDER + 1;
2640  }
2641 
2642 #ifdef TRACE_SORT
2643  if (trace_sort)
2644  elog(LOG, "worker %d switching to external sort with %d tapes: %s",
2645  state->worker, maxTapes, pg_rusage_show(&state->ru_start));
2646 #endif
2647 
2648  /* Create the tape set and allocate the per-tape data arrays */
2649  inittapestate(state, maxTapes);
2650  state->tapeset =
2651  LogicalTapeSetCreate(maxTapes, false, NULL,
2652  state->shared ? &state->shared->fileset : NULL,
2653  state->worker);
2654 
2655  state->currentRun = 0;
2656 
2657  /*
2658  * Initialize variables of Algorithm D (step D1).
2659  */
2660  for (j = 0; j < maxTapes; j++)
2661  {
2662  state->tp_fib[j] = 1;
2663  state->tp_runs[j] = 0;
2664  state->tp_dummy[j] = 1;
2665  state->tp_tapenum[j] = j;
2666  }
2667  state->tp_fib[state->tapeRange] = 0;
2668  state->tp_dummy[state->tapeRange] = 0;
2669 
2670  state->Level = 1;
2671  state->destTape = 0;
2672 
2673  state->status = TSS_BUILDRUNS;
2674 }
LogicalTapeSet * LogicalTapeSetCreate(int ntapes, bool preallocate, TapeShare *shared, SharedFileSet *fileset, int worker)
Definition: logtape.c:685
TupSortStatus status
Definition: tuplesort.c:242
PGRUsage ru_start
Definition: tuplesort.c:481
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
static void mergeruns(Tuplesortstate *state)
Definition: tuplesort.c:2792
Sharedsort * shared
Definition: tuplesort.c:421
#define MINORDER
Definition: tuplesort.c:229
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define LEADER(state)
Definition: tuplesort.c:550
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
#define WORKER(state)
Definition: tuplesort.c:549
int64 allowedMem
Definition: tuplesort.c:251
#define Assert(condition)
Definition: c.h:746
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2583
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:214
static void inittapestate(Tuplesortstate *state, int maxTapes)
Definition: tuplesort.c:2680
SharedFileSet fileset
Definition: tuplesort.c:506

◆ inittapestate()

static void inittapestate ( Tuplesortstate state,
int  maxTapes 
)
static

Definition at line 2680 of file tuplesort.c.

References Tuplesortstate::allowedMem, GetMemoryChunkSpace(), Tuplesortstate::maxTapes, Tuplesortstate::memtuples, Tuplesortstate::mergeactive, palloc0(), PrepareTempTablespaces(), TAPE_BUFFER_OVERHEAD, Tuplesortstate::tapeRange, Tuplesortstate::tp_dummy, Tuplesortstate::tp_fib, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, and USEMEM.

Referenced by inittapes(), and leader_takeover_tapes().

2681 {
2682  int64 tapeSpace;
2683 
2684  /*
2685  * Decrease availMem to reflect the space needed for tape buffers; but
2686  * don't decrease it to the point that we have no room for tuples. (That
2687  * case is only likely to occur if sorting pass-by-value Datums; in all
2688  * other scenarios the memtuples[] array is unlikely to occupy more than
2689  * half of allowedMem. In the pass-by-value case it's not important to
2690  * account for tuple space, so we don't care if LACKMEM becomes
2691  * inaccurate.)
2692  */
2693  tapeSpace = (int64) maxTapes * TAPE_BUFFER_OVERHEAD;
2694 
2695  if (tapeSpace + GetMemoryChunkSpace(state->memtuples) < state->allowedMem)
2696  USEMEM(state, tapeSpace);
2697 
2698  /*
2699  * Make sure that the temp file(s) underlying the tape set are created in
2700  * suitable temp tablespaces. For parallel sorts, this should have been
2701  * called already, but it doesn't matter if it is called a second time.
2702  */
2704 
2705  state->mergeactive = (bool *) palloc0(maxTapes * sizeof(bool));
2706  state->tp_fib = (int *) palloc0(maxTapes * sizeof(int));
2707  state->tp_runs = (int *) palloc0(maxTapes * sizeof(int));
2708  state->tp_dummy = (int *) palloc0(maxTapes * sizeof(int));
2709  state->tp_tapenum = (int *) palloc0(maxTapes * sizeof(int));
2710 
2711  /* Record # of tapes allocated (for duration of sort) */
2712  state->maxTapes = maxTapes;
2713  /* Record maximum # of tapes usable as inputs when merging */
2714  state->tapeRange = maxTapes - 1;
2715 }
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
#define TAPE_BUFFER_OVERHEAD
Definition: tuplesort.c:231
void PrepareTempTablespaces(void)
Definition: tablespace.c:1326
int64 allowedMem
Definition: tuplesort.c:251
void * palloc0(Size size)
Definition: mcxt.c:981
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
#define USEMEM(state, amt)
Definition: tuplesort.c:546
bool * mergeactive
Definition: tuplesort.c:376
SortTuple * memtuples
Definition: tuplesort.c:311

◆ leader_takeover_tapes()

static void leader_takeover_tapes ( Tuplesortstate state)
static

Definition at line 4689 of file tuplesort.c.

References Assert, Tuplesortstate::currentRun, Tuplesortstate::destTape, elog, ERROR, Sharedsort::fileset, inittapestate(), LEADER, Tuplesortstate::Level, LogicalTapeSetCreate(), Tuplesortstate::maxTapes, Sharedsort::mutex, Tuplesortstate::nParticipants, Tuplesortstate::shared, SpinLockAcquire, SpinLockRelease, Tuplesortstate::status, Tuplesortstate::tapeRange, Sharedsort::tapes, Tuplesortstate::tapeset, Tuplesortstate::tp_dummy, Tuplesortstate::tp_fib, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, TSS_BUILDRUNS, Tuplesortstate::worker, and Sharedsort::workersFinished.

Referenced by tuplesort_performsort().

4690 {
4691  Sharedsort *shared = state->shared;
4692  int nParticipants = state->nParticipants;
4693  int workersFinished;
4694  int j;
4695 
4696  Assert(LEADER(state));
4697  Assert(nParticipants >= 1);
4698 
4699  SpinLockAcquire(&shared->mutex);
4700  workersFinished = shared->workersFinished;
4701  SpinLockRelease(&shared->mutex);
4702 
4703  if (nParticipants != workersFinished)
4704  elog(ERROR, "cannot take over tapes before all workers finish");
4705 
4706  /*
4707  * Create the tapeset from worker tapes, including a leader-owned tape at
4708  * the end. Parallel workers are far more expensive than logical tapes,
4709  * so the number of tapes allocated here should never be excessive.
4710  *
4711  * We still have a leader tape, though it's not possible to write to it
4712  * due to restrictions in the shared fileset infrastructure used by
4713  * logtape.c. It will never be written to in practice because
4714  * randomAccess is disallowed for parallel sorts.
4715  */
4716  inittapestate(state, nParticipants + 1);
4717  state->tapeset = LogicalTapeSetCreate(nParticipants + 1, false,
4718  shared->tapes, &shared->fileset,
4719  state->worker);
4720 
4721  /* mergeruns() relies on currentRun for # of runs (in one-pass cases) */
4722  state->currentRun = nParticipants;
4723 
4724  /*
4725  * Initialize variables of Algorithm D to be consistent with runs from
4726  * workers having been generated in the leader.
4727  *
4728  * There will always be exactly 1 run per worker, and exactly one input
4729  * tape per run, because workers always output exactly 1 run, even when
4730  * there were no input tuples for workers to sort.
4731  */
4732  for (j = 0; j < state->maxTapes; j++)
4733  {
4734  /* One real run; no dummy runs for worker tapes */
4735  state->tp_fib[j] = 1;
4736  state->tp_runs[j] = 1;
4737  state->tp_dummy[j] = 0;
4738  state->tp_tapenum[j] = j;
4739  }
4740  /* Leader tape gets one dummy run, and no real runs */
4741  state->tp_fib[state->tapeRange] = 0;
4742  state->tp_runs[state->tapeRange] = 0;
4743  state->tp_dummy[state->tapeRange] = 1;
4744 
4745  state->Level = 1;
4746  state->destTape = 0;
4747 
4748  state->status = TSS_BUILDRUNS;
4749 }
LogicalTapeSet * LogicalTapeSetCreate(int ntapes, bool preallocate, TapeShare *shared, SharedFileSet *fileset, int worker)
Definition: logtape.c:685
TupSortStatus status
Definition: tuplesort.c:242
slock_t mutex
Definition: tuplesort.c:492
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:43
Sharedsort * shared
Definition: tuplesort.c:421
#define LEADER(state)
Definition: tuplesort.c:550
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
int workersFinished
Definition: tuplesort.c:503
#define SpinLockRelease(lock)
Definition: spin.h:64
#define Assert(condition)
Definition: c.h:746
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:214
TapeShare tapes[FLEXIBLE_ARRAY_MEMBER]
Definition: tuplesort.c:515
static void inittapestate(Tuplesortstate *state, int maxTapes)
Definition: tuplesort.c:2680
SharedFileSet fileset
Definition: tuplesort.c:506

◆ make_bounded_heap()

static void make_bounded_heap ( Tuplesortstate state)
static

Definition at line 3447 of file tuplesort.c.

References Assert, Tuplesortstate::bound, Tuplesortstate::bounded, CHECK_FOR_INTERRUPTS, COMPARETUP, free_sort_tuple(), i, Tuplesortstate::memtupcount, Tuplesortstate::memtuples, reversedirection(), SERIAL, Tuplesortstate::status, TSS_BOUNDED, TSS_INITIAL, tuplesort_heap_insert(), and tuplesort_heap_replace_top().

Referenced by puttuple_common().

3448 {
3449  int tupcount = state->memtupcount;
3450  int i;
3451 
3452  Assert(state->status == TSS_INITIAL);
3453  Assert(state->bounded);
3454  Assert(tupcount >= state->bound);
3455  Assert(SERIAL(state));
3456 
3457  /* Reverse sort direction so largest entry will be at root */
3458  reversedirection(state);
3459 
3460  state->memtupcount = 0; /* make the heap empty */
3461  for (i = 0; i < tupcount; i++)
3462  {
3463  if (state->memtupcount < state->bound)
3464  {
3465  /* Insert next tuple into heap */
3466  /* Must copy source tuple to avoid possible overwrite */
3467  SortTuple stup = state->memtuples[i];
3468 
3469  tuplesort_heap_insert(state, &stup);
3470  }
3471  else
3472  {
3473  /*
3474  * The heap is full. Replace the largest entry with the new
3475  * tuple, or just discard it, if it's larger than anything already
3476  * in the heap.
3477  */
3478  if (COMPARETUP(state, &state->memtuples[i], &state->memtuples[0]) <= 0)
3479  {
3480  free_sort_tuple(state, &state->memtuples[i]);
3482  }
3483  else
3484  tuplesort_heap_replace_top(state, &state->memtuples[i]);
3485  }
3486  }
3487 
3488  Assert(state->memtupcount == state->bound);
3489  state->status = TSS_BOUNDED;
3490 }
static void reversedirection(Tuplesortstate *state)
Definition: tuplesort.c:3663
TupSortStatus status
Definition: tuplesort.c:242
#define SERIAL(state)
Definition: tuplesort.c:548
static void free_sort_tuple(Tuplesortstate *state, SortTuple *stup)
Definition: tuplesort.c:4755
#define COMPARETUP(state, a, b)
Definition: tuplesort.c:541
static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3564
#define Assert(condition)
Definition: c.h:746
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3623
SortTuple * memtuples
Definition: tuplesort.c:311

◆ markrunend()

static void markrunend ( Tuplesortstate state,
int  tapenum 
)
static

Definition at line 3694 of file tuplesort.c.

References LogicalTapeWrite(), and Tuplesortstate::tapeset.

Referenced by dumptuples(), and mergeonerun().

3695 {
3696  unsigned int len = 0;
3697 
3698  LogicalTapeWrite(state->tapeset, tapenum, (void *) &len, sizeof(len));
3699 }
void LogicalTapeWrite(LogicalTapeSet *lts, int tapenum, void *ptr, size_t size)
Definition: logtape.c:775
LogicalTapeSet * tapeset
Definition: tuplesort.c:264

◆ mergeonerun()

static void mergeonerun ( Tuplesortstate state)
static

Definition at line 3019 of file tuplesort.c.

References Tuplesortstate::activeTapes, beginmerge(), elog, LOG, markrunend(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, mergereadnext(), pg_rusage_show(), RELEASE_SLAB_SLOT, Tuplesortstate::ru_start, SortTuple::srctape, Tuplesortstate::tapeRange, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, trace_sort, SortTuple::tuple, tuplesort_heap_delete_top(), tuplesort_heap_replace_top(), Tuplesortstate::worker, and WRITETUP.

Referenced by mergeruns().

3020 {
3021  int destTape = state->tp_tapenum[state->tapeRange];
3022  int srcTape;
3023 
3024  /*
3025  * Start the merge by loading one tuple from each active source tape into
3026  * the heap. We can also decrease the input run/dummy run counts.
3027  */
3028  beginmerge(state);
3029 
3030  /*
3031  * Execute merge by repeatedly extracting lowest tuple in heap, writing it
3032  * out, and replacing it with next tuple from same tape (if there is
3033  * another one).
3034  */
3035  while (state->memtupcount > 0)
3036  {
3037  SortTuple stup;
3038 
3039  /* write the tuple to destTape */
3040  srcTape = state->memtuples[0].srctape;
3041  WRITETUP(state, destTape, &state->memtuples[0]);
3042 
3043  /* recycle the slot of the tuple we just wrote out, for the next read */
3044  if (state->memtuples[0].tuple)
3045  RELEASE_SLAB_SLOT(state, state->memtuples[0].tuple);
3046 
3047  /*
3048  * pull next tuple from the tape, and replace the written-out tuple in
3049  * the heap with it.
3050  */
3051  if (mergereadnext(state, srcTape, &stup))
3052  {
3053  stup.srctape = srcTape;
3054  tuplesort_heap_replace_top(state, &stup);
3055  }
3056  else
3058  }
3059 
3060  /*
3061  * When the heap empties, we're done. Write an end-of-run marker on the
3062  * output tape, and increment its count of real runs.
3063  */
3064  markrunend(state, destTape);
3065  state->tp_runs[state->tapeRange]++;
3066 
3067 #ifdef TRACE_SORT
3068  if (trace_sort)
3069  elog(LOG, "worker %d finished %d-way merge step: %s", state->worker,
3070  state->activeTapes, pg_rusage_show(&state->ru_start));
3071 #endif
3072 }
PGRUsage ru_start
Definition: tuplesort.c:481
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
static void markrunend(Tuplesortstate *state, int tapenum)
Definition: tuplesort.c:3694
void * tuple
Definition: tuplesort.c:179
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define WRITETUP(state, tape, stup)
Definition: tuplesort.c:543
#define RELEASE_SLAB_SLOT(state, tuple)
Definition: tuplesort.c:529
static void tuplesort_heap_delete_top(Tuplesortstate *state)
Definition: tuplesort.c:3599
static bool mergereadnext(Tuplesortstate *state, int srcTape, SortTuple *stup)
Definition: tuplesort.c:3130
int srctape
Definition: tuplesort.c:182
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:214
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3623
static void beginmerge(Tuplesortstate *state)
Definition: tuplesort.c:3082
SortTuple * memtuples
Definition: tuplesort.c:311

◆ mergereadnext()

static bool mergereadnext ( Tuplesortstate state,
int  srcTape,
SortTuple stup 
)
static

Definition at line 3130 of file tuplesort.c.

References getlen(), Tuplesortstate::mergeactive, and READTUP.

Referenced by beginmerge(), mergeonerun(), and tuplesort_gettuple_common().

3131 {
3132  unsigned int tuplen;
3133 
3134  if (!state->mergeactive[srcTape])
3135  return false; /* tape's run is already exhausted */
3136 
3137  /* read next tuple, if any */
3138  if ((tuplen = getlen(state, srcTape, true)) == 0)
3139  {
3140  state->mergeactive[srcTape] = false;
3141  return false;
3142  }
3143  READTUP(state, stup, srcTape, tuplen);
3144 
3145  return true;
3146 }
static unsigned int getlen(Tuplesortstate *state, int tapenum, bool eofOK)
Definition: tuplesort.c:3681
#define READTUP(state, stup, tape, len)
Definition: tuplesort.c:544
bool * mergeactive
Definition: tuplesort.c:376

◆ mergeruns()

static void mergeruns ( Tuplesortstate state)
static

Definition at line 2792 of file tuplesort.c.

References SortSupportData::abbrev_abort, SortSupportData::abbrev_converter, SortSupportData::abbrev_full_comparator, Assert, Tuplesortstate::availMem, beginmerge(), SortSupportData::comparator, Tuplesortstate::currentRun, elog, FREEMEM, GetMemoryChunkSpace(), init_slab_allocator(), INT64_FORMAT, Tuplesortstate::Level, LOG, LogicalTapeFreeze(), LogicalTapeRewindForRead(), LogicalTapeRewindForWrite(), LogicalTapeSetForgetFreeSpace(), Tuplesortstate::maincontext, Max, Tuplesortstate::maxTapes, MemoryContextAlloc(), MemoryContextResetOnly(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, Tuplesortstate::memtupsize, mergeonerun(), pfree(), Tuplesortstate::randomAccess, Tuplesortstate::read_buffer_size, Tuplesortstate::result_tape, Tuplesortstate::sortKeys, Tuplesortstate::status, TAPE_BUFFER_OVERHEAD, Tuplesortstate::tapeRange, Tuplesortstate::tapeset, Tuplesortstate::tp_dummy, Tuplesortstate::tp_runs, Tuplesortstate::tp_tapenum, trace_sort, TSS_BUILDRUNS, TSS_FINALMERGE, TSS_SORTEDONTAPE, Tuplesortstate::tuplecontext, Tuplesortstate::tuples, USEMEM, Tuplesortstate::worker, WORKER, and worker_freeze_result_tape().

Referenced by tuplesort_performsort().

2793 {
2794  int tapenum,
2795  svTape,
2796  svRuns,
2797  svDummy;
2798  int numTapes;
2799  int numInputTapes;
2800 
2801  Assert(state->status == TSS_BUILDRUNS);
2802  Assert(state->memtupcount == 0);
2803 
2804  if (state->sortKeys != NULL && state->sortKeys->abbrev_converter != NULL)
2805  {
2806  /*
2807  * If there are multiple runs to be merged, when we go to read back
2808  * tuples from disk, abbreviated keys will not have been stored, and
2809  * we don't care to regenerate them. Disable abbreviation from this
2810  * point on.
2811  */
2812  state->sortKeys->abbrev_converter = NULL;
2814 
2815  /* Not strictly necessary, but be tidy */
2816  state->sortKeys->abbrev_abort = NULL;
2817  state->sortKeys->abbrev_full_comparator = NULL;
2818  }
2819 
2820  /*
2821  * Reset tuple memory. We've freed all the tuples that we previously
2822  * allocated. We will use the slab allocator from now on.
2823  */
2825 
2826  /*
2827  * We no longer need a large memtuples array. (We will allocate a smaller
2828  * one for the heap later.)
2829  */
2830  FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
2831  pfree(state->memtuples);
2832  state->memtuples = NULL;
2833 
2834  /*
2835  * If we had fewer runs than tapes, refund the memory that we imagined we
2836  * would need for the tape buffers of the unused tapes.
2837  *
2838  * numTapes and numInputTapes reflect the actual number of tapes we will
2839  * use. Note that the output tape's tape number is maxTapes - 1, so the
2840  * tape numbers of the used tapes are not consecutive, and you cannot just
2841  * loop from 0 to numTapes to visit all used tapes!
2842  */
2843  if (state->Level == 1)
2844  {
2845  numInputTapes = state->currentRun;
2846  numTapes = numInputTapes + 1;
2847  FREEMEM(state, (state->maxTapes - numTapes) * TAPE_BUFFER_OVERHEAD);
2848  }
2849  else
2850  {
2851  numInputTapes = state->tapeRange;
2852  numTapes = state->maxTapes;
2853  }
2854 
2855  /*
2856  * Initialize the slab allocator. We need one slab slot per input tape,
2857  * for the tuples in the heap, plus one to hold the tuple last returned
2858  * from tuplesort_gettuple. (If we're sorting pass-by-val Datums,
2859  * however, we don't need to do allocate anything.)
2860  *
2861  * From this point on, we no longer use the USEMEM()/LACKMEM() mechanism
2862  * to track memory usage of individual tuples.
2863  */
2864  if (state->tuples)
2865  init_slab_allocator(state, numInputTapes + 1);
2866  else
2867  init_slab_allocator(state, 0);
2868 
2869  /*
2870  * Allocate a new 'memtuples' array, for the heap. It will hold one tuple
2871  * from each input tape.
2872  */
2873  state->memtupsize = numInputTapes;
2874  state->memtuples = (SortTuple *) MemoryContextAlloc(state->maincontext,
2875  numInputTapes * sizeof(SortTuple));
2876  USEMEM(state, GetMemoryChunkSpace(state->memtuples));
2877 
2878  /*
2879  * Use all the remaining memory we have available for read buffers among
2880  * the input tapes.
2881  *
2882  * We don't try to "rebalance" the memory among tapes, when we start a new
2883  * merge phase, even if some tapes are inactive in the new phase. That
2884  * would be hard, because logtape.c doesn't know where one run ends and
2885  * another begins. When a new merge phase begins, and a tape doesn't
2886  * participate in it, its buffer nevertheless already contains tuples from
2887  * the next run on same tape, so we cannot release the buffer. That's OK
2888  * in practice, merge performance isn't that sensitive to the amount of
2889  * buffers used, and most merge phases use all or almost all tapes,
2890  * anyway.
2891  */
2892 #ifdef TRACE_SORT
2893  if (trace_sort)
2894  elog(LOG, "worker %d using " INT64_FORMAT " KB of memory for read buffers among %d input tapes",
2895  state->worker, state->availMem / 1024, numInputTapes);
2896 #endif
2897 
2898  state->read_buffer_size = Max(state->availMem / numInputTapes, 0);
2899  USEMEM(state, state->read_buffer_size * numInputTapes);
2900 
2901  /* End of step D2: rewind all output tapes to prepare for merging */
2902  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
2903  LogicalTapeRewindForRead(state->tapeset, tapenum, state->read_buffer_size);
2904 
2905  for (;;)
2906  {
2907  /*
2908  * At this point we know that tape[T] is empty. If there's just one
2909  * (real or dummy) run left on each input tape, then only one merge
2910  * pass remains. If we don't have to produce a materialized sorted
2911  * tape, we can stop at this point and do the final merge on-the-fly.
2912  */
2913  if (!state->randomAccess && !WORKER(state))
2914  {
2915  bool allOneRun = true;
2916 
2917  Assert(state->tp_runs[state->tapeRange] == 0);
2918  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
2919  {
2920  if (state->tp_runs[tapenum] + state->tp_dummy[tapenum] != 1)
2921  {
2922  allOneRun = false;
2923  break;
2924  }
2925  }
2926  if (allOneRun)
2927  {
2928  /* Tell logtape.c we won't be writing anymore */
2930  /* Initialize for the final merge pass */
2931  beginmerge(state);
2932  state->status = TSS_FINALMERGE;
2933  return;
2934  }
2935  }
2936 
2937  /* Step D5: merge runs onto tape[T] until tape[P] is empty */
2938  while (state->tp_runs[state->tapeRange - 1] ||
2939  state->tp_dummy[state->tapeRange - 1])
2940  {
2941  bool allDummy = true;
2942 
2943  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
2944  {
2945  if (state->tp_dummy[tapenum] == 0)
2946  {
2947  allDummy = false;
2948  break;
2949  }
2950  }
2951 
2952  if (allDummy)
2953  {
2954  state->tp_dummy[state->tapeRange]++;
2955  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
2956  state->tp_dummy[tapenum]--;
2957  }
2958  else
2959  mergeonerun(state);
2960  }
2961 
2962  /* Step D6: decrease level */
2963  if (--state->Level == 0)
2964  break;
2965  /* rewind output tape T to use as new input */
2966  LogicalTapeRewindForRead(state->tapeset, state->tp_tapenum[state->tapeRange],
2967  state->read_buffer_size);
2968  /* rewind used-up input tape P, and prepare it for write pass */
2969  LogicalTapeRewindForWrite(state->tapeset, state->tp_tapenum[state->tapeRange - 1]);
2970  state->tp_runs[state->tapeRange - 1] = 0;
2971 
2972  /*
2973  * reassign tape units per step D6; note we no longer care about A[]
2974  */
2975  svTape = state->tp_tapenum[state->tapeRange];
2976  svDummy = state->tp_dummy[state->tapeRange];
2977  svRuns = state->tp_runs[state->tapeRange];
2978  for (tapenum = state->tapeRange; tapenum > 0; tapenum--)
2979  {
2980  state->tp_tapenum[tapenum] = state->tp_tapenum[tapenum - 1];
2981  state->tp_dummy[tapenum] = state->tp_dummy[tapenum - 1];
2982  state->tp_runs[tapenum] = state->tp_runs[tapenum - 1];
2983  }
2984  state->tp_tapenum[0] = svTape;
2985  state->tp_dummy[0] = svDummy;
2986  state->tp_runs[0] = svRuns;
2987  }
2988 
2989  /*
2990  * Done. Knuth says that the result is on TAPE[1], but since we exited
2991  * the loop without performing the last iteration of step D6, we have not
2992  * rearranged the tape unit assignment, and therefore the result is on
2993  * TAPE[T]. We need to do it this way so that we can freeze the final
2994  * output tape while rewinding it. The last iteration of step D6 would be
2995  * a waste of cycles anyway...
2996  */
2997  state->result_tape = state->tp_tapenum[state->tapeRange];
2998  if (!WORKER(state))
2999  LogicalTapeFreeze(state->tapeset, state->result_tape, NULL);
3000  else
3002  state->status = TSS_SORTEDONTAPE;
3003 
3004  /* Release the read buffers of all the other tapes, by rewinding them. */
3005  for (tapenum = 0; tapenum < state->maxTapes; tapenum++)
3006  {
3007  if (tapenum != state->result_tape)
3008  LogicalTapeRewindForWrite(state->tapeset, tapenum);
3009  }
3010 }
int64 availMem
Definition: tuplesort.c:250
size_t read_buffer_size
Definition: tuplesort.c:350
TupSortStatus status
Definition: tuplesort.c:242
static void mergeonerun(Tuplesortstate *state)
Definition: tuplesort.c:3019
static void worker_freeze_result_tape(Tuplesortstate *state)
Definition: tuplesort.c:4630
SortSupport sortKeys
Definition: tuplesort.c:430
MemoryContext maincontext
Definition: tuplesort.c:260
bool randomAccess
Definition: tuplesort.c:244
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
#define LOG
Definition: elog.h:26
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:156
bool trace_sort
Definition: tuplesort.c:140
void LogicalTapeRewindForWrite(LogicalTapeSet *lts, int tapenum)
Definition: logtape.c:951
static void init_slab_allocator(Tuplesortstate *state, int numSlots)
Definition: tuplesort.c:2756
#define TAPE_BUFFER_OVERHEAD
Definition: tuplesort.c:231
void pfree(void *pointer)
Definition: mcxt.c:1057
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:106
int(* abbrev_full_comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:191
#define FREEMEM(state, amt)
Definition: tuplesort.c:547
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
#define WORKER(state)
Definition: tuplesort.c:549
#define Max(x, y)
Definition: c.h:922
#define Assert(condition)
Definition: c.h:746
bool(* abbrev_abort)(int memtupcount, SortSupport ssup)
Definition: sortsupport.h:182
#define INT64_FORMAT
Definition: c.h:417
void LogicalTapeRewindForRead(LogicalTapeSet *lts, int tapenum, size_t buffer_size)
Definition: logtape.c:863
int * tp_dummy
Definition: tuplesort.c:387
void LogicalTapeFreeze(LogicalTapeSet *lts, int tapenum, TapeShare *share)
Definition: logtape.c:1034
MemoryContext tuplecontext
Definition: tuplesort.c:263
int * tp_tapenum
Definition: tuplesort.c:388
#define USEMEM(state, amt)
Definition: tuplesort.c:546
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
#define elog(elevel,...)
Definition: elog.h:214
void LogicalTapeSetForgetFreeSpace(LogicalTapeSet *lts)
Definition: logtape.c:764
static void beginmerge(Tuplesortstate *state)
Definition: tuplesort.c:3082
SortTuple * memtuples
Definition: tuplesort.c:311

◆ puttuple_common()

static void puttuple_common ( Tuplesortstate state,
SortTuple tuple 
)
static

Definition at line 1868 of file tuplesort.c.

References Assert, Tuplesortstate::bound, Tuplesortstate::bounded, CHECK_FOR_INTERRUPTS, COMPARETUP, dumptuples(), elog, ERROR, free_sort_tuple(), grow_memtuples(), inittapes(), LACKMEM, LEADER, LOG, make_bounded_heap(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, Tuplesortstate::memtupsize, pg_rusage_show(), Tuplesortstate::ru_start, Tuplesortstate::status, trace_sort, TSS_BOUNDED, TSS_BUILDRUNS, TSS_INITIAL, and tuplesort_heap_replace_top().

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

1869 {
1870  Assert(!LEADER(state));
1871 
1872  switch (state->status)
1873  {
1874  case TSS_INITIAL:
1875 
1876  /*
1877  * Save the tuple into the unsorted array. First, grow the array
1878  * as needed. Note that we try to grow the array when there is
1879  * still one free slot remaining --- if we fail, there'll still be
1880  * room to store the incoming tuple, and then we'll switch to
1881  * tape-based operation.
1882  */
1883  if (state->memtupcount >= state->memtupsize - 1)
1884  {
1885  (void) grow_memtuples(state);
1886  Assert(state->memtupcount < state->memtupsize);
1887  }
1888  state->memtuples[state->memtupcount++] = *tuple;
1889 
1890  /*
1891  * Check if it's time to switch over to a bounded heapsort. We do
1892  * so if the input tuple count exceeds twice the desired tuple
1893  * count (this is a heuristic for where heapsort becomes cheaper
1894  * than a quicksort), or if we've just filled workMem and have
1895  * enough tuples to meet the bound.
1896  *
1897  * Note that once we enter TSS_BOUNDED state we will always try to
1898  * complete the sort that way. In the worst case, if later input
1899  * tuples are larger than earlier ones, this might cause us to
1900  * exceed workMem significantly.
1901  */
1902  if (state->bounded &&
1903  (state->memtupcount > state->bound * 2 ||
1904  (state->memtupcount > state->bound && LACKMEM(state))))
1905  {
1906 #ifdef TRACE_SORT
1907  if (trace_sort)
1908  elog(LOG, "switching to bounded heapsort at %d tuples: %s",
1909  state->memtupcount,
1910  pg_rusage_show(&state->ru_start));
1911 #endif
1912  make_bounded_heap(state);
1913  return;
1914  }
1915 
1916  /*
1917  * Done if we still fit in available memory and have array slots.
1918  */
1919  if (state->memtupcount < state->memtupsize && !LACKMEM(state))
1920  return;
1921 
1922  /*
1923  * Nope; time to switch to tape-based operation.
1924  */
1925  inittapes(state, true);
1926 
1927  /*
1928  * Dump all tuples.
1929  */
1930  dumptuples(state, false);
1931  break;
1932 
1933  case TSS_BOUNDED:
1934 
1935  /*
1936  * We don't want to grow the array here, so check whether the new
1937  * tuple can be discarded before putting it in. This should be a
1938  * good speed optimization, too, since when there are many more
1939  * input tuples than the bound, most input tuples can be discarded
1940  * with just this one comparison. Note that because we currently
1941  * have the sort direction reversed, we must check for <= not >=.
1942  */
1943  if (COMPARETUP(state, tuple, &state->memtuples[0]) <= 0)
1944  {
1945  /* new tuple <= top of the heap, so we can discard it */
1946  free_sort_tuple(state, tuple);
1948  }
1949  else
1950  {
1951  /* discard top of heap, replacing it with the new tuple */
1952  free_sort_tuple(state, &state->memtuples[0]);
1953  tuplesort_heap_replace_top(state, tuple);
1954  }
1955  break;
1956 
1957  case TSS_BUILDRUNS:
1958 
1959  /*
1960  * Save the tuple into the unsorted array (there must be space)
1961  */
1962  state->memtuples[state->memtupcount++] = *tuple;
1963 
1964  /*
1965  * If we are over the memory limit, dump all tuples.
1966  */
1967  dumptuples(state, false);
1968  break;
1969 
1970  default:
1971  elog(ERROR, "invalid tuplesort state");
1972  break;
1973  }
1974 }
static void dumptuples(Tuplesortstate *state, bool alltuples)
Definition: tuplesort.c:3155
TupSortStatus status
Definition: tuplesort.c:242
static bool grow_memtuples(Tuplesortstate *state)
Definition: tuplesort.c:1546
PGRUsage ru_start
Definition: tuplesort.c:481
static void inittapes(Tuplesortstate *state, bool mergeruns)
Definition: tuplesort.c:2623
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
#define ERROR
Definition: elog.h:43
static void free_sort_tuple(Tuplesortstate *state, SortTuple *stup)
Definition: tuplesort.c:4755
#define COMPARETUP(state, a, b)
Definition: tuplesort.c:541
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define LEADER(state)
Definition: tuplesort.c:550
#define Assert(condition)
Definition: c.h:746
#define elog(elevel,...)
Definition: elog.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void make_bounded_heap(Tuplesortstate *state)
Definition: tuplesort.c:3447
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3623
#define LACKMEM(state)
Definition: tuplesort.c:545
SortTuple * memtuples
Definition: tuplesort.c:311

◆ readtup_alloc()

static void * readtup_alloc ( Tuplesortstate state,
Size  tuplen 
)
static

Definition at line 3708 of file tuplesort.c.

References Assert, buf, MemoryContextAlloc(), SlabSlot::nextfree, SLAB_SLOT_SIZE, Tuplesortstate::slabFreeHead, and Tuplesortstate::sortcontext.

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

3709 {
3710  SlabSlot *buf;
3711 
3712  /*
3713  * We pre-allocate enough slots in the slab arena that we should never run
3714  * out.
3715  */
3716  Assert(state->slabFreeHead);
3717 
3718  if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
3719  return MemoryContextAlloc(state->sortcontext, tuplen);
3720  else
3721  {
3722  buf = state->slabFreeHead;
3723  /* Reuse this slot */
3724  state->slabFreeHead = buf->nextfree;
3725 
3726  return buf;
3727  }
3728 }
#define SLAB_SLOT_SIZE
Definition: tuplesort.c:196
union SlabSlot * nextfree
Definition: tuplesort.c:200
MemoryContext sortcontext
Definition: tuplesort.c:262
static char * buf
Definition: pg_test_fsync.c:68
#define Assert(condition)
Definition: c.h:746
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
SlabSlot * slabFreeHead
Definition: tuplesort.c:347

◆ readtup_cluster()

static void readtup_cluster ( Tuplesortstate state,
SortTuple stup,
int  tapenum,
unsigned int  len 
)
static

Definition at line 4143 of file tuplesort.c.

References SortTuple::datum1, heap_getattr, HEAPTUPLESIZE, IndexInfo::ii_IndexAttrNumbers, Tuplesortstate::indexInfo, InvalidOid, SortTuple::isnull1, LogicalTapeReadExact, Tuplesortstate::randomAccess, readtup_alloc(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, Tuplesortstate::tapeset, Tuplesortstate::tupDesc, and SortTuple::tuple.

Referenced by tuplesort_begin_cluster().

4145 {
4146  unsigned int t_len = tuplen - sizeof(ItemPointerData) - sizeof(int);
4147  HeapTuple tuple = (HeapTuple) readtup_alloc(state,
4148  t_len + HEAPTUPLESIZE);
4149 
4150  /* Reconstruct the HeapTupleData header */
4151  tuple->t_data = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
4152  tuple->t_len = t_len;
4153  LogicalTapeReadExact(state->tapeset, tapenum,
4154  &tuple->t_self, sizeof(ItemPointerData));
4155  /* We don't currently bother to reconstruct t_tableOid */
4156  tuple->t_tableOid = InvalidOid;
4157  /* Read in the tuple body */
4158  LogicalTapeReadExact(state->tapeset, tapenum,
4159  tuple->t_data, tuple->t_len);
4160  if (state->randomAccess) /* need trailing length word? */
4161  LogicalTapeReadExact(state->tapeset, tapenum,
4162  &tuplen, sizeof(tuplen));
4163  stup->tuple = (void *) tuple;
4164  /* set up first-column key value, if it's a simple column */
4165  if (state->indexInfo->ii_IndexAttrNumbers[0] != 0)
4166  stup->datum1 = heap_getattr(tuple,
4167  state->indexInfo->ii_IndexAttrNumbers[0],
4168  state->tupDesc,
4169  &stup->isnull1);
4170 }
HeapTupleData * HeapTuple
Definition: htup.h:71
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
bool randomAccess
Definition: tuplesort.c:244
Datum datum1
Definition: tuplesort.c:180
#define LogicalTapeReadExact(tapeset, tapenum, ptr, len)
Definition: tuplesort.c:602
bool isnull1
Definition: tuplesort.c:181
HeapTupleHeader t_data
Definition: htup.h:68
void * tuple
Definition: tuplesort.c:179
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
IndexInfo * indexInfo
Definition: tuplesort.c:451
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
Oid t_tableOid
Definition: htup.h:66
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
#define InvalidOid
Definition: postgres_ext.h:36
struct ItemPointerData ItemPointerData
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3708
#define HEAPTUPLESIZE
Definition: htup.h:73
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:159
TupleDesc tupDesc
Definition: tuplesort.c:429

◆ readtup_datum()

static void readtup_datum ( Tuplesortstate state,
SortTuple stup,
int  tapenum,
unsigned int  len 
)
static

Definition at line 4491 of file tuplesort.c.

References Assert, SortTuple::datum1, SortTuple::isnull1, LogicalTapeReadExact, PointerGetDatum, Tuplesortstate::randomAccess, readtup_alloc(), Tuplesortstate::tapeset, SortTuple::tuple, and Tuplesortstate::tuples.

Referenced by tuplesort_begin_datum().

4493 {
4494  unsigned int tuplen = len - sizeof(unsigned int);
4495 
4496  if (tuplen == 0)
4497  {
4498  /* it's NULL */
4499  stup->datum1 = (Datum) 0;
4500  stup->isnull1 = true;
4501  stup->tuple = NULL;
4502  }
4503  else if (!state->tuples)
4504  {
4505  Assert(tuplen == sizeof(Datum));
4506  LogicalTapeReadExact(state->tapeset, tapenum,
4507  &stup->datum1, tuplen);
4508  stup->isnull1 = false;
4509  stup->tuple = NULL;
4510  }
4511  else
4512  {
4513  void *raddr = readtup_alloc(state, tuplen);
4514 
4515  LogicalTapeReadExact(state->tapeset, tapenum,
4516  raddr, tuplen);
4517  stup->datum1 = PointerGetDatum(raddr);
4518  stup->isnull1 = false;
4519  stup->tuple = raddr;
4520  }
4521 
4522  if (state->randomAccess) /* need trailing length word? */
4523  LogicalTapeReadExact(state->tapeset, tapenum,
4524  &tuplen, sizeof(tuplen));
4525 }
#define PointerGetDatum(X)
Definition: postgres.h:556
bool randomAccess
Definition: tuplesort.c:244
Datum datum1
Definition: tuplesort.c:180
#define LogicalTapeReadExact(tapeset, tapenum, ptr, len)
Definition: tuplesort.c:602
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:746
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3708

◆ readtup_heap()

static void readtup_heap ( Tuplesortstate state,
SortTuple stup,
int  tapenum,
unsigned int  len 
)
static

Definition at line 3903 of file tuplesort.c.

References SortTuple::datum1, heap_getattr, SortTuple::isnull1, LogicalTapeReadExact, MINIMAL_TUPLE_DATA_OFFSET, MINIMAL_TUPLE_OFFSET, Tuplesortstate::randomAccess, readtup_alloc(), Tuplesortstate::sortKeys, SortSupportData::ssup_attno, HeapTupleData::t_data, HeapTupleData::t_len, MinimalTupleData::t_len, Tuplesortstate::tapeset, Tuplesortstate::tupDesc, and SortTuple::tuple.

Referenced by tuplesort_begin_heap().

3905 {
3906  unsigned int tupbodylen = len - sizeof(int);
3907  unsigned int tuplen = tupbodylen + MINIMAL_TUPLE_DATA_OFFSET;
3908  MinimalTuple tuple = (MinimalTuple) readtup_alloc(state, tuplen);
3909  char *tupbody = (char *) tuple + MINIMAL_TUPLE_DATA_OFFSET;
3910  HeapTupleData htup;
3911 
3912  /* read in the tuple proper */
3913  tuple->t_len = tuplen;
3914  LogicalTapeReadExact(state->tapeset, tapenum,
3915  tupbody, tupbodylen);
3916  if (state->randomAccess) /* need trailing length word? */
3917  LogicalTapeReadExact(state->tapeset, tapenum,
3918  &tuplen, sizeof(tuplen));
3919  stup->tuple = (void *) tuple;
3920  /* set up first-column key value */
3921  htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
3922  htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
3923  stup->datum1 = heap_getattr(&htup,
3924  state->sortKeys[0].ssup_attno,
3925  state->tupDesc,
3926  &stup->isnull1);
3927 }
#define MINIMAL_TUPLE_DATA_OFFSET
Definition: htup_details.h:623
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
SortSupport sortKeys
Definition: tuplesort.c:430
bool randomAccess
Definition: tuplesort.c:244
Datum datum1
Definition: tuplesort.c:180
#define LogicalTapeReadExact(tapeset, tapenum, ptr, len)
Definition: tuplesort.c:602
bool isnull1
Definition: tuplesort.c:181
HeapTupleHeader t_data
Definition: htup.h:68
void * tuple
Definition: tuplesort.c:179
uint32 t_len
Definition: htup.h:64
MinimalTupleData * MinimalTuple
Definition: htup.h:27
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:619
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3708
TupleDesc tupDesc
Definition: tuplesort.c:429

◆ readtup_index()

static void readtup_index ( Tuplesortstate state,
SortTuple stup,
int  tapenum,
unsigned int  len 
)
static

Definition at line 4398 of file tuplesort.c.

References SortTuple::datum1, index_getattr, Tuplesortstate::indexRel, SortTuple::isnull1, LogicalTapeReadExact, Tuplesortstate::randomAccess, readtup_alloc(), RelationGetDescr, Tuplesortstate::tapeset, and SortTuple::tuple.

Referenced by tuplesort_begin_index_btree(), tuplesort_begin_index_gist(), and tuplesort_begin_index_hash().

4400 {
4401  unsigned int tuplen = len - sizeof(unsigned int);
4402  IndexTuple tuple = (IndexTuple) readtup_alloc(state, tuplen);
4403 
4404  LogicalTapeReadExact(state->tapeset, tapenum,
4405  tuple, tuplen);
4406  if (state->randomAccess) /* need trailing length word? */
4407  LogicalTapeReadExact(state->tapeset, tapenum,
4408  &tuplen, sizeof(tuplen));
4409  stup->tuple = (void *) tuple;
4410  /* set up first-column key value */
4411  stup->datum1 = index_getattr(tuple,
4412  1,
4413  RelationGetDescr(state->indexRel),
4414  &stup->isnull1);
4415 }
#define RelationGetDescr(relation)
Definition: rel.h:482
bool randomAccess
Definition: tuplesort.c:244
Datum datum1
Definition: tuplesort.c:180
#define LogicalTapeReadExact(tapeset, tapenum, ptr, len)
Definition: tuplesort.c:602
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
IndexTupleData * IndexTuple
Definition: itup.h:53
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
Relation indexRel
Definition: tuplesort.c:459
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3708

◆ reversedirection()

static void reversedirection ( Tuplesortstate state)
static

Definition at line 3663 of file tuplesort.c.

References Tuplesortstate::nKeys, Tuplesortstate::sortKeys, SortSupportData::ssup_nulls_first, and SortSupportData::ssup_reverse.

Referenced by make_bounded_heap(), and sort_bounded_heap().

3664 {
3665  SortSupport sortKey = state->sortKeys;
3666  int nkey;
3667 
3668  for (nkey = 0; nkey < state->nKeys; nkey++, sortKey++)
3669  {
3670  sortKey->ssup_reverse = !sortKey->ssup_reverse;
3671  sortKey->ssup_nulls_first = !sortKey->ssup_nulls_first;
3672  }
3673 }
bool ssup_nulls_first
Definition: sortsupport.h:75
SortSupport sortKeys
Definition: tuplesort.c:430

◆ selectnewtape()

static void selectnewtape ( Tuplesortstate state)
static

Definition at line 2724 of file tuplesort.c.

References Tuplesortstate::destTape, Tuplesortstate::Level, Tuplesortstate::tapeRange, Tuplesortstate::tp_dummy, and Tuplesortstate::tp_fib.

Referenced by dumptuples().

2725 {
2726  int j;
2727  int a;
2728 
2729  /* Step D3: advance j (destTape) */
2730  if (state->tp_dummy[state->destTape] < state->tp_dummy[state->destTape + 1])
2731  {
2732  state->destTape++;
2733  return;
2734  }
2735  if (state->tp_dummy[state->destTape] != 0)
2736  {
2737  state->destTape = 0;
2738  return;
2739  }
2740 
2741  /* Step D4: increase level */
2742  state->Level++;
2743  a = state->tp_fib[0];
2744  for (j = 0; j < state->tapeRange; j++)
2745  {
2746  state->tp_dummy[j] = a + state->tp_fib[j + 1] - state->tp_fib[j];
2747  state->tp_fib[j] = a + state->tp_fib[j + 1];
2748  }
2749  state->destTape = 0;
2750 }
int * tp_dummy
Definition: tuplesort.c:387

◆ sort_bounded_heap()

static void sort_bounded_heap ( Tuplesortstate state)
static

Definition at line 3496 of file tuplesort.c.

References Assert, Tuplesortstate::bound, Tuplesortstate::bounded, Tuplesortstate::boundUsed, Tuplesortstate::memtupcount, Tuplesortstate::memtuples, reversedirection(), SERIAL, Tuplesortstate::status, TSS_BOUNDED, TSS_SORTEDINMEM, and tuplesort_heap_delete_top().

Referenced by tuplesort_performsort().

3497 {
3498  int tupcount = state->memtupcount;
3499 
3500  Assert(state->status == TSS_BOUNDED);
3501  Assert(state->bounded);
3502  Assert(tupcount == state->bound);
3503  Assert(SERIAL(state));
3504 
3505  /*
3506  * We can unheapify in place because each delete-top call will remove the
3507  * largest entry, which we can promptly store in the newly freed slot at
3508  * the end. Once we're down to a single-entry heap, we're done.
3509  */
3510  while (state->memtupcount > 1)
3511  {
3512  SortTuple stup = state->memtuples[0];
3513 
3514  /* this sifts-up the next-largest entry and decreases memtupcount */
3516  state->memtuples[state->memtupcount] = stup;
3517  }
3518  state->memtupcount = tupcount;
3519 
3520  /*
3521  * Reverse sort direction back to the original state. This is not
3522  * actually necessary but seems like a good idea for tidiness.
3523  */
3524  reversedirection(state);
3525 
3526  state->status = TSS_SORTEDINMEM;
3527  state->boundUsed = true;
3528 }
static void reversedirection(Tuplesortstate *state)
Definition: tuplesort.c:3663
TupSortStatus status
Definition: tuplesort.c:242
#define SERIAL(state)
Definition: tuplesort.c:548
static void tuplesort_heap_delete_top(Tuplesortstate *state)
Definition: tuplesort.c:3599
#define Assert(condition)
Definition: c.h:746
SortTuple * memtuples
Definition: tuplesort.c:311

◆ tuplesort_attach_shared()

void tuplesort_attach_shared ( Sharedsort shared,
dsm_segment seg 
)

Definition at line 4582 of file tuplesort.c.

References Sharedsort::fileset, and SharedFileSetAttach().

Referenced by _bt_parallel_build_main().

4583 {
4584  /* Attach to SharedFileSet */
4585  SharedFileSetAttach(&shared->fileset, seg);
4586 }
void SharedFileSetAttach(SharedFileSet *fileset, dsm_segment *seg)
SharedFileSet fileset
Definition: tuplesort.c:506

◆ tuplesort_begin_batch()

static void tuplesort_begin_batch ( Tuplesortstate state)
static

Definition at line 814 of file tuplesort.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Tuplesortstate::allowedMem, Tuplesortstate::availMem, Tuplesortstate::bounded, Tuplesortstate::boundUsed, Tuplesortstate::currentRun, elog, ERROR, GetMemoryChunkSpace(), Tuplesortstate::growmemtuples, INITIAL_MEMTUPSIZE, LACKMEM, Tuplesortstate::maincontext, MemoryContextSwitchTo(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, Tuplesortstate::memtupsize, palloc(), pfree(), Tuplesortstate::result_tape, Tuplesortstate::slabAllocatorUsed, Tuplesortstate::sortcontext, Tuplesortstate::status, Tuplesortstate::tapeset, TSS_INITIAL, Tuplesortstate::tuplecontext, and USEMEM.

Referenced by tuplesort_begin_common(), and tuplesort_reset().

815 {
816  MemoryContext oldcontext;
817 
818  oldcontext = MemoryContextSwitchTo(state->maincontext);
819 
820  /*
821  * Caller tuple (e.g. IndexTuple) memory context.
822  *
823  * A dedicated child context used exclusively for caller passed tuples
824  * eases memory management. Resetting at key points reduces
825  * fragmentation. Note that the memtuples array of SortTuples is allocated
826  * in the parent context, not this context, because there is no need to
827  * free memtuples early.
828  */
830  "Caller tuples",
832 
833  state->status = TSS_INITIAL;
834  state->bounded = false;
835  state->boundUsed = false;
836 
837  state->availMem = state->allowedMem;
838 
839  state->tapeset = NULL;
840 
841  state->memtupcount = 0;
842 
843  /*
844  * Initial size of array must be more than ALLOCSET_SEPARATE_THRESHOLD;
845  * see comments in grow_memtuples().
846  */
847  state->growmemtuples = true;
848  state->slabAllocatorUsed = false;
849  if (state->memtuples != NULL && state->memtupsize != INITIAL_MEMTUPSIZE)
850  {
851  pfree(state->memtuples);
852  state->memtuples = NULL;
854  }
855  if (state->memtuples == NULL)
856  {
857  state->memtuples = (SortTuple *) palloc(state->memtupsize * sizeof(SortTuple));
858  USEMEM(state, GetMemoryChunkSpace(state->memtuples));
859  }
860 
861  /* workMem must be large enough for the minimal memtuples array */
862  if (LACKMEM(state))
863  elog(ERROR, "insufficient memory allowed for sort");
864 
865  state->currentRun = 0;
866 
867  /*
868  * maxTapes, tapeRange, and Algorithm D variables will be initialized by
869  * inittapes(), if needed
870  */
871 
872  state->result_tape = -1; /* flag that result tape has not been formed */
873 
874  MemoryContextSwitchTo(oldcontext);
875 }
int64 availMem
Definition: tuplesort.c:250
TupSortStatus status
Definition: tuplesort.c:242
#define AllocSetContextCreate
Definition: memutils.h:170
MemoryContext maincontext
Definition: tuplesort.c:260
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool growmemtuples
Definition: tuplesort.c:314
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:428
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:43
MemoryContext sortcontext
Definition: tuplesort.c:262
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
int64 allowedMem
Definition: tuplesort.c:251
#define INITIAL_MEMTUPSIZE
Definition: tuplesort.c:135
bool slabAllocatorUsed
Definition: tuplesort.c:343
MemoryContext tuplecontext
Definition: tuplesort.c:263
void * palloc(Size size)
Definition: mcxt.c:950
#define USEMEM(state, amt)
Definition: tuplesort.c:546
#define elog(elevel,...)
Definition: elog.h:214
#define LACKMEM(state)
Definition: tuplesort.c:545
SortTuple * memtuples
Definition: tuplesort.c:311

◆ tuplesort_begin_cluster()

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

Definition at line 952 of file tuplesort.c.

References _bt_mkscankey(), SortSupportData::abbreviate, Tuplesortstate::abbrevNext, Assert, AssertState, BTGreaterStrategyNumber, BTLessStrategyNumber, BuildIndexInfo(), CLUSTER_SORT, Tuplesortstate::comparetup, comparetup_cluster(), Tuplesortstate::copytup, copytup_cluster(), CreateExecutorState(), CurrentMemoryContext, ExprContext::ecxt_scantuple, elog, Tuplesortstate::estate, GetPerTupleExprContext, i, IndexInfo::ii_Expressions, Tuplesortstate::indexInfo, IndexRelationGetNumberOfKeyAttributes, LOG, Tuplesortstate::maincontext, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), Tuplesortstate::nKeys, palloc0(), PARALLEL_SORT, pfree(), PrepareSortSupportFromIndexRel(), RelationData::rd_rel, Tuplesortstate::readtup, readtup_cluster(), RelationGetNumberOfAttributes, BTScanInsertData::scankeys, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, Tuplesortstate::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, TTSOpsHeapTuple, Tuplesortstate::tupDesc, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_cluster().

Referenced by heapam_relation_copy_for_cluster().

956 {
957  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
958  randomAccess);
959  BTScanInsert indexScanKey;
960  MemoryContext oldcontext;
961  int i;
962 
963  Assert(indexRel->rd_rel->relam == BTREE_AM_OID);
964 
965  oldcontext = MemoryContextSwitchTo(state->maincontext);
966 
967 #ifdef TRACE_SORT
968  if (trace_sort)
969  elog(LOG,
970  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
972  workMem, randomAccess ? 't' : 'f');
973 #endif
974 
975  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
976 
977  TRACE_POSTGRESQL_SORT_START(CLUSTER_SORT,
978  false, /* no unique check */
979  state->nKeys,
980  workMem,
981  randomAccess,
982  PARALLEL_SORT(state));
983 
985  state->copytup = copytup_cluster;
986  state->writetup = writetup_cluster;
987  state->readtup = readtup_cluster;
988  state->abbrevNext = 10;
989 
990  state->indexInfo = BuildIndexInfo(indexRel);
991 
992  state->tupDesc = tupDesc; /* assume we need not copy tupDesc */
993 
994  indexScanKey = _bt_mkscankey(indexRel, NULL);
995 
996  if (state->indexInfo->ii_Expressions != NULL)
997  {
998  TupleTableSlot *slot;
999  ExprContext *econtext;
1000 
1001  /*
1002  * We will need to use FormIndexDatum to evaluate the index
1003  * expressions. To do that, we need an EState, as well as a
1004  * TupleTableSlot to put the table tuples into. The econtext's
1005  * scantuple has to point to that slot, too.
1006  */
1007  state->estate = CreateExecutorState();
1008  slot = MakeSingleTupleTableSlot(tupDesc, &TTSOpsHeapTuple);
1009  econtext = GetPerTupleExprContext(state->estate);
1010  econtext->ecxt_scantuple = slot;
1011  }
1012 
1013  /* Prepare SortSupport data for each column */
1014  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1015  sizeof(SortSupportData));
1016 
1017  for (i = 0; i < state->nKeys; i++)
1018  {
1019  SortSupport sortKey = state->sortKeys + i;
1020  ScanKey scanKey = indexScanKey->scankeys + i;
1021  int16 strategy;
1022 
1023  sortKey->ssup_cxt = CurrentMemoryContext;
1024  sortKey->ssup_collation = scanKey->sk_collation;
1025  sortKey->ssup_nulls_first =
1026  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1027  sortKey->ssup_attno = scanKey->sk_attno;
1028  /* Convey if abbreviation optimization is applicable in principle */
1029  sortKey->abbreviate = (i == 0);
1030 
1031  AssertState(sortKey->ssup_attno != 0);
1032 
1033  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1035 
1036  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
1037  }
1038 
1039  pfree(indexScanKey);
1040 
1041  MemoryContextSwitchTo(oldcontext);
1042 
1043  return state;
1044 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:362
bool ssup_nulls_first
Definition: sortsupport.h:75
static void writetup_cluster(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4119
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define AssertState(condition)
Definition: c.h:749
int64 abbrevNext
Definition: tuplesort.c:444
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:462
EState * estate
Definition: tuplesort.c:452
SortSupport sortKeys
Definition: tuplesort.c:430
MemoryContext maincontext
Definition: tuplesort.c:260
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define CLUSTER_SORT
Definition: tuplesort.c:122
static int comparetup_cluster(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:3935
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2301
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:109
static void copytup_cluster(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4046
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
#define GetPerTupleExprContext(estate)
Definition: executor.h:506
void pfree(void *pointer)
Definition: mcxt.c:1057
static void readtup_cluster(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4143
MemoryContext ssup_cxt
Definition: sortsupport.h:66
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
IndexInfo * indexInfo
Definition: tuplesort.c:451
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:162
EState * CreateExecutorState(void)
Definition: execUtils.c:89
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:957
void * palloc0(Size size)
Definition: mcxt.c:981
AttrNumber ssup_attno
Definition: sortsupport.h:81
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
int sk_flags
Definition: skey.h:66
List * ii_Expressions
Definition: execnodes.h:160
#define Assert(condition)
Definition: c.h:746
#define SK_BT_DESC
Definition: nbtree.h:956
Definition: regguts.h:298
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:666
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
Oid sk_collation
Definition: skey.h:70
#define elog(elevel,...)
Definition: elog.h:214
int i
const TupleTableSlotOps TTSOpsHeapTuple
Definition: execTuples.c:84
#define BTLessStrategyNumber
Definition: stratnum.h:29
AttrNumber sk_attno
Definition: skey.h:67
TupleDesc tupDesc
Definition: tuplesort.c:429

◆ tuplesort_begin_common()

static Tuplesortstate * tuplesort_begin_common ( int  workMem,
SortCoordinate  coordinate,
bool  randomAccess 
)
static

Definition at line 702 of file tuplesort.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Tuplesortstate::allowedMem, Assert, CurrentMemoryContext, elog, ERROR, INITIAL_MEMTUPSIZE, SortCoordinateData::isWorker, Tuplesortstate::maincontext, Max, MemoryContextSwitchTo(), Tuplesortstate::memtuples, Tuplesortstate::memtupsize, SortCoordinateData::nParticipants, Tuplesortstate::nParticipants, palloc0(), pg_rusage_init(), Tuplesortstate::randomAccess, Tuplesortstate::ru_start, Tuplesortstate::shared, SortCoordinateData::sharedsort, Tuplesortstate::sortcontext, trace_sort, Tuplesortstate::tuples, tuplesort_begin_batch(), Tuplesortstate::worker, and worker_get_identifier().

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

704 {
706  MemoryContext maincontext;
707  MemoryContext sortcontext;
708  MemoryContext oldcontext;
709 
710  /* See leader_takeover_tapes() remarks on randomAccess support */
711  if (coordinate && randomAccess)
712  elog(ERROR, "random access disallowed under parallel sort");
713 
714  /*
715  * Memory context surviving tuplesort_reset. This memory context holds
716  * data which is useful to keep while sorting multiple similar batches.
717  */
719  "TupleSort main",
721 
722  /*
723  * Create a working memory context for one sort operation. The content of
724  * this context is deleted by tuplesort_reset.
725  */
726  sortcontext = AllocSetContextCreate(maincontext,
727  "TupleSort sort",
729 
730  /*
731  * Additionally a working memory context for tuples is setup in
732  * tuplesort_begin_batch.
733  */
734 
735  /*
736  * Make the Tuplesortstate within the per-sortstate context. This way, we
737  * don't need a separate pfree() operation for it at shutdown.
738  */
739  oldcontext = MemoryContextSwitchTo(maincontext);
740 
741  state = (Tuplesortstate *) palloc0(sizeof(Tuplesortstate));
742 
743 #ifdef TRACE_SORT
744  if (trace_sort)
745  pg_rusage_init(&state->ru_start);
746 #endif
747 
748  state->randomAccess = randomAccess;
749  state->tuples = true;
750 
751  /*
752  * workMem is forced to be at least 64KB, the current minimum valid value
753  * for the work_mem GUC. This is a defense against parallel sort callers
754  * that divide out memory among many workers in a way that leaves each
755  * with very little memory.
756  */
757  state->allowedMem = Max(workMem, 64) * (int64) 1024;
758  state->sortcontext = sortcontext;
759  state->maincontext = maincontext;
760 
761  /*
762  * Initial size of array must be more than ALLOCSET_SEPARATE_THRESHOLD;
763  * see comments in grow_memtuples().
764  */
766  state->memtuples = NULL;
767 
768  /*
769  * After all of the other non-parallel-related state, we setup all of the
770  * state needed for each batch.
771  */
772  tuplesort_begin_batch(state);
773 
774  /*
775  * Initialize parallel-related state based on coordination information
776  * from caller
777  */
778  if (!coordinate)
779  {
780  /* Serial sort */
781  state->shared = NULL;
782  state->worker = -1;
783  state->nParticipants = -1;
784  }
785  else if (coordinate->isWorker)
786  {
787  /* Parallel worker produces exactly one final run from all input */
788  state->shared = coordinate->sharedsort;
789  state->worker = worker_get_identifier(state);
790  state->nParticipants = -1;
791  }
792  else
793  {
794  /* Parallel leader state only used for final merge */
795  state->shared = coordinate->sharedsort;
796  state->worker = -1;
797  state->nParticipants = coordinate->nParticipants;
798  Assert(state->nParticipants >= 1);
799  }
800 
801  MemoryContextSwitchTo(oldcontext);
802 
803  return state;
804 }
#define AllocSetContextCreate
Definition: memutils.h:170
PGRUsage ru_start
Definition: tuplesort.c:481
MemoryContext maincontext
Definition: tuplesort.c:260
bool randomAccess
Definition: tuplesort.c:244
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Sharedsort * sharedsort
Definition: tuplesort.h:55
static int worker_get_identifier(Tuplesortstate *state)
Definition: tuplesort.c:4602
bool trace_sort
Definition: tuplesort.c:140
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
static void tuplesort_begin_batch(Tuplesortstate *state)
Definition: tuplesort.c:814
#define ERROR
Definition: elog.h:43
MemoryContext sortcontext
Definition: tuplesort.c:262
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Sharedsort * shared
Definition: tuplesort.c:421
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
int64 allowedMem
Definition: tuplesort.c:251
void * palloc0(Size size)
Definition: mcxt.c:981
#define Max(x, y)
Definition: c.h:922
#define Assert(condition)
Definition: c.h:746
Definition: regguts.h:298
#define INITIAL_MEMTUPSIZE
Definition: tuplesort.c:135
#define elog(elevel,...)
Definition: elog.h:214
SortTuple * memtuples
Definition: tuplesort.c:311

◆ tuplesort_begin_datum()

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

Definition at line 1228 of file tuplesort.c.

References SortSupportData::abbrev_converter, SortSupportData::abbreviate, Tuplesortstate::abbrevNext, Tuplesortstate::comparetup, comparetup_datum(), Tuplesortstate::copytup, copytup_datum(), CurrentMemoryContext, DATUM_SORT, Tuplesortstate::datumType, Tuplesortstate::datumTypeLen, elog, get_typlenbyval(), LOG, Tuplesortstate::maincontext, MemoryContextSwitchTo(), Tuplesortstate::nKeys, Tuplesortstate::onlyKey, palloc0(), PARALLEL_SORT, PrepareSortSupportFromOrderingOp(), Tuplesortstate::readtup, readtup_datum(), Tuplesortstate::sortKeys, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, Tuplesortstate::tuples, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_datum().

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

1231 {
1232  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1233  randomAccess);
1234  MemoryContext oldcontext;
1235  int16 typlen;
1236  bool typbyval;
1237 
1238  oldcontext = MemoryContextSwitchTo(state->maincontext);
1239 
1240 #ifdef TRACE_SORT
1241  if (trace_sort)
1242  elog(LOG,
1243  "begin datum sort: workMem = %d, randomAccess = %c",
1244  workMem, randomAccess ? 't' : 'f');
1245 #endif
1246 
1247  state->nKeys = 1; /* always a one-column sort */
1248 
1249  TRACE_POSTGRESQL_SORT_START(DATUM_SORT,
1250  false, /* no unique check */
1251  1,
1252  workMem,
1253  randomAccess,
1254  PARALLEL_SORT(state));
1255 
1256  state->comparetup = comparetup_datum;
1257  state->copytup = copytup_datum;
1258  state->writetup = writetup_datum;
1259  state->readtup = readtup_datum;
1260  state->abbrevNext = 10;
1261 
1262  state->datumType = datumType;
1263 
1264  /* lookup necessary attributes of the datum type */
1265  get_typlenbyval(datumType, &typlen, &typbyval);
1266  state->datumTypeLen = typlen;
1267  state->tuples = !typbyval;
1268 
1269  /* Prepare SortSupport data */
1270  state->sortKeys = (SortSupport) palloc0(sizeof(SortSupportData));
1271 
1273  state->sortKeys->ssup_collation = sortCollation;
1274  state->sortKeys->ssup_nulls_first = nullsFirstFlag;
1275 
1276  /*
1277  * Abbreviation is possible here only for by-reference types. In theory,
1278  * a pass-by-value datatype could have an abbreviated form that is cheaper
1279  * to compare. In a tuple sort, we could support that, because we can
1280  * always extract the original datum from the tuple as needed. Here, we
1281  * can't, because a datum sort only stores a single copy of the datum; the
1282  * "tuple" field of each SortTuple is NULL.
1283  */
1284  state->sortKeys->abbreviate = !typbyval;
1285 
1286  PrepareSortSupportFromOrderingOp(sortOperator, state->sortKeys);
1287 
1288  /*
1289  * The "onlyKey" optimization cannot be used with abbreviated keys, since
1290  * tie-breaker comparisons may be required. Typically, the optimization
1291  * is only of value to pass-by-value types anyway, whereas abbreviated
1292  * keys are typically only of value to pass-by-reference types.
1293  */
1294  if (!state->sortKeys->abbrev_converter)
1295  state->onlyKey = state->sortKeys;
1296 
1297  MemoryContextSwitchTo(oldcontext);
1298 
1299  return state;
1300 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:362
bool ssup_nulls_first
Definition: sortsupport.h:75
int64 abbrevNext
Definition: tuplesort.c:444
SortSupport sortKeys
Definition: tuplesort.c:430
MemoryContext maincontext
Definition: tuplesort.c:260
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:135
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
#define DATUM_SORT
Definition: tuplesort.c:121
MemoryContext ssup_cxt
Definition: sortsupport.h:66
static int comparetup_datum(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:4422
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
static void copytup_datum(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4443
static void readtup_datum(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4491
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static void writetup_datum(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4450
void * palloc0(Size size)
Definition: mcxt.c:981
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:298
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2139
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
#define elog(elevel,...)
Definition: elog.h:214
SortSupport onlyKey
Definition: tuplesort.c:436

◆ tuplesort_begin_heap()

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

Definition at line 878 of file tuplesort.c.

References SortSupportData::abbrev_converter, SortSupportData::abbreviate, Tuplesortstate::abbrevNext, AssertArg, Tuplesortstate::comparetup, comparetup_heap(), Tuplesortstate::copytup, copytup_heap(), CurrentMemoryContext, elog, HEAP_SORT, i, LOG, Tuplesortstate::maincontext, MemoryContextSwitchTo(), Tuplesortstate::nKeys, Tuplesortstate::onlyKey, palloc0(), PARALLEL_SORT, PrepareSortSupportFromOrderingOp(), Tuplesortstate::readtup, readtup_heap(), Tuplesortstate::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, Tuplesortstate::tupDesc, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_heap().

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

883 {
884  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
885  randomAccess);
886  MemoryContext oldcontext;
887  int i;
888 
889  oldcontext = MemoryContextSwitchTo(state->maincontext);
890 
891  AssertArg(nkeys > 0);
892 
893 #ifdef TRACE_SORT
894  if (trace_sort)
895  elog(LOG,
896  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
897  nkeys, workMem, randomAccess ? 't' : 'f');
898 #endif
899 
900  state->nKeys = nkeys;
901 
902  TRACE_POSTGRESQL_SORT_START(HEAP_SORT,
903  false, /* no unique check */
904  nkeys,
905  workMem,
906  randomAccess,
907  PARALLEL_SORT(state));
908 
909  state->comparetup = comparetup_heap;
910  state->copytup = copytup_heap;
911  state->writetup = writetup_heap;
912  state->readtup = readtup_heap;
913 
914  state->tupDesc = tupDesc; /* assume we need not copy tupDesc */
915  state->abbrevNext = 10;
916 
917  /* Prepare SortSupport data for each column */
918  state->sortKeys = (SortSupport) palloc0(nkeys * sizeof(SortSupportData));
919 
920  for (i = 0; i < nkeys; i++)
921  {
922  SortSupport sortKey = state->sortKeys + i;
923 
924  AssertArg(attNums[i] != 0);
925  AssertArg(sortOperators[i] != 0);
926 
927  sortKey->ssup_cxt = CurrentMemoryContext;
928  sortKey->ssup_collation = sortCollations[i];
929  sortKey->ssup_nulls_first = nullsFirstFlags[i];
930  sortKey->ssup_attno = attNums[i];
931  /* Convey if abbreviation optimization is applicable in principle */
932  sortKey->abbreviate = (i == 0);
933 
934  PrepareSortSupportFromOrderingOp(sortOperators[i], sortKey);
935  }
936 
937  /*
938  * The "onlyKey" optimization cannot be used with abbreviated keys, since
939  * tie-breaker comparisons may be required. Typically, the optimization
940  * is only of value to pass-by-value types anyway, whereas abbreviated
941  * keys are typically only of value to pass-by-reference types.
942  */
943  if (nkeys == 1 && !state->sortKeys->abbrev_converter)
944  state->onlyKey = state->sortKeys;
945 
946  MemoryContextSwitchTo(oldcontext);
947 
948  return state;
949 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
bool ssup_nulls_first
Definition: sortsupport.h:75
static int comparetup_heap(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:3736
int64 abbrevNext
Definition: tuplesort.c:444
SortSupport sortKeys
Definition: tuplesort.c:430
MemoryContext maincontext
Definition: tuplesort.c:260
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
void PrepareSortSupportFromOrderingOp(Oid orderingOp, SortSupport ssup)
Definition: sortsupport.c:135
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define LOG
Definition: elog.h:26
#define HEAP_SORT
Definition: tuplesort.c:119
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
static void writetup_heap(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:3876
MemoryContext ssup_cxt
Definition: sortsupport.h:66
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define AssertArg(condition)
Definition: c.h:748
static void copytup_heap(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:3798
void * palloc0(Size size)
Definition: mcxt.c:981
AttrNumber ssup_attno
Definition: sortsupport.h:81
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:298
static void readtup_heap(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:3903
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
#define elog(elevel,...)
Definition: elog.h:214
int i
SortSupport onlyKey
Definition: tuplesort.c:436
TupleDesc tupDesc
Definition: tuplesort.c:429

◆ tuplesort_begin_index_btree()

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

Definition at line 1047 of file tuplesort.c.

References _bt_mkscankey(), SortSupportData::abbreviate, Tuplesortstate::abbrevNext, AssertState, BTGreaterStrategyNumber, BTLessStrategyNumber, Tuplesortstate::comparetup, comparetup_index_btree(), Tuplesortstate::copytup, copytup_index(), CurrentMemoryContext, elog, Tuplesortstate::enforceUnique, Tuplesortstate::heapRel, i, INDEX_SORT, Tuplesortstate::indexRel, IndexRelationGetNumberOfKeyAttributes, LOG, Tuplesortstate::maincontext, MemoryContextSwitchTo(), Tuplesortstate::nKeys, palloc0(), PARALLEL_SORT, pfree(), PrepareSortSupportFromIndexRel(), Tuplesortstate::readtup, readtup_index(), BTScanInsertData::scankeys, ScanKeyData::sk_attno, SK_BT_DESC, SK_BT_NULLS_FIRST, ScanKeyData::sk_collation, ScanKeyData::sk_flags, Tuplesortstate::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_index().

Referenced by _bt_parallel_scan_and_sort(), and _bt_spools_heapscan().

1053 {
1054  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1055  randomAccess);
1056  BTScanInsert indexScanKey;
1057  MemoryContext oldcontext;
1058  int i;
1059 
1060  oldcontext = MemoryContextSwitchTo(state->maincontext);
1061 
1062 #ifdef TRACE_SORT
1063  if (trace_sort)
1064  elog(LOG,
1065  "begin index sort: unique = %c, workMem = %d, randomAccess = %c",
1066  enforceUnique ? 't' : 'f',
1067  workMem, randomAccess ? 't' : 'f');
1068 #endif
1069 
1070  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
1071 
1072  TRACE_POSTGRESQL_SORT_START(INDEX_SORT,
1073  enforceUnique,
1074  state->nKeys,
1075  workMem,
1076  randomAccess,
1077  PARALLEL_SORT(state));
1078 
1080  state->copytup = copytup_index;
1081  state->writetup = writetup_index;
1082  state->readtup = readtup_index;
1083  state->abbrevNext = 10;
1084 
1085  state->heapRel = heapRel;
1086  state->indexRel = indexRel;
1087  state->enforceUnique = enforceUnique;
1088 
1089  indexScanKey = _bt_mkscankey(indexRel, NULL);
1090 
1091  /* Prepare SortSupport data for each column */
1092  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1093  sizeof(SortSupportData));
1094 
1095  for (i = 0; i < state->nKeys; i++)
1096  {
1097  SortSupport sortKey = state->sortKeys + i;
1098  ScanKey scanKey = indexScanKey->scankeys + i;
1099  int16 strategy;
1100 
1101  sortKey->ssup_cxt = CurrentMemoryContext;
1102  sortKey->ssup_collation = scanKey->sk_collation;
1103  sortKey->ssup_nulls_first =
1104  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1105  sortKey->ssup_attno = scanKey->sk_attno;
1106  /* Convey if abbreviation optimization is applicable in principle */
1107  sortKey->abbreviate = (i == 0);
1108 
1109  AssertState(sortKey->ssup_attno != 0);
1110 
1111  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1113 
1114  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
1115  }
1116 
1117  pfree(indexScanKey);
1118 
1119  MemoryContextSwitchTo(oldcontext);
1120 
1121  return state;
1122 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:362
bool ssup_nulls_first
Definition: sortsupport.h:75
Relation heapRel
Definition: tuplesort.c:458
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define AssertState(condition)
Definition: c.h:749
int64 abbrevNext
Definition: tuplesort.c:444
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
static void copytup_index(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4369
SortSupport sortKeys
Definition: tuplesort.c:430
MemoryContext maincontext
Definition: tuplesort.c:260
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define INDEX_SORT
Definition: tuplesort.c:120
#define LOG
Definition: elog.h:26
static int comparetup_index_btree(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:4181
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
void pfree(void *pointer)
Definition: mcxt.c:1057
static void writetup_index(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4376
MemoryContext ssup_cxt
Definition: sortsupport.h:66
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
static void readtup_index(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4398
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:162
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:957
void * palloc0(Size size)
Definition: mcxt.c:981
Relation indexRel
Definition: tuplesort.c:459
AttrNumber ssup_attno
Definition: sortsupport.h:81
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
int sk_flags
Definition: skey.h:66
#define SK_BT_DESC
Definition: nbtree.h:956
Definition: regguts.h:298
bool enforceUnique
Definition: tuplesort.c:462
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:666
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
Oid sk_collation
Definition: skey.h:70
#define elog(elevel,...)
Definition: elog.h:214
int i
#define BTLessStrategyNumber
Definition: stratnum.h:29
AttrNumber sk_attno
Definition: skey.h:67

◆ tuplesort_begin_index_gist()

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

Definition at line 1171 of file tuplesort.c.

References SortSupportData::abbreviate, AssertState, Tuplesortstate::comparetup, comparetup_index_btree(), Tuplesortstate::copytup, copytup_index(), CurrentMemoryContext, elog, Tuplesortstate::heapRel, i, Tuplesortstate::indexRel, IndexRelationGetNumberOfKeyAttributes, LOG, MemoryContextSwitchTo(), Tuplesortstate::nKeys, palloc0(), PrepareSortSupportFromGistIndexRel(), RelationData::rd_indcollation, Tuplesortstate::readtup, readtup_index(), Tuplesortstate::sortcontext, Tuplesortstate::sortKeys, SortSupportData::ssup_attno, SortSupportData::ssup_collation, SortSupportData::ssup_cxt, SortSupportData::ssup_nulls_first, trace_sort, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_index().

Referenced by gistbuild().

1176 {
1177  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1178  randomAccess);
1179  MemoryContext oldcontext;
1180  int i;
1181 
1182  oldcontext = MemoryContextSwitchTo(state->sortcontext);
1183 
1184 #ifdef TRACE_SORT
1185  if (trace_sort)
1186  elog(LOG,
1187  "begin index sort: workMem = %d, randomAccess = %c",
1188  workMem, randomAccess ? 't' : 'f');
1189 #endif
1190 
1191  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
1192 
1194  state->copytup = copytup_index;
1195  state->writetup = writetup_index;
1196  state->readtup = readtup_index;
1197 
1198  state->heapRel = heapRel;
1199  state->indexRel = indexRel;
1200 
1201  /* Prepare SortSupport data for each column */
1202  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1203  sizeof(SortSupportData));
1204 
1205  for (i = 0; i < state->nKeys; i++)
1206  {
1207  SortSupport sortKey = state->sortKeys + i;
1208 
1209  sortKey->ssup_cxt = CurrentMemoryContext;
1210  sortKey->ssup_collation = indexRel->rd_indcollation[i];
1211  sortKey->ssup_nulls_first = false;
1212  sortKey->ssup_attno = i + 1;
1213  /* Convey if abbreviation optimization is applicable in principle */
1214  sortKey->abbreviate = (i == 0);
1215 
1216  AssertState(sortKey->ssup_attno != 0);
1217 
1218  /* Look for a sort support function */
1219  PrepareSortSupportFromGistIndexRel(indexRel, sortKey);
1220  }
1221 
1222  MemoryContextSwitchTo(oldcontext);
1223 
1224  return state;
1225 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
bool ssup_nulls_first
Definition: sortsupport.h:75
Relation heapRel
Definition: tuplesort.c:458
#define AssertState(condition)
Definition: c.h:749
static void copytup_index(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4369
SortSupport sortKeys
Definition: tuplesort.c:430
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define LOG
Definition: elog.h:26
static int comparetup_index_btree(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:4181
bool trace_sort
Definition: tuplesort.c:140
Oid * rd_indcollation
Definition: rel.h:199
void PrepareSortSupportFromGistIndexRel(Relation indexRel, SortSupport ssup)
Definition: sortsupport.c:189
MemoryContext sortcontext
Definition: tuplesort.c:262
static void writetup_index(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4376
MemoryContext ssup_cxt
Definition: sortsupport.h:66
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
static void readtup_index(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4398
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:475
void * palloc0(Size size)
Definition: mcxt.c:981
Relation indexRel
Definition: tuplesort.c:459
AttrNumber ssup_attno
Definition: sortsupport.h:81
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:298
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
#define elog(elevel,...)
Definition: elog.h:214
int i

◆ 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,
bool  randomAccess 
)

Definition at line 1125 of file tuplesort.c.

References Tuplesortstate::comparetup, comparetup_index_hash(), Tuplesortstate::copytup, copytup_index(), elog, Tuplesortstate::heapRel, Tuplesortstate::high_mask, Tuplesortstate::indexRel, LOG, Tuplesortstate::low_mask, Tuplesortstate::maincontext, Tuplesortstate::max_buckets, MemoryContextSwitchTo(), Tuplesortstate::nKeys, Tuplesortstate::readtup, readtup_index(), trace_sort, tuplesort_begin_common(), Tuplesortstate::writetup, and writetup_index().

Referenced by _h_spoolinit().

1133 {
1134  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1135  randomAccess);
1136  MemoryContext oldcontext;
1137 
1138  oldcontext = MemoryContextSwitchTo(state->maincontext);
1139 
1140 #ifdef TRACE_SORT
1141  if (trace_sort)
1142  elog(LOG,
1143  "begin index sort: high_mask = 0x%x, low_mask = 0x%x, "
1144  "max_buckets = 0x%x, workMem = %d, randomAccess = %c",
1145  high_mask,
1146  low_mask,
1147  max_buckets,
1148  workMem, randomAccess ? 't' : 'f');
1149 #endif
1150 
1151  state->nKeys = 1; /* Only one sort column, the hash code */
1152 
1154  state->copytup = copytup_index;
1155  state->writetup = writetup_index;
1156  state->readtup = readtup_index;
1157 
1158  state->heapRel = heapRel;
1159  state->indexRel = indexRel;
1160 
1161  state->high_mask = high_mask;
1162  state->low_mask = low_mask;
1163  state->max_buckets = max_buckets;
1164 
1165  MemoryContextSwitchTo(oldcontext);
1166 
1167  return state;
1168 }
static int comparetup_index_hash(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:4314
Relation heapRel
Definition: tuplesort.c:458
static void copytup_index(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4369
MemoryContext maincontext
Definition: tuplesort.c:260
void(* copytup)(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:283
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SortTupleComparator comparetup
Definition: tuplesort.c:275
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
static void writetup_index(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4376
uint32 high_mask
Definition: tuplesort.c:465
void(* readtup)(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:301
static void readtup_index(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4398
Relation indexRel
Definition: tuplesort.c:459
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:298
uint32 max_buckets
Definition: tuplesort.c:467
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:702
#define elog(elevel,...)
Definition: elog.h:214
uint32 low_mask
Definition: tuplesort.c:466

◆ tuplesort_end()

void tuplesort_end ( Tuplesortstate state)

Definition at line 1445 of file tuplesort.c.

References Tuplesortstate::maincontext, MemoryContextDelete(), and tuplesort_free().

Referenced by _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().

1446 {
1447  tuplesort_free(state);
1448 
1449  /*
1450  * Free the main memory context, including the Tuplesortstate struct
1451  * itself.
1452  */
1454 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
MemoryContext maincontext
Definition: tuplesort.c:260
static void tuplesort_free(Tuplesortstate *state)
Definition: tuplesort.c:1372

◆ tuplesort_estimate_shared()

Size tuplesort_estimate_shared ( int  nWorkers)

Definition at line 4538 of file tuplesort.c.

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

Referenced by _bt_begin_parallel().

4539 {
4540  Size tapesSize;
4541 
4542  Assert(nWorkers > 0);
4543 
4544  /* Make sure that BufFile shared state is MAXALIGN'd */
4545  tapesSize = mul_size(sizeof(TapeShare), nWorkers);
4546  tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
4547 
4548  return tapesSize;
4549 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
#define Assert(condition)
Definition: c.h:746
size_t Size
Definition: c.h:474
#define MAXALIGN(LEN)
Definition: c.h:699
#define offsetof(type, field)
Definition: c.h:669

◆ tuplesort_free()

static void tuplesort_free ( Tuplesortstate state)
static

Definition at line 1372 of file tuplesort.c.

References Tuplesortstate::allowedMem, Tuplesortstate::availMem, ExprContext::ecxt_scantuple, elog, Tuplesortstate::estate, ExecDropSingleTupleTableSlot(), FreeExecutorState(), GetPerTupleExprContext, LOG, LogicalTapeSetBlocks(), LogicalTapeSetClose(), MemoryContextReset(), MemoryContextSwitchTo(), pg_rusage_show(), Tuplesortstate::ru_start, SERIAL, Tuplesortstate::sortcontext, Tuplesortstate::tapeset, trace_sort, and Tuplesortstate::worker.

Referenced by tuplesort_end(), and tuplesort_reset().

1373 {
1374  /* context swap probably not needed, but let's be safe */
1375  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
1376 
1377 #ifdef TRACE_SORT
1378  long spaceUsed;
1379 
1380  if (state->tapeset)
1381  spaceUsed = LogicalTapeSetBlocks(state->tapeset);
1382  else
1383  spaceUsed = (state->allowedMem - state->availMem + 1023) / 1024;
1384 #endif
1385 
1386  /*
1387  * Delete temporary "tape" files, if any.
1388  *
1389  * Note: want to include this in reported total cost of sort, hence need
1390  * for two #ifdef TRACE_SORT sections.
1391  */
1392  if (state->tapeset)
1393  LogicalTapeSetClose(state->tapeset);
1394 
1395 #ifdef TRACE_SORT
1396  if (trace_sort)
1397  {
1398  if (state->tapeset)
1399  elog(LOG, "%s of worker %d ended, %ld disk blocks used: %s",
1400  SERIAL(state) ? "external sort" : "parallel external sort",
1401  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
1402  else
1403  elog(LOG, "%s of worker %d ended, %ld KB used: %s",
1404  SERIAL(state) ? "internal sort" : "unperformed parallel sort",
1405  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
1406  }
1407 
1408  TRACE_POSTGRESQL_SORT_DONE(state->tapeset != NULL, spaceUsed);
1409 #else
1410 
1411  /*
1412  * If you disabled TRACE_SORT, you can still probe sort__done, but you
1413  * ain't getting space-used stats.
1414  */
1415  TRACE_POSTGRESQL_SORT_DONE(state->tapeset != NULL, 0L);
1416 #endif
1417 
1418  /* Free any execution state created for CLUSTER case */
1419  if (state->estate != NULL)
1420  {
1421  ExprContext *econtext = GetPerTupleExprContext(state->estate);
1422 
1424  FreeExecutorState(state->estate);
1425  }
1426 
1427  MemoryContextSwitchTo(oldcontext);
1428 
1429  /*
1430  * Free the per-sort memory context, thereby releasing all working memory.
1431  */
1433 }
int64 availMem
Definition: tuplesort.c:250
PGRUsage ru_start
Definition: tuplesort.c:481
#define SERIAL(state)
Definition: tuplesort.c:548
EState * estate
Definition: tuplesort.c:452
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:506
MemoryContext sortcontext
Definition: tuplesort.c:262
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
int64 allowedMem
Definition: tuplesort.c:251
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
#define elog(elevel,...)
Definition: elog.h:214
void LogicalTapeSetClose(LogicalTapeSet *lts)
Definition: logtape.c:737
long LogicalTapeSetBlocks(LogicalTapeSet *lts)
Definition: logtape.c:1272

◆ tuplesort_get_stats()

void tuplesort_get_stats ( Tuplesortstate state,
TuplesortInstrumentation stats 
)

Definition at line 3359 of file tuplesort.c.

References Tuplesortstate::boundUsed, Tuplesortstate::isMaxSpaceDisk, Tuplesortstate::maxSpace, Tuplesortstate::maxSpaceStatus, 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().

3361 {
3362  /*
3363  * Note: it might seem we should provide both memory and disk usage for a
3364  * disk-based sort. However, the current code doesn't track memory space
3365  * accurately once we have begun to return tuples to the caller (since we
3366  * don't account for pfree's the caller is expected to do), so we cannot
3367  * rely on availMem in a disk sort. This does not seem worth the overhead
3368  * to fix. Is it worth creating an API for the memory context code to
3369  * tell us how much is actually used in sortcontext?
3370  */
3371  tuplesort_updatemax(state);
3372 
3373  if (state->isMaxSpaceDisk)
3375  else
3377  stats->spaceUsed = (state->maxSpace + 1023) / 1024;
3378 
3379  switch (state->maxSpaceStatus)
3380  {
3381  case TSS_SORTEDINMEM:
3382  if (state->boundUsed)
3384  else
3386  break;
3387  case TSS_SORTEDONTAPE:
3389  break;
3390  case TSS_FINALMERGE:
3392  break;
3393  default:
3395  break;
3396  }
3397 }
bool isMaxSpaceDisk
Definition: tuplesort.c:256
int64 maxSpace
Definition: tuplesort.c:254
static void tuplesort_updatemax(Tuplesortstate *state)
Definition: tuplesort.c:1462
TupSortStatus maxSpaceStatus
Definition: tuplesort.c:259
TuplesortMethod sortMethod
Definition: tuplesort.h:91
TuplesortSpaceType spaceType
Definition: tuplesort.h:92

◆ tuplesort_getdatum()

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

Definition at line 2475 of file tuplesort.c.

References SortSupportData::abbrev_converter, SortTuple::datum1, datumCopy(), Tuplesortstate::datumTypeLen, SortTuple::isnull1, MemoryContextSwitchTo(), PointerGetDatum, Tuplesortstate::sortcontext, Tuplesortstate::sortKeys, SortTuple::tuple, Tuplesortstate::tuples, and tuplesort_gettuple_common().

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

2477 {
2478  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2479  SortTuple stup;
2480 
2481  if (!tuplesort_gettuple_common(state, forward, &stup))
2482  {
2483  MemoryContextSwitchTo(oldcontext);
2484  return false;
2485  }
2486 
2487  /* Ensure we copy into caller's memory context */
2488  MemoryContextSwitchTo(oldcontext);
2489 
2490  /* Record abbreviated key for caller */
2491  if (state->sortKeys->abbrev_converter && abbrev)
2492  *abbrev = stup.datum1;
2493 
2494  if (stup.isnull1 || !state->tuples)
2495  {
2496  *val = stup.datum1;
2497  *isNull = stup.isnull1;
2498  }
2499  else
2500  {
2501  /* use stup.tuple because stup.datum1 may be an abbreviation */
2502  *val = datumCopy(PointerGetDatum(stup.tuple), false, state->datumTypeLen);
2503  *isNull = false;
2504  }
2505 
2506  return true;
2507 }
#define PointerGetDatum(X)
Definition: postgres.h:556
SortSupport sortKeys
Definition: tuplesort.c:430
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Datum datum1
Definition: tuplesort.c:180
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
MemoryContext sortcontext
Definition: tuplesort.c:262
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
static bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup)
Definition: tuplesort.c:2132
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
long val
Definition: informix.c:664

◆ tuplesort_getheaptuple()

HeapTuple tuplesort_getheaptuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 2426 of file tuplesort.c.

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

Referenced by heapam_relation_copy_for_cluster().

2427 {
2428  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2429  SortTuple stup;
2430 
2431  if (!tuplesort_gettuple_common(state, forward, &stup))
2432  stup.tuple = NULL;
2433 
2434  MemoryContextSwitchTo(oldcontext);
2435 
2436  return stup.tuple;
2437 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * tuple
Definition: tuplesort.c:179
MemoryContext sortcontext
Definition: tuplesort.c:262
static bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup)
Definition: tuplesort.c:2132

◆ tuplesort_getindextuple()

IndexTuple tuplesort_getindextuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 2446 of file tuplesort.c.

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

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

2447 {
2448  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2449  SortTuple stup;
2450 
2451  if (!tuplesort_gettuple_common(state, forward, &stup))
2452  stup.tuple = NULL;
2453 
2454  MemoryContextSwitchTo(oldcontext);
2455 
2456  return (IndexTuple) stup.tuple;
2457 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * tuple
Definition: tuplesort.c:179
MemoryContext sortcontext
Definition: tuplesort.c:262
static bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup)
Definition: tuplesort.c:2132

◆ tuplesort_gettuple_common()

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

Definition at line 2132 of file tuplesort.c.

References Assert, Tuplesortstate::bound, Tuplesortstate::bounded, Tuplesortstate::current, elog, Tuplesortstate::eof_reached, ERROR, getlen(), Tuplesortstate::lastReturnedTuple, LogicalTapeBackspace(), LogicalTapeRewindForWrite(), Tuplesortstate::memtupcount, Tuplesortstate::memtuples, mergereadnext(), Tuplesortstate::randomAccess, READTUP, RELEASE_SLAB_SLOT, Tuplesortstate::result_tape, Tuplesortstate::slabAllocatorUsed, SortTuple::srctape, Tuplesortstate::status, Tuplesortstate::tapeset, TSS_FINALMERGE, TSS_SORTEDINMEM, TSS_SORTEDONTAPE, SortTuple::tuple, tuplesort_heap_delete_top(), tuplesort_heap_replace_top(), and WORKER.

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

2134 {
2135  unsigned int tuplen;
2136  size_t nmoved;
2137 
2138  Assert(!WORKER(state));
2139 
2140  switch (state->status)
2141  {
2142  case TSS_SORTEDINMEM:
2143  Assert(forward || state->randomAccess);
2144  Assert(!state->slabAllocatorUsed);
2145  if (forward)
2146  {
2147  if (state->current < state->memtupcount)
2148  {
2149  *stup = state->memtuples[state->current++];
2150  return true;
2151  }
2152  state->eof_reached = true;
2153 
2154  /*
2155  * Complain if caller tries to retrieve more tuples than
2156  * originally asked for in a bounded sort. This is because
2157  * returning EOF here might be the wrong thing.
2158  */
2159  if (state->bounded && state->current >= state->bound)
2160  elog(ERROR, "retrieved too many tuples in a bounded sort");
2161 
2162  return false;
2163  }
2164  else
2165  {
2166  if (state->current <= 0)
2167  return false;
2168 
2169  /*
2170  * if all tuples are fetched already then we return last
2171  * tuple, else - tuple before last returned.
2172  */
2173  if (state->eof_reached)
2174  state->eof_reached = false;
2175  else
2176  {
2177  state->current--; /* last returned tuple */
2178  if (state->current <= 0)
2179  return false;
2180  }
2181  *stup = state->memtuples[state->current - 1];
2182  return true;
2183  }
2184  break;
2185 
2186  case TSS_SORTEDONTAPE:
2187  Assert(forward || state->randomAccess);
2188  Assert(state->slabAllocatorUsed);
2189 
2190  /*
2191  * The slot that held the tuple that we returned in previous
2192  * gettuple call can now be reused.
2193  */
2194  if (state->lastReturnedTuple)
2195  {
2196  RELEASE_SLAB_SLOT(state, state->lastReturnedTuple);
2197  state->lastReturnedTuple = NULL;
2198  }
2199 
2200  if (forward)
2201  {
2202  if (state->eof_reached)
2203  return false;
2204 
2205  if ((tuplen = getlen(state, state->result_tape, true)) != 0)
2206  {
2207  READTUP(state, stup, state->result_tape, tuplen);
2208 
2209  /*
2210  * Remember the tuple we return, so that we can recycle
2211  * its memory on next call. (This can be NULL, in the
2212  * !state->tuples case).
2213  */
2214  state->lastReturnedTuple = stup->tuple;
2215 
2216  return true;
2217  }
2218  else
2219  {
2220  state->eof_reached = true;
2221  return false;
2222  }
2223  }
2224 
2225  /*
2226  * Backward.
2227  *
2228  * if all tuples are fetched already then we return last tuple,
2229  * else - tuple before last returned.
2230  */
2231  if (state->eof_reached)
2232  {
2233  /*
2234  * Seek position is pointing just past the zero tuplen at the
2235  * end of file; back up to fetch last tuple's ending length
2236  * word. If seek fails we must have a completely empty file.
2237  */
2238  nmoved = LogicalTapeBackspace(state->tapeset,
2239  state->result_tape,
2240  2 * sizeof(unsigned int));
2241  if (nmoved == 0)
2242  return false;
2243  else if (nmoved != 2 * sizeof(unsigned int))
2244  elog(ERROR, "unexpected tape position");
2245  state->eof_reached = false;
2246  }
2247  else
2248  {
2249  /*
2250  * Back up and fetch previously-returned tuple's ending length
2251  * word. If seek fails, assume we are at start of file.
2252  */
2253  nmoved = LogicalTapeBackspace(state->tapeset,
2254  state->result_tape,
2255  sizeof(unsigned int));
2256  if (nmoved == 0)
2257  return false;
2258  else if (nmoved != sizeof(unsigned int))
2259  elog(ERROR, "unexpected tape position");
2260  tuplen = getlen(state, state->result_tape, false);
2261 
2262  /*
2263  * Back up to get ending length word of tuple before it.
2264  */
2