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 "lib/sort_template.h"
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)
 
#define ST_SORT   qsort_tuple
 
#define ST_ELEMENT_TYPE   SortTuple
 
#define ST_COMPARE_RUNTIME_POINTER
 
#define ST_COMPARE_ARG_TYPE   Tuplesortstate
 
#define ST_CHECK_FOR_INTERRUPTS
 
#define ST_SCOPE   static
 
#define ST_DECLARE
 
#define ST_DEFINE
 
#define ST_SORT   qsort_ssup
 
#define ST_ELEMENT_TYPE   SortTuple
 
#define ST_COMPARE(a, b, ssup)
 
#define ST_COMPARE_ARG_TYPE   SortSupportData
 
#define ST_CHECK_FOR_INTERRUPTS
 
#define ST_SCOPE   static
 
#define ST_DEFINE
 

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:222
#define Max(x, y)
Definition: c.h:980

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

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

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

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:1169
static char * buf
Definition: pg_test_fsync.c:68
Definition: regguts.h:317
#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().

◆ ST_CHECK_FOR_INTERRUPTS [1/2]

#define ST_CHECK_FOR_INTERRUPTS

Definition at line 696 of file tuplesort.c.

◆ ST_CHECK_FOR_INTERRUPTS [2/2]

#define ST_CHECK_FOR_INTERRUPTS

Definition at line 696 of file tuplesort.c.

◆ ST_COMPARE

#define ST_COMPARE (   a,
  b,
  ssup 
)
Value:
ApplySortComparator((a)->datum1, (a)->isnull1, \
(b)->datum1, (b)->isnull1, (ssup))
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:200

Definition at line 692 of file tuplesort.c.

◆ ST_COMPARE_ARG_TYPE [1/2]

#define ST_COMPARE_ARG_TYPE   Tuplesortstate

Definition at line 695 of file tuplesort.c.

◆ ST_COMPARE_ARG_TYPE [2/2]

#define ST_COMPARE_ARG_TYPE   SortSupportData

Definition at line 695 of file tuplesort.c.

◆ ST_COMPARE_RUNTIME_POINTER

#define ST_COMPARE_RUNTIME_POINTER

Definition at line 682 of file tuplesort.c.

◆ ST_DECLARE

#define ST_DECLARE

Definition at line 686 of file tuplesort.c.

◆ ST_DEFINE [1/2]

#define ST_DEFINE

Definition at line 698 of file tuplesort.c.

◆ ST_DEFINE [2/2]

#define ST_DEFINE

Definition at line 698 of file tuplesort.c.

◆ ST_ELEMENT_TYPE [1/2]

#define ST_ELEMENT_TYPE   SortTuple

Definition at line 691 of file tuplesort.c.

◆ ST_ELEMENT_TYPE [2/2]

#define ST_ELEMENT_TYPE   SortTuple

Definition at line 691 of file tuplesort.c.

◆ ST_SCOPE [1/2]

#define ST_SCOPE   static

Definition at line 697 of file tuplesort.c.

◆ ST_SCOPE [2/2]

#define ST_SCOPE   static

Definition at line 697 of file tuplesort.c.

◆ ST_SORT [1/2]

#define ST_SORT   qsort_tuple

Definition at line 690 of file tuplesort.c.

◆ ST_SORT [2/2]

#define ST_SORT   qsort_ssup

Definition at line 690 of file tuplesort.c.

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

3102 {
3103  int activeTapes;
3104  int tapenum;
3105  int srcTape;
3106 
3107  /* Heap should be empty here */
3108  Assert(state->memtupcount == 0);
3109 
3110  /* Adjust run counts and mark the active tapes */
3111  memset(state->mergeactive, 0,
3112  state->maxTapes * sizeof(*state->mergeactive));
3113  activeTapes = 0;
3114  for (tapenum = 0; tapenum < state->tapeRange; tapenum++)
3115  {
3116  if (state->tp_dummy[tapenum] > 0)
3117  state->tp_dummy[tapenum]--;
3118  else
3119  {
3120  Assert(state->tp_runs[tapenum] > 0);
3121  state->tp_runs[tapenum]--;
3122  srcTape = state->tp_tapenum[tapenum];
3123  state->mergeactive[srcTape] = true;
3124  activeTapes++;
3125  }
3126  }
3127  Assert(activeTapes > 0);
3128  state->activeTapes = activeTapes;
3129 
3130  /* Load the merge heap with the first tuple from each input tape */
3131  for (srcTape = 0; srcTape < state->maxTapes; srcTape++)
3132  {
3133  SortTuple tup;
3134 
3135  if (mergereadnext(state, srcTape, &tup))
3136  {
3137  tup.srctape = srcTape;
3138  tuplesort_heap_insert(state, &tup);
3139  }
3140  }
3141 }
static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3583
static bool mergereadnext(Tuplesortstate *state, int srcTape, SortTuple *stup)
Definition: tuplesort.c:3149
#define Assert(condition)
Definition: c.h:804
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 3954 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().

3956 {
3957  SortSupport sortKey = state->sortKeys;
3958  HeapTuple ltup;
3959  HeapTuple rtup;
3960  TupleDesc tupDesc;
3961  int nkey;
3962  int32 compare;
3963  Datum datum1,
3964  datum2;
3965  bool isnull1,
3966  isnull2;
3967  AttrNumber leading = state->indexInfo->ii_IndexAttrNumbers[0];
3968 
3969  /* Be prepared to compare additional sort keys */
3970  ltup = (HeapTuple) a->tuple;
3971  rtup = (HeapTuple) b->tuple;
3972  tupDesc = state->tupDesc;
3973 
3974  /* Compare the leading sort key, if it's simple */
3975  if (leading != 0)
3976  {
3977  compare = ApplySortComparator(a->datum1, a->isnull1,
3978  b->datum1, b->isnull1,
3979  sortKey);
3980  if (compare != 0)
3981  return compare;
3982 
3983  if (sortKey->abbrev_converter)
3984  {
3985  datum1 = heap_getattr(ltup, leading, tupDesc, &isnull1);
3986  datum2 = heap_getattr(rtup, leading, tupDesc, &isnull2);
3987 
3988  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
3989  datum2, isnull2,
3990  sortKey);
3991  }
3992  if (compare != 0 || state->nKeys == 1)
3993  return compare;
3994  /* Compare additional columns the hard way */
3995  sortKey++;
3996  nkey = 1;
3997  }
3998  else
3999  {
4000  /* Must compare all keys the hard way */
4001  nkey = 0;
4002  }
4003 
4004  if (state->indexInfo->ii_Expressions == NULL)
4005  {
4006  /* If not expression index, just compare the proper heap attrs */
4007 
4008  for (; nkey < state->nKeys; nkey++, sortKey++)
4009  {
4010  AttrNumber attno = state->indexInfo->ii_IndexAttrNumbers[nkey];
4011 
4012  datum1 = heap_getattr(ltup, attno, tupDesc, &isnull1);
4013  datum2 = heap_getattr(rtup, attno, tupDesc, &isnull2);
4014 
4015  compare = ApplySortComparator(datum1, isnull1,
4016  datum2, isnull2,
4017  sortKey);
4018  if (compare != 0)
4019  return compare;
4020  }
4021  }
4022  else
4023  {
4024  /*
4025  * In the expression index case, compute the whole index tuple and
4026  * then compare values. It would perhaps be faster to compute only as
4027  * many columns as we need to compare, but that would require
4028  * duplicating all the logic in FormIndexDatum.
4029  */
4030  Datum l_index_values[INDEX_MAX_KEYS];
4031  bool l_index_isnull[INDEX_MAX_KEYS];
4032  Datum r_index_values[INDEX_MAX_KEYS];
4033  bool r_index_isnull[INDEX_MAX_KEYS];
4034  TupleTableSlot *ecxt_scantuple;
4035 
4036  /* Reset context each time to prevent memory leakage */
4038 
4039  ecxt_scantuple = GetPerTupleExprContext(state->estate)->ecxt_scantuple;
4040 
4041  ExecStoreHeapTuple(ltup, ecxt_scantuple, false);
4042  FormIndexDatum(state->indexInfo, ecxt_scantuple, state->estate,
4043  l_index_values, l_index_isnull);
4044 
4045  ExecStoreHeapTuple(rtup, ecxt_scantuple, false);
4046  FormIndexDatum(state->indexInfo, ecxt_scantuple, state->estate,
4047  r_index_values, r_index_isnull);
4048 
4049  for (; nkey < state->nKeys; nkey++, sortKey++)
4050  {
4051  compare = ApplySortComparator(l_index_values[nkey],
4052  l_index_isnull[nkey],
4053  r_index_values[nkey],
4054  r_index_isnull[nkey],
4055  sortKey);
4056  if (compare != 0)
4057  return compare;
4058  }
4059  }
4060 
4061  return 0;
4062 }
void FormIndexDatum(IndexInfo *indexInfo, TupleTableSlot *slot, EState *estate, Datum *values, bool *isnull)
Definition: index.c:2827
HeapTupleData * HeapTuple
Definition: htup.h:71
#define ResetPerTupleExprContext(estate)
Definition: executor.h:541
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:429
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
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:761
uintptr_t Datum
Definition: postgres.h:411
List * ii_Expressions
Definition: execnodes.h:161
#define INDEX_MAX_KEYS
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
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:1352
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 4441 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().

4442 {
4443  int compare;
4444 
4445  compare = ApplySortComparator(a->datum1, a->isnull1,
4446  b->datum1, b->isnull1,
4447  state->sortKeys);
4448  if (compare != 0)
4449  return compare;
4450 
4451  /* if we have abbreviations, then "tuple" has the original value */
4452 
4453  if (state->sortKeys->abbrev_converter)
4455  PointerGetDatum(b->tuple), b->isnull1,
4456  state->sortKeys);
4457 
4458  return compare;
4459 }
#define PointerGetDatum(X)
Definition: postgres.h:600
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 3755 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().

3756 {
3757  SortSupport sortKey = state->sortKeys;
3758  HeapTupleData ltup;
3759  HeapTupleData rtup;
3760  TupleDesc tupDesc;
3761  int nkey;
3762  int32 compare;
3763  AttrNumber attno;
3764  Datum datum1,
3765  datum2;
3766  bool isnull1,
3767  isnull2;
3768 
3769 
3770  /* Compare the leading sort key */
3771  compare = ApplySortComparator(a->datum1, a->isnull1,
3772  b->datum1, b->isnull1,
3773  sortKey);
3774  if (compare != 0)
3775  return compare;
3776 
3777  /* Compare additional sort keys */
3778  ltup.t_len = ((MinimalTuple) a->tuple)->t_len + MINIMAL_TUPLE_OFFSET;
3779  ltup.t_data = (HeapTupleHeader) ((char *) a->tuple - MINIMAL_TUPLE_OFFSET);
3780  rtup.t_len = ((MinimalTuple) b->tuple)->t_len + MINIMAL_TUPLE_OFFSET;
3781  rtup.t_data = (HeapTupleHeader) ((char *) b->tuple - MINIMAL_TUPLE_OFFSET);
3782  tupDesc = state->tupDesc;
3783 
3784  if (sortKey->abbrev_converter)
3785  {
3786  attno = sortKey->ssup_attno;
3787 
3788  datum1 = heap_getattr(&ltup, attno, tupDesc, &isnull1);
3789  datum2 = heap_getattr(&rtup, attno, tupDesc, &isnull2);
3790 
3791  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
3792  datum2, isnull2,
3793  sortKey);
3794  if (compare != 0)
3795  return compare;
3796  }
3797 
3798  sortKey++;
3799  for (nkey = 1; nkey < state->nKeys; nkey++, sortKey++)
3800  {
3801  attno = sortKey->ssup_attno;
3802 
3803  datum1 = heap_getattr(&ltup, attno, tupDesc, &isnull1);
3804  datum2 = heap_getattr(&rtup, attno, tupDesc, &isnull2);
3805 
3806  compare = ApplySortComparator(datum1, isnull1,
3807  datum2, isnull2,
3808  sortKey);
3809  if (compare != 0)
3810  return compare;
3811  }
3812 
3813  return 0;
3814 }
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:429
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:761
uintptr_t Datum
Definition: postgres.h:411
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:618
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 4200 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().

4202 {
4203  /*
4204  * This is similar to comparetup_heap(), but expects index tuples. There
4205  * is also special handling for enforcing uniqueness, and special
4206  * treatment for equal keys at the end.
4207  */
4208  SortSupport sortKey = state->sortKeys;
4209  IndexTuple tuple1;
4210  IndexTuple tuple2;
4211  int keysz;
4212  TupleDesc tupDes;
4213  bool equal_hasnull = false;
4214  int nkey;
4215  int32 compare;
4216  Datum datum1,
4217  datum2;
4218  bool isnull1,
4219  isnull2;
4220 
4221 
4222  /* Compare the leading sort key */
4223  compare = ApplySortComparator(a->datum1, a->isnull1,
4224  b->datum1, b->isnull1,
4225  sortKey);
4226  if (compare != 0)
4227  return compare;
4228 
4229  /* Compare additional sort keys */
4230  tuple1 = (IndexTuple) a->tuple;
4231  tuple2 = (IndexTuple) b->tuple;
4232  keysz = state->nKeys;
4233  tupDes = RelationGetDescr(state->indexRel);
4234 
4235  if (sortKey->abbrev_converter)
4236  {
4237  datum1 = index_getattr(tuple1, 1, tupDes, &isnull1);
4238  datum2 = index_getattr(tuple2, 1, tupDes, &isnull2);
4239 
4240  compare = ApplySortAbbrevFullComparator(datum1, isnull1,
4241  datum2, isnull2,
4242  sortKey);
4243  if (compare != 0)
4244  return compare;
4245  }
4246 
4247  /* they are equal, so we only need to examine one null flag */
4248  if (a->isnull1)
4249  equal_hasnull = true;
4250 
4251  sortKey++;
4252  for (nkey = 2; nkey <= keysz; nkey++, sortKey++)
4253  {
4254  datum1 = index_getattr(tuple1, nkey, tupDes, &isnull1);
4255  datum2 = index_getattr(tuple2, nkey, tupDes, &isnull2);
4256 
4257  compare = ApplySortComparator(datum1, isnull1,
4258  datum2, isnull2,
4259  sortKey);
4260  if (compare != 0)
4261  return compare; /* done when we find unequal attributes */
4262 
4263  /* they are equal, so we only need to examine one null flag */
4264  if (isnull1)
4265  equal_hasnull = true;
4266  }
4267 
4268  /*
4269  * If btree has asked us to enforce uniqueness, complain if two equal
4270  * tuples are detected (unless there was at least one NULL field).
4271  *
4272  * It is sufficient to make the test here, because if two tuples are equal
4273  * they *must* get compared at some stage of the sort --- otherwise the
4274  * sort algorithm wouldn't have checked whether one must appear before the
4275  * other.
4276  */
4277  if (state->enforceUnique && !equal_hasnull)
4278  {
4280  bool isnull[INDEX_MAX_KEYS];
4281  char *key_desc;
4282 
4283  /*
4284  * Some rather brain-dead implementations of qsort (such as the one in
4285  * QNX 4) will sometimes call the comparison routine to compare a
4286  * value to itself, but we always use our own implementation, which
4287  * does not.
4288  */
4289  Assert(tuple1 != tuple2);
4290 
4291  index_deform_tuple(tuple1, tupDes, values, isnull);
4292 
4293  key_desc = BuildIndexValueDescription(state->indexRel, values, isnull);
4294 
4295  ereport(ERROR,
4296  (errcode(ERRCODE_UNIQUE_VIOLATION),
4297  errmsg("could not create unique index \"%s\"",
4299  key_desc ? errdetail("Key %s is duplicated.", key_desc) :
4300  errdetail("Duplicate keys exist."),
4301  errtableconstraint(state->heapRel,
4302  RelationGetRelationName(state->indexRel))));
4303  }
4304 
4305  /*
4306  * If key values are equal, we sort on ItemPointer. This is required for
4307  * btree indexes, since heap TID is treated as an implicit last key
4308  * attribute in order to ensure that all keys in the index are physically
4309  * unique.
4310  */
4311  {
4312  BlockNumber blk1 = ItemPointerGetBlockNumber(&tuple1->t_tid);
4313  BlockNumber blk2 = ItemPointerGetBlockNumber(&tuple2->t_tid);
4314 
4315  if (blk1 != blk2)
4316  return (blk1 < blk2) ? -1 : 1;
4317  }
4318  {
4321 
4322  if (pos1 != pos2)
4323  return (pos1 < pos2) ? -1 : 1;
4324  }
4325 
4326  /* ItemPointer values should never be equal */
4327  Assert(false);
4328 
4329  return 0;
4330 }
Relation heapRel
Definition: tuplesort.c:458
#define RelationGetDescr(relation)
Definition: rel.h:498
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:698
uint32 BlockNumber
Definition: block.h:31
bool isnull1
Definition: tuplesort.c:181
signed int int32
Definition: c.h:429
uint16 OffsetNumber
Definition: off.h:24
void * tuple
Definition: tuplesort.c:179
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5683
static int compare(const void *arg1, const void *arg2)
Definition: geqo_pool.c:145
#define ERROR
Definition: elog.h:46
IndexTupleData * IndexTuple
Definition: itup.h:53
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:506
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:446
Relation indexRel
Definition: tuplesort.c:459
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
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:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
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 4333 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().

4335 {
4336  Bucket bucket1;
4337  Bucket bucket2;
4338  IndexTuple tuple1;
4339  IndexTuple tuple2;
4340 
4341  /*
4342  * Fetch hash keys and mask off bits we don't want to sort by. We know
4343  * that the first column of the index tuple is the hash key.
4344  */
4345  Assert(!a->isnull1);
4347  state->max_buckets, state->high_mask,
4348  state->low_mask);
4349  Assert(!b->isnull1);
4351  state->max_buckets, state->high_mask,
4352  state->low_mask);
4353  if (bucket1 > bucket2)
4354  return 1;
4355  else if (bucket1 < bucket2)
4356  return -1;
4357 
4358  /*
4359  * If hash values are equal, we sort on ItemPointer. This does not affect
4360  * validity of the finished index, but it may be useful to have index
4361  * scans in physical order.
4362  */
4363  tuple1 = (IndexTuple) a->tuple;
4364  tuple2 = (IndexTuple) b->tuple;
4365 
4366  {
4367  BlockNumber blk1 = ItemPointerGetBlockNumber(&tuple1->t_tid);
4368  BlockNumber blk2 = ItemPointerGetBlockNumber(&tuple2->t_tid);
4369 
4370  if (blk1 != blk2)
4371  return (blk1 < blk2) ? -1 : 1;
4372  }
4373  {
4376 
4377  if (pos1 != pos2)
4378  return (pos1 < pos2) ? -1 : 1;
4379  }
4380 
4381  /* ItemPointer values should never be equal */
4382  Assert(false);
4383 
4384  return 0;
4385 }
#define DatumGetUInt32(X)
Definition: postgres.h:530
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:804
#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 1996 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().

1997 {
1998  Assert(state->sortKeys[0].abbrev_converter != NULL);
1999  Assert(state->sortKeys[0].abbrev_abort != NULL);
2000  Assert(state->sortKeys[0].abbrev_full_comparator != NULL);
2001 
2002  /*
2003  * Check effectiveness of abbreviation optimization. Consider aborting
2004  * when still within memory limit.
2005  */
2006  if (state->status == TSS_INITIAL &&
2007  state->memtupcount >= state->abbrevNext)
2008  {
2009  state->abbrevNext *= 2;
2010 
2011  /*
2012  * Check opclass-supplied abbreviation abort routine. It may indicate
2013  * that abbreviation should not proceed.
2014  */
2015  if (!state->sortKeys->abbrev_abort(state->memtupcount,
2016  state->sortKeys))
2017  return false;
2018 
2019  /*
2020  * Finally, restore authoritative comparator, and indicate that
2021  * abbreviation is not in play by setting abbrev_converter to NULL
2022  */
2023  state->sortKeys[0].comparator = state->sortKeys[0].abbrev_full_comparator;
2024  state->sortKeys[0].abbrev_converter = NULL;
2025  /* Not strictly necessary, but be tidy */
2026  state->sortKeys[0].abbrev_abort = NULL;
2027  state->sortKeys[0].abbrev_full_comparator = NULL;
2028 
2029  /* Give up - expect original pass-by-value representation */
2030  return true;
2031  }
2032 
2033  return false;
2034 }
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:804
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 4065 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().

4066 {
4067  HeapTuple tuple = (HeapTuple) tup;
4068  Datum original;
4069  MemoryContext oldcontext = MemoryContextSwitchTo(state->tuplecontext);
4070 
4071  /* copy the tuple into sort storage */
4072  tuple = heap_copytuple(tuple);
4073  stup->tuple = (void *) tuple;
4074  USEMEM(state, GetMemoryChunkSpace(tuple));
4075 
4076  MemoryContextSwitchTo(oldcontext);
4077 
4078  /*
4079  * set up first-column key value, and potentially abbreviate, if it's a
4080  * simple column
4081  */
4082  if (state->indexInfo->ii_IndexAttrNumbers[0] == 0)
4083  return;
4084 
4085  original = heap_getattr(tuple,
4086  state->indexInfo->ii_IndexAttrNumbers[0],
4087  state->tupDesc,
4088  &stup->isnull1);
4089 
4090  if (!state->sortKeys->abbrev_converter || stup->isnull1)
4091  {
4092  /*
4093  * Store ordinary Datum representation, or NULL value. If there is a
4094  * converter it won't expect NULL values, and cost model is not
4095  * required to account for NULL, so in that case we avoid calling
4096  * converter and just set datum1 to zeroed representation (to be
4097  * consistent, and to support cheap inequality tests for NULL
4098  * abbreviated keys).
4099  */
4100  stup->datum1 = original;
4101  }
4102  else if (!consider_abort_common(state))
4103  {
4104  /* Store abbreviated key representation */
4105  stup->datum1 = state->sortKeys->abbrev_converter(original,
4106  state->sortKeys);
4107  }
4108  else
4109  {
4110  /* Abort abbreviation */
4111  int i;
4112 
4113  stup->datum1 = original;
4114 
4115  /*
4116  * Set state to be consistent with never trying abbreviation.
4117  *
4118  * Alter datum1 representation in already-copied tuples, so as to
4119  * ensure a consistent representation (current tuple was just
4120  * handled). It does not matter if some dumped tuples are already
4121  * sorted on tape, since serialized tuples lack abbreviated keys
4122  * (TSS_BUILDRUNS state prevents control reaching here in any case).
4123  */
4124  for (i = 0; i < state->memtupcount; i++)
4125  {
4126  SortTuple *mtup = &state->memtuples[i];
4127 
4128  tuple = (HeapTuple) mtup->tuple;
4129  mtup->datum1 = heap_getattr(tuple,
4130  state->indexInfo->ii_IndexAttrNumbers[0],
4131  state->tupDesc,
4132  &mtup->isnull1);
4133  }
4134  }
4135 }
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:434
bool isnull1
Definition: tuplesort.c:181
void * tuple
Definition: tuplesort.c:179
static bool consider_abort_common(Tuplesortstate *state)
Definition: tuplesort.c:1996
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:761
uintptr_t Datum
Definition: postgres.h:411
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:160
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 4462 of file tuplesort.c.

References elog, and ERROR.

Referenced by tuplesort_begin_datum().

4463 {
4464  /* Not currently needed */
4465  elog(ERROR, "copytup_datum() should not be called");
4466 }
#define ERROR
Definition: elog.h:46
#define elog(elevel,...)
Definition: elog.h:232

◆ copytup_heap()

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

Definition at line 3817 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().

3818 {
3819  /*
3820  * We expect the passed "tup" to be a TupleTableSlot, and form a
3821  * MinimalTuple using the exported interface for that.
3822  */
3823  TupleTableSlot *slot = (TupleTableSlot *) tup;
3824  Datum original;
3825  MinimalTuple tuple;
3826  HeapTupleData htup;
3827  MemoryContext oldcontext = MemoryContextSwitchTo(state->tuplecontext);
3828 
3829  /* copy the tuple into sort storage */
3830  tuple = ExecCopySlotMinimalTuple(slot);
3831  stup->tuple = (void *) tuple;
3832  USEMEM(state, GetMemoryChunkSpace(tuple));
3833  /* set up first-column key value */
3834  htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
3835  htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
3836  original = heap_getattr(&htup,
3837  state->sortKeys[0].ssup_attno,
3838  state->tupDesc,
3839  &stup->isnull1);
3840 
3841  MemoryContextSwitchTo(oldcontext);
3842 
3843  if (!state->sortKeys->abbrev_converter || stup->isnull1)
3844  {
3845  /*
3846  * Store ordinary Datum representation, or NULL value. If there is a
3847  * converter it won't expect NULL values, and cost model is not
3848  * required to account for NULL, so in that case we avoid calling
3849  * converter and just set datum1 to zeroed representation (to be
3850  * consistent, and to support cheap inequality tests for NULL
3851  * abbreviated keys).
3852  */
3853  stup->datum1 = original;
3854  }
3855  else if (!consider_abort_common(state))
3856  {
3857  /* Store abbreviated key representation */
3858  stup->datum1 = state->sortKeys->abbrev_converter(original,
3859  state->sortKeys);
3860  }
3861  else
3862  {
3863  /* Abort abbreviation */
3864  int i;
3865 
3866  stup->datum1 = original;
3867 
3868  /*
3869  * Set state to be consistent with never trying abbreviation.
3870  *
3871  * Alter datum1 representation in already-copied tuples, so as to
3872  * ensure a consistent representation (current tuple was just
3873  * handled). It does not matter if some dumped tuples are already
3874  * sorted on tape, since serialized tuples lack abbreviated keys
3875  * (TSS_BUILDRUNS state prevents control reaching here in any case).
3876  */
3877  for (i = 0; i < state->memtupcount; i++)
3878  {
3879  SortTuple *mtup = &state->memtuples[i];
3880 
3881  htup.t_len = ((MinimalTuple) mtup->tuple)->t_len +
3883  htup.t_data = (HeapTupleHeader) ((char *) mtup->tuple -
3885 
3886  mtup->datum1 = heap_getattr(&htup,
3887  state->sortKeys[0].ssup_attno,
3888  state->tupDesc,
3889  &mtup->isnull1);
3890  }
3891  }
3892 }
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:434
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:1996
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:761
uintptr_t Datum
Definition: postgres.h:411
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:618
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 4388 of file tuplesort.c.

References elog, and ERROR.

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

4389 {
4390  /* Not currently needed */
4391  elog(ERROR, "copytup_index() should not be called");
4392 }
#define ERROR
Definition: elog.h:46
#define elog(elevel,...)
Definition: elog.h:232

◆ dumptuples()

static void dumptuples ( Tuplesortstate state,
bool  alltuples 
)
static

Definition at line 3174 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().

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

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

Referenced by make_bounded_heap(), and puttuple_common().

4775 {
4776  FREEMEM(state, GetMemoryChunkSpace(stup->tuple));
4777  pfree(stup->tuple);
4778 }
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:434
void * tuple
Definition: tuplesort.c:179
void pfree(void *pointer)
Definition: mcxt.c:1169
#define FREEMEM(state, amt)
Definition: tuplesort.c:547

◆ getlen()

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

Definition at line 3700 of file tuplesort.c.

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

Referenced by mergereadnext(), and tuplesort_gettuple_common().

3701 {
3702  unsigned int len;
3703 
3704  if (LogicalTapeRead(state->tapeset, tapenum,
3705  &len, sizeof(len)) != sizeof(len))
3706  elog(ERROR, "unexpected end of tape");
3707  if (len == 0 && !eofOK)
3708  elog(ERROR, "unexpected end of data");
3709  return len;
3710 }
size_t LogicalTapeRead(LogicalTapeSet *lts, int tapenum, void *ptr, size_t size)
Definition: logtape.c:977
#define ERROR
Definition: elog.h:46
LogicalTapeSet * tapeset
Definition: tuplesort.c:264
#define elog(elevel,...)
Definition: elog.h:232

◆ grow_memtuples()

static bool grow_memtuples ( Tuplesortstate state)
static

Definition at line 1565 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().

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

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

Referenced by mergeruns().

2776 {
2777  if (numSlots > 0)
2778  {
2779  char *p;
2780  int i;
2781 
2782  state->slabMemoryBegin = palloc(numSlots * SLAB_SLOT_SIZE);
2783  state->slabMemoryEnd = state->slabMemoryBegin +
2784  numSlots * SLAB_SLOT_SIZE;
2785  state->slabFreeHead = (SlabSlot *) state->slabMemoryBegin;
2786  USEMEM(state, numSlots * SLAB_SLOT_SIZE);
2787 
2788  p = state->slabMemoryBegin;
2789  for (i = 0; i < numSlots - 1; i++)
2790  {
2791  ((SlabSlot *) p)->nextfree = (SlabSlot *) (p + SLAB_SLOT_SIZE);
2792  p += SLAB_SLOT_SIZE;
2793  }
2794  ((SlabSlot *) p)->nextfree = NULL;
2795  }
2796  else
2797  {
2798  state->slabMemoryBegin = state->slabMemoryEnd = NULL;
2799  state->slabFreeHead = NULL;
2800  }
2801  state->slabAllocatorUsed = true;
2802 }
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:1062
#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 2642 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().

2643 {
2644  int maxTapes,
2645  j;
2646 
2647  Assert(!LEADER(state));
2648 
2649  if (mergeruns)
2650  {
2651  /* Compute number of tapes to use: merge order plus 1 */
2652  maxTapes = tuplesort_merge_order(state->allowedMem) + 1;
2653  }
2654  else
2655  {
2656  /* Workers can sometimes produce single run, output without merge */
2657  Assert(WORKER(state));
2658  maxTapes = MINORDER + 1;
2659  }
2660 
2661 #ifdef TRACE_SORT
2662  if (trace_sort)
2663  elog(LOG, "worker %d switching to external sort with %d tapes: %s",
2664  state->worker, maxTapes, pg_rusage_show(&state->ru_start));
2665 #endif
2666 
2667  /* Create the tape set and allocate the per-tape data arrays */
2668  inittapestate(state, maxTapes);
2669  state->tapeset =
2670  LogicalTapeSetCreate(maxTapes, false, NULL,
2671  state->shared ? &state->shared->fileset : NULL,
2672  state->worker);
2673 
2674  state->currentRun = 0;
2675 
2676  /*
2677  * Initialize variables of Algorithm D (step D1).
2678  */
2679  for (j = 0; j < maxTapes; j++)
2680  {
2681  state->tp_fib[j] = 1;
2682  state->tp_runs[j] = 0;
2683  state->tp_dummy[j] = 1;
2684  state->tp_tapenum[j] = j;
2685  }
2686  state->tp_fib[state->tapeRange] = 0;
2687  state->tp_dummy[state->tapeRange] = 0;
2688 
2689  state->Level = 1;
2690  state->destTape = 0;
2691 
2692  state->status = TSS_BUILDRUNS;
2693 }
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:2811
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:804
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2602
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:232
static void inittapestate(Tuplesortstate *state, int maxTapes)
Definition: tuplesort.c:2699
SharedFileSet fileset
Definition: tuplesort.c:506

◆ inittapestate()

static void inittapestate ( Tuplesortstate state,
int  maxTapes 
)
static

Definition at line 2699 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().

2700 {
2701  int64 tapeSpace;
2702 
2703  /*
2704  * Decrease availMem to reflect the space needed for tape buffers; but
2705  * don't decrease it to the point that we have no room for tuples. (That
2706  * case is only likely to occur if sorting pass-by-value Datums; in all
2707  * other scenarios the memtuples[] array is unlikely to occupy more than
2708  * half of allowedMem. In the pass-by-value case it's not important to
2709  * account for tuple space, so we don't care if LACKMEM becomes
2710  * inaccurate.)
2711  */
2712  tapeSpace = (int64) maxTapes * TAPE_BUFFER_OVERHEAD;
2713 
2714  if (tapeSpace + GetMemoryChunkSpace(state->memtuples) < state->allowedMem)
2715  USEMEM(state, tapeSpace);
2716 
2717  /*
2718  * Make sure that the temp file(s) underlying the tape set are created in
2719  * suitable temp tablespaces. For parallel sorts, this should have been
2720  * called already, but it doesn't matter if it is called a second time.
2721  */
2723 
2724  state->mergeactive = (bool *) palloc0(maxTapes * sizeof(bool));
2725  state->tp_fib = (int *) palloc0(maxTapes * sizeof(int));
2726  state->tp_runs = (int *) palloc0(maxTapes * sizeof(int));
2727  state->tp_dummy = (int *) palloc0(maxTapes * sizeof(int));
2728  state->tp_tapenum = (int *) palloc0(maxTapes * sizeof(int));
2729 
2730  /* Record # of tapes allocated (for duration of sort) */
2731  state->maxTapes = maxTapes;
2732  /* Record maximum # of tapes usable as inputs when merging */
2733  state->tapeRange = maxTapes - 1;
2734 }
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:434
#define TAPE_BUFFER_OVERHEAD
Definition: tuplesort.c:231
void PrepareTempTablespaces(void)
Definition: tablespace.c:1338
int64 allowedMem
Definition: tuplesort.c:251
void * palloc0(Size size)
Definition: mcxt.c:1093
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 4708 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().

4709 {
4710  Sharedsort *shared = state->shared;
4711  int nParticipants = state->nParticipants;
4712  int workersFinished;
4713  int j;
4714 
4715  Assert(LEADER(state));
4716  Assert(nParticipants >= 1);
4717 
4718  SpinLockAcquire(&shared->mutex);
4719  workersFinished = shared->workersFinished;
4720  SpinLockRelease(&shared->mutex);
4721 
4722  if (nParticipants != workersFinished)
4723  elog(ERROR, "cannot take over tapes before all workers finish");
4724 
4725  /*
4726  * Create the tapeset from worker tapes, including a leader-owned tape at
4727  * the end. Parallel workers are far more expensive than logical tapes,
4728  * so the number of tapes allocated here should never be excessive.
4729  *
4730  * We still have a leader tape, though it's not possible to write to it
4731  * due to restrictions in the shared fileset infrastructure used by
4732  * logtape.c. It will never be written to in practice because
4733  * randomAccess is disallowed for parallel sorts.
4734  */
4735  inittapestate(state, nParticipants + 1);
4736  state->tapeset = LogicalTapeSetCreate(nParticipants + 1, false,
4737  shared->tapes, &shared->fileset,
4738  state->worker);
4739 
4740  /* mergeruns() relies on currentRun for # of runs (in one-pass cases) */
4741  state->currentRun = nParticipants;
4742 
4743  /*
4744  * Initialize variables of Algorithm D to be consistent with runs from
4745  * workers having been generated in the leader.
4746  *
4747  * There will always be exactly 1 run per worker, and exactly one input
4748  * tape per run, because workers always output exactly 1 run, even when
4749  * there were no input tuples for workers to sort.
4750  */
4751  for (j = 0; j < state->maxTapes; j++)
4752  {
4753  /* One real run; no dummy runs for worker tapes */
4754  state->tp_fib[j] = 1;
4755  state->tp_runs[j] = 1;
4756  state->tp_dummy[j] = 0;
4757  state->tp_tapenum[j] = j;
4758  }
4759  /* Leader tape gets one dummy run, and no real runs */
4760  state->tp_fib[state->tapeRange] = 0;
4761  state->tp_runs[state->tapeRange] = 0;
4762  state->tp_dummy[state->tapeRange] = 1;
4763 
4764  state->Level = 1;
4765  state->destTape = 0;
4766 
4767  state->status = TSS_BUILDRUNS;
4768 }
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:46
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:804
int * tp_dummy
Definition: tuplesort.c:387
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:232
TapeShare tapes[FLEXIBLE_ARRAY_MEMBER]
Definition: tuplesort.c:515
static void inittapestate(Tuplesortstate *state, int maxTapes)
Definition: tuplesort.c:2699
SharedFileSet fileset
Definition: tuplesort.c:506

◆ make_bounded_heap()

static void make_bounded_heap ( Tuplesortstate state)
static

Definition at line 3466 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().

3467 {
3468  int tupcount = state->memtupcount;
3469  int i;
3470 
3471  Assert(state->status == TSS_INITIAL);
3472  Assert(state->bounded);
3473  Assert(tupcount >= state->bound);
3474  Assert(SERIAL(state));
3475 
3476  /* Reverse sort direction so largest entry will be at root */
3477  reversedirection(state);
3478 
3479  state->memtupcount = 0; /* make the heap empty */
3480  for (i = 0; i < tupcount; i++)
3481  {
3482  if (state->memtupcount < state->bound)
3483  {
3484  /* Insert next tuple into heap */
3485  /* Must copy source tuple to avoid possible overwrite */
3486  SortTuple stup = state->memtuples[i];
3487 
3488  tuplesort_heap_insert(state, &stup);
3489  }
3490  else
3491  {
3492  /*
3493  * The heap is full. Replace the largest entry with the new
3494  * tuple, or just discard it, if it's larger than anything already
3495  * in the heap.
3496  */
3497  if (COMPARETUP(state, &state->memtuples[i], &state->memtuples[0]) <= 0)
3498  {
3499  free_sort_tuple(state, &state->memtuples[i]);
3501  }
3502  else
3503  tuplesort_heap_replace_top(state, &state->memtuples[i]);
3504  }
3505  }
3506 
3507  Assert(state->memtupcount == state->bound);
3508  state->status = TSS_BOUNDED;
3509 }
static void reversedirection(Tuplesortstate *state)
Definition: tuplesort.c:3682
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:4774
#define COMPARETUP(state, a, b)
Definition: tuplesort.c:541
static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3583
#define Assert(condition)
Definition: c.h:804
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3642
SortTuple * memtuples
Definition: tuplesort.c:311

◆ markrunend()

static void markrunend ( Tuplesortstate state,
int  tapenum 
)
static

Definition at line 3713 of file tuplesort.c.

References LogicalTapeWrite(), and Tuplesortstate::tapeset.

Referenced by dumptuples(), and mergeonerun().

3714 {
3715  unsigned int len = 0;
3716 
3717  LogicalTapeWrite(state->tapeset, tapenum, (void *) &len, sizeof(len));
3718 }
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 3038 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().

3039 {
3040  int destTape = state->tp_tapenum[state->tapeRange];
3041  int srcTape;
3042 
3043  /*
3044  * Start the merge by loading one tuple from each active source tape into
3045  * the heap. We can also decrease the input run/dummy run counts.
3046  */
3047  beginmerge(state);
3048 
3049  /*
3050  * Execute merge by repeatedly extracting lowest tuple in heap, writing it
3051  * out, and replacing it with next tuple from same tape (if there is
3052  * another one).
3053  */
3054  while (state->memtupcount > 0)
3055  {
3056  SortTuple stup;
3057 
3058  /* write the tuple to destTape */
3059  srcTape = state->memtuples[0].srctape;
3060  WRITETUP(state, destTape, &state->memtuples[0]);
3061 
3062  /* recycle the slot of the tuple we just wrote out, for the next read */
3063  if (state->memtuples[0].tuple)
3064  RELEASE_SLAB_SLOT(state, state->memtuples[0].tuple);
3065 
3066  /*
3067  * pull next tuple from the tape, and replace the written-out tuple in
3068  * the heap with it.
3069  */
3070  if (mergereadnext(state, srcTape, &stup))
3071  {
3072  stup.srctape = srcTape;
3073  tuplesort_heap_replace_top(state, &stup);
3074  }
3075  else
3077  }
3078 
3079  /*
3080  * When the heap empties, we're done. Write an end-of-run marker on the
3081  * output tape, and increment its count of real runs.
3082  */
3083  markrunend(state, destTape);
3084  state->tp_runs[state->tapeRange]++;
3085 
3086 #ifdef TRACE_SORT
3087  if (trace_sort)
3088  elog(LOG, "worker %d finished %d-way merge step: %s", state->worker,
3089  state->activeTapes, pg_rusage_show(&state->ru_start));
3090 #endif
3091 }
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:3713
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:3618
static bool mergereadnext(Tuplesortstate *state, int srcTape, SortTuple *stup)
Definition: tuplesort.c:3149
int srctape
Definition: tuplesort.c:182
int * tp_tapenum
Definition: tuplesort.c:388
#define elog(elevel,...)
Definition: elog.h:232
static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple)
Definition: tuplesort.c:3642
static void beginmerge(Tuplesortstate *state)
Definition: tuplesort.c:3101
SortTuple * memtuples
Definition: tuplesort.c:311

◆ mergereadnext()

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

Definition at line 3149 of file tuplesort.c.

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

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

3150 {
3151  unsigned int tuplen;
3152 
3153  if (!state->mergeactive[srcTape])
3154  return false; /* tape's run is already exhausted */
3155 
3156  /* read next tuple, if any */
3157  if ((tuplen = getlen(state, srcTape, true)) == 0)
3158  {
3159  state->mergeactive[srcTape] = false;
3160  return false;
3161  }
3162  READTUP(state, stup, srcTape, tuplen);
3163 
3164  return true;
3165 }
static unsigned int getlen(Tuplesortstate *state, int tapenum, bool eofOK)
Definition: tuplesort.c:3700
#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 2811 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().

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

◆ puttuple_common()

static void puttuple_common ( Tuplesortstate state,
SortTuple tuple 
)
static

Definition at line 1887 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().

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

3728 {
3729  SlabSlot *buf;
3730 
3731  /*
3732  * We pre-allocate enough slots in the slab arena that we should never run
3733  * out.
3734  */
3735  Assert(state->slabFreeHead);
3736 
3737  if (tuplen > SLAB_SLOT_SIZE || !state->slabFreeHead)
3738  return MemoryContextAlloc(state->sortcontext, tuplen);
3739  else
3740  {
3741  buf = state->slabFreeHead;
3742  /* Reuse this slot */
3743  state->slabFreeHead = buf->nextfree;
3744 
3745  return buf;
3746  }
3747 }
#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:804
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
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 4162 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().

4164 {
4165  unsigned int t_len = tuplen - sizeof(ItemPointerData) - sizeof(int);
4166  HeapTuple tuple = (HeapTuple) readtup_alloc(state,
4167  t_len + HEAPTUPLESIZE);
4168 
4169  /* Reconstruct the HeapTupleData header */
4170  tuple->t_data = (HeapTupleHeader) ((char *) tuple + HEAPTUPLESIZE);
4171  tuple->t_len = t_len;
4172  LogicalTapeReadExact(state->tapeset, tapenum,
4173  &tuple->t_self, sizeof(ItemPointerData));
4174  /* We don't currently bother to reconstruct t_tableOid */
4175  tuple->t_tableOid = InvalidOid;
4176  /* Read in the tuple body */
4177  LogicalTapeReadExact(state->tapeset, tapenum,
4178  tuple->t_data, tuple->t_len);
4179  if (state->randomAccess) /* need trailing length word? */
4180  LogicalTapeReadExact(state->tapeset, tapenum,
4181  &tuplen, sizeof(tuplen));
4182  stup->tuple = (void *) tuple;
4183  /* set up first-column key value, if it's a simple column */
4184  if (state->indexInfo->ii_IndexAttrNumbers[0] != 0)
4185  stup->datum1 = heap_getattr(tuple,
4186  state->indexInfo->ii_IndexAttrNumbers[0],
4187  state->tupDesc,
4188  &stup->isnull1);
4189 }
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:761
#define InvalidOid
Definition: postgres_ext.h:36
struct ItemPointerData ItemPointerData
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3727
#define HEAPTUPLESIZE
Definition: htup.h:73
AttrNumber ii_IndexAttrNumbers[INDEX_MAX_KEYS]
Definition: execnodes.h:160
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 4510 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().

4512 {
4513  unsigned int tuplen = len - sizeof(unsigned int);
4514 
4515  if (tuplen == 0)
4516  {
4517  /* it's NULL */
4518  stup->datum1 = (Datum) 0;
4519  stup->isnull1 = true;
4520  stup->tuple = NULL;
4521  }
4522  else if (!state->tuples)
4523  {
4524  Assert(tuplen == sizeof(Datum));
4525  LogicalTapeReadExact(state->tapeset, tapenum,
4526  &stup->datum1, tuplen);
4527  stup->isnull1 = false;
4528  stup->tuple = NULL;
4529  }
4530  else
4531  {
4532  void *raddr = readtup_alloc(state, tuplen);
4533 
4534  LogicalTapeReadExact(state->tapeset, tapenum,
4535  raddr, tuplen);
4536  stup->datum1 = PointerGetDatum(raddr);
4537  stup->isnull1 = false;
4538  stup->tuple = raddr;
4539  }
4540 
4541  if (state->randomAccess) /* need trailing length word? */
4542  LogicalTapeReadExact(state->tapeset, tapenum,
4543  &tuplen, sizeof(tuplen));
4544 }
#define PointerGetDatum(X)
Definition: postgres.h:600
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:411
#define Assert(condition)
Definition: c.h:804
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3727

◆ readtup_heap()

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

Definition at line 3922 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().

3924 {
3925  unsigned int tupbodylen = len - sizeof(int);
3926  unsigned int tuplen = tupbodylen + MINIMAL_TUPLE_DATA_OFFSET;
3927  MinimalTuple tuple = (MinimalTuple) readtup_alloc(state, tuplen);
3928  char *tupbody = (char *) tuple + MINIMAL_TUPLE_DATA_OFFSET;
3929  HeapTupleData htup;
3930 
3931  /* read in the tuple proper */
3932  tuple->t_len = tuplen;
3933  LogicalTapeReadExact(state->tapeset, tapenum,
3934  tupbody, tupbodylen);
3935  if (state->randomAccess) /* need trailing length word? */
3936  LogicalTapeReadExact(state->tapeset, tapenum,
3937  &tuplen, sizeof(tuplen));
3938  stup->tuple = (void *) tuple;
3939  /* set up first-column key value */
3940  htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
3941  htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
3942  stup->datum1 = heap_getattr(&htup,
3943  state->sortKeys[0].ssup_attno,
3944  state->tupDesc,
3945  &stup->isnull1);
3946 }
#define MINIMAL_TUPLE_DATA_OFFSET
Definition: htup_details.h:622
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:761
AttrNumber ssup_attno
Definition: sortsupport.h:81
#define MINIMAL_TUPLE_OFFSET
Definition: htup_details.h:618
static void * readtup_alloc(Tuplesortstate *state, Size tuplen)
Definition: tuplesort.c:3727
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 4417 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().

4419 {
4420  unsigned int tuplen = len - sizeof(unsigned int);
4421  IndexTuple tuple = (IndexTuple) readtup_alloc(state, tuplen);
4422 
4423  LogicalTapeReadExact(state->tapeset, tapenum,
4424  tuple, tuplen);
4425  if (state->randomAccess) /* need trailing length word? */
4426  LogicalTapeReadExact(state->tapeset, tapenum,
4427  &tuplen, sizeof(tuplen));
4428  stup->tuple = (void *) tuple;
4429  /* set up first-column key value */
4430  stup->datum1 = index_getattr(tuple,
4431  1,
4432  RelationGetDescr(state->indexRel),
4433  &stup->isnull1);
4434 }
#define RelationGetDescr(relation)
Definition: rel.h:498
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:3727

◆ reversedirection()

static void reversedirection ( Tuplesortstate state)
static

Definition at line 3682 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().

3683 {
3684  SortSupport sortKey = state->sortKeys;
3685  int nkey;
3686 
3687  for (nkey = 0; nkey < state->nKeys; nkey++, sortKey++)
3688  {
3689  sortKey->ssup_reverse = !sortKey->ssup_reverse;
3690  sortKey->ssup_nulls_first = !sortKey->ssup_nulls_first;
3691  }
3692 }
bool ssup_nulls_first
Definition: sortsupport.h:75
SortSupport sortKeys
Definition: tuplesort.c:430

◆ selectnewtape()

static void selectnewtape ( Tuplesortstate state)
static

Definition at line 2743 of file tuplesort.c.

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

Referenced by dumptuples().

2744 {
2745  int j;
2746  int a;
2747 
2748  /* Step D3: advance j (destTape) */
2749  if (state->tp_dummy[state->destTape] < state->tp_dummy[state->destTape + 1])
2750  {
2751  state->destTape++;
2752  return;
2753  }
2754  if (state->tp_dummy[state->destTape] != 0)
2755  {
2756  state->destTape = 0;
2757  return;
2758  }
2759 
2760  /* Step D4: increase level */
2761  state->Level++;
2762  a = state->tp_fib[0];
2763  for (j = 0; j < state->tapeRange; j++)
2764  {
2765  state->tp_dummy[j] = a + state->tp_fib[j + 1] - state->tp_fib[j];
2766  state->tp_fib[j] = a + state->tp_fib[j + 1];
2767  }
2768  state->destTape = 0;
2769 }
int * tp_dummy
Definition: tuplesort.c:387

◆ sort_bounded_heap()

static void sort_bounded_heap ( Tuplesortstate state)
static

Definition at line 3515 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().

3516 {
3517  int tupcount = state->memtupcount;
3518 
3519  Assert(state->status == TSS_BOUNDED);
3520  Assert(state->bounded);
3521  Assert(tupcount == state->bound);
3522  Assert(SERIAL(state));
3523 
3524  /*
3525  * We can unheapify in place because each delete-top call will remove the
3526  * largest entry, which we can promptly store in the newly freed slot at
3527  * the end. Once we're down to a single-entry heap, we're done.
3528  */
3529  while (state->memtupcount > 1)
3530  {
3531  SortTuple stup = state->memtuples[0];
3532 
3533  /* this sifts-up the next-largest entry and decreases memtupcount */
3535  state->memtuples[state->memtupcount] = stup;
3536  }
3537  state->memtupcount = tupcount;
3538 
3539  /*
3540  * Reverse sort direction back to the original state. This is not
3541  * actually necessary but seems like a good idea for tidiness.
3542  */
3543  reversedirection(state);
3544 
3545  state->status = TSS_SORTEDINMEM;
3546  state->boundUsed = true;
3547 }
static void reversedirection(Tuplesortstate *state)
Definition: tuplesort.c:3682
TupSortStatus status
Definition: tuplesort.c:242
#define SERIAL(state)
Definition: tuplesort.c:548
static void tuplesort_heap_delete_top(Tuplesortstate *state)
Definition: tuplesort.c:3618
#define Assert(condition)
Definition: c.h:804
SortTuple * memtuples
Definition: tuplesort.c:311

◆ tuplesort_attach_shared()

void tuplesort_attach_shared ( Sharedsort shared,
dsm_segment seg 
)

Definition at line 4601 of file tuplesort.c.

References Sharedsort::fileset, and SharedFileSetAttach().

Referenced by _bt_parallel_build_main().

4602 {
4603  /* Attach to SharedFileSet */
4604  SharedFileSetAttach(&shared->fileset, seg);
4605 }
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 833 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().

834 {
835  MemoryContext oldcontext;
836 
837  oldcontext = MemoryContextSwitchTo(state->maincontext);
838 
839  /*
840  * Caller tuple (e.g. IndexTuple) memory context.
841  *
842  * A dedicated child context used exclusively for caller passed tuples
843  * eases memory management. Resetting at key points reduces
844  * fragmentation. Note that the memtuples array of SortTuples is allocated
845  * in the parent context, not this context, because there is no need to
846  * free memtuples early.
847  */
849  "Caller tuples",
851 
852  state->status = TSS_INITIAL;
853  state->bounded = false;
854  state->boundUsed = false;
855 
856  state->availMem = state->allowedMem;
857 
858  state->tapeset = NULL;
859 
860  state->memtupcount = 0;
861 
862  /*
863  * Initial size of array must be more than ALLOCSET_SEPARATE_THRESHOLD;
864  * see comments in grow_memtuples().
865  */
866  state->growmemtuples = true;
867  state->slabAllocatorUsed = false;
868  if (state->memtuples != NULL && state->memtupsize != INITIAL_MEMTUPSIZE)
869  {
870  pfree(state->memtuples);
871  state->memtuples = NULL;
873  }
874  if (state->memtuples == NULL)
875  {
876  state->memtuples = (SortTuple *) palloc(state->memtupsize * sizeof(SortTuple));
877  USEMEM(state, GetMemoryChunkSpace(state->memtuples));
878  }
879 
880  /* workMem must be large enough for the minimal memtuples array */
881  if (LACKMEM(state))
882  elog(ERROR, "insufficient memory allowed for sort");
883 
884  state->currentRun = 0;
885 
886  /*
887  * maxTapes, tapeRange, and Algorithm D variables will be initialized by
888  * inittapes(), if needed
889  */
890 
891  state->result_tape = -1; /* flag that result tape has not been formed */
892 
893  MemoryContextSwitchTo(oldcontext);
894 }
int64 availMem
Definition: tuplesort.c:250
TupSortStatus status
Definition: tuplesort.c:242
#define AllocSetContextCreate
Definition: memutils.h:173
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:434
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
MemoryContext sortcontext
Definition: tuplesort.c:262
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
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:1062
#define USEMEM(state, amt)
Definition: tuplesort.c:546
#define elog(elevel,...)
Definition: elog.h:232
#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 971 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().

975 {
976  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
977  randomAccess);
978  BTScanInsert indexScanKey;
979  MemoryContext oldcontext;
980  int i;
981 
982  Assert(indexRel->rd_rel->relam == BTREE_AM_OID);
983 
984  oldcontext = MemoryContextSwitchTo(state->maincontext);
985 
986 #ifdef TRACE_SORT
987  if (trace_sort)
988  elog(LOG,
989  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
991  workMem, randomAccess ? 't' : 'f');
992 #endif
993 
994  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
995 
996  TRACE_POSTGRESQL_SORT_START(CLUSTER_SORT,
997  false, /* no unique check */
998  state->nKeys,
999  workMem,
1000  randomAccess,
1001  PARALLEL_SORT(state));
1002 
1003  state->comparetup = comparetup_cluster;
1004  state->copytup = copytup_cluster;
1005  state->writetup = writetup_cluster;
1006  state->readtup = readtup_cluster;
1007  state->abbrevNext = 10;
1008 
1009  state->indexInfo = BuildIndexInfo(indexRel);
1010 
1011  state->tupDesc = tupDesc; /* assume we need not copy tupDesc */
1012 
1013  indexScanKey = _bt_mkscankey(indexRel, NULL);
1014 
1015  if (state->indexInfo->ii_Expressions != NULL)
1016  {
1017  TupleTableSlot *slot;
1018  ExprContext *econtext;
1019 
1020  /*
1021  * We will need to use FormIndexDatum to evaluate the index
1022  * expressions. To do that, we need an EState, as well as a
1023  * TupleTableSlot to put the table tuples into. The econtext's
1024  * scantuple has to point to that slot, too.
1025  */
1026  state->estate = CreateExecutorState();
1027  slot = MakeSingleTupleTableSlot(tupDesc, &TTSOpsHeapTuple);
1028  econtext = GetPerTupleExprContext(state->estate);
1029  econtext->ecxt_scantuple = slot;
1030  }
1031 
1032  /* Prepare SortSupport data for each column */
1033  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1034  sizeof(SortSupportData));
1035 
1036  for (i = 0; i < state->nKeys; i++)
1037  {
1038  SortSupport sortKey = state->sortKeys + i;
1039  ScanKey scanKey = indexScanKey->scankeys + i;
1040  int16 strategy;
1041 
1042  sortKey->ssup_cxt = CurrentMemoryContext;
1043  sortKey->ssup_collation = scanKey->sk_collation;
1044  sortKey->ssup_nulls_first =
1045  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1046  sortKey->ssup_attno = scanKey->sk_attno;
1047  /* Convey if abbreviation optimization is applicable in principle */
1048  sortKey->abbreviate = (i == 0);
1049 
1050  AssertState(sortKey->ssup_attno != 0);
1051 
1052  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1054 
1055  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
1056  }
1057 
1058  pfree(indexScanKey);
1059 
1060  MemoryContextSwitchTo(oldcontext);
1061 
1062  return state;
1063 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:428
bool ssup_nulls_first
Definition: sortsupport.h:75
static void writetup_cluster(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4138
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
#define AssertState(condition)
Definition: c.h:807
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:1238
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:478
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:3954
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2543
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:110
static void copytup_cluster(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4065
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
void pfree(void *pointer)
Definition: mcxt.c:1169
static void readtup_cluster(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4162
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:42
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:491
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:162
EState * CreateExecutorState(void)
Definition: execUtils.c:90
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1083
void * palloc0(Size size)
Definition: mcxt.c:1093
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:161
#define Assert(condition)
Definition: c.h:804
#define SK_BT_DESC
Definition: nbtree.h:1082
Definition: regguts.h:317
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:791
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
Oid sk_collation
Definition: skey.h:70
#define elog(elevel,...)
Definition: elog.h:232
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 721 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().

723 {
725  MemoryContext maincontext;
726  MemoryContext sortcontext;
727  MemoryContext oldcontext;
728 
729  /* See leader_takeover_tapes() remarks on randomAccess support */
730  if (coordinate && randomAccess)
731  elog(ERROR, "random access disallowed under parallel sort");
732 
733  /*
734  * Memory context surviving tuplesort_reset. This memory context holds
735  * data which is useful to keep while sorting multiple similar batches.
736  */
738  "TupleSort main",
740 
741  /*
742  * Create a working memory context for one sort operation. The content of
743  * this context is deleted by tuplesort_reset.
744  */
745  sortcontext = AllocSetContextCreate(maincontext,
746  "TupleSort sort",
748 
749  /*
750  * Additionally a working memory context for tuples is setup in
751  * tuplesort_begin_batch.
752  */
753 
754  /*
755  * Make the Tuplesortstate within the per-sortstate context. This way, we
756  * don't need a separate pfree() operation for it at shutdown.
757  */
758  oldcontext = MemoryContextSwitchTo(maincontext);
759 
760  state = (Tuplesortstate *) palloc0(sizeof(Tuplesortstate));
761 
762 #ifdef TRACE_SORT
763  if (trace_sort)
764  pg_rusage_init(&state->ru_start);
765 #endif
766 
767  state->randomAccess = randomAccess;
768  state->tuples = true;
769 
770  /*
771  * workMem is forced to be at least 64KB, the current minimum valid value
772  * for the work_mem GUC. This is a defense against parallel sort callers
773  * that divide out memory among many workers in a way that leaves each
774  * with very little memory.
775  */
776  state->allowedMem = Max(workMem, 64) * (int64) 1024;
777  state->sortcontext = sortcontext;
778  state->maincontext = maincontext;
779 
780  /*
781  * Initial size of array must be more than ALLOCSET_SEPARATE_THRESHOLD;
782  * see comments in grow_memtuples().
783  */
785  state->memtuples = NULL;
786 
787  /*
788  * After all of the other non-parallel-related state, we setup all of the
789  * state needed for each batch.
790  */
791  tuplesort_begin_batch(state);
792 
793  /*
794  * Initialize parallel-related state based on coordination information
795  * from caller
796  */
797  if (!coordinate)
798  {
799  /* Serial sort */
800  state->shared = NULL;
801  state->worker = -1;
802  state->nParticipants = -1;
803  }
804  else if (coordinate->isWorker)
805  {
806  /* Parallel worker produces exactly one final run from all input */
807  state->shared = coordinate->sharedsort;
808  state->worker = worker_get_identifier(state);
809  state->nParticipants = -1;
810  }
811  else
812  {
813  /* Parallel leader state only used for final merge */
814  state->shared = coordinate->sharedsort;
815  state->worker = -1;
816  state->nParticipants = coordinate->nParticipants;
817  Assert(state->nParticipants >= 1);
818  }
819 
820  MemoryContextSwitchTo(oldcontext);
821 
822  return state;
823 }
#define AllocSetContextCreate
Definition: memutils.h:173
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:4621
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:833
#define ERROR
Definition: elog.h:46
MemoryContext sortcontext
Definition: tuplesort.c:262
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
Sharedsort * shared
Definition: tuplesort.c:421
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
int64 allowedMem
Definition: tuplesort.c:251
void * palloc0(Size size)
Definition: mcxt.c:1093
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
#define INITIAL_MEMTUPSIZE
Definition: tuplesort.c:135
#define elog(elevel,...)
Definition: elog.h:232
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 1247 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().

1250 {
1251  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1252  randomAccess);
1253  MemoryContext oldcontext;
1254  int16 typlen;
1255  bool typbyval;
1256 
1257  oldcontext = MemoryContextSwitchTo(state->maincontext);
1258 
1259 #ifdef TRACE_SORT
1260  if (trace_sort)
1261  elog(LOG,
1262  "begin datum sort: workMem = %d, randomAccess = %c",
1263  workMem, randomAccess ? 't' : 'f');
1264 #endif
1265 
1266  state->nKeys = 1; /* always a one-column sort */
1267 
1268  TRACE_POSTGRESQL_SORT_START(DATUM_SORT,
1269  false, /* no unique check */
1270  1,
1271  workMem,
1272  randomAccess,
1273  PARALLEL_SORT(state));
1274 
1275  state->comparetup = comparetup_datum;
1276  state->copytup = copytup_datum;
1277  state->writetup = writetup_datum;
1278  state->readtup = readtup_datum;
1279  state->abbrevNext = 10;
1280 
1281  state->datumType = datumType;
1282 
1283  /* lookup necessary attributes of the datum type */
1284  get_typlenbyval(datumType, &typlen, &typbyval);
1285  state->datumTypeLen = typlen;
1286  state->tuples = !typbyval;
1287 
1288  /* Prepare SortSupport data */
1289  state->sortKeys = (SortSupport) palloc0(sizeof(SortSupportData));
1290 
1292  state->sortKeys->ssup_collation = sortCollation;
1293  state->sortKeys->ssup_nulls_first = nullsFirstFlag;
1294 
1295  /*
1296  * Abbreviation is possible here only for by-reference types. In theory,
1297  * a pass-by-value datatype could have an abbreviated form that is cheaper
1298  * to compare. In a tuple sort, we could support that, because we can
1299  * always extract the original datum from the tuple as needed. Here, we
1300  * can't, because a datum sort only stores a single copy of the datum; the
1301  * "tuple" field of each SortTuple is NULL.
1302  */
1303  state->sortKeys->abbreviate = !typbyval;
1304 
1305  PrepareSortSupportFromOrderingOp(sortOperator, state->sortKeys);
1306 
1307  /*
1308  * The "onlyKey" optimization cannot be used with abbreviated keys, since
1309  * tie-breaker comparisons may be required. Typically, the optimization
1310  * is only of value to pass-by-value types anyway, whereas abbreviated
1311  * keys are typically only of value to pass-by-reference types.
1312  */
1313  if (!state->sortKeys->abbrev_converter)
1314  state->onlyKey = state->sortKeys;
1315 
1316  MemoryContextSwitchTo(oldcontext);
1317 
1318  return state;
1319 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:428
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:4441
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:4462
static void readtup_datum(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:4510
Datum(* abbrev_converter)(Datum original, SortSupport ssup)
Definition: sortsupport.h:172
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void writetup_datum(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4469
void * palloc0(Size size)
Definition: mcxt.c:1093
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:317
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2198
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
#define elog(elevel,...)
Definition: elog.h:232
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 897 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().

902 {
903  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
904  randomAccess);
905  MemoryContext oldcontext;
906  int i;
907 
908  oldcontext = MemoryContextSwitchTo(state->maincontext);
909 
910  AssertArg(nkeys > 0);
911 
912 #ifdef TRACE_SORT
913  if (trace_sort)
914  elog(LOG,
915  "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
916  nkeys, workMem, randomAccess ? 't' : 'f');
917 #endif
918 
919  state->nKeys = nkeys;
920 
921  TRACE_POSTGRESQL_SORT_START(HEAP_SORT,
922  false, /* no unique check */
923  nkeys,
924  workMem,
925  randomAccess,
926  PARALLEL_SORT(state));
927 
928  state->comparetup = comparetup_heap;
929  state->copytup = copytup_heap;
930  state->writetup = writetup_heap;
931  state->readtup = readtup_heap;
932 
933  state->tupDesc = tupDesc; /* assume we need not copy tupDesc */
934  state->abbrevNext = 10;
935 
936  /* Prepare SortSupport data for each column */
937  state->sortKeys = (SortSupport) palloc0(nkeys * sizeof(SortSupportData));
938 
939  for (i = 0; i < nkeys; i++)
940  {
941  SortSupport sortKey = state->sortKeys + i;
942 
943  AssertArg(attNums[i] != 0);
944  AssertArg(sortOperators[i] != 0);
945 
946  sortKey->ssup_cxt = CurrentMemoryContext;
947  sortKey->ssup_collation = sortCollations[i];
948  sortKey->ssup_nulls_first = nullsFirstFlags[i];
949  sortKey->ssup_attno = attNums[i];
950  /* Convey if abbreviation optimization is applicable in principle */
951  sortKey->abbreviate = (i == 0);
952 
953  PrepareSortSupportFromOrderingOp(sortOperators[i], sortKey);
954  }
955 
956  /*
957  * The "onlyKey" optimization cannot be used with abbreviated keys, since
958  * tie-breaker comparisons may be required. Typically, the optimization
959  * is only of value to pass-by-value types anyway, whereas abbreviated
960  * keys are typically only of value to pass-by-reference types.
961  */
962  if (nkeys == 1 && !state->sortKeys->abbrev_converter)
963  state->onlyKey = state->sortKeys;
964 
965  MemoryContextSwitchTo(oldcontext);
966 
967  return state;
968 }
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:3755
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:3895
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:42
#define AssertArg(condition)
Definition: c.h:806
static void copytup_heap(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:3817
void * palloc0(Size size)
Definition: mcxt.c:1093
AttrNumber ssup_attno
Definition: sortsupport.h:81
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:317
static void readtup_heap(Tuplesortstate *state, SortTuple *stup, int tapenum, unsigned int len)
Definition: tuplesort.c:3922
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
#define elog(elevel,...)
Definition: elog.h:232
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 1066 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().

1072 {
1073  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1074  randomAccess);
1075  BTScanInsert indexScanKey;
1076  MemoryContext oldcontext;
1077  int i;
1078 
1079  oldcontext = MemoryContextSwitchTo(state->maincontext);
1080 
1081 #ifdef TRACE_SORT
1082  if (trace_sort)
1083  elog(LOG,
1084  "begin index sort: unique = %c, workMem = %d, randomAccess = %c",
1085  enforceUnique ? 't' : 'f',
1086  workMem, randomAccess ? 't' : 'f');
1087 #endif
1088 
1089  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
1090 
1091  TRACE_POSTGRESQL_SORT_START(INDEX_SORT,
1092  enforceUnique,
1093  state->nKeys,
1094  workMem,
1095  randomAccess,
1096  PARALLEL_SORT(state));
1097 
1099  state->copytup = copytup_index;
1100  state->writetup = writetup_index;
1101  state->readtup = readtup_index;
1102  state->abbrevNext = 10;
1103 
1104  state->heapRel = heapRel;
1105  state->indexRel = indexRel;
1106  state->enforceUnique = enforceUnique;
1107 
1108  indexScanKey = _bt_mkscankey(indexRel, NULL);
1109 
1110  /* Prepare SortSupport data for each column */
1111  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1112  sizeof(SortSupportData));
1113 
1114  for (i = 0; i < state->nKeys; i++)
1115  {
1116  SortSupport sortKey = state->sortKeys + i;
1117  ScanKey scanKey = indexScanKey->scankeys + i;
1118  int16 strategy;
1119 
1120  sortKey->ssup_cxt = CurrentMemoryContext;
1121  sortKey->ssup_collation = scanKey->sk_collation;
1122  sortKey->ssup_nulls_first =
1123  (scanKey->sk_flags & SK_BT_NULLS_FIRST) != 0;
1124  sortKey->ssup_attno = scanKey->sk_attno;
1125  /* Convey if abbreviation optimization is applicable in principle */
1126  sortKey->abbreviate = (i == 0);
1127 
1128  AssertState(sortKey->ssup_attno != 0);
1129 
1130  strategy = (scanKey->sk_flags & SK_BT_DESC) != 0 ?
1132 
1133  PrepareSortSupportFromIndexRel(indexRel, strategy, sortKey);
1134  }
1135 
1136  pfree(indexScanKey);
1137 
1138  MemoryContextSwitchTo(oldcontext);
1139 
1140  return state;
1141 }
struct SortSupportData * SortSupport
Definition: sortsupport.h:58
signed short int16
Definition: c.h:428
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:807
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:4388
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:4200
bool trace_sort
Definition: tuplesort.c:140
#define PARALLEL_SORT(state)
Definition: tuplesort.c:125
void pfree(void *pointer)
Definition: mcxt.c:1169
static void writetup_index(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:4395
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:4417
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:491
void PrepareSortSupportFromIndexRel(Relation indexRel, int16 strategy, SortSupport ssup)
Definition: sortsupport.c:162
#define SK_BT_NULLS_FIRST
Definition: nbtree.h:1083
void * palloc0(Size size)
Definition: mcxt.c:1093
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:1082
Definition: regguts.h:317
bool enforceUnique
Definition: tuplesort.c:462
ScanKeyData scankeys[INDEX_MAX_KEYS]
Definition: nbtree.h:791
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
Oid sk_collation
Definition: skey.h:70
#define elog(elevel,...)
Definition: elog.h:232
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 1190 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().

1195 {
1196  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1197  randomAccess);
1198  MemoryContext oldcontext;
1199  int i;
1200 
1201  oldcontext = MemoryContextSwitchTo(state->sortcontext);
1202 
1203 #ifdef TRACE_SORT
1204  if (trace_sort)
1205  elog(LOG,
1206  "begin index sort: workMem = %d, randomAccess = %c",
1207  workMem, randomAccess ? 't' : 'f');
1208 #endif
1209 
1210  state->nKeys = IndexRelationGetNumberOfKeyAttributes(indexRel);
1211 
1213  state->copytup = copytup_index;
1214  state->writetup = writetup_index;
1215  state->readtup = readtup_index;
1216 
1217  state->heapRel = heapRel;
1218  state->indexRel = indexRel;
1219 
1220  /* Prepare SortSupport data for each column */
1221  state->sortKeys = (SortSupport) palloc0(state->nKeys *
1222  sizeof(SortSupportData));
1223 
1224  for (i = 0; i < state->nKeys; i++)
1225  {
1226  SortSupport sortKey = state->sortKeys + i;
1227 
1228  sortKey->ssup_cxt = CurrentMemoryContext;
1229  sortKey->ssup_collation = indexRel->rd_indcollation[i];
1230  sortKey->ssup_nulls_first = false;
1231  sortKey->ssup_attno = i + 1;
1232  /* Convey if abbreviation optimization is applicable in principle */
1233  sortKey->abbreviate = (i == 0);
1234 
1235  AssertState(sortKey->ssup_attno != 0);
1236 
1237  /* Look for a sort support function */
1238  PrepareSortSupportFromGistIndexRel(indexRel, sortKey);
1239  }
1240 
1241  MemoryContextSwitchTo(oldcontext);
1242 
1243  return state;
1244 }
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:807
static void copytup_index(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4388
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:4200
bool trace_sort
Definition: tuplesort.c:140
Oid * rd_indcollation
Definition: rel.h:215
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:4395
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:4417
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
#define IndexRelationGetNumberOfKeyAttributes(relation)
Definition: rel.h:491
void * palloc0(Size size)
Definition: mcxt.c:1093
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:317
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
#define elog(elevel,...)
Definition: elog.h:232
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 1144 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().

1152 {
1153  Tuplesortstate *state = tuplesort_begin_common(workMem, coordinate,
1154  randomAccess);
1155  MemoryContext oldcontext;
1156 
1157  oldcontext = MemoryContextSwitchTo(state->maincontext);
1158 
1159 #ifdef TRACE_SORT
1160  if (trace_sort)
1161  elog(LOG,
1162  "begin index sort: high_mask = 0x%x, low_mask = 0x%x, "
1163  "max_buckets = 0x%x, workMem = %d, randomAccess = %c",
1164  high_mask,
1165  low_mask,
1166  max_buckets,
1167  workMem, randomAccess ? 't' : 'f');
1168 #endif
1169 
1170  state->nKeys = 1; /* Only one sort column, the hash code */
1171 
1173  state->copytup = copytup_index;
1174  state->writetup = writetup_index;
1175  state->readtup = readtup_index;
1176 
1177  state->heapRel = heapRel;
1178  state->indexRel = indexRel;
1179 
1180  state->high_mask = high_mask;
1181  state->low_mask = low_mask;
1182  state->max_buckets = max_buckets;
1183 
1184  MemoryContextSwitchTo(oldcontext);
1185 
1186  return state;
1187 }
static int comparetup_index_hash(const SortTuple *a, const SortTuple *b, Tuplesortstate *state)
Definition: tuplesort.c:4333
Relation heapRel
Definition: tuplesort.c:458
static void copytup_index(Tuplesortstate *state, SortTuple *stup, void *tup)
Definition: tuplesort.c:4388
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:4395
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:4417
Relation indexRel
Definition: tuplesort.c:459
void(* writetup)(Tuplesortstate *state, int tapenum, SortTuple *stup)
Definition: tuplesort.c:293
Definition: regguts.h:317
uint32 max_buckets
Definition: tuplesort.c:467
static Tuplesortstate * tuplesort_begin_common(int workMem, SortCoordinate coordinate, bool randomAccess)
Definition: tuplesort.c:721
#define elog(elevel,...)
Definition: elog.h:232
uint32 low_mask
Definition: tuplesort.c:466

◆ tuplesort_end()

void tuplesort_end ( Tuplesortstate state)

Definition at line 1464 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().

1465 {
1466  tuplesort_free(state);
1467 
1468  /*
1469  * Free the main memory context, including the Tuplesortstate struct
1470  * itself.
1471  */
1473 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
MemoryContext maincontext
Definition: tuplesort.c:260
static void tuplesort_free(Tuplesortstate *state)
Definition: tuplesort.c:1391

◆ tuplesort_estimate_shared()

Size tuplesort_estimate_shared ( int  nWorkers)

Definition at line 4557 of file tuplesort.c.

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

Referenced by _bt_begin_parallel().

4558 {
4559  Size tapesSize;
4560 
4561  Assert(nWorkers > 0);
4562 
4563  /* Make sure that BufFile shared state is MAXALIGN'd */
4564  tapesSize = mul_size(sizeof(TapeShare), nWorkers);
4565  tapesSize = MAXALIGN(add_size(tapesSize, offsetof(Sharedsort, tapes)));
4566 
4567  return tapesSize;
4568 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
#define Assert(condition)
Definition: c.h:804
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
#define offsetof(type, field)
Definition: c.h:727

◆ tuplesort_free()

static void tuplesort_free ( Tuplesortstate state)
static

Definition at line 1391 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().

1392 {
1393  /* context swap probably not needed, but let's be safe */
1394  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
1395 
1396 #ifdef TRACE_SORT
1397  long spaceUsed;
1398 
1399  if (state->tapeset)
1400  spaceUsed = LogicalTapeSetBlocks(state->tapeset);
1401  else
1402  spaceUsed = (state->allowedMem - state->availMem + 1023) / 1024;
1403 #endif
1404 
1405  /*
1406  * Delete temporary "tape" files, if any.
1407  *
1408  * Note: want to include this in reported total cost of sort, hence need
1409  * for two #ifdef TRACE_SORT sections.
1410  */
1411  if (state->tapeset)
1412  LogicalTapeSetClose(state->tapeset);
1413 
1414 #ifdef TRACE_SORT
1415  if (trace_sort)
1416  {
1417  if (state->tapeset)
1418  elog(LOG, "%s of worker %d ended, %ld disk blocks used: %s",
1419  SERIAL(state) ? "external sort" : "parallel external sort",
1420  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
1421  else
1422  elog(LOG, "%s of worker %d ended, %ld KB used: %s",
1423  SERIAL(state) ? "internal sort" : "unperformed parallel sort",
1424  state->worker, spaceUsed, pg_rusage_show(&state->ru_start));
1425  }
1426 
1427  TRACE_POSTGRESQL_SORT_DONE(state->tapeset != NULL, spaceUsed);
1428 #else
1429 
1430  /*
1431  * If you disabled TRACE_SORT, you can still probe sort__done, but you
1432  * ain't getting space-used stats.
1433  */
1434  TRACE_POSTGRESQL_SORT_DONE(state->tapeset != NULL, 0L);
1435 #endif
1436 
1437  /* Free any execution state created for CLUSTER case */
1438  if (state->estate != NULL)
1439  {
1440  ExprContext *econtext = GetPerTupleExprContext(state->estate);
1441 
1443  FreeExecutorState(state->estate);
1444  }
1445 
1446  MemoryContextSwitchTo(oldcontext);
1447 
1448  /*
1449  * Free the per-sort memory context, thereby releasing all working memory.
1450  */
1452 }
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:143
#define LOG
Definition: elog.h:26
bool trace_sort
Definition: tuplesort.c:140
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:532
MemoryContext sortcontext
Definition: tuplesort.c:262
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
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:226
#define elog(elevel,...)
Definition: elog.h:232
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 3378 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().

3380 {
3381  /*
3382  * Note: it might seem we should provide both memory and disk usage for a
3383  * disk-based sort. However, the current code doesn't track memory space
3384  * accurately once we have begun to return tuples to the caller (since we
3385  * don't account for pfree's the caller is expected to do), so we cannot
3386  * rely on availMem in a disk sort. This does not seem worth the overhead
3387  * to fix. Is it worth creating an API for the memory context code to
3388  * tell us how much is actually used in sortcontext?
3389  */
3390  tuplesort_updatemax(state);
3391 
3392  if (state->isMaxSpaceDisk)
3394  else
3396  stats->spaceUsed = (state->maxSpace + 1023) / 1024;
3397 
3398  switch (state->maxSpaceStatus)
3399  {
3400  case TSS_SORTEDINMEM:
3401  if (state->boundUsed)
3403  else
3405  break;
3406  case TSS_SORTEDONTAPE:
3408  break;
3409  case TSS_FINALMERGE:
3411  break;
3412  default:
3414  break;
3415  }
3416 }
bool isMaxSpaceDisk
Definition: tuplesort.c:256
int64 maxSpace
Definition: tuplesort.c:254
static void tuplesort_updatemax(Tuplesortstate *state)
Definition: tuplesort.c:1481
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 2494 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().

2496 {
2497  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2498  SortTuple stup;
2499 
2500  if (!tuplesort_gettuple_common(state, forward, &stup))
2501  {
2502  MemoryContextSwitchTo(oldcontext);
2503  return false;
2504  }
2505 
2506  /* Ensure we copy into caller's memory context */
2507  MemoryContextSwitchTo(oldcontext);
2508 
2509  /* Record abbreviated key for caller */
2510  if (state->sortKeys->abbrev_converter && abbrev)
2511  *abbrev = stup.datum1;
2512 
2513  if (stup.isnull1 || !state->tuples)
2514  {
2515  *val = stup.datum1;
2516  *isNull = stup.isnull1;
2517  }
2518  else
2519  {
2520  /* use stup.tuple because stup.datum1 may be an abbreviation */
2521  *val = datumCopy(PointerGetDatum(stup.tuple), false, state->datumTypeLen);
2522  *isNull = false;
2523  }
2524 
2525  return true;
2526 }
#define PointerGetDatum(X)
Definition: postgres.h:600
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:2151
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 2445 of file tuplesort.c.

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

Referenced by heapam_relation_copy_for_cluster().

2446 {
2447  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2448  SortTuple stup;
2449 
2450  if (!tuplesort_gettuple_common(state, forward, &stup))
2451  stup.tuple = NULL;
2452 
2453  MemoryContextSwitchTo(oldcontext);
2454 
2455  return stup.tuple;
2456 }
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:2151

◆ tuplesort_getindextuple()

IndexTuple tuplesort_getindextuple ( Tuplesortstate state,
bool  forward 
)

Definition at line 2465 of file tuplesort.c.

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

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

2466 {
2467  MemoryContext oldcontext = MemoryContextSwitchTo(state->sortcontext);
2468  SortTuple stup;
2469 
2470  if (!tuplesort_gettuple_common(state, forward, &stup))
2471  stup.tuple = NULL;
2472 
2473  MemoryContextSwitchTo(oldcontext);
2474 
2475  return (IndexTuple) stup.tuple;
2476 }
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:2151

◆ tuplesort_gettuple_common()

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

Definition at line 2151 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().

2153 {
2154  unsigned int tuplen;
2155  size_t nmoved;
2156 
2157  Assert(!WORKER(state));
2158 
2159  switch (state->status)
2160  {
2161  case TSS_SORTEDINMEM:
2162  Assert(forward || state->randomAccess);
2163  Assert(!state->slabAllocatorUsed);
2164  if (forward)
2165  {
2166  if (state->current < state->memtupcount)
2167  {
2168  *stup = state->memtuples[state->current++];
2169  return true;
2170  }
2171  state->eof_reached = true;
2172 
2173  /*
2174  * Complain if caller tries to retrieve more tuples than
2175  * originally asked for in a bounded sort. This is because
2176  * returning EOF here might be the wrong thing.
2177  */
2178  if (state->bounded && state->current >= state->bound)
2179  elog(ERROR, "retrieved too many tuples in a bounded sort");
2180 
2181  return false;
2182  }
2183  else
2184  {
2185  if (state->current <= 0)
2186  return false;
2187 
2188  /*
2189  * if all tuples are fetched already then we return last
2190  * tuple, else - tuple before last returned.
2191  */
2192  if (state->eof_reached)
2193