1 /*-------------------------------------------------------------------------
4 * Generalized tuple sorting routines.
6 * This module handles sorting of heap tuples, index tuples, or single
7 * Datums (and could easily support other kinds of sortable objects,
8 * if necessary). It works efficiently for both small and large amounts
9 * of data. Small amounts are sorted in-memory using qsort(). Large
10 * amounts are sorted using temporary files and a standard external sort
13 * See Knuth, volume 3, for more than you want to know about the external
14 * sorting algorithm. We divide the input into sorted runs using replacement
15 * selection, in the form of a priority tree implemented as a heap
16 * (essentially his Algorithm 5.2.3H), then merge the runs using polyphase
17 * merge, Knuth's Algorithm 5.4.2D. The logical "tapes" used by Algorithm D
18 * are implemented by logtape.c, which avoids space wastage by recycling
19 * disk space as soon as each block is read from its "tape".
21 * We do not form the initial runs using Knuth's recommended replacement
22 * selection data structure (Algorithm 5.4.1R), because it uses a fixed
23 * number of records in memory at all times. Since we are dealing with
24 * tuples that may vary considerably in size, we want to be able to vary
25 * the number of records kept in memory to ensure full utilization of the
26 * allowed sort memory space. So, we keep the tuples in a variable-size
27 * heap, with the next record to go out at the top of the heap. Like
28 * Algorithm 5.4.1R, each record is stored with the run number that it
29 * must go into, and we use (run number, key) as the ordering key for the
30 * heap. When the run number at the top of the heap changes, we know that
31 * no more records of the prior run are left in the heap.
33 * The approximate amount of memory allowed for any one sort operation
34 * is specified in kilobytes by the caller (most pass work_mem). Initially,
35 * we absorb tuples and simply store them in an unsorted array as long as
36 * we haven't exceeded workMem. If we reach the end of the input without
37 * exceeding workMem, we sort the array using qsort() and subsequently return
38 * tuples just by scanning the tuple array sequentially. If we do exceed
39 * workMem, we construct a heap using Algorithm H and begin to emit tuples
40 * into sorted runs in temporary tapes, emitting just enough tuples at each
41 * step to get back within the workMem limit. Whenever the run number at
42 * the top of the heap changes, we begin a new run with a new output tape
43 * (selected per Algorithm D). After the end of the input is reached,
44 * we dump out remaining tuples in memory into a final run (or two),
45 * then merge the runs using Algorithm D.
47 * When merging runs, we use a heap containing just the frontmost tuple from
48 * each source run; we repeatedly output the smallest tuple and insert the
49 * next tuple from its source tape (if any). When the heap empties, the merge
50 * is complete. The basic merge algorithm thus needs very little memory ---
51 * only M tuples for an M-way merge, and M is at most six in the present code.
52 * However, we can still make good use of our full workMem allocation by
53 * pre-reading additional tuples from each source tape. Without prereading,
54 * our access pattern to the temporary file would be very erratic; on average
55 * we'd read one block from each of M source tapes during the same time that
56 * we're writing M blocks to the output tape, so there is no sequentiality of
57 * access at all, defeating the read-ahead methods used by most Unix kernels.
58 * Worse, the output tape gets written into a very random sequence of blocks
59 * of the temp file, ensuring that things will be even worse when it comes
60 * time to read that tape. A straightforward merge pass thus ends up doing a
61 * lot of waiting for disk seeks. We can improve matters by prereading from
62 * each source tape sequentially, loading about workMem/M bytes from each tape
63 * in turn. Then we run the merge algorithm, writing but not reading until
64 * one of the preloaded tuple series runs out. Then we switch back to preread
65 * mode, fill memory again, and repeat. This approach helps to localize both
66 * read and write accesses.
68 * When the caller requests random access to the sort result, we form
69 * the final sorted run on a logical tape which is then "frozen", so
70 * that we can access it randomly. When the caller does not need random
71 * access, we return from tuplesort_performsort() as soon as we are down
72 * to one run per logical tape. The final merge is then performed
73 * on-the-fly as the caller repeatedly calls tuplesort_gettuple; this
74 * saves one cycle of writing all the data out to disk and reading it in.
77 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
78 * Portions Copyright (c) 1994, Regents of the University of California
81 * $PostgreSQL: pgsql/src/backend/utils/sort/tuplesort.c,v 1.51 2005/10/03 22:55:54 tgl Exp $
83 *-------------------------------------------------------------------------
88 #include "access/heapam.h"
89 #include "access/nbtree.h"
90 #include "catalog/pg_amop.h"
91 #include "catalog/pg_operator.h"
92 #include "miscadmin.h"
93 #include "utils/catcache.h"
94 #include "utils/datum.h"
95 #include "utils/logtape.h"
96 #include "utils/lsyscache.h"
97 #include "utils/memutils.h"
98 #include "utils/pg_rusage.h"
99 #include "utils/syscache.h"
100 #include "utils/tuplesort.h"
105 bool trace_sort = false;
110 * Possible states of a Tuplesort object. These denote the states that
111 * persist between calls of Tuplesort routines.
115 TSS_INITIAL, /* Loading tuples; still within memory
117 TSS_BUILDRUNS, /* Loading tuples; writing to tape */
118 TSS_SORTEDINMEM, /* Sort completed entirely in memory */
119 TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */
120 TSS_FINALMERGE /* Performing final merge on-the-fly */
124 * We use a seven-tape polyphase merge, which is the "sweet spot" on the
125 * tapes-to-passes curve according to Knuth's figure 70 (section 5.4.2).
127 #define MAXTAPES 7 /* Knuth's T */
128 #define TAPERANGE (MAXTAPES-1) /* Knuth's P */
131 * Private state of a Tuplesort operation.
133 struct Tuplesortstate
135 TupSortStatus status; /* enumerated value as shown above */
136 bool randomAccess; /* did caller request random access? */
137 long availMem; /* remaining memory available, in bytes */
138 LogicalTapeSet *tapeset; /* logtape.c object for tapes in a temp
142 * These function pointers decouple the routines that must know what
143 * kind of tuple we are sorting from the routines that don't need to
144 * know it. They are set up by the tuplesort_begin_xxx routines.
146 * Function to compare two tuples; result is per qsort() convention, ie:
148 * <0, 0, >0 according as a<b, a=b, a>b.
150 int (*comparetup) (Tuplesortstate *state, const void *a, const void *b);
153 * Function to copy a supplied input tuple into palloc'd space. (NB:
154 * we assume that a single pfree() is enough to release the tuple
155 * later, so the representation must be "flat" in one palloc chunk.)
156 * state->availMem must be decreased by the amount of space used.
158 void *(*copytup) (Tuplesortstate *state, void *tup);
161 * Function to write a stored tuple onto tape. The representation of
162 * the tuple on tape need not be the same as it is in memory;
163 * requirements on the tape representation are given below. After
164 * writing the tuple, pfree() it, and increase state->availMem by the
165 * amount of memory space thereby released.
167 void (*writetup) (Tuplesortstate *state, int tapenum, void *tup);
170 * Function to read a stored tuple from tape back into memory. 'len'
171 * is the already-read length of the stored tuple. Create and return
172 * a palloc'd copy, and decrease state->availMem by the amount of
173 * memory space consumed.
175 void *(*readtup) (Tuplesortstate *state, int tapenum, unsigned int len);
178 * This array holds pointers to tuples in sort memory. If we are in
179 * state INITIAL, the tuples are in no particular order; if we are in
180 * state SORTEDINMEM, the tuples are in final sorted order; in states
181 * BUILDRUNS and FINALMERGE, the tuples are organized in "heap" order
182 * per Algorithm H. (Note that memtupcount only counts the tuples
183 * that are part of the heap --- during merge passes, memtuples[]
184 * entries beyond TAPERANGE are never in the heap and are used to hold
185 * pre-read tuples.) In state SORTEDONTAPE, the array is not used.
187 void **memtuples; /* array of pointers to palloc'd tuples */
188 int memtupcount; /* number of tuples currently present */
189 int memtupsize; /* allocated length of memtuples array */
192 * While building initial runs, this array holds the run number for
193 * each tuple in memtuples[]. During merge passes, we re-use it to
194 * hold the input tape number that each tuple in the heap was read
195 * from, or to hold the index of the next tuple pre-read from the same
196 * tape in the case of pre-read entries. This array is never
197 * allocated unless we need to use tapes. Whenever it is allocated,
198 * it has the same length as memtuples[].
200 int *memtupindex; /* index value associated with
204 * While building initial runs, this is the current output run number
205 * (starting at 0). Afterwards, it is the number of initial runs we
211 * These variables are only used during merge passes. mergeactive[i]
212 * is true if we are reading an input run from (actual) tape number i
213 * and have not yet exhausted that run. mergenext[i] is the memtuples
214 * index of the next pre-read tuple (next to be loaded into the heap)
215 * for tape i, or 0 if we are out of pre-read tuples. mergelast[i]
216 * similarly points to the last pre-read tuple from each tape.
217 * mergeavailmem[i] is the amount of unused space allocated for tape
218 * i. mergefreelist and mergefirstfree keep track of unused locations
219 * in the memtuples[] array. memtupindex[] links together pre-read
220 * tuples for each tape as well as recycled locations in
221 * mergefreelist. It is OK to use 0 as a null link in these lists,
222 * because memtuples[0] is part of the merge heap and is never a
225 bool mergeactive[MAXTAPES]; /* Active input run source? */
226 int mergenext[MAXTAPES]; /* first preread tuple for each
228 int mergelast[MAXTAPES]; /* last preread tuple for each
230 long mergeavailmem[MAXTAPES]; /* availMem for prereading
232 long spacePerTape; /* actual per-tape target usage */
233 int mergefreelist; /* head of freelist of recycled slots */
234 int mergefirstfree; /* first slot never used in this merge */
237 * Variables for Algorithm D. Note that destTape is a "logical" tape
238 * number, ie, an index into the tp_xxx[] arrays. Be careful to keep
239 * "logical" and "actual" tape numbers straight!
241 int Level; /* Knuth's l */
242 int destTape; /* current output tape (Knuth's j, less 1) */
243 int tp_fib[MAXTAPES]; /* Target Fibonacci run counts
245 int tp_runs[MAXTAPES]; /* # of real runs on each tape */
246 int tp_dummy[MAXTAPES]; /* # of dummy runs for each tape
248 int tp_tapenum[MAXTAPES]; /* Actual tape numbers (TAPE[]) */
251 * These variables are used after completion of sorting to keep track
252 * of the next tuple to return. (In the tape case, the tape's current
253 * read position is also critical state.)
255 int result_tape; /* actual tape number of finished output */
256 int current; /* array index (only used if SORTEDINMEM) */
257 bool eof_reached; /* reached EOF (needed for cursors) */
259 /* markpos_xxx holds marked position for mark and restore */
260 long markpos_block; /* tape block# (only used if SORTEDONTAPE) */
261 int markpos_offset; /* saved "current", or offset in tape
263 bool markpos_eof; /* saved "eof_reached" */
266 * These variables are specific to the HeapTuple case; they are set by
267 * tuplesort_begin_heap and used only by the HeapTuple routines.
272 SortFunctionKind *sortFnKinds;
275 * These variables are specific to the IndexTuple case; they are set
276 * by tuplesort_begin_index and used only by the IndexTuple routines.
279 ScanKey indexScanKey;
280 bool enforceUnique; /* complain if we find duplicate tuples */
283 * These variables are specific to the Datum case; they are set by
284 * tuplesort_begin_datum and used only by the DatumTuple routines.
288 FmgrInfo sortOpFn; /* cached lookup data for sortOperator */
289 SortFunctionKind sortFnKind;
290 /* we need typelen and byval in order to know how to copy the Datums. */
295 * Resource snapshot for time of sort start.
302 #define COMPARETUP(state,a,b) ((*(state)->comparetup) (state, a, b))
303 #define COPYTUP(state,tup) ((*(state)->copytup) (state, tup))
304 #define WRITETUP(state,tape,tup) ((*(state)->writetup) (state, tape, tup))
305 #define READTUP(state,tape,len) ((*(state)->readtup) (state, tape, len))
306 #define LACKMEM(state) ((state)->availMem < 0)
307 #define USEMEM(state,amt) ((state)->availMem -= (amt))
308 #define FREEMEM(state,amt) ((state)->availMem += (amt))
310 /*--------------------
312 * NOTES about on-tape representation of tuples:
314 * We require the first "unsigned int" of a stored tuple to be the total size
315 * on-tape of the tuple, including itself (so it is never zero; an all-zero
316 * unsigned int is used to delimit runs). The remainder of the stored tuple
317 * may or may not match the in-memory representation of the tuple ---
318 * any conversion needed is the job of the writetup and readtup routines.
320 * If state->randomAccess is true, then the stored representation of the
321 * tuple must be followed by another "unsigned int" that is a copy of the
322 * length --- so the total tape space used is actually sizeof(unsigned int)
323 * more than the stored length value. This allows read-backwards. When
324 * randomAccess is not true, the write/read routines may omit the extra
327 * writetup is expected to write both length words as well as the tuple
328 * data. When readtup is called, the tape is positioned just after the
329 * front length word; readtup must read the tuple data and advance past
330 * the back length word (if present).
332 * The write/read routines can make use of the tuple description data
333 * stored in the Tuplesortstate record, if needed. They are also expected
334 * to adjust state->availMem by the amount of memory space (not tape space!)
335 * released or consumed. There is no error return from either writetup
336 * or readtup; they should ereport() on failure.
339 * NOTES about memory consumption calculations:
341 * We count space allocated for tuples against the workMem limit, plus
342 * the space used by the variable-size arrays memtuples and memtupindex.
343 * Fixed-size space (primarily the LogicalTapeSet I/O buffers) is not
346 * Note that we count actual space used (as shown by GetMemoryChunkSpace)
347 * rather than the originally-requested size. This is important since
348 * palloc can add substantial overhead. It's not a complete answer since
349 * we won't count any wasted space in palloc allocation blocks, but it's
350 * a lot better than what we were doing before 7.3.
352 *--------------------
356 * For sorting single Datums, we build "pseudo tuples" that just carry
357 * the datum's value and null flag. For pass-by-reference data types,
358 * the actual data value appears after the DatumTupleHeader (MAXALIGNed,
359 * of course), and the value field in the header is just a pointer to it.
369 static Tuplesortstate *tuplesort_begin_common(int workMem, bool randomAccess);
370 static void puttuple_common(Tuplesortstate *state, void *tuple);
371 static void inittapes(Tuplesortstate *state);
372 static void selectnewtape(Tuplesortstate *state);
373 static void mergeruns(Tuplesortstate *state);
374 static void mergeonerun(Tuplesortstate *state);
375 static void beginmerge(Tuplesortstate *state);
376 static void mergepreread(Tuplesortstate *state);
377 static void dumptuples(Tuplesortstate *state, bool alltuples);
378 static void tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
379 int tupleindex, bool checkIndex);
380 static void tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex);
381 static unsigned int getlen(Tuplesortstate *state, int tapenum, bool eofOK);
382 static void markrunend(Tuplesortstate *state, int tapenum);
383 static int qsort_comparetup(const void *a, const void *b);
384 static int comparetup_heap(Tuplesortstate *state,
385 const void *a, const void *b);
386 static void *copytup_heap(Tuplesortstate *state, void *tup);
387 static void writetup_heap(Tuplesortstate *state, int tapenum, void *tup);
388 static void *readtup_heap(Tuplesortstate *state, int tapenum,
390 static int comparetup_index(Tuplesortstate *state,
391 const void *a, const void *b);
392 static void *copytup_index(Tuplesortstate *state, void *tup);
393 static void writetup_index(Tuplesortstate *state, int tapenum, void *tup);
394 static void *readtup_index(Tuplesortstate *state, int tapenum,
396 static int comparetup_datum(Tuplesortstate *state,
397 const void *a, const void *b);
398 static void *copytup_datum(Tuplesortstate *state, void *tup);
399 static void writetup_datum(Tuplesortstate *state, int tapenum, void *tup);
400 static void *readtup_datum(Tuplesortstate *state, int tapenum,
404 * Since qsort(3) will not pass any context info to qsort_comparetup(),
405 * we have to use this ugly static variable. It is set to point to the
406 * active Tuplesortstate object just before calling qsort. It should
407 * not be used directly by anything except qsort_comparetup().
409 static Tuplesortstate *qsort_tuplesortstate;
413 * tuplesort_begin_xxx
415 * Initialize for a tuple sort operation.
417 * After calling tuplesort_begin, the caller should call tuplesort_puttuple
418 * zero or more times, then call tuplesort_performsort when all the tuples
419 * have been supplied. After performsort, retrieve the tuples in sorted
420 * order by calling tuplesort_gettuple until it returns NULL. (If random
421 * access was requested, rescan, markpos, and restorepos can also be called.)
422 * For Datum sorts, putdatum/getdatum are used instead of puttuple/gettuple.
423 * Call tuplesort_end to terminate the operation and release memory/disk space.
425 * Each variant of tuplesort_begin has a workMem parameter specifying the
426 * maximum number of kilobytes of RAM to use before spilling data to disk.
427 * (The normal value of this parameter is work_mem, but some callers use
428 * other values.) Each variant also has a randomAccess parameter specifying
429 * whether the caller needs non-sequential access to the sort result.
432 static Tuplesortstate *
433 tuplesort_begin_common(int workMem, bool randomAccess)
435 Tuplesortstate *state;
437 state = (Tuplesortstate *) palloc0(sizeof(Tuplesortstate));
441 pg_rusage_init(&state->ru_start);
444 state->status = TSS_INITIAL;
445 state->randomAccess = randomAccess;
446 state->availMem = workMem * 1024L;
447 state->tapeset = NULL;
449 state->memtupcount = 0;
450 state->memtupsize = 1024; /* initial guess */
451 state->memtuples = (void **) palloc(state->memtupsize * sizeof(void *));
453 state->memtupindex = NULL; /* until and unless needed */
455 USEMEM(state, GetMemoryChunkSpace(state->memtuples));
457 state->currentRun = 0;
459 /* Algorithm D variables will be initialized by inittapes, if needed */
461 state->result_tape = -1; /* flag that result tape has not been
468 tuplesort_begin_heap(TupleDesc tupDesc,
470 Oid *sortOperators, AttrNumber *attNums,
471 int workMem, bool randomAccess)
473 Tuplesortstate *state = tuplesort_begin_common(workMem, randomAccess);
476 AssertArg(nkeys > 0);
481 "begin tuple sort: nkeys = %d, workMem = %d, randomAccess = %c",
482 nkeys, workMem, randomAccess ? 't' : 'f');
485 state->comparetup = comparetup_heap;
486 state->copytup = copytup_heap;
487 state->writetup = writetup_heap;
488 state->readtup = readtup_heap;
490 state->tupDesc = tupDesc;
491 state->nKeys = nkeys;
492 state->scanKeys = (ScanKey) palloc0(nkeys * sizeof(ScanKeyData));
493 state->sortFnKinds = (SortFunctionKind *)
494 palloc0(nkeys * sizeof(SortFunctionKind));
496 for (i = 0; i < nkeys; i++)
498 RegProcedure sortFunction;
500 AssertArg(sortOperators[i] != 0);
501 AssertArg(attNums[i] != 0);
503 /* select a function that implements the sort operator */
504 SelectSortFunction(sortOperators[i], &sortFunction,
505 &state->sortFnKinds[i]);
508 * We needn't fill in sk_strategy or sk_subtype since these
509 * scankeys will never be passed to an index.
511 ScanKeyInit(&state->scanKeys[i],
522 tuplesort_begin_index(Relation indexRel,
524 int workMem, bool randomAccess)
526 Tuplesortstate *state = tuplesort_begin_common(workMem, randomAccess);
531 "begin index sort: unique = %c, workMem = %d, randomAccess = %c",
532 enforceUnique ? 't' : 'f',
533 workMem, randomAccess ? 't' : 'f');
536 state->comparetup = comparetup_index;
537 state->copytup = copytup_index;
538 state->writetup = writetup_index;
539 state->readtup = readtup_index;
541 state->indexRel = indexRel;
542 /* see comments below about btree dependence of this code... */
543 state->indexScanKey = _bt_mkscankey_nodata(indexRel);
544 state->enforceUnique = enforceUnique;
550 tuplesort_begin_datum(Oid datumType,
552 int workMem, bool randomAccess)
554 Tuplesortstate *state = tuplesort_begin_common(workMem, randomAccess);
555 RegProcedure sortFunction;
562 "begin datum sort: workMem = %d, randomAccess = %c",
563 workMem, randomAccess ? 't' : 'f');
566 state->comparetup = comparetup_datum;
567 state->copytup = copytup_datum;
568 state->writetup = writetup_datum;
569 state->readtup = readtup_datum;
571 state->datumType = datumType;
572 state->sortOperator = sortOperator;
574 /* select a function that implements the sort operator */
575 SelectSortFunction(sortOperator, &sortFunction, &state->sortFnKind);
576 /* and look up the function */
577 fmgr_info(sortFunction, &state->sortOpFn);
579 /* lookup necessary attributes of the datum type */
580 get_typlenbyval(datumType, &typlen, &typbyval);
581 state->datumTypeLen = typlen;
582 state->datumTypeByVal = typbyval;
590 * Release resources and clean up.
593 tuplesort_end(Tuplesortstate *state)
598 LogicalTapeSetClose(state->tapeset);
599 if (state->memtuples)
601 for (i = 0; i < state->memtupcount; i++)
602 pfree(state->memtuples[i]);
603 pfree(state->memtuples);
605 if (state->memtupindex)
606 pfree(state->memtupindex);
609 * this stuff might better belong in a variant-specific shutdown
613 pfree(state->scanKeys);
614 if (state->sortFnKinds)
615 pfree(state->sortFnKinds);
619 elog(NOTICE, "sort ended: %s",
620 pg_rusage_show(&state->ru_start));
627 * Accept one tuple while collecting input data for sort.
629 * Note that the input tuple is always copied; the caller need not save it.
632 tuplesort_puttuple(Tuplesortstate *state, void *tuple)
635 * Copy the given tuple into memory we control, and decrease availMem.
636 * Then call the code shared with the Datum case.
638 tuple = COPYTUP(state, tuple);
640 puttuple_common(state, tuple);
644 * Accept one Datum while collecting input data for sort.
646 * If the Datum is pass-by-ref type, the value will be copied.
649 tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
654 * Build pseudo-tuple carrying the datum, and decrease availMem.
656 if (isNull || state->datumTypeByVal)
658 tuple = (DatumTuple *) palloc(sizeof(DatumTuple));
660 tuple->isNull = isNull;
668 datalen = datumGetSize(val, false, state->datumTypeLen);
669 tuplelen = datalen + MAXALIGN(sizeof(DatumTuple));
670 tuple = (DatumTuple *) palloc(tuplelen);
671 newVal = ((char *) tuple) + MAXALIGN(sizeof(DatumTuple));
672 memcpy(newVal, DatumGetPointer(val), datalen);
673 tuple->val = PointerGetDatum(newVal);
674 tuple->isNull = false;
677 USEMEM(state, GetMemoryChunkSpace(tuple));
679 puttuple_common(state, (void *) tuple);
683 * Shared code for tuple and datum cases.
686 puttuple_common(Tuplesortstate *state, void *tuple)
688 switch (state->status)
693 * Save the copied tuple into the unsorted array.
695 if (state->memtupcount >= state->memtupsize)
697 /* Grow the unsorted array as needed. */
698 FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
699 state->memtupsize *= 2;
700 state->memtuples = (void **)
701 repalloc(state->memtuples,
702 state->memtupsize * sizeof(void *));
703 USEMEM(state, GetMemoryChunkSpace(state->memtuples));
705 state->memtuples[state->memtupcount++] = tuple;
708 * Done if we still fit in available memory.
714 * Nope; time to switch to tape-based operation.
719 * Dump tuples until we are back under the limit.
721 dumptuples(state, false);
726 * Insert the copied tuple into the heap, with run number
727 * currentRun if it can go into the current run, else run
728 * number currentRun+1. The tuple can go into the current run
729 * if it is >= the first not-yet-output tuple. (Actually, it
730 * could go into the current run if it is >= the most recently
731 * output tuple ... but that would require keeping around the
732 * tuple we last output, and it's simplest to let writetup
733 * free each tuple as soon as it's written.)
735 * Note there will always be at least one tuple in the heap at
736 * this point; see dumptuples.
738 Assert(state->memtupcount > 0);
739 if (COMPARETUP(state, tuple, state->memtuples[0]) >= 0)
740 tuplesort_heap_insert(state, tuple, state->currentRun, true);
742 tuplesort_heap_insert(state, tuple, state->currentRun + 1, true);
745 * If we are over the memory limit, dump tuples till we're
748 dumptuples(state, false);
751 elog(ERROR, "invalid tuplesort state");
757 * All tuples have been provided; finish the sort.
760 tuplesort_performsort(Tuplesortstate *state)
764 elog(NOTICE, "performsort starting: %s",
765 pg_rusage_show(&state->ru_start));
768 switch (state->status)
773 * We were able to accumulate all the tuples within the
774 * allowed amount of memory. Just qsort 'em and we're done.
776 if (state->memtupcount > 1)
778 qsort_tuplesortstate = state;
779 qsort((void *) state->memtuples, state->memtupcount,
780 sizeof(void *), qsort_comparetup);
783 state->eof_reached = false;
784 state->markpos_offset = 0;
785 state->markpos_eof = false;
786 state->status = TSS_SORTEDINMEM;
791 * Finish tape-based sort. First, flush all tuples remaining
792 * in memory out to tape; then merge until we have a single
793 * remaining run (or, if !randomAccess, one run per tape).
794 * Note that mergeruns sets the correct state->status.
796 dumptuples(state, true);
798 state->eof_reached = false;
799 state->markpos_block = 0L;
800 state->markpos_offset = 0;
801 state->markpos_eof = false;
804 elog(ERROR, "invalid tuplesort state");
810 elog(NOTICE, "performsort done%s: %s",
811 (state->status == TSS_FINALMERGE) ? " (except final merge)" : "",
812 pg_rusage_show(&state->ru_start));
817 * Fetch the next tuple in either forward or back direction.
818 * Returns NULL if no more tuples. If should_free is set, the
819 * caller must pfree the returned tuple when done with it.
822 tuplesort_gettuple(Tuplesortstate *state, bool forward,
828 switch (state->status)
830 case TSS_SORTEDINMEM:
831 Assert(forward || state->randomAccess);
832 *should_free = false;
835 if (state->current < state->memtupcount)
836 return state->memtuples[state->current++];
837 state->eof_reached = true;
842 if (state->current <= 0)
846 * if all tuples are fetched already then we return last
847 * tuple, else - tuple before last returned.
849 if (state->eof_reached)
850 state->eof_reached = false;
853 state->current--; /* last returned tuple */
854 if (state->current <= 0)
857 return state->memtuples[state->current - 1];
861 case TSS_SORTEDONTAPE:
862 Assert(forward || state->randomAccess);
866 if (state->eof_reached)
868 if ((tuplen = getlen(state, state->result_tape, true)) != 0)
870 tup = READTUP(state, state->result_tape, tuplen);
875 state->eof_reached = true;
883 * if all tuples are fetched already then we return last tuple,
884 * else - tuple before last returned.
886 if (state->eof_reached)
889 * Seek position is pointing just past the zero tuplen at
890 * the end of file; back up to fetch last tuple's ending
891 * length word. If seek fails we must have a completely
894 if (!LogicalTapeBackspace(state->tapeset,
896 2 * sizeof(unsigned int)))
898 state->eof_reached = false;
903 * Back up and fetch previously-returned tuple's ending
904 * length word. If seek fails, assume we are at start of
907 if (!LogicalTapeBackspace(state->tapeset,
909 sizeof(unsigned int)))
911 tuplen = getlen(state, state->result_tape, false);
914 * Back up to get ending length word of tuple before it.
916 if (!LogicalTapeBackspace(state->tapeset,
918 tuplen + 2 * sizeof(unsigned int)))
921 * If that fails, presumably the prev tuple is the
922 * first in the file. Back up so that it becomes next
923 * to read in forward direction (not obviously right,
924 * but that is what in-memory case does).
926 if (!LogicalTapeBackspace(state->tapeset,
928 tuplen + sizeof(unsigned int)))
929 elog(ERROR, "bogus tuple length in backward scan");
934 tuplen = getlen(state, state->result_tape, false);
937 * Now we have the length of the prior tuple, back up and read
938 * it. Note: READTUP expects we are positioned after the
939 * initial length word of the tuple, so back up to that point.
941 if (!LogicalTapeBackspace(state->tapeset,
944 elog(ERROR, "bogus tuple length in backward scan");
945 tup = READTUP(state, state->result_tape, tuplen);
953 * This code should match the inner loop of mergeonerun().
955 if (state->memtupcount > 0)
957 int srcTape = state->memtupindex[0];
962 tup = state->memtuples[0];
963 /* returned tuple is no longer counted in our memory space */
964 tuplen = GetMemoryChunkSpace(tup);
965 state->availMem += tuplen;
966 state->mergeavailmem[srcTape] += tuplen;
967 tuplesort_heap_siftup(state, false);
968 if ((tupIndex = state->mergenext[srcTape]) == 0)
971 * out of preloaded data on this tape, try to read
977 * if still no data, we've reached end of run on this
980 if ((tupIndex = state->mergenext[srcTape]) == 0)
983 /* pull next preread tuple from list, insert in heap */
984 newtup = state->memtuples[tupIndex];
985 state->mergenext[srcTape] = state->memtupindex[tupIndex];
986 if (state->mergenext[srcTape] == 0)
987 state->mergelast[srcTape] = 0;
988 state->memtupindex[tupIndex] = state->mergefreelist;
989 state->mergefreelist = tupIndex;
990 tuplesort_heap_insert(state, newtup, srcTape, false);
996 elog(ERROR, "invalid tuplesort state");
997 return NULL; /* keep compiler quiet */
1002 * Fetch the next Datum in either forward or back direction.
1003 * Returns FALSE if no more datums.
1005 * If the Datum is pass-by-ref type, the returned value is freshly palloc'd
1006 * and is now owned by the caller.
1009 tuplesort_getdatum(Tuplesortstate *state, bool forward,
1010 Datum *val, bool *isNull)
1015 tuple = (DatumTuple *) tuplesort_gettuple(state, forward, &should_free);
1020 if (tuple->isNull || state->datumTypeByVal)
1023 *isNull = tuple->isNull;
1027 *val = datumCopy(tuple->val, false, state->datumTypeLen);
1039 * inittapes - initialize for tape sorting.
1041 * This is called only if we have found we don't have room to sort in memory.
1044 inittapes(Tuplesortstate *state)
1051 elog(NOTICE, "switching to external sort: %s",
1052 pg_rusage_show(&state->ru_start));
1055 state->tapeset = LogicalTapeSetCreate(MAXTAPES);
1058 * Allocate the memtupindex array, same size as memtuples.
1060 state->memtupindex = (int *) palloc(state->memtupsize * sizeof(int));
1062 USEMEM(state, GetMemoryChunkSpace(state->memtupindex));
1065 * Convert the unsorted contents of memtuples[] into a heap. Each
1066 * tuple is marked as belonging to run number zero.
1068 * NOTE: we pass false for checkIndex since there's no point in comparing
1069 * indexes in this step, even though we do intend the indexes to be
1070 * part of the sort key...
1072 ntuples = state->memtupcount;
1073 state->memtupcount = 0; /* make the heap empty */
1074 for (j = 0; j < ntuples; j++)
1075 tuplesort_heap_insert(state, state->memtuples[j], 0, false);
1076 Assert(state->memtupcount == ntuples);
1078 state->currentRun = 0;
1081 * Initialize variables of Algorithm D (step D1).
1083 for (j = 0; j < MAXTAPES; j++)
1085 state->tp_fib[j] = 1;
1086 state->tp_runs[j] = 0;
1087 state->tp_dummy[j] = 1;
1088 state->tp_tapenum[j] = j;
1090 state->tp_fib[TAPERANGE] = 0;
1091 state->tp_dummy[TAPERANGE] = 0;
1094 state->destTape = 0;
1096 state->status = TSS_BUILDRUNS;
1100 * selectnewtape -- select new tape for new initial run.
1102 * This is called after finishing a run when we know another run
1103 * must be started. This implements steps D3, D4 of Algorithm D.
1106 selectnewtape(Tuplesortstate *state)
1111 /* Step D3: advance j (destTape) */
1112 if (state->tp_dummy[state->destTape] < state->tp_dummy[state->destTape + 1])
1117 if (state->tp_dummy[state->destTape] != 0)
1119 state->destTape = 0;
1123 /* Step D4: increase level */
1125 a = state->tp_fib[0];
1126 for (j = 0; j < TAPERANGE; j++)
1128 state->tp_dummy[j] = a + state->tp_fib[j + 1] - state->tp_fib[j];
1129 state->tp_fib[j] = a + state->tp_fib[j + 1];
1131 state->destTape = 0;
1135 * mergeruns -- merge all the completed initial runs.
1137 * This implements steps D5, D6 of Algorithm D. All input data has
1138 * already been written to initial runs on tape (see dumptuples).
1141 mergeruns(Tuplesortstate *state)
1148 Assert(state->status == TSS_BUILDRUNS);
1149 Assert(state->memtupcount == 0);
1152 * If we produced only one initial run (quite likely if the total data
1153 * volume is between 1X and 2X workMem), we can just use that tape as
1154 * the finished output, rather than doing a useless merge.
1156 if (state->currentRun == 1)
1158 state->result_tape = state->tp_tapenum[state->destTape];
1159 /* must freeze and rewind the finished output tape */
1160 LogicalTapeFreeze(state->tapeset, state->result_tape);
1161 state->status = TSS_SORTEDONTAPE;
1165 /* End of step D2: rewind all output tapes to prepare for merging */
1166 for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
1167 LogicalTapeRewind(state->tapeset, tapenum, false);
1171 /* Step D5: merge runs onto tape[T] until tape[P] is empty */
1172 while (state->tp_runs[TAPERANGE - 1] || state->tp_dummy[TAPERANGE - 1])
1174 bool allDummy = true;
1175 bool allOneRun = true;
1177 for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
1179 if (state->tp_dummy[tapenum] == 0)
1181 if (state->tp_runs[tapenum] + state->tp_dummy[tapenum] != 1)
1186 * If we don't have to produce a materialized sorted tape,
1187 * quit as soon as we're down to one real/dummy run per tape.
1189 if (!state->randomAccess && allOneRun)
1192 /* Initialize for the final merge pass */
1194 state->status = TSS_FINALMERGE;
1199 state->tp_dummy[TAPERANGE]++;
1200 for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
1201 state->tp_dummy[tapenum]--;
1206 /* Step D6: decrease level */
1207 if (--state->Level == 0)
1209 /* rewind output tape T to use as new input */
1210 LogicalTapeRewind(state->tapeset, state->tp_tapenum[TAPERANGE],
1212 /* rewind used-up input tape P, and prepare it for write pass */
1213 LogicalTapeRewind(state->tapeset, state->tp_tapenum[TAPERANGE - 1],
1215 state->tp_runs[TAPERANGE - 1] = 0;
1218 * reassign tape units per step D6; note we no longer care about
1221 svTape = state->tp_tapenum[TAPERANGE];
1222 svDummy = state->tp_dummy[TAPERANGE];
1223 svRuns = state->tp_runs[TAPERANGE];
1224 for (tapenum = TAPERANGE; tapenum > 0; tapenum--)
1226 state->tp_tapenum[tapenum] = state->tp_tapenum[tapenum - 1];
1227 state->tp_dummy[tapenum] = state->tp_dummy[tapenum - 1];
1228 state->tp_runs[tapenum] = state->tp_runs[tapenum - 1];
1230 state->tp_tapenum[0] = svTape;
1231 state->tp_dummy[0] = svDummy;
1232 state->tp_runs[0] = svRuns;
1236 * Done. Knuth says that the result is on TAPE[1], but since we
1237 * exited the loop without performing the last iteration of step D6,
1238 * we have not rearranged the tape unit assignment, and therefore the
1239 * result is on TAPE[T]. We need to do it this way so that we can
1240 * freeze the final output tape while rewinding it. The last
1241 * iteration of step D6 would be a waste of cycles anyway...
1243 state->result_tape = state->tp_tapenum[TAPERANGE];
1244 LogicalTapeFreeze(state->tapeset, state->result_tape);
1245 state->status = TSS_SORTEDONTAPE;
1249 * Merge one run from each input tape, except ones with dummy runs.
1251 * This is the inner loop of Algorithm D step D5. We know that the
1252 * output tape is TAPE[T].
1255 mergeonerun(Tuplesortstate *state)
1257 int destTape = state->tp_tapenum[TAPERANGE];
1265 * Start the merge by loading one tuple from each active source tape
1266 * into the heap. We can also decrease the input run/dummy run
1272 * Execute merge by repeatedly extracting lowest tuple in heap,
1273 * writing it out, and replacing it with next tuple from same tape (if
1274 * there is another one).
1276 while (state->memtupcount > 0)
1278 CHECK_FOR_INTERRUPTS();
1279 /* write the tuple to destTape */
1280 priorAvail = state->availMem;
1281 srcTape = state->memtupindex[0];
1282 WRITETUP(state, destTape, state->memtuples[0]);
1283 /* writetup adjusted total free space, now fix per-tape space */
1284 spaceFreed = state->availMem - priorAvail;
1285 state->mergeavailmem[srcTape] += spaceFreed;
1286 /* compact the heap */
1287 tuplesort_heap_siftup(state, false);
1288 if ((tupIndex = state->mergenext[srcTape]) == 0)
1290 /* out of preloaded data on this tape, try to read more */
1291 mergepreread(state);
1292 /* if still no data, we've reached end of run on this tape */
1293 if ((tupIndex = state->mergenext[srcTape]) == 0)
1296 /* pull next preread tuple from list, insert in heap */
1297 tup = state->memtuples[tupIndex];
1298 state->mergenext[srcTape] = state->memtupindex[tupIndex];
1299 if (state->mergenext[srcTape] == 0)
1300 state->mergelast[srcTape] = 0;
1301 state->memtupindex[tupIndex] = state->mergefreelist;
1302 state->mergefreelist = tupIndex;
1303 tuplesort_heap_insert(state, tup, srcTape, false);
1307 * When the heap empties, we're done. Write an end-of-run marker on
1308 * the output tape, and increment its count of real runs.
1310 markrunend(state, destTape);
1311 state->tp_runs[TAPERANGE]++;
1315 elog(NOTICE, "finished merge step: %s",
1316 pg_rusage_show(&state->ru_start));
1321 * beginmerge - initialize for a merge pass
1323 * We decrease the counts of real and dummy runs for each tape, and mark
1324 * which tapes contain active input runs in mergeactive[]. Then, load
1325 * as many tuples as we can from each active input tape, and finally
1326 * fill the merge heap with the first tuple from each active tape.
1329 beginmerge(Tuplesortstate *state)
1335 /* Heap should be empty here */
1336 Assert(state->memtupcount == 0);
1338 /* Clear merge-pass state variables */
1339 memset(state->mergeactive, 0, sizeof(state->mergeactive));
1340 memset(state->mergenext, 0, sizeof(state->mergenext));
1341 memset(state->mergelast, 0, sizeof(state->mergelast));
1342 memset(state->mergeavailmem, 0, sizeof(state->mergeavailmem));
1343 state->mergefreelist = 0; /* nothing in the freelist */
1344 state->mergefirstfree = MAXTAPES; /* first slot available for
1347 /* Adjust run counts and mark the active tapes */
1349 for (tapenum = 0; tapenum < TAPERANGE; tapenum++)
1351 if (state->tp_dummy[tapenum] > 0)
1352 state->tp_dummy[tapenum]--;
1355 Assert(state->tp_runs[tapenum] > 0);
1356 state->tp_runs[tapenum]--;
1357 srcTape = state->tp_tapenum[tapenum];
1358 state->mergeactive[srcTape] = true;
1364 * Initialize space allocation to let each active input tape have an
1365 * equal share of preread space.
1367 Assert(activeTapes > 0);
1368 state->spacePerTape = state->availMem / activeTapes;
1369 for (srcTape = 0; srcTape < MAXTAPES; srcTape++)
1371 if (state->mergeactive[srcTape])
1372 state->mergeavailmem[srcTape] = state->spacePerTape;
1376 * Preread as many tuples as possible (and at least one) from each
1379 mergepreread(state);
1381 /* Load the merge heap with the first tuple from each input tape */
1382 for (srcTape = 0; srcTape < MAXTAPES; srcTape++)
1384 int tupIndex = state->mergenext[srcTape];
1389 tup = state->memtuples[tupIndex];
1390 state->mergenext[srcTape] = state->memtupindex[tupIndex];
1391 if (state->mergenext[srcTape] == 0)
1392 state->mergelast[srcTape] = 0;
1393 state->memtupindex[tupIndex] = state->mergefreelist;
1394 state->mergefreelist = tupIndex;
1395 tuplesort_heap_insert(state, tup, srcTape, false);
1401 * mergepreread - load tuples from merge input tapes
1403 * This routine exists to improve sequentiality of reads during a merge pass,
1404 * as explained in the header comments of this file. Load tuples from each
1405 * active source tape until the tape's run is exhausted or it has used up
1406 * its fair share of available memory. In any case, we guarantee that there
1407 * is at least one preread tuple available from each unexhausted input tape.
1410 mergepreread(Tuplesortstate *state)
1413 unsigned int tuplen;
1419 for (srcTape = 0; srcTape < MAXTAPES; srcTape++)
1421 if (!state->mergeactive[srcTape])
1425 * Skip reading from any tape that still has at least half of its
1426 * target memory filled with tuples (threshold fraction may need
1427 * adjustment?). This avoids reading just a few tuples when the
1428 * incoming runs are not being consumed evenly.
1430 if (state->mergenext[srcTape] != 0 &&
1431 state->mergeavailmem[srcTape] <= state->spacePerTape / 2)
1435 * Read tuples from this tape until it has used up its free
1436 * memory, but ensure that we have at least one.
1438 priorAvail = state->availMem;
1439 state->availMem = state->mergeavailmem[srcTape];
1440 while (!LACKMEM(state) || state->mergenext[srcTape] == 0)
1442 /* read next tuple, if any */
1443 if ((tuplen = getlen(state, srcTape, true)) == 0)
1445 state->mergeactive[srcTape] = false;
1448 tup = READTUP(state, srcTape, tuplen);
1449 /* find or make a free slot in memtuples[] for it */
1450 tupIndex = state->mergefreelist;
1452 state->mergefreelist = state->memtupindex[tupIndex];
1455 tupIndex = state->mergefirstfree++;
1456 /* Might need to enlarge arrays! */
1457 if (tupIndex >= state->memtupsize)
1459 FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
1460 FREEMEM(state, GetMemoryChunkSpace(state->memtupindex));
1461 state->memtupsize *= 2;
1462 state->memtuples = (void **)
1463 repalloc(state->memtuples,
1464 state->memtupsize * sizeof(void *));
1465 state->memtupindex = (int *)
1466 repalloc(state->memtupindex,
1467 state->memtupsize * sizeof(int));
1468 USEMEM(state, GetMemoryChunkSpace(state->memtuples));
1469 USEMEM(state, GetMemoryChunkSpace(state->memtupindex));
1472 /* store tuple, append to list for its tape */
1473 state->memtuples[tupIndex] = tup;
1474 state->memtupindex[tupIndex] = 0;
1475 if (state->mergelast[srcTape])
1476 state->memtupindex[state->mergelast[srcTape]] = tupIndex;
1478 state->mergenext[srcTape] = tupIndex;
1479 state->mergelast[srcTape] = tupIndex;
1481 /* update per-tape and global availmem counts */
1482 spaceUsed = state->mergeavailmem[srcTape] - state->availMem;
1483 state->mergeavailmem[srcTape] = state->availMem;
1484 state->availMem = priorAvail - spaceUsed;
1489 * dumptuples - remove tuples from heap and write to tape
1491 * This is used during initial-run building, but not during merging.
1493 * When alltuples = false, dump only enough tuples to get under the
1494 * availMem limit (and leave at least one tuple in the heap in any case,
1495 * since puttuple assumes it always has a tuple to compare to).
1497 * When alltuples = true, dump everything currently in memory.
1498 * (This case is only used at end of input data.)
1500 * If we empty the heap, close out the current run and return (this should
1501 * only happen at end of input data). If we see that the tuple run number
1502 * at the top of the heap has changed, start a new run.
1505 dumptuples(Tuplesortstate *state, bool alltuples)
1508 (LACKMEM(state) && state->memtupcount > 1))
1511 * Dump the heap's frontmost entry, and sift up to remove it from
1514 Assert(state->memtupcount > 0);
1515 WRITETUP(state, state->tp_tapenum[state->destTape],
1516 state->memtuples[0]);
1517 tuplesort_heap_siftup(state, true);
1520 * If the heap is empty *or* top run number has changed, we've
1521 * finished the current run.
1523 if (state->memtupcount == 0 ||
1524 state->currentRun != state->memtupindex[0])
1526 markrunend(state, state->tp_tapenum[state->destTape]);
1527 state->currentRun++;
1528 state->tp_runs[state->destTape]++;
1529 state->tp_dummy[state->destTape]--; /* per Alg D step D2 */
1533 elog(NOTICE, "finished writing%s run %d: %s",
1534 (state->memtupcount == 0) ? " final" : "",
1536 pg_rusage_show(&state->ru_start));
1540 * Done if heap is empty, else prepare for new run.
1542 if (state->memtupcount == 0)
1544 Assert(state->currentRun == state->memtupindex[0]);
1545 selectnewtape(state);
1551 * tuplesort_rescan - rewind and replay the scan
1554 tuplesort_rescan(Tuplesortstate *state)
1556 Assert(state->randomAccess);
1558 switch (state->status)
1560 case TSS_SORTEDINMEM:
1562 state->eof_reached = false;
1563 state->markpos_offset = 0;
1564 state->markpos_eof = false;
1566 case TSS_SORTEDONTAPE:
1567 LogicalTapeRewind(state->tapeset,
1570 state->eof_reached = false;
1571 state->markpos_block = 0L;
1572 state->markpos_offset = 0;
1573 state->markpos_eof = false;
1576 elog(ERROR, "invalid tuplesort state");
1582 * tuplesort_markpos - saves current position in the merged sort file
1585 tuplesort_markpos(Tuplesortstate *state)
1587 Assert(state->randomAccess);
1589 switch (state->status)
1591 case TSS_SORTEDINMEM:
1592 state->markpos_offset = state->current;
1593 state->markpos_eof = state->eof_reached;
1595 case TSS_SORTEDONTAPE:
1596 LogicalTapeTell(state->tapeset,
1598 &state->markpos_block,
1599 &state->markpos_offset);
1600 state->markpos_eof = state->eof_reached;
1603 elog(ERROR, "invalid tuplesort state");
1609 * tuplesort_restorepos - restores current position in merged sort file to
1610 * last saved position
1613 tuplesort_restorepos(Tuplesortstate *state)
1615 Assert(state->randomAccess);
1617 switch (state->status)
1619 case TSS_SORTEDINMEM:
1620 state->current = state->markpos_offset;
1621 state->eof_reached = state->markpos_eof;
1623 case TSS_SORTEDONTAPE:
1624 if (!LogicalTapeSeek(state->tapeset,
1626 state->markpos_block,
1627 state->markpos_offset))
1628 elog(ERROR, "tuplesort_restorepos failed");
1629 state->eof_reached = state->markpos_eof;
1632 elog(ERROR, "invalid tuplesort state");
1639 * Heap manipulation routines, per Knuth's Algorithm 5.2.3H.
1641 * The heap lives in state->memtuples[], with parallel data storage
1642 * for indexes in state->memtupindex[]. If checkIndex is true, use
1643 * the tuple index as the front of the sort key; otherwise, no.
1646 #define HEAPCOMPARE(tup1,index1,tup2,index2) \
1647 (checkIndex && (index1 != index2) ? (index1) - (index2) : \
1648 COMPARETUP(state, tup1, tup2))
1651 * Insert a new tuple into an empty or existing heap, maintaining the
1655 tuplesort_heap_insert(Tuplesortstate *state, void *tuple,
1656 int tupleindex, bool checkIndex)
1663 * Make sure memtuples[] can handle another entry.
1665 if (state->memtupcount >= state->memtupsize)
1667 FREEMEM(state, GetMemoryChunkSpace(state->memtuples));
1668 FREEMEM(state, GetMemoryChunkSpace(state->memtupindex));
1669 state->memtupsize *= 2;
1670 state->memtuples = (void **)
1671 repalloc(state->memtuples,
1672 state->memtupsize * sizeof(void *));
1673 state->memtupindex = (int *)
1674 repalloc(state->memtupindex,
1675 state->memtupsize * sizeof(int));
1676 USEMEM(state, GetMemoryChunkSpace(state->memtuples));
1677 USEMEM(state, GetMemoryChunkSpace(state->memtupindex));
1679 memtuples = state->memtuples;
1680 memtupindex = state->memtupindex;
1683 * Sift-up the new entry, per Knuth 5.2.3 exercise 16. Note that Knuth
1684 * is using 1-based array indexes, not 0-based.
1686 j = state->memtupcount++;
1689 int i = (j - 1) >> 1;
1691 if (HEAPCOMPARE(tuple, tupleindex,
1692 memtuples[i], memtupindex[i]) >= 0)
1694 memtuples[j] = memtuples[i];
1695 memtupindex[j] = memtupindex[i];
1698 memtuples[j] = tuple;
1699 memtupindex[j] = tupleindex;
1703 * The tuple at state->memtuples[0] has been removed from the heap.
1704 * Decrement memtupcount, and sift up to maintain the heap invariant.
1707 tuplesort_heap_siftup(Tuplesortstate *state, bool checkIndex)
1709 void **memtuples = state->memtuples;
1710 int *memtupindex = state->memtupindex;
1716 if (--state->memtupcount <= 0)
1718 n = state->memtupcount;
1719 tuple = memtuples[n]; /* tuple that must be reinserted */
1720 tupindex = memtupindex[n];
1721 i = 0; /* i is where the "hole" is */
1729 HEAPCOMPARE(memtuples[j], memtupindex[j],
1730 memtuples[j + 1], memtupindex[j + 1]) > 0)
1732 if (HEAPCOMPARE(tuple, tupindex,
1733 memtuples[j], memtupindex[j]) <= 0)
1735 memtuples[i] = memtuples[j];
1736 memtupindex[i] = memtupindex[j];
1739 memtuples[i] = tuple;
1740 memtupindex[i] = tupindex;
1745 * Tape interface routines
1749 getlen(Tuplesortstate *state, int tapenum, bool eofOK)
1753 if (LogicalTapeRead(state->tapeset, tapenum, (void *) &len,
1754 sizeof(len)) != sizeof(len))
1755 elog(ERROR, "unexpected end of tape");
1756 if (len == 0 && !eofOK)
1757 elog(ERROR, "unexpected end of data");
1762 markrunend(Tuplesortstate *state, int tapenum)
1764 unsigned int len = 0;
1766 LogicalTapeWrite(state->tapeset, tapenum, (void *) &len, sizeof(len));
1775 qsort_comparetup(const void *a, const void *b)
1777 /* The passed pointers are pointers to void * ... */
1779 return COMPARETUP(qsort_tuplesortstate, *(void **) a, *(void **) b);
1784 * This routine selects an appropriate sorting function to implement
1785 * a sort operator as efficiently as possible. The straightforward
1786 * method is to use the operator's implementation proc --- ie, "<"
1787 * comparison. However, that way often requires two calls of the function
1788 * per comparison. If we can find a btree three-way comparator function
1789 * associated with the operator, we can use it to do the comparisons
1790 * more efficiently. We also support the possibility that the operator
1791 * is ">" (descending sort), in which case we have to reverse the output
1792 * of the btree comparator.
1794 * Possibly this should live somewhere else (backend/catalog/, maybe?).
1797 SelectSortFunction(Oid sortOperator,
1798 RegProcedure *sortFunction,
1799 SortFunctionKind *kind)
1804 Form_pg_operator optup;
1805 Oid opclass = InvalidOid;
1808 * Search pg_amop to see if the target operator is registered as the
1809 * "<" or ">" operator of any btree opclass. It's possible that it
1810 * might be registered both ways (eg, if someone were to build a
1811 * "reverse sort" opclass for some reason); prefer the "<" case if so.
1812 * If the operator is registered the same way in multiple opclasses,
1813 * assume we can use the associated comparator function from any one.
1815 catlist = SearchSysCacheList(AMOPOPID, 1,
1816 ObjectIdGetDatum(sortOperator),
1819 for (i = 0; i < catlist->n_members; i++)
1823 tuple = &catlist->members[i]->tuple;
1824 aform = (Form_pg_amop) GETSTRUCT(tuple);
1826 if (!opclass_is_btree(aform->amopclaid))
1828 /* must be of default subtype, too */
1829 if (aform->amopsubtype != InvalidOid)
1832 if (aform->amopstrategy == BTLessStrategyNumber)
1834 opclass = aform->amopclaid;
1835 *kind = SORTFUNC_CMP;
1836 break; /* done looking */
1838 else if (aform->amopstrategy == BTGreaterStrategyNumber)
1840 opclass = aform->amopclaid;
1841 *kind = SORTFUNC_REVCMP;
1842 /* keep scanning in hopes of finding a BTLess entry */
1846 ReleaseSysCacheList(catlist);
1848 if (OidIsValid(opclass))
1850 /* Found a suitable opclass, get its default comparator function */
1851 *sortFunction = get_opclass_proc(opclass, InvalidOid, BTORDER_PROC);
1852 Assert(RegProcedureIsValid(*sortFunction));
1857 * Can't find a comparator, so use the operator as-is. Decide whether
1858 * it is forward or reverse sort by looking at its name (grotty, but
1859 * this only matters for deciding which end NULLs should get sorted
1860 * to). XXX possibly better idea: see whether its selectivity
1861 * function is scalargtcmp?
1863 tuple = SearchSysCache(OPEROID,
1864 ObjectIdGetDatum(sortOperator),
1866 if (!HeapTupleIsValid(tuple))
1867 elog(ERROR, "cache lookup failed for operator %u", sortOperator);
1868 optup = (Form_pg_operator) GETSTRUCT(tuple);
1869 if (strcmp(NameStr(optup->oprname), ">") == 0)
1870 *kind = SORTFUNC_REVLT;
1872 *kind = SORTFUNC_LT;
1873 *sortFunction = optup->oprcode;
1874 ReleaseSysCache(tuple);
1876 Assert(RegProcedureIsValid(*sortFunction));
1880 * Inline-able copy of FunctionCall2() to save some cycles in sorting.
1883 myFunctionCall2(FmgrInfo *flinfo, Datum arg1, Datum arg2)
1885 FunctionCallInfoData fcinfo;
1888 InitFunctionCallInfoData(fcinfo, flinfo, 2, NULL, NULL);
1890 fcinfo.arg[0] = arg1;
1891 fcinfo.arg[1] = arg2;
1892 fcinfo.argnull[0] = false;
1893 fcinfo.argnull[1] = false;
1895 result = FunctionCallInvoke(&fcinfo);
1897 /* Check for null result, since caller is clearly not expecting one */
1899 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1905 * Apply a sort function (by now converted to fmgr lookup form)
1906 * and return a 3-way comparison result. This takes care of handling
1907 * NULLs and sort ordering direction properly.
1910 inlineApplySortFunction(FmgrInfo *sortFunction, SortFunctionKind kind,
1911 Datum datum1, bool isNull1,
1912 Datum datum2, bool isNull2)
1921 return 1; /* NULL sorts after non-NULL */
1925 if (DatumGetBool(myFunctionCall2(sortFunction, datum1, datum2)))
1926 return -1; /* a < b */
1927 if (DatumGetBool(myFunctionCall2(sortFunction, datum2, datum1)))
1928 return 1; /* a > b */
1931 case SORTFUNC_REVLT:
1932 /* We reverse the ordering of NULLs, but not the operator */
1937 return -1; /* NULL sorts before non-NULL */
1941 if (DatumGetBool(myFunctionCall2(sortFunction, datum1, datum2)))
1942 return -1; /* a < b */
1943 if (DatumGetBool(myFunctionCall2(sortFunction, datum2, datum1)))
1944 return 1; /* a > b */
1952 return 1; /* NULL sorts after non-NULL */
1956 return DatumGetInt32(myFunctionCall2(sortFunction,
1959 case SORTFUNC_REVCMP:
1964 return -1; /* NULL sorts before non-NULL */
1968 return -DatumGetInt32(myFunctionCall2(sortFunction,
1972 elog(ERROR, "unrecognized SortFunctionKind: %d", (int) kind);
1973 return 0; /* can't get here, but keep compiler quiet */
1978 * Non-inline ApplySortFunction() --- this is needed only to conform to
1979 * C99's brain-dead notions about how to implement inline functions...
1982 ApplySortFunction(FmgrInfo *sortFunction, SortFunctionKind kind,
1983 Datum datum1, bool isNull1,
1984 Datum datum2, bool isNull2)
1986 return inlineApplySortFunction(sortFunction, kind,
1993 * Routines specialized for HeapTuple case
1997 comparetup_heap(Tuplesortstate *state, const void *a, const void *b)
1999 HeapTuple ltup = (HeapTuple) a;
2000 HeapTuple rtup = (HeapTuple) b;
2001 TupleDesc tupDesc = state->tupDesc;
2004 for (nkey = 0; nkey < state->nKeys; nkey++)
2006 ScanKey scanKey = state->scanKeys + nkey;
2007 AttrNumber attno = scanKey->sk_attno;
2014 datum1 = heap_getattr(ltup, attno, tupDesc, &isnull1);
2015 datum2 = heap_getattr(rtup, attno, tupDesc, &isnull2);
2017 compare = inlineApplySortFunction(&scanKey->sk_func,
2018 state->sortFnKinds[nkey],
2029 copytup_heap(Tuplesortstate *state, void *tup)
2031 HeapTuple tuple = (HeapTuple) tup;
2033 tuple = heap_copytuple(tuple);
2034 USEMEM(state, GetMemoryChunkSpace(tuple));
2035 return (void *) tuple;
2039 * We don't bother to write the HeapTupleData part of the tuple.
2043 writetup_heap(Tuplesortstate *state, int tapenum, void *tup)
2045 HeapTuple tuple = (HeapTuple) tup;
2046 unsigned int tuplen;
2048 tuplen = tuple->t_len + sizeof(tuplen);
2049 LogicalTapeWrite(state->tapeset, tapenum,
2050 (void *) &tuplen, sizeof(tuplen));
2051 LogicalTapeWrite(state->tapeset, tapenum,
2052 (void *) tuple->t_data, tuple->t_len);
2053 if (state->randomAccess) /* need trailing length word? */
2054 LogicalTapeWrite(state->tapeset, tapenum,
2055 (void *) &tuplen, sizeof(tuplen));
2057 FREEMEM(state, GetMemoryChunkSpace(tuple));
2058 heap_freetuple(tuple);
2062 readtup_heap(Tuplesortstate *state, int tapenum, unsigned int len)
2064 unsigned int tuplen = len - sizeof(unsigned int) + HEAPTUPLESIZE;
2065 HeapTuple tuple = (HeapTuple) palloc(tuplen);
2067 USEMEM(state, GetMemoryChunkSpace(tuple));
2068 /* reconstruct the HeapTupleData portion */
2069 tuple->t_len = len - sizeof(unsigned int);
2070 ItemPointerSetInvalid(&(tuple->t_self));
2071 tuple->t_datamcxt = CurrentMemoryContext;
2072 tuple->t_data = (HeapTupleHeader) (((char *) tuple) + HEAPTUPLESIZE);
2073 /* read in the tuple proper */
2074 if (LogicalTapeRead(state->tapeset, tapenum, (void *) tuple->t_data,
2075 tuple->t_len) != tuple->t_len)
2076 elog(ERROR, "unexpected end of data");
2077 if (state->randomAccess) /* need trailing length word? */
2078 if (LogicalTapeRead(state->tapeset, tapenum, (void *) &tuplen,
2079 sizeof(tuplen)) != sizeof(tuplen))
2080 elog(ERROR, "unexpected end of data");
2081 return (void *) tuple;
2086 * Routines specialized for IndexTuple case
2088 * NOTE: actually, these are specialized for the btree case; it's not
2089 * clear whether you could use them for a non-btree index. Possibly
2090 * you'd need to make another set of routines if you needed to sort
2091 * according to another kind of index.
2095 comparetup_index(Tuplesortstate *state, const void *a, const void *b)
2098 * This is almost the same as _bt_tuplecompare(), but we need to keep
2099 * track of whether any null fields are present. Also see the special
2100 * treatment for equal keys at the end.
2102 IndexTuple tuple1 = (IndexTuple) a;
2103 IndexTuple tuple2 = (IndexTuple) b;
2104 Relation rel = state->indexRel;
2105 int keysz = RelationGetNumberOfAttributes(rel);
2106 ScanKey scankey = state->indexScanKey;
2109 bool equal_hasnull = false;
2111 tupDes = RelationGetDescr(rel);
2113 for (i = 1; i <= keysz; i++)
2115 ScanKey entry = &scankey[i - 1];
2122 datum1 = index_getattr(tuple1, i, tupDes, &isnull1);
2123 datum2 = index_getattr(tuple2, i, tupDes, &isnull2);
2125 /* see comments about NULLs handling in btbuild */
2127 /* the comparison function is always of CMP type */
2128 compare = inlineApplySortFunction(&entry->sk_func, SORTFUNC_CMP,
2133 return (int) compare; /* done when we find unequal
2136 /* they are equal, so we only need to examine one null flag */
2138 equal_hasnull = true;
2142 * If btree has asked us to enforce uniqueness, complain if two equal
2143 * tuples are detected (unless there was at least one NULL field).
2145 * It is sufficient to make the test here, because if two tuples are
2146 * equal they *must* get compared at some stage of the sort ---
2147 * otherwise the sort algorithm wouldn't have checked whether one must
2148 * appear before the other.
2150 * Some rather brain-dead implementations of qsort will sometimes call
2151 * the comparison routine to compare a value to itself. (At this
2152 * writing only QNX 4 is known to do such silly things.) Don't raise
2153 * a bogus error in that case.
2155 if (state->enforceUnique && !equal_hasnull && tuple1 != tuple2)
2157 (errcode(ERRCODE_UNIQUE_VIOLATION),
2158 errmsg("could not create unique index"),
2159 errdetail("Table contains duplicated values.")));
2162 * If key values are equal, we sort on ItemPointer. This does not
2163 * affect validity of the finished index, but it offers cheap
2164 * insurance against performance problems with bad qsort
2165 * implementations that have trouble with large numbers of equal keys.
2168 BlockNumber blk1 = ItemPointerGetBlockNumber(&tuple1->t_tid);
2169 BlockNumber blk2 = ItemPointerGetBlockNumber(&tuple2->t_tid);
2172 return (blk1 < blk2) ? -1 : 1;
2175 OffsetNumber pos1 = ItemPointerGetOffsetNumber(&tuple1->t_tid);
2176 OffsetNumber pos2 = ItemPointerGetOffsetNumber(&tuple2->t_tid);
2179 return (pos1 < pos2) ? -1 : 1;
2186 copytup_index(Tuplesortstate *state, void *tup)
2188 IndexTuple tuple = (IndexTuple) tup;
2189 unsigned int tuplen = IndexTupleSize(tuple);
2190 IndexTuple newtuple;
2192 newtuple = (IndexTuple) palloc(tuplen);
2193 USEMEM(state, GetMemoryChunkSpace(newtuple));
2195 memcpy(newtuple, tuple, tuplen);
2197 return (void *) newtuple;
2201 writetup_index(Tuplesortstate *state, int tapenum, void *tup)
2203 IndexTuple tuple = (IndexTuple) tup;
2204 unsigned int tuplen;
2206 tuplen = IndexTupleSize(tuple) + sizeof(tuplen);
2207 LogicalTapeWrite(state->tapeset, tapenum,
2208 (void *) &tuplen, sizeof(tuplen));
2209 LogicalTapeWrite(state->tapeset, tapenum,
2210 (void *) tuple, IndexTupleSize(tuple));
2211 if (state->randomAccess) /* need trailing length word? */
2212 LogicalTapeWrite(state->tapeset, tapenum,
2213 (void *) &tuplen, sizeof(tuplen));
2215 FREEMEM(state, GetMemoryChunkSpace(tuple));
2220 readtup_index(Tuplesortstate *state, int tapenum, unsigned int len)
2222 unsigned int tuplen = len - sizeof(unsigned int);
2223 IndexTuple tuple = (IndexTuple) palloc(tuplen);
2225 USEMEM(state, GetMemoryChunkSpace(tuple));
2226 if (LogicalTapeRead(state->tapeset, tapenum, (void *) tuple,
2228 elog(ERROR, "unexpected end of data");
2229 if (state->randomAccess) /* need trailing length word? */
2230 if (LogicalTapeRead(state->tapeset, tapenum, (void *) &tuplen,
2231 sizeof(tuplen)) != sizeof(tuplen))
2232 elog(ERROR, "unexpected end of data");
2233 return (void *) tuple;
2238 * Routines specialized for DatumTuple case
2242 comparetup_datum(Tuplesortstate *state, const void *a, const void *b)
2244 DatumTuple *ltup = (DatumTuple *) a;
2245 DatumTuple *rtup = (DatumTuple *) b;
2247 return inlineApplySortFunction(&state->sortOpFn, state->sortFnKind,
2248 ltup->val, ltup->isNull,
2249 rtup->val, rtup->isNull);
2253 copytup_datum(Tuplesortstate *state, void *tup)
2255 /* Not currently needed */
2256 elog(ERROR, "copytup_datum() should not be called");
2261 writetup_datum(Tuplesortstate *state, int tapenum, void *tup)
2263 DatumTuple *tuple = (DatumTuple *) tup;
2264 unsigned int tuplen;
2265 unsigned int writtenlen;
2267 if (tuple->isNull || state->datumTypeByVal)
2268 tuplen = sizeof(DatumTuple);
2273 datalen = datumGetSize(tuple->val, false, state->datumTypeLen);
2274 tuplen = datalen + MAXALIGN(sizeof(DatumTuple));
2277 writtenlen = tuplen + sizeof(unsigned int);
2279 LogicalTapeWrite(state->tapeset, tapenum,
2280 (void *) &writtenlen, sizeof(writtenlen));
2281 LogicalTapeWrite(state->tapeset, tapenum,
2282 (void *) tuple, tuplen);
2283 if (state->randomAccess) /* need trailing length word? */
2284 LogicalTapeWrite(state->tapeset, tapenum,
2285 (void *) &writtenlen, sizeof(writtenlen));
2287 FREEMEM(state, GetMemoryChunkSpace(tuple));
2292 readtup_datum(Tuplesortstate *state, int tapenum, unsigned int len)
2294 unsigned int tuplen = len - sizeof(unsigned int);
2295 DatumTuple *tuple = (DatumTuple *) palloc(tuplen);
2297 USEMEM(state, GetMemoryChunkSpace(tuple));
2298 if (LogicalTapeRead(state->tapeset, tapenum, (void *) tuple,
2300 elog(ERROR, "unexpected end of data");
2301 if (state->randomAccess) /* need trailing length word? */
2302 if (LogicalTapeRead(state->tapeset, tapenum, (void *) &tuplen,
2303 sizeof(tuplen)) != sizeof(tuplen))
2304 elog(ERROR, "unexpected end of data");
2306 if (!tuple->isNull && !state->datumTypeByVal)
2307 tuple->val = PointerGetDatum(((char *) tuple) +
2308 MAXALIGN(sizeof(DatumTuple)));
2309 return (void *) tuple;