deprecate cipher_store_pass
[sqlcipher.git] / src / vdbesort.c
blob777c2054e8923ef78e00948233935075208907b9
1 /*
2 ** 2011-07-09
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code for the VdbeSorter object, used in concert with
13 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
14 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
15 ** using indexes and without LIMIT clauses.
17 ** The VdbeSorter object implements a multi-threaded external merge sort
18 ** algorithm that is efficient even if the number of elements being sorted
19 ** exceeds the available memory.
21 ** Here is the (internal, non-API) interface between this module and the
22 ** rest of the SQLite system:
24 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
26 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
27 ** object. The row is a binary blob in the
28 ** OP_MakeRecord format that contains both
29 ** the ORDER BY key columns and result columns
30 ** in the case of a SELECT w/ ORDER BY, or
31 ** the complete record for an index entry
32 ** in the case of a CREATE INDEX.
34 ** sqlite3VdbeSorterRewind() Sort all content previously added.
35 ** Position the read cursor on the
36 ** first sorted element.
38 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
39 ** element.
41 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
42 ** row currently under the read cursor.
44 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
45 ** currently under the read cursor against
46 ** another binary blob X and report if
47 ** X is strictly less than the read cursor.
48 ** Used to enforce uniqueness in a
49 ** CREATE UNIQUE INDEX statement.
51 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
52 ** all resources.
54 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
55 ** is like Close() followed by Init() only
56 ** much faster.
58 ** The interfaces above must be called in a particular order. Write() can
59 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
60 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
62 ** Init()
63 ** for each record: Write()
64 ** Rewind()
65 ** Rowkey()/Compare()
66 ** Next()
67 ** Close()
69 ** Algorithm:
71 ** Records passed to the sorter via calls to Write() are initially held
72 ** unsorted in main memory. Assuming the amount of memory used never exceeds
73 ** a threshold, when Rewind() is called the set of records is sorted using
74 ** an in-memory merge sort. In this case, no temporary files are required
75 ** and subsequent calls to Rowkey(), Next() and Compare() read records
76 ** directly from main memory.
78 ** If the amount of space used to store records in main memory exceeds the
79 ** threshold, then the set of records currently in memory are sorted and
80 ** written to a temporary file in "Packed Memory Array" (PMA) format.
81 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
82 ** of PMAs may be created by merging existing PMAs together - for example
83 ** merging two or more level-0 PMAs together creates a level-1 PMA.
85 ** The threshold for the amount of main memory to use before flushing
86 ** records to a PMA is roughly the same as the limit configured for the
87 ** page-cache of the main database. Specifically, the threshold is set to
88 ** the value returned by "PRAGMA main.page_size" multipled by
89 ** that returned by "PRAGMA main.cache_size", in bytes.
91 ** If the sorter is running in single-threaded mode, then all PMAs generated
92 ** are appended to a single temporary file. Or, if the sorter is running in
93 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
94 ** N is the configured number of worker threads. In this case, instead of
95 ** sorting the records and writing the PMA to a temporary file itself, the
96 ** calling thread usually launches a worker thread to do so. Except, if
97 ** there are already N worker threads running, the main thread does the work
98 ** itself.
100 ** The sorter is running in multi-threaded mode if (a) the library was built
101 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
102 ** than zero, and (b) worker threads have been enabled at runtime by calling
103 ** "PRAGMA threads=N" with some value of N greater than 0.
105 ** When Rewind() is called, any data remaining in memory is flushed to a
106 ** final PMA. So at this point the data is stored in some number of sorted
107 ** PMAs within temporary files on disk.
109 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
110 ** sorter is running in single-threaded mode, then these PMAs are merged
111 ** incrementally as keys are retreived from the sorter by the VDBE. The
112 ** MergeEngine object, described in further detail below, performs this
113 ** merge.
115 ** Or, if running in multi-threaded mode, then a background thread is
116 ** launched to merge the existing PMAs. Once the background thread has
117 ** merged T bytes of data into a single sorted PMA, the main thread
118 ** begins reading keys from that PMA while the background thread proceeds
119 ** with merging the next T bytes of data. And so on.
121 ** Parameter T is set to half the value of the memory threshold used
122 ** by Write() above to determine when to create a new PMA.
124 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
125 ** Rewind() is called, then a hierarchy of incremental-merges is used.
126 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
127 ** disk are merged together. Then T bytes of data from the second set, and
128 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
129 ** PMAs at a time. This done is to improve locality.
131 ** If running in multi-threaded mode and there are more than
132 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
133 ** than one background thread may be created. Specifically, there may be
134 ** one background thread for each temporary file on disk, and one background
135 ** thread to merge the output of each of the others to a single PMA for
136 ** the main thread to read from.
138 #include "sqliteInt.h"
139 #include "vdbeInt.h"
142 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
143 ** messages to stderr that may be helpful in understanding the performance
144 ** characteristics of the sorter in multi-threaded mode.
146 #if 0
147 # define SQLITE_DEBUG_SORTER_THREADS 1
148 #endif
151 ** Hard-coded maximum amount of data to accumulate in memory before flushing
152 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
153 ** overflows. 512MiB.
155 #define SQLITE_MAX_PMASZ (1<<29)
158 ** Private objects used by the sorter
160 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
161 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
162 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
163 typedef struct SorterRecord SorterRecord; /* A record being sorted */
164 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
165 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
166 typedef struct SorterList SorterList; /* In-memory list of records */
167 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
170 ** A container for a temp file handle and the current amount of data
171 ** stored in the file.
173 struct SorterFile {
174 sqlite3_file *pFd; /* File handle */
175 i64 iEof; /* Bytes of data stored in pFd */
179 ** An in-memory list of objects to be sorted.
181 ** If aMemory==0 then each object is allocated separately and the objects
182 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
183 ** are stored in the aMemory[] bulk memory, one right after the other, and
184 ** are connected using SorterRecord.u.iNext.
186 struct SorterList {
187 SorterRecord *pList; /* Linked list of records */
188 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
189 int szPMA; /* Size of pList as PMA in bytes */
193 ** The MergeEngine object is used to combine two or more smaller PMAs into
194 ** one big PMA using a merge operation. Separate PMAs all need to be
195 ** combined into one big PMA in order to be able to step through the sorted
196 ** records in order.
198 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
199 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
200 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
201 ** For the purposes of the paragraphs below, we assume that the array is
202 ** actually N elements in size, where N is the smallest power of 2 greater
203 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
204 ** are treated as if they are empty (always at EOF).
206 ** The aTree[] array is also N elements in size. The value of N is stored in
207 ** the MergeEngine.nTree variable.
209 ** The final (N/2) elements of aTree[] contain the results of comparing
210 ** pairs of PMA keys together. Element i contains the result of
211 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
212 ** aTree element is set to the index of it.
214 ** For the purposes of this comparison, EOF is considered greater than any
215 ** other key value. If the keys are equal (only possible with two EOF
216 ** values), it doesn't matter which index is stored.
218 ** The (N/4) elements of aTree[] that precede the final (N/2) described
219 ** above contains the index of the smallest of each block of 4 PmaReaders
220 ** And so on. So that aTree[1] contains the index of the PmaReader that
221 ** currently points to the smallest key value. aTree[0] is unused.
223 ** Example:
225 ** aReadr[0] -> Banana
226 ** aReadr[1] -> Feijoa
227 ** aReadr[2] -> Elderberry
228 ** aReadr[3] -> Currant
229 ** aReadr[4] -> Grapefruit
230 ** aReadr[5] -> Apple
231 ** aReadr[6] -> Durian
232 ** aReadr[7] -> EOF
234 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
236 ** The current element is "Apple" (the value of the key indicated by
237 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
238 ** be advanced to the next key in its segment. Say the next key is
239 ** "Eggplant":
241 ** aReadr[5] -> Eggplant
243 ** The contents of aTree[] are updated first by comparing the new PmaReader
244 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
245 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
246 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
247 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
248 ** so the value written into element 1 of the array is 0. As follows:
250 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
252 ** In other words, each time we advance to the next sorter element, log2(N)
253 ** key comparison operations are required, where N is the number of segments
254 ** being merged (rounded up to the next power of 2).
256 struct MergeEngine {
257 int nTree; /* Used size of aTree/aReadr (power of 2) */
258 SortSubtask *pTask; /* Used by this thread only */
259 int *aTree; /* Current state of incremental merge */
260 PmaReader *aReadr; /* Array of PmaReaders to merge data from */
264 ** This object represents a single thread of control in a sort operation.
265 ** Exactly VdbeSorter.nTask instances of this object are allocated
266 ** as part of each VdbeSorter object. Instances are never allocated any
267 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
268 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
269 ** single-threaded operation, there is exactly one instance of this object
270 ** and for multi-threaded operation there are two or more instances.
272 ** Essentially, this structure contains all those fields of the VdbeSorter
273 ** structure for which each thread requires a separate instance. For example,
274 ** each thread requries its own UnpackedRecord object to unpack records in
275 ** as part of comparison operations.
277 ** Before a background thread is launched, variable bDone is set to 0. Then,
278 ** right before it exits, the thread itself sets bDone to 1. This is used for
279 ** two purposes:
281 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
282 ** attempt to select a SortSubtask for which there is not already an
283 ** active background thread (since doing so causes the main thread
284 ** to block until it finishes).
286 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
287 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
288 ** block provoke debugging output.
290 ** In both cases, the effects of the main thread seeing (bDone==0) even
291 ** after the thread has finished are not dire. So we don't worry about
292 ** memory barriers and such here.
294 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
295 struct SortSubtask {
296 SQLiteThread *pThread; /* Background thread, if any */
297 int bDone; /* Set if thread is finished but not joined */
298 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
299 UnpackedRecord *pUnpacked; /* Space to unpack a record */
300 SorterList list; /* List for thread to write to a PMA */
301 int nPMA; /* Number of PMAs currently in file */
302 SorterCompare xCompare; /* Compare function to use */
303 SorterFile file; /* Temp file for level-0 PMAs */
304 SorterFile file2; /* Space for other PMAs */
309 ** Main sorter structure. A single instance of this is allocated for each
310 ** sorter cursor created by the VDBE.
312 ** mxKeysize:
313 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
314 ** this variable is updated so as to be set to the size on disk of the
315 ** largest record in the sorter.
317 struct VdbeSorter {
318 int mnPmaSize; /* Minimum PMA size, in bytes */
319 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
320 int mxKeysize; /* Largest serialized key seen so far */
321 int pgsz; /* Main database page size */
322 PmaReader *pReader; /* Readr data from here after Rewind() */
323 MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
324 sqlite3 *db; /* Database connection */
325 KeyInfo *pKeyInfo; /* How to compare records */
326 UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
327 SorterList list; /* List of in-memory records */
328 int iMemory; /* Offset of free space in list.aMemory */
329 int nMemory; /* Size of list.aMemory allocation in bytes */
330 u8 bUsePMA; /* True if one or more PMAs created */
331 u8 bUseThreads; /* True to use background threads */
332 u8 iPrev; /* Previous thread used to flush PMA */
333 u8 nTask; /* Size of aTask[] array */
334 u8 typeMask;
335 SortSubtask aTask[1]; /* One or more subtasks */
338 #define SORTER_TYPE_INTEGER 0x01
339 #define SORTER_TYPE_TEXT 0x02
342 ** An instance of the following object is used to read records out of a
343 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
344 ** aKey might point into aMap or into aBuffer. If neither of those locations
345 ** contain a contiguous representation of the key, then aAlloc is allocated
346 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
348 ** pFd==0 at EOF.
350 struct PmaReader {
351 i64 iReadOff; /* Current read offset */
352 i64 iEof; /* 1 byte past EOF for this PmaReader */
353 int nAlloc; /* Bytes of space at aAlloc */
354 int nKey; /* Number of bytes in key */
355 sqlite3_file *pFd; /* File handle we are reading from */
356 u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
357 u8 *aKey; /* Pointer to current key */
358 u8 *aBuffer; /* Current read buffer */
359 int nBuffer; /* Size of read buffer in bytes */
360 u8 *aMap; /* Pointer to mapping of entire file */
361 IncrMerger *pIncr; /* Incremental merger */
365 ** Normally, a PmaReader object iterates through an existing PMA stored
366 ** within a temp file. However, if the PmaReader.pIncr variable points to
367 ** an object of the following type, it may be used to iterate/merge through
368 ** multiple PMAs simultaneously.
370 ** There are two types of IncrMerger object - single (bUseThread==0) and
371 ** multi-threaded (bUseThread==1).
373 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
374 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
375 ** size. When the IncrMerger is initialized, it reads enough data from
376 ** pMerger to populate aFile[0]. It then sets variables within the
377 ** corresponding PmaReader object to read from that file and kicks off
378 ** a background thread to populate aFile[1] with the next mxSz bytes of
379 ** sorted record data from pMerger.
381 ** When the PmaReader reaches the end of aFile[0], it blocks until the
382 ** background thread has finished populating aFile[1]. It then exchanges
383 ** the contents of the aFile[0] and aFile[1] variables within this structure,
384 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
385 ** another background thread to populate the new aFile[1]. And so on, until
386 ** the contents of pMerger are exhausted.
388 ** A single-threaded IncrMerger does not open any temporary files of its
389 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
390 ** at offset iStartOff of file pTask->file2. And instead of using a
391 ** background thread to prepare data for the PmaReader, with a single
392 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
393 ** keys from pMerger by the calling thread whenever the PmaReader runs out
394 ** of data.
396 struct IncrMerger {
397 SortSubtask *pTask; /* Task that owns this merger */
398 MergeEngine *pMerger; /* Merge engine thread reads data from */
399 i64 iStartOff; /* Offset to start writing file at */
400 int mxSz; /* Maximum bytes of data to store */
401 int bEof; /* Set to true when merge is finished */
402 int bUseThread; /* True to use a bg thread for this object */
403 SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
407 ** An instance of this object is used for writing a PMA.
409 ** The PMA is written one record at a time. Each record is of an arbitrary
410 ** size. But I/O is more efficient if it occurs in page-sized blocks where
411 ** each block is aligned on a page boundary. This object caches writes to
412 ** the PMA so that aligned, page-size blocks are written.
414 struct PmaWriter {
415 int eFWErr; /* Non-zero if in an error state */
416 u8 *aBuffer; /* Pointer to write buffer */
417 int nBuffer; /* Size of write buffer in bytes */
418 int iBufStart; /* First byte of buffer to write */
419 int iBufEnd; /* Last byte of buffer to write */
420 i64 iWriteOff; /* Offset of start of buffer in file */
421 sqlite3_file *pFd; /* File handle to write to */
425 ** This object is the header on a single record while that record is being
426 ** held in memory and prior to being written out as part of a PMA.
428 ** How the linked list is connected depends on how memory is being managed
429 ** by this module. If using a separate allocation for each in-memory record
430 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
431 ** SorterRecord.u.pNext pointers.
433 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
434 ** then while records are being accumulated the list is linked using the
435 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
436 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
437 ** has finished passing records to the sorter, or when the in-memory buffer
438 ** is full, the list is sorted. As part of the sorting process, it is
439 ** converted to use the SorterRecord.u.pNext pointers. See function
440 ** vdbeSorterSort() for details.
442 struct SorterRecord {
443 int nVal; /* Size of the record in bytes */
444 union {
445 SorterRecord *pNext; /* Pointer to next record in list */
446 int iNext; /* Offset within aMemory of next record */
447 } u;
448 /* The data for the record immediately follows this header */
451 /* Return a pointer to the buffer containing the record data for SorterRecord
452 ** object p. Should be used as if:
454 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
456 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
459 /* Maximum number of PMAs that a single MergeEngine can merge */
460 #define SORTER_MAX_MERGE_COUNT 16
462 static int vdbeIncrSwap(IncrMerger*);
463 static void vdbeIncrFree(IncrMerger *);
466 ** Free all memory belonging to the PmaReader object passed as the
467 ** argument. All structure fields are set to zero before returning.
469 static void vdbePmaReaderClear(PmaReader *pReadr){
470 sqlite3_free(pReadr->aAlloc);
471 sqlite3_free(pReadr->aBuffer);
472 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
473 vdbeIncrFree(pReadr->pIncr);
474 memset(pReadr, 0, sizeof(PmaReader));
478 ** Read the next nByte bytes of data from the PMA p.
479 ** If successful, set *ppOut to point to a buffer containing the data
480 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
481 ** error code.
483 ** The buffer returned in *ppOut is only valid until the
484 ** next call to this function.
486 static int vdbePmaReadBlob(
487 PmaReader *p, /* PmaReader from which to take the blob */
488 int nByte, /* Bytes of data to read */
489 u8 **ppOut /* OUT: Pointer to buffer containing data */
491 int iBuf; /* Offset within buffer to read from */
492 int nAvail; /* Bytes of data available in buffer */
494 if( p->aMap ){
495 *ppOut = &p->aMap[p->iReadOff];
496 p->iReadOff += nByte;
497 return SQLITE_OK;
500 assert( p->aBuffer );
502 /* If there is no more data to be read from the buffer, read the next
503 ** p->nBuffer bytes of data from the file into it. Or, if there are less
504 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
505 iBuf = p->iReadOff % p->nBuffer;
506 if( iBuf==0 ){
507 int nRead; /* Bytes to read from disk */
508 int rc; /* sqlite3OsRead() return code */
510 /* Determine how many bytes of data to read. */
511 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
512 nRead = p->nBuffer;
513 }else{
514 nRead = (int)(p->iEof - p->iReadOff);
516 assert( nRead>0 );
518 /* Readr data from the file. Return early if an error occurs. */
519 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
520 assert( rc!=SQLITE_IOERR_SHORT_READ );
521 if( rc!=SQLITE_OK ) return rc;
523 nAvail = p->nBuffer - iBuf;
525 if( nByte<=nAvail ){
526 /* The requested data is available in the in-memory buffer. In this
527 ** case there is no need to make a copy of the data, just return a
528 ** pointer into the buffer to the caller. */
529 *ppOut = &p->aBuffer[iBuf];
530 p->iReadOff += nByte;
531 }else{
532 /* The requested data is not all available in the in-memory buffer.
533 ** In this case, allocate space at p->aAlloc[] to copy the requested
534 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
535 int nRem; /* Bytes remaining to copy */
537 /* Extend the p->aAlloc[] allocation if required. */
538 if( p->nAlloc<nByte ){
539 u8 *aNew;
540 sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
541 while( nByte>nNew ) nNew = nNew*2;
542 aNew = sqlite3Realloc(p->aAlloc, nNew);
543 if( !aNew ) return SQLITE_NOMEM_BKPT;
544 p->nAlloc = nNew;
545 p->aAlloc = aNew;
548 /* Copy as much data as is available in the buffer into the start of
549 ** p->aAlloc[]. */
550 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
551 p->iReadOff += nAvail;
552 nRem = nByte - nAvail;
554 /* The following loop copies up to p->nBuffer bytes per iteration into
555 ** the p->aAlloc[] buffer. */
556 while( nRem>0 ){
557 int rc; /* vdbePmaReadBlob() return code */
558 int nCopy; /* Number of bytes to copy */
559 u8 *aNext; /* Pointer to buffer to copy data from */
561 nCopy = nRem;
562 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
563 rc = vdbePmaReadBlob(p, nCopy, &aNext);
564 if( rc!=SQLITE_OK ) return rc;
565 assert( aNext!=p->aAlloc );
566 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
567 nRem -= nCopy;
570 *ppOut = p->aAlloc;
573 return SQLITE_OK;
577 ** Read a varint from the stream of data accessed by p. Set *pnOut to
578 ** the value read.
580 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
581 int iBuf;
583 if( p->aMap ){
584 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
585 }else{
586 iBuf = p->iReadOff % p->nBuffer;
587 if( iBuf && (p->nBuffer-iBuf)>=9 ){
588 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
589 }else{
590 u8 aVarint[16], *a;
591 int i = 0, rc;
593 rc = vdbePmaReadBlob(p, 1, &a);
594 if( rc ) return rc;
595 aVarint[(i++)&0xf] = a[0];
596 }while( (a[0]&0x80)!=0 );
597 sqlite3GetVarint(aVarint, pnOut);
601 return SQLITE_OK;
605 ** Attempt to memory map file pFile. If successful, set *pp to point to the
606 ** new mapping and return SQLITE_OK. If the mapping is not attempted
607 ** (because the file is too large or the VFS layer is configured not to use
608 ** mmap), return SQLITE_OK and set *pp to NULL.
610 ** Or, if an error occurs, return an SQLite error code. The final value of
611 ** *pp is undefined in this case.
613 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
614 int rc = SQLITE_OK;
615 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
616 sqlite3_file *pFd = pFile->pFd;
617 if( pFd->pMethods->iVersion>=3 ){
618 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
619 testcase( rc!=SQLITE_OK );
622 return rc;
626 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
627 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
628 ** if successful, or an SQLite error code if an error occurs.
630 static int vdbePmaReaderSeek(
631 SortSubtask *pTask, /* Task context */
632 PmaReader *pReadr, /* Reader whose cursor is to be moved */
633 SorterFile *pFile, /* Sorter file to read from */
634 i64 iOff /* Offset in pFile */
636 int rc = SQLITE_OK;
638 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
640 if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
641 if( pReadr->aMap ){
642 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
643 pReadr->aMap = 0;
645 pReadr->iReadOff = iOff;
646 pReadr->iEof = pFile->iEof;
647 pReadr->pFd = pFile->pFd;
649 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
650 if( rc==SQLITE_OK && pReadr->aMap==0 ){
651 int pgsz = pTask->pSorter->pgsz;
652 int iBuf = pReadr->iReadOff % pgsz;
653 if( pReadr->aBuffer==0 ){
654 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
655 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
656 pReadr->nBuffer = pgsz;
658 if( rc==SQLITE_OK && iBuf ){
659 int nRead = pgsz - iBuf;
660 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
661 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
663 rc = sqlite3OsRead(
664 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
666 testcase( rc!=SQLITE_OK );
670 return rc;
674 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
675 ** no error occurs, or an SQLite error code if one does.
677 static int vdbePmaReaderNext(PmaReader *pReadr){
678 int rc = SQLITE_OK; /* Return Code */
679 u64 nRec = 0; /* Size of record in bytes */
682 if( pReadr->iReadOff>=pReadr->iEof ){
683 IncrMerger *pIncr = pReadr->pIncr;
684 int bEof = 1;
685 if( pIncr ){
686 rc = vdbeIncrSwap(pIncr);
687 if( rc==SQLITE_OK && pIncr->bEof==0 ){
688 rc = vdbePmaReaderSeek(
689 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
691 bEof = 0;
695 if( bEof ){
696 /* This is an EOF condition */
697 vdbePmaReaderClear(pReadr);
698 testcase( rc!=SQLITE_OK );
699 return rc;
703 if( rc==SQLITE_OK ){
704 rc = vdbePmaReadVarint(pReadr, &nRec);
706 if( rc==SQLITE_OK ){
707 pReadr->nKey = (int)nRec;
708 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
709 testcase( rc!=SQLITE_OK );
712 return rc;
716 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
717 ** starting at offset iStart and ending at offset iEof-1. This function
718 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
719 ** PMA is empty).
721 ** If the pnByte parameter is NULL, then it is assumed that the file
722 ** contains a single PMA, and that that PMA omits the initial length varint.
724 static int vdbePmaReaderInit(
725 SortSubtask *pTask, /* Task context */
726 SorterFile *pFile, /* Sorter file to read from */
727 i64 iStart, /* Start offset in pFile */
728 PmaReader *pReadr, /* PmaReader to populate */
729 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
731 int rc;
733 assert( pFile->iEof>iStart );
734 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
735 assert( pReadr->aBuffer==0 );
736 assert( pReadr->aMap==0 );
738 rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
739 if( rc==SQLITE_OK ){
740 u64 nByte = 0; /* Size of PMA in bytes */
741 rc = vdbePmaReadVarint(pReadr, &nByte);
742 pReadr->iEof = pReadr->iReadOff + nByte;
743 *pnByte += nByte;
746 if( rc==SQLITE_OK ){
747 rc = vdbePmaReaderNext(pReadr);
749 return rc;
753 ** A version of vdbeSorterCompare() that assumes that it has already been
754 ** determined that the first field of key1 is equal to the first field of
755 ** key2.
757 static int vdbeSorterCompareTail(
758 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
759 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
760 const void *pKey1, int nKey1, /* Left side of comparison */
761 const void *pKey2, int nKey2 /* Right side of comparison */
763 UnpackedRecord *r2 = pTask->pUnpacked;
764 if( *pbKey2Cached==0 ){
765 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
766 *pbKey2Cached = 1;
768 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
772 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
773 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
774 ** used by the comparison. Return the result of the comparison.
776 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
777 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
778 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
779 ** version of key2 and *pbKey2Cached set to true before returning.
781 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
782 ** to SQLITE_NOMEM.
784 static int vdbeSorterCompare(
785 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
786 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
787 const void *pKey1, int nKey1, /* Left side of comparison */
788 const void *pKey2, int nKey2 /* Right side of comparison */
790 UnpackedRecord *r2 = pTask->pUnpacked;
791 if( !*pbKey2Cached ){
792 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
793 *pbKey2Cached = 1;
795 return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
799 ** A specially optimized version of vdbeSorterCompare() that assumes that
800 ** the first field of each key is a TEXT value and that the collation
801 ** sequence to compare them with is BINARY.
803 static int vdbeSorterCompareText(
804 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
805 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
806 const void *pKey1, int nKey1, /* Left side of comparison */
807 const void *pKey2, int nKey2 /* Right side of comparison */
809 const u8 * const p1 = (const u8 * const)pKey1;
810 const u8 * const p2 = (const u8 * const)pKey2;
811 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
812 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
814 int n1;
815 int n2;
816 int res;
818 getVarint32NR(&p1[1], n1);
819 getVarint32NR(&p2[1], n2);
820 res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
821 if( res==0 ){
822 res = n1 - n2;
825 if( res==0 ){
826 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
827 res = vdbeSorterCompareTail(
828 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
831 }else{
832 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
833 if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
834 res = res * -1;
838 return res;
842 ** A specially optimized version of vdbeSorterCompare() that assumes that
843 ** the first field of each key is an INTEGER value.
845 static int vdbeSorterCompareInt(
846 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
847 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
848 const void *pKey1, int nKey1, /* Left side of comparison */
849 const void *pKey2, int nKey2 /* Right side of comparison */
851 const u8 * const p1 = (const u8 * const)pKey1;
852 const u8 * const p2 = (const u8 * const)pKey2;
853 const int s1 = p1[1]; /* Left hand serial type */
854 const int s2 = p2[1]; /* Right hand serial type */
855 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
856 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
857 int res; /* Return value */
859 assert( (s1>0 && s1<7) || s1==8 || s1==9 );
860 assert( (s2>0 && s2<7) || s2==8 || s2==9 );
862 if( s1==s2 ){
863 /* The two values have the same sign. Compare using memcmp(). */
864 static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
865 const u8 n = aLen[s1];
866 int i;
867 res = 0;
868 for(i=0; i<n; i++){
869 if( (res = v1[i] - v2[i])!=0 ){
870 if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
871 res = v1[0] & 0x80 ? -1 : +1;
873 break;
876 }else if( s1>7 && s2>7 ){
877 res = s1 - s2;
878 }else{
879 if( s2>7 ){
880 res = +1;
881 }else if( s1>7 ){
882 res = -1;
883 }else{
884 res = s1 - s2;
886 assert( res!=0 );
888 if( res>0 ){
889 if( *v1 & 0x80 ) res = -1;
890 }else{
891 if( *v2 & 0x80 ) res = +1;
895 if( res==0 ){
896 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
897 res = vdbeSorterCompareTail(
898 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
901 }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
902 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
903 res = res * -1;
906 return res;
910 ** Initialize the temporary index cursor just opened as a sorter cursor.
912 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
913 ** to determine the number of fields that should be compared from the
914 ** records being sorted. However, if the value passed as argument nField
915 ** is non-zero and the sorter is able to guarantee a stable sort, nField
916 ** is used instead. This is used when sorting records for a CREATE INDEX
917 ** statement. In this case, keys are always delivered to the sorter in
918 ** order of the primary key, which happens to be make up the final part
919 ** of the records being sorted. So if the sort is stable, there is never
920 ** any reason to compare PK fields and they can be ignored for a small
921 ** performance boost.
923 ** The sorter can guarantee a stable sort when running in single-threaded
924 ** mode, but not in multi-threaded mode.
926 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
928 int sqlite3VdbeSorterInit(
929 sqlite3 *db, /* Database connection (for malloc()) */
930 int nField, /* Number of key fields in each record */
931 VdbeCursor *pCsr /* Cursor that holds the new sorter */
933 int pgsz; /* Page size of main database */
934 int i; /* Used to iterate through aTask[] */
935 VdbeSorter *pSorter; /* The new sorter */
936 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
937 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
938 int sz; /* Size of pSorter in bytes */
939 int rc = SQLITE_OK;
940 #if SQLITE_MAX_WORKER_THREADS==0
941 # define nWorker 0
942 #else
943 int nWorker;
944 #endif
946 /* Initialize the upper limit on the number of worker threads */
947 #if SQLITE_MAX_WORKER_THREADS>0
948 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
949 nWorker = 0;
950 }else{
951 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
953 #endif
955 /* Do not allow the total number of threads (main thread + all workers)
956 ** to exceed the maximum merge count */
957 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
958 if( nWorker>=SORTER_MAX_MERGE_COUNT ){
959 nWorker = SORTER_MAX_MERGE_COUNT-1;
961 #endif
963 assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
964 assert( pCsr->eCurType==CURTYPE_SORTER );
965 szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
966 sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
968 pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
969 pCsr->uc.pSorter = pSorter;
970 if( pSorter==0 ){
971 rc = SQLITE_NOMEM_BKPT;
972 }else{
973 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
974 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
975 pKeyInfo->db = 0;
976 if( nField && nWorker==0 ){
977 pKeyInfo->nKeyField = nField;
979 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
980 pSorter->nTask = nWorker + 1;
981 pSorter->iPrev = (u8)(nWorker - 1);
982 pSorter->bUseThreads = (pSorter->nTask>1);
983 pSorter->db = db;
984 for(i=0; i<pSorter->nTask; i++){
985 SortSubtask *pTask = &pSorter->aTask[i];
986 pTask->pSorter = pSorter;
989 if( !sqlite3TempInMemory(db) ){
990 i64 mxCache; /* Cache size in bytes*/
991 u32 szPma = sqlite3GlobalConfig.szPma;
992 pSorter->mnPmaSize = szPma * pgsz;
994 mxCache = db->aDb[0].pSchema->cache_size;
995 if( mxCache<0 ){
996 /* A negative cache-size value C indicates that the cache is abs(C)
997 ** KiB in size. */
998 mxCache = mxCache * -1024;
999 }else{
1000 mxCache = mxCache * pgsz;
1002 mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
1003 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
1005 /* Avoid large memory allocations if the application has requested
1006 ** SQLITE_CONFIG_SMALL_MALLOC. */
1007 if( sqlite3GlobalConfig.bSmallMalloc==0 ){
1008 assert( pSorter->iMemory==0 );
1009 pSorter->nMemory = pgsz;
1010 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
1011 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
1015 if( pKeyInfo->nAllField<13
1016 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
1017 && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
1019 pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
1023 return rc;
1025 #undef nWorker /* Defined at the top of this function */
1028 ** Free the list of sorted records starting at pRecord.
1030 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
1031 SorterRecord *p;
1032 SorterRecord *pNext;
1033 for(p=pRecord; p; p=pNext){
1034 pNext = p->u.pNext;
1035 sqlite3DbFree(db, p);
1040 ** Free all resources owned by the object indicated by argument pTask. All
1041 ** fields of *pTask are zeroed before returning.
1043 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
1044 sqlite3DbFree(db, pTask->pUnpacked);
1045 #if SQLITE_MAX_WORKER_THREADS>0
1046 /* pTask->list.aMemory can only be non-zero if it was handed memory
1047 ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
1048 if( pTask->list.aMemory ){
1049 sqlite3_free(pTask->list.aMemory);
1050 }else
1051 #endif
1053 assert( pTask->list.aMemory==0 );
1054 vdbeSorterRecordFree(0, pTask->list.pList);
1056 if( pTask->file.pFd ){
1057 sqlite3OsCloseFree(pTask->file.pFd);
1059 if( pTask->file2.pFd ){
1060 sqlite3OsCloseFree(pTask->file2.pFd);
1062 memset(pTask, 0, sizeof(SortSubtask));
1065 #ifdef SQLITE_DEBUG_SORTER_THREADS
1066 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
1067 i64 t;
1068 int iTask = (pTask - pTask->pSorter->aTask);
1069 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
1070 fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
1072 static void vdbeSorterRewindDebug(const char *zEvent){
1073 i64 t;
1074 sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
1075 fprintf(stderr, "%lld:X %s\n", t, zEvent);
1077 static void vdbeSorterPopulateDebug(
1078 SortSubtask *pTask,
1079 const char *zEvent
1081 i64 t;
1082 int iTask = (pTask - pTask->pSorter->aTask);
1083 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
1084 fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
1086 static void vdbeSorterBlockDebug(
1087 SortSubtask *pTask,
1088 int bBlocked,
1089 const char *zEvent
1091 if( bBlocked ){
1092 i64 t;
1093 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
1094 fprintf(stderr, "%lld:main %s\n", t, zEvent);
1097 #else
1098 # define vdbeSorterWorkDebug(x,y)
1099 # define vdbeSorterRewindDebug(y)
1100 # define vdbeSorterPopulateDebug(x,y)
1101 # define vdbeSorterBlockDebug(x,y,z)
1102 #endif
1104 #if SQLITE_MAX_WORKER_THREADS>0
1106 ** Join thread pTask->thread.
1108 static int vdbeSorterJoinThread(SortSubtask *pTask){
1109 int rc = SQLITE_OK;
1110 if( pTask->pThread ){
1111 #ifdef SQLITE_DEBUG_SORTER_THREADS
1112 int bDone = pTask->bDone;
1113 #endif
1114 void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
1115 vdbeSorterBlockDebug(pTask, !bDone, "enter");
1116 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
1117 vdbeSorterBlockDebug(pTask, !bDone, "exit");
1118 rc = SQLITE_PTR_TO_INT(pRet);
1119 assert( pTask->bDone==1 );
1120 pTask->bDone = 0;
1121 pTask->pThread = 0;
1123 return rc;
1127 ** Launch a background thread to run xTask(pIn).
1129 static int vdbeSorterCreateThread(
1130 SortSubtask *pTask, /* Thread will use this task object */
1131 void *(*xTask)(void*), /* Routine to run in a separate thread */
1132 void *pIn /* Argument passed into xTask() */
1134 assert( pTask->pThread==0 && pTask->bDone==0 );
1135 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
1139 ** Join all outstanding threads launched by SorterWrite() to create
1140 ** level-0 PMAs.
1142 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
1143 int rc = rcin;
1144 int i;
1146 /* This function is always called by the main user thread.
1148 ** If this function is being called after SorterRewind() has been called,
1149 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
1150 ** is currently attempt to join one of the other threads. To avoid a race
1151 ** condition where this thread also attempts to join the same object, join
1152 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
1153 for(i=pSorter->nTask-1; i>=0; i--){
1154 SortSubtask *pTask = &pSorter->aTask[i];
1155 int rc2 = vdbeSorterJoinThread(pTask);
1156 if( rc==SQLITE_OK ) rc = rc2;
1158 return rc;
1160 #else
1161 # define vdbeSorterJoinAll(x,rcin) (rcin)
1162 # define vdbeSorterJoinThread(pTask) SQLITE_OK
1163 #endif
1166 ** Allocate a new MergeEngine object capable of handling up to
1167 ** nReader PmaReader inputs.
1169 ** nReader is automatically rounded up to the next power of two.
1170 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
1172 static MergeEngine *vdbeMergeEngineNew(int nReader){
1173 int N = 2; /* Smallest power of two >= nReader */
1174 int nByte; /* Total bytes of space to allocate */
1175 MergeEngine *pNew; /* Pointer to allocated object to return */
1177 assert( nReader<=SORTER_MAX_MERGE_COUNT );
1179 while( N<nReader ) N += N;
1180 nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
1182 pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
1183 if( pNew ){
1184 pNew->nTree = N;
1185 pNew->pTask = 0;
1186 pNew->aReadr = (PmaReader*)&pNew[1];
1187 pNew->aTree = (int*)&pNew->aReadr[N];
1189 return pNew;
1193 ** Free the MergeEngine object passed as the only argument.
1195 static void vdbeMergeEngineFree(MergeEngine *pMerger){
1196 int i;
1197 if( pMerger ){
1198 for(i=0; i<pMerger->nTree; i++){
1199 vdbePmaReaderClear(&pMerger->aReadr[i]);
1202 sqlite3_free(pMerger);
1206 ** Free all resources associated with the IncrMerger object indicated by
1207 ** the first argument.
1209 static void vdbeIncrFree(IncrMerger *pIncr){
1210 if( pIncr ){
1211 #if SQLITE_MAX_WORKER_THREADS>0
1212 if( pIncr->bUseThread ){
1213 vdbeSorterJoinThread(pIncr->pTask);
1214 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
1215 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
1217 #endif
1218 vdbeMergeEngineFree(pIncr->pMerger);
1219 sqlite3_free(pIncr);
1224 ** Reset a sorting cursor back to its original empty state.
1226 void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
1227 int i;
1228 (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
1229 assert( pSorter->bUseThreads || pSorter->pReader==0 );
1230 #if SQLITE_MAX_WORKER_THREADS>0
1231 if( pSorter->pReader ){
1232 vdbePmaReaderClear(pSorter->pReader);
1233 sqlite3DbFree(db, pSorter->pReader);
1234 pSorter->pReader = 0;
1236 #endif
1237 vdbeMergeEngineFree(pSorter->pMerger);
1238 pSorter->pMerger = 0;
1239 for(i=0; i<pSorter->nTask; i++){
1240 SortSubtask *pTask = &pSorter->aTask[i];
1241 vdbeSortSubtaskCleanup(db, pTask);
1242 pTask->pSorter = pSorter;
1244 if( pSorter->list.aMemory==0 ){
1245 vdbeSorterRecordFree(0, pSorter->list.pList);
1247 pSorter->list.pList = 0;
1248 pSorter->list.szPMA = 0;
1249 pSorter->bUsePMA = 0;
1250 pSorter->iMemory = 0;
1251 pSorter->mxKeysize = 0;
1252 sqlite3DbFree(db, pSorter->pUnpacked);
1253 pSorter->pUnpacked = 0;
1257 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
1259 void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
1260 VdbeSorter *pSorter;
1261 assert( pCsr->eCurType==CURTYPE_SORTER );
1262 pSorter = pCsr->uc.pSorter;
1263 if( pSorter ){
1264 sqlite3VdbeSorterReset(db, pSorter);
1265 sqlite3_free(pSorter->list.aMemory);
1266 sqlite3DbFree(db, pSorter);
1267 pCsr->uc.pSorter = 0;
1271 #if SQLITE_MAX_MMAP_SIZE>0
1273 ** The first argument is a file-handle open on a temporary file. The file
1274 ** is guaranteed to be nByte bytes or smaller in size. This function
1275 ** attempts to extend the file to nByte bytes in size and to ensure that
1276 ** the VFS has memory mapped it.
1278 ** Whether or not the file does end up memory mapped of course depends on
1279 ** the specific VFS implementation.
1281 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
1282 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
1283 void *p = 0;
1284 int chunksize = 4*1024;
1285 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
1286 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
1287 sqlite3OsFetch(pFd, 0, (int)nByte, &p);
1288 sqlite3OsUnfetch(pFd, 0, p);
1291 #else
1292 # define vdbeSorterExtendFile(x,y,z)
1293 #endif
1296 ** Allocate space for a file-handle and open a temporary file. If successful,
1297 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
1298 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
1300 static int vdbeSorterOpenTempFile(
1301 sqlite3 *db, /* Database handle doing sort */
1302 i64 nExtend, /* Attempt to extend file to this size */
1303 sqlite3_file **ppFd
1305 int rc;
1306 if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
1307 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
1308 SQLITE_OPEN_TEMP_JOURNAL |
1309 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
1310 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
1312 if( rc==SQLITE_OK ){
1313 i64 max = SQLITE_MAX_MMAP_SIZE;
1314 sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
1315 if( nExtend>0 ){
1316 vdbeSorterExtendFile(db, *ppFd, nExtend);
1319 return rc;
1323 ** If it has not already been allocated, allocate the UnpackedRecord
1324 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
1325 ** if no allocation was required), or SQLITE_NOMEM otherwise.
1327 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
1328 if( pTask->pUnpacked==0 ){
1329 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
1330 if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
1331 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
1332 pTask->pUnpacked->errCode = 0;
1334 return SQLITE_OK;
1339 ** Merge the two sorted lists p1 and p2 into a single list.
1341 static SorterRecord *vdbeSorterMerge(
1342 SortSubtask *pTask, /* Calling thread context */
1343 SorterRecord *p1, /* First list to merge */
1344 SorterRecord *p2 /* Second list to merge */
1346 SorterRecord *pFinal = 0;
1347 SorterRecord **pp = &pFinal;
1348 int bCached = 0;
1350 assert( p1!=0 && p2!=0 );
1351 for(;;){
1352 int res;
1353 res = pTask->xCompare(
1354 pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
1357 if( res<=0 ){
1358 *pp = p1;
1359 pp = &p1->u.pNext;
1360 p1 = p1->u.pNext;
1361 if( p1==0 ){
1362 *pp = p2;
1363 break;
1365 }else{
1366 *pp = p2;
1367 pp = &p2->u.pNext;
1368 p2 = p2->u.pNext;
1369 bCached = 0;
1370 if( p2==0 ){
1371 *pp = p1;
1372 break;
1376 return pFinal;
1380 ** Return the SorterCompare function to compare values collected by the
1381 ** sorter object passed as the only argument.
1383 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
1384 if( p->typeMask==SORTER_TYPE_INTEGER ){
1385 return vdbeSorterCompareInt;
1386 }else if( p->typeMask==SORTER_TYPE_TEXT ){
1387 return vdbeSorterCompareText;
1389 return vdbeSorterCompare;
1393 ** Sort the linked list of records headed at pTask->pList. Return
1394 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
1395 ** an error occurs.
1397 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
1398 int i;
1399 SorterRecord *p;
1400 int rc;
1401 SorterRecord *aSlot[64];
1403 rc = vdbeSortAllocUnpacked(pTask);
1404 if( rc!=SQLITE_OK ) return rc;
1406 p = pList->pList;
1407 pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
1408 memset(aSlot, 0, sizeof(aSlot));
1410 while( p ){
1411 SorterRecord *pNext;
1412 if( pList->aMemory ){
1413 if( (u8*)p==pList->aMemory ){
1414 pNext = 0;
1415 }else{
1416 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
1417 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
1419 }else{
1420 pNext = p->u.pNext;
1423 p->u.pNext = 0;
1424 for(i=0; aSlot[i]; i++){
1425 p = vdbeSorterMerge(pTask, p, aSlot[i]);
1426 aSlot[i] = 0;
1428 aSlot[i] = p;
1429 p = pNext;
1432 p = 0;
1433 for(i=0; i<ArraySize(aSlot); i++){
1434 if( aSlot[i]==0 ) continue;
1435 p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
1437 pList->pList = p;
1439 assert( pTask->pUnpacked->errCode==SQLITE_OK
1440 || pTask->pUnpacked->errCode==SQLITE_NOMEM
1442 return pTask->pUnpacked->errCode;
1446 ** Initialize a PMA-writer object.
1448 static void vdbePmaWriterInit(
1449 sqlite3_file *pFd, /* File handle to write to */
1450 PmaWriter *p, /* Object to populate */
1451 int nBuf, /* Buffer size */
1452 i64 iStart /* Offset of pFd to begin writing at */
1454 memset(p, 0, sizeof(PmaWriter));
1455 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
1456 if( !p->aBuffer ){
1457 p->eFWErr = SQLITE_NOMEM_BKPT;
1458 }else{
1459 p->iBufEnd = p->iBufStart = (iStart % nBuf);
1460 p->iWriteOff = iStart - p->iBufStart;
1461 p->nBuffer = nBuf;
1462 p->pFd = pFd;
1467 ** Write nData bytes of data to the PMA. Return SQLITE_OK
1468 ** if successful, or an SQLite error code if an error occurs.
1470 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
1471 int nRem = nData;
1472 while( nRem>0 && p->eFWErr==0 ){
1473 int nCopy = nRem;
1474 if( nCopy>(p->nBuffer - p->iBufEnd) ){
1475 nCopy = p->nBuffer - p->iBufEnd;
1478 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
1479 p->iBufEnd += nCopy;
1480 if( p->iBufEnd==p->nBuffer ){
1481 p->eFWErr = sqlite3OsWrite(p->pFd,
1482 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
1483 p->iWriteOff + p->iBufStart
1485 p->iBufStart = p->iBufEnd = 0;
1486 p->iWriteOff += p->nBuffer;
1488 assert( p->iBufEnd<p->nBuffer );
1490 nRem -= nCopy;
1495 ** Flush any buffered data to disk and clean up the PMA-writer object.
1496 ** The results of using the PMA-writer after this call are undefined.
1497 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
1498 ** required. Otherwise, return an SQLite error code.
1500 ** Before returning, set *piEof to the offset immediately following the
1501 ** last byte written to the file.
1503 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
1504 int rc;
1505 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
1506 p->eFWErr = sqlite3OsWrite(p->pFd,
1507 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
1508 p->iWriteOff + p->iBufStart
1511 *piEof = (p->iWriteOff + p->iBufEnd);
1512 sqlite3_free(p->aBuffer);
1513 rc = p->eFWErr;
1514 memset(p, 0, sizeof(PmaWriter));
1515 return rc;
1519 ** Write value iVal encoded as a varint to the PMA. Return
1520 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
1522 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
1523 int nByte;
1524 u8 aByte[10];
1525 nByte = sqlite3PutVarint(aByte, iVal);
1526 vdbePmaWriteBlob(p, aByte, nByte);
1530 ** Write the current contents of in-memory linked-list pList to a level-0
1531 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
1532 ** successful, or an SQLite error code otherwise.
1534 ** The format of a PMA is:
1536 ** * A varint. This varint contains the total number of bytes of content
1537 ** in the PMA (not including the varint itself).
1539 ** * One or more records packed end-to-end in order of ascending keys.
1540 ** Each record consists of a varint followed by a blob of data (the
1541 ** key). The varint is the number of bytes in the blob of data.
1543 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
1544 sqlite3 *db = pTask->pSorter->db;
1545 int rc = SQLITE_OK; /* Return code */
1546 PmaWriter writer; /* Object used to write to the file */
1548 #ifdef SQLITE_DEBUG
1549 /* Set iSz to the expected size of file pTask->file after writing the PMA.
1550 ** This is used by an assert() statement at the end of this function. */
1551 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
1552 #endif
1554 vdbeSorterWorkDebug(pTask, "enter");
1555 memset(&writer, 0, sizeof(PmaWriter));
1556 assert( pList->szPMA>0 );
1558 /* If the first temporary PMA file has not been opened, open it now. */
1559 if( pTask->file.pFd==0 ){
1560 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
1561 assert( rc!=SQLITE_OK || pTask->file.pFd );
1562 assert( pTask->file.iEof==0 );
1563 assert( pTask->nPMA==0 );
1566 /* Try to get the file to memory map */
1567 if( rc==SQLITE_OK ){
1568 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
1571 /* Sort the list */
1572 if( rc==SQLITE_OK ){
1573 rc = vdbeSorterSort(pTask, pList);
1576 if( rc==SQLITE_OK ){
1577 SorterRecord *p;
1578 SorterRecord *pNext = 0;
1580 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
1581 pTask->file.iEof);
1582 pTask->nPMA++;
1583 vdbePmaWriteVarint(&writer, pList->szPMA);
1584 for(p=pList->pList; p; p=pNext){
1585 pNext = p->u.pNext;
1586 vdbePmaWriteVarint(&writer, p->nVal);
1587 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
1588 if( pList->aMemory==0 ) sqlite3_free(p);
1590 pList->pList = p;
1591 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
1594 vdbeSorterWorkDebug(pTask, "exit");
1595 assert( rc!=SQLITE_OK || pList->pList==0 );
1596 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
1597 return rc;
1601 ** Advance the MergeEngine to its next entry.
1602 ** Set *pbEof to true there is no next entry because
1603 ** the MergeEngine has reached the end of all its inputs.
1605 ** Return SQLITE_OK if successful or an error code if an error occurs.
1607 static int vdbeMergeEngineStep(
1608 MergeEngine *pMerger, /* The merge engine to advance to the next row */
1609 int *pbEof /* Set TRUE at EOF. Set false for more content */
1611 int rc;
1612 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
1613 SortSubtask *pTask = pMerger->pTask;
1615 /* Advance the current PmaReader */
1616 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
1618 /* Update contents of aTree[] */
1619 if( rc==SQLITE_OK ){
1620 int i; /* Index of aTree[] to recalculate */
1621 PmaReader *pReadr1; /* First PmaReader to compare */
1622 PmaReader *pReadr2; /* Second PmaReader to compare */
1623 int bCached = 0;
1625 /* Find the first two PmaReaders to compare. The one that was just
1626 ** advanced (iPrev) and the one next to it in the array. */
1627 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
1628 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
1630 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
1631 /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
1632 int iRes;
1633 if( pReadr1->pFd==0 ){
1634 iRes = +1;
1635 }else if( pReadr2->pFd==0 ){
1636 iRes = -1;
1637 }else{
1638 iRes = pTask->xCompare(pTask, &bCached,
1639 pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
1643 /* If pReadr1 contained the smaller value, set aTree[i] to its index.
1644 ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
1645 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
1646 ** pKey2 to point to the record belonging to pReadr2.
1648 ** Alternatively, if pReadr2 contains the smaller of the two values,
1649 ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
1650 ** was actually called above, then pTask->pUnpacked now contains
1651 ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
1652 ** vdbeSorterCompare() from decoding pReadr2 again.
1654 ** If the two values were equal, then the value from the oldest
1655 ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
1656 ** is sorted from oldest to newest, so pReadr1 contains older values
1657 ** than pReadr2 iff (pReadr1<pReadr2). */
1658 if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
1659 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
1660 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
1661 bCached = 0;
1662 }else{
1663 if( pReadr1->pFd ) bCached = 0;
1664 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
1665 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
1668 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
1671 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
1674 #if SQLITE_MAX_WORKER_THREADS>0
1676 ** The main routine for background threads that write level-0 PMAs.
1678 static void *vdbeSorterFlushThread(void *pCtx){
1679 SortSubtask *pTask = (SortSubtask*)pCtx;
1680 int rc; /* Return code */
1681 assert( pTask->bDone==0 );
1682 rc = vdbeSorterListToPMA(pTask, &pTask->list);
1683 pTask->bDone = 1;
1684 return SQLITE_INT_TO_PTR(rc);
1686 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
1689 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
1690 ** using a background thread.
1692 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
1693 #if SQLITE_MAX_WORKER_THREADS==0
1694 pSorter->bUsePMA = 1;
1695 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
1696 #else
1697 int rc = SQLITE_OK;
1698 int i;
1699 SortSubtask *pTask = 0; /* Thread context used to create new PMA */
1700 int nWorker = (pSorter->nTask-1);
1702 /* Set the flag to indicate that at least one PMA has been written.
1703 ** Or will be, anyhow. */
1704 pSorter->bUsePMA = 1;
1706 /* Select a sub-task to sort and flush the current list of in-memory
1707 ** records to disk. If the sorter is running in multi-threaded mode,
1708 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
1709 ** the background thread from a sub-tasks previous turn is still running,
1710 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
1711 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
1712 ** sub-tasks are prefered as they use background threads - the final
1713 ** sub-task uses the main thread. */
1714 for(i=0; i<nWorker; i++){
1715 int iTest = (pSorter->iPrev + i + 1) % nWorker;
1716 pTask = &pSorter->aTask[iTest];
1717 if( pTask->bDone ){
1718 rc = vdbeSorterJoinThread(pTask);
1720 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
1723 if( rc==SQLITE_OK ){
1724 if( i==nWorker ){
1725 /* Use the foreground thread for this operation */
1726 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
1727 }else{
1728 /* Launch a background thread for this operation */
1729 u8 *aMem;
1730 void *pCtx;
1732 assert( pTask!=0 );
1733 assert( pTask->pThread==0 && pTask->bDone==0 );
1734 assert( pTask->list.pList==0 );
1735 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
1737 aMem = pTask->list.aMemory;
1738 pCtx = (void*)pTask;
1739 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
1740 pTask->list = pSorter->list;
1741 pSorter->list.pList = 0;
1742 pSorter->list.szPMA = 0;
1743 if( aMem ){
1744 pSorter->list.aMemory = aMem;
1745 pSorter->nMemory = sqlite3MallocSize(aMem);
1746 }else if( pSorter->list.aMemory ){
1747 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
1748 if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
1751 rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
1755 return rc;
1756 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
1760 ** Add a record to the sorter.
1762 int sqlite3VdbeSorterWrite(
1763 const VdbeCursor *pCsr, /* Sorter cursor */
1764 Mem *pVal /* Memory cell containing record */
1766 VdbeSorter *pSorter;
1767 int rc = SQLITE_OK; /* Return Code */
1768 SorterRecord *pNew; /* New list element */
1769 int bFlush; /* True to flush contents of memory to PMA */
1770 int nReq; /* Bytes of memory required */
1771 int nPMA; /* Bytes of PMA space required */
1772 int t; /* serial type of first record field */
1774 assert( pCsr->eCurType==CURTYPE_SORTER );
1775 pSorter = pCsr->uc.pSorter;
1776 getVarint32NR((const u8*)&pVal->z[1], t);
1777 if( t>0 && t<10 && t!=7 ){
1778 pSorter->typeMask &= SORTER_TYPE_INTEGER;
1779 }else if( t>10 && (t & 0x01) ){
1780 pSorter->typeMask &= SORTER_TYPE_TEXT;
1781 }else{
1782 pSorter->typeMask = 0;
1785 assert( pSorter );
1787 /* Figure out whether or not the current contents of memory should be
1788 ** flushed to a PMA before continuing. If so, do so.
1790 ** If using the single large allocation mode (pSorter->aMemory!=0), then
1791 ** flush the contents of memory to a new PMA if (a) at least one value is
1792 ** already in memory and (b) the new value will not fit in memory.
1794 ** Or, if using separate allocations for each record, flush the contents
1795 ** of memory to a PMA if either of the following are true:
1797 ** * The total memory allocated for the in-memory list is greater
1798 ** than (page-size * cache-size), or
1800 ** * The total memory allocated for the in-memory list is greater
1801 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
1803 nReq = pVal->n + sizeof(SorterRecord);
1804 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
1805 if( pSorter->mxPmaSize ){
1806 if( pSorter->list.aMemory ){
1807 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
1808 }else{
1809 bFlush = (
1810 (pSorter->list.szPMA > pSorter->mxPmaSize)
1811 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
1814 if( bFlush ){
1815 rc = vdbeSorterFlushPMA(pSorter);
1816 pSorter->list.szPMA = 0;
1817 pSorter->iMemory = 0;
1818 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
1822 pSorter->list.szPMA += nPMA;
1823 if( nPMA>pSorter->mxKeysize ){
1824 pSorter->mxKeysize = nPMA;
1827 if( pSorter->list.aMemory ){
1828 int nMin = pSorter->iMemory + nReq;
1830 if( nMin>pSorter->nMemory ){
1831 u8 *aNew;
1832 sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
1833 int iListOff = -1;
1834 if( pSorter->list.pList ){
1835 iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
1837 while( nNew < nMin ) nNew = nNew*2;
1838 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
1839 if( nNew < nMin ) nNew = nMin;
1840 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
1841 if( !aNew ) return SQLITE_NOMEM_BKPT;
1842 if( iListOff>=0 ){
1843 pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
1845 pSorter->list.aMemory = aNew;
1846 pSorter->nMemory = nNew;
1849 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
1850 pSorter->iMemory += ROUND8(nReq);
1851 if( pSorter->list.pList ){
1852 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
1854 }else{
1855 pNew = (SorterRecord *)sqlite3Malloc(nReq);
1856 if( pNew==0 ){
1857 return SQLITE_NOMEM_BKPT;
1859 pNew->u.pNext = pSorter->list.pList;
1862 memcpy(SRVAL(pNew), pVal->z, pVal->n);
1863 pNew->nVal = pVal->n;
1864 pSorter->list.pList = pNew;
1866 return rc;
1870 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
1871 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
1872 ** except that the number-of-bytes varint is omitted from the start.
1874 static int vdbeIncrPopulate(IncrMerger *pIncr){
1875 int rc = SQLITE_OK;
1876 int rc2;
1877 i64 iStart = pIncr->iStartOff;
1878 SorterFile *pOut = &pIncr->aFile[1];
1879 SortSubtask *pTask = pIncr->pTask;
1880 MergeEngine *pMerger = pIncr->pMerger;
1881 PmaWriter writer;
1882 assert( pIncr->bEof==0 );
1884 vdbeSorterPopulateDebug(pTask, "enter");
1886 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
1887 while( rc==SQLITE_OK ){
1888 int dummy;
1889 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
1890 int nKey = pReader->nKey;
1891 i64 iEof = writer.iWriteOff + writer.iBufEnd;
1893 /* Check if the output file is full or if the input has been exhausted.
1894 ** In either case exit the loop. */
1895 if( pReader->pFd==0 ) break;
1896 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
1898 /* Write the next key to the output. */
1899 vdbePmaWriteVarint(&writer, nKey);
1900 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
1901 assert( pIncr->pMerger->pTask==pTask );
1902 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
1905 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
1906 if( rc==SQLITE_OK ) rc = rc2;
1907 vdbeSorterPopulateDebug(pTask, "exit");
1908 return rc;
1911 #if SQLITE_MAX_WORKER_THREADS>0
1913 ** The main routine for background threads that populate aFile[1] of
1914 ** multi-threaded IncrMerger objects.
1916 static void *vdbeIncrPopulateThread(void *pCtx){
1917 IncrMerger *pIncr = (IncrMerger*)pCtx;
1918 void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
1919 pIncr->pTask->bDone = 1;
1920 return pRet;
1924 ** Launch a background thread to populate aFile[1] of pIncr.
1926 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
1927 void *p = (void*)pIncr;
1928 assert( pIncr->bUseThread );
1929 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
1931 #endif
1934 ** This function is called when the PmaReader corresponding to pIncr has
1935 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
1936 ** aFile[0] such that the PmaReader should start rereading it from the
1937 ** beginning.
1939 ** For single-threaded objects, this is accomplished by literally reading
1940 ** keys from pIncr->pMerger and repopulating aFile[0].
1942 ** For multi-threaded objects, all that is required is to wait until the
1943 ** background thread is finished (if it is not already) and then swap
1944 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
1945 ** been exhausted, this function also launches a new background thread
1946 ** to populate the new aFile[1].
1948 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
1950 static int vdbeIncrSwap(IncrMerger *pIncr){
1951 int rc = SQLITE_OK;
1953 #if SQLITE_MAX_WORKER_THREADS>0
1954 if( pIncr->bUseThread ){
1955 rc = vdbeSorterJoinThread(pIncr->pTask);
1957 if( rc==SQLITE_OK ){
1958 SorterFile f0 = pIncr->aFile[0];
1959 pIncr->aFile[0] = pIncr->aFile[1];
1960 pIncr->aFile[1] = f0;
1963 if( rc==SQLITE_OK ){
1964 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
1965 pIncr->bEof = 1;
1966 }else{
1967 rc = vdbeIncrBgPopulate(pIncr);
1970 }else
1971 #endif
1973 rc = vdbeIncrPopulate(pIncr);
1974 pIncr->aFile[0] = pIncr->aFile[1];
1975 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
1976 pIncr->bEof = 1;
1980 return rc;
1984 ** Allocate and return a new IncrMerger object to read data from pMerger.
1986 ** If an OOM condition is encountered, return NULL. In this case free the
1987 ** pMerger argument before returning.
1989 static int vdbeIncrMergerNew(
1990 SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
1991 MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
1992 IncrMerger **ppOut /* Write the new IncrMerger here */
1994 int rc = SQLITE_OK;
1995 IncrMerger *pIncr = *ppOut = (IncrMerger*)
1996 (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
1997 if( pIncr ){
1998 pIncr->pMerger = pMerger;
1999 pIncr->pTask = pTask;
2000 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
2001 pTask->file2.iEof += pIncr->mxSz;
2002 }else{
2003 vdbeMergeEngineFree(pMerger);
2004 rc = SQLITE_NOMEM_BKPT;
2006 return rc;
2009 #if SQLITE_MAX_WORKER_THREADS>0
2011 ** Set the "use-threads" flag on object pIncr.
2013 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
2014 pIncr->bUseThread = 1;
2015 pIncr->pTask->file2.iEof -= pIncr->mxSz;
2017 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
2022 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
2023 ** two PmaReaders that feed that entry. Neither of the PmaReaders
2024 ** are advanced. This routine merely does the comparison.
2026 static void vdbeMergeEngineCompare(
2027 MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
2028 int iOut /* Store the result in pMerger->aTree[iOut] */
2030 int i1;
2031 int i2;
2032 int iRes;
2033 PmaReader *p1;
2034 PmaReader *p2;
2036 assert( iOut<pMerger->nTree && iOut>0 );
2038 if( iOut>=(pMerger->nTree/2) ){
2039 i1 = (iOut - pMerger->nTree/2) * 2;
2040 i2 = i1 + 1;
2041 }else{
2042 i1 = pMerger->aTree[iOut*2];
2043 i2 = pMerger->aTree[iOut*2+1];
2046 p1 = &pMerger->aReadr[i1];
2047 p2 = &pMerger->aReadr[i2];
2049 if( p1->pFd==0 ){
2050 iRes = i2;
2051 }else if( p2->pFd==0 ){
2052 iRes = i1;
2053 }else{
2054 SortSubtask *pTask = pMerger->pTask;
2055 int bCached = 0;
2056 int res;
2057 assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
2058 res = pTask->xCompare(
2059 pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
2061 if( res<=0 ){
2062 iRes = i1;
2063 }else{
2064 iRes = i2;
2068 pMerger->aTree[iOut] = iRes;
2072 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
2073 ** and vdbePmaReaderIncrMergeInit().
2075 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
2076 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
2077 ** when there exists one or more separate worker threads.
2079 #define INCRINIT_NORMAL 0
2080 #define INCRINIT_TASK 1
2081 #define INCRINIT_ROOT 2
2084 ** Forward reference required as the vdbeIncrMergeInit() and
2085 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
2086 ** building a merge tree.
2088 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
2091 ** Initialize the MergeEngine object passed as the second argument. Once this
2092 ** function returns, the first key of merged data may be read from the
2093 ** MergeEngine object in the usual fashion.
2095 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
2096 ** objects attached to the PmaReader objects that the merger reads from have
2097 ** already been populated, but that they have not yet populated aFile[0] and
2098 ** set the PmaReader objects up to read from it. In this case all that is
2099 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
2100 ** its first key.
2102 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
2103 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
2104 ** to pMerger.
2106 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
2108 static int vdbeMergeEngineInit(
2109 SortSubtask *pTask, /* Thread that will run pMerger */
2110 MergeEngine *pMerger, /* MergeEngine to initialize */
2111 int eMode /* One of the INCRINIT_XXX constants */
2113 int rc = SQLITE_OK; /* Return code */
2114 int i; /* For looping over PmaReader objects */
2115 int nTree; /* Number of subtrees to merge */
2117 /* Failure to allocate the merge would have been detected prior to
2118 ** invoking this routine */
2119 assert( pMerger!=0 );
2121 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
2122 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
2124 /* Verify that the MergeEngine is assigned to a single thread */
2125 assert( pMerger->pTask==0 );
2126 pMerger->pTask = pTask;
2128 nTree = pMerger->nTree;
2129 for(i=0; i<nTree; i++){
2130 if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
2131 /* PmaReaders should be normally initialized in order, as if they are
2132 ** reading from the same temp file this makes for more linear file IO.
2133 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
2134 ** in use it will block the vdbePmaReaderNext() call while it uses
2135 ** the main thread to fill its buffer. So calling PmaReaderNext()
2136 ** on this PmaReader before any of the multi-threaded PmaReaders takes
2137 ** better advantage of multi-processor hardware. */
2138 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
2139 }else{
2140 rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
2142 if( rc!=SQLITE_OK ) return rc;
2145 for(i=pMerger->nTree-1; i>0; i--){
2146 vdbeMergeEngineCompare(pMerger, i);
2148 return pTask->pUnpacked->errCode;
2152 ** The PmaReader passed as the first argument is guaranteed to be an
2153 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
2154 ** and/or initialize the temp file related fields of the IncrMerge
2155 ** object at (pReadr->pIncr).
2157 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
2158 ** in the sub-tree headed by pReadr are also initialized. Data is then
2159 ** loaded into the buffers belonging to pReadr and it is set to point to
2160 ** the first key in its range.
2162 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
2163 ** to be a multi-threaded PmaReader and this function is being called in a
2164 ** background thread. In this case all PmaReaders in the sub-tree are
2165 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
2166 ** pReadr is populated. However, pReadr itself is not set up to point
2167 ** to its first key. A call to vdbePmaReaderNext() is still required to do
2168 ** that.
2170 ** The reason this function does not call vdbePmaReaderNext() immediately
2171 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
2172 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
2173 ** this entire function is being run by thread (pTask->thread), that will
2174 ** lead to the current background thread attempting to join itself.
2176 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
2177 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
2178 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
2179 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
2180 ** the current PmaReader set to point to the first key in its range.
2182 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
2184 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
2185 int rc = SQLITE_OK;
2186 IncrMerger *pIncr = pReadr->pIncr;
2187 SortSubtask *pTask = pIncr->pTask;
2188 sqlite3 *db = pTask->pSorter->db;
2190 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
2191 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
2193 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
2195 /* Set up the required files for pIncr. A multi-theaded IncrMerge object
2196 ** requires two temp files to itself, whereas a single-threaded object
2197 ** only requires a region of pTask->file2. */
2198 if( rc==SQLITE_OK ){
2199 int mxSz = pIncr->mxSz;
2200 #if SQLITE_MAX_WORKER_THREADS>0
2201 if( pIncr->bUseThread ){
2202 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
2203 if( rc==SQLITE_OK ){
2204 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
2206 }else
2207 #endif
2208 /*if( !pIncr->bUseThread )*/{
2209 if( pTask->file2.pFd==0 ){
2210 assert( pTask->file2.iEof>0 );
2211 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
2212 pTask->file2.iEof = 0;
2214 if( rc==SQLITE_OK ){
2215 pIncr->aFile[1].pFd = pTask->file2.pFd;
2216 pIncr->iStartOff = pTask->file2.iEof;
2217 pTask->file2.iEof += mxSz;
2222 #if SQLITE_MAX_WORKER_THREADS>0
2223 if( rc==SQLITE_OK && pIncr->bUseThread ){
2224 /* Use the current thread to populate aFile[1], even though this
2225 ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
2226 ** then this function is already running in background thread
2227 ** pIncr->pTask->thread.
2229 ** If this is the INCRINIT_ROOT object, then it is running in the
2230 ** main VDBE thread. But that is Ok, as that thread cannot return
2231 ** control to the VDBE or proceed with anything useful until the
2232 ** first results are ready from this merger object anyway.
2234 assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
2235 rc = vdbeIncrPopulate(pIncr);
2237 #endif
2239 if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
2240 rc = vdbePmaReaderNext(pReadr);
2243 return rc;
2246 #if SQLITE_MAX_WORKER_THREADS>0
2248 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
2249 ** background threads.
2251 static void *vdbePmaReaderBgIncrInit(void *pCtx){
2252 PmaReader *pReader = (PmaReader*)pCtx;
2253 void *pRet = SQLITE_INT_TO_PTR(
2254 vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
2256 pReader->pIncr->pTask->bDone = 1;
2257 return pRet;
2259 #endif
2262 ** If the PmaReader passed as the first argument is not an incremental-reader
2263 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
2264 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
2265 ** this routine to initialize the incremental merge.
2267 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
2268 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
2269 ** Or, if the IncrMerger is single threaded, the same function is called
2270 ** using the current thread.
2272 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
2273 IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
2274 int rc = SQLITE_OK; /* Return code */
2275 if( pIncr ){
2276 #if SQLITE_MAX_WORKER_THREADS>0
2277 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
2278 if( pIncr->bUseThread ){
2279 void *pCtx = (void*)pReadr;
2280 rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
2281 }else
2282 #endif
2284 rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
2287 return rc;
2291 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
2292 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
2293 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
2294 ** to NULL and return an SQLite error code.
2296 ** When this function is called, *piOffset is set to the offset of the
2297 ** first PMA to read from pTask->file. Assuming no error occurs, it is
2298 ** set to the offset immediately following the last byte of the last
2299 ** PMA before returning. If an error does occur, then the final value of
2300 ** *piOffset is undefined.
2302 static int vdbeMergeEngineLevel0(
2303 SortSubtask *pTask, /* Sorter task to read from */
2304 int nPMA, /* Number of PMAs to read */
2305 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
2306 MergeEngine **ppOut /* OUT: New merge-engine */
2308 MergeEngine *pNew; /* Merge engine to return */
2309 i64 iOff = *piOffset;
2310 int i;
2311 int rc = SQLITE_OK;
2313 *ppOut = pNew = vdbeMergeEngineNew(nPMA);
2314 if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
2316 for(i=0; i<nPMA && rc==SQLITE_OK; i++){
2317 i64 nDummy = 0;
2318 PmaReader *pReadr = &pNew->aReadr[i];
2319 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
2320 iOff = pReadr->iEof;
2323 if( rc!=SQLITE_OK ){
2324 vdbeMergeEngineFree(pNew);
2325 *ppOut = 0;
2327 *piOffset = iOff;
2328 return rc;
2332 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
2333 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
2335 ** i.e.
2337 ** nPMA<=16 -> TreeDepth() == 0
2338 ** nPMA<=256 -> TreeDepth() == 1
2339 ** nPMA<=65536 -> TreeDepth() == 2
2341 static int vdbeSorterTreeDepth(int nPMA){
2342 int nDepth = 0;
2343 i64 nDiv = SORTER_MAX_MERGE_COUNT;
2344 while( nDiv < (i64)nPMA ){
2345 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
2346 nDepth++;
2348 return nDepth;
2352 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
2353 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
2354 ** tree, counting from zero. This function adds pLeaf to the tree.
2356 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
2357 ** code is returned and pLeaf is freed.
2359 static int vdbeSorterAddToTree(
2360 SortSubtask *pTask, /* Task context */
2361 int nDepth, /* Depth of tree according to TreeDepth() */
2362 int iSeq, /* Sequence number of leaf within tree */
2363 MergeEngine *pRoot, /* Root of tree */
2364 MergeEngine *pLeaf /* Leaf to add to tree */
2366 int rc = SQLITE_OK;
2367 int nDiv = 1;
2368 int i;
2369 MergeEngine *p = pRoot;
2370 IncrMerger *pIncr;
2372 rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
2374 for(i=1; i<nDepth; i++){
2375 nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
2378 for(i=1; i<nDepth && rc==SQLITE_OK; i++){
2379 int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
2380 PmaReader *pReadr = &p->aReadr[iIter];
2382 if( pReadr->pIncr==0 ){
2383 MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
2384 if( pNew==0 ){
2385 rc = SQLITE_NOMEM_BKPT;
2386 }else{
2387 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
2390 if( rc==SQLITE_OK ){
2391 p = pReadr->pIncr->pMerger;
2392 nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
2396 if( rc==SQLITE_OK ){
2397 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
2398 }else{
2399 vdbeIncrFree(pIncr);
2401 return rc;
2405 ** This function is called as part of a SorterRewind() operation on a sorter
2406 ** that has already written two or more level-0 PMAs to one or more temp
2407 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
2408 ** can be used to incrementally merge all PMAs on disk.
2410 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
2411 ** MergeEngine object at the root of the tree before returning. Or, if an
2412 ** error occurs, an SQLite error code is returned and the final value
2413 ** of *ppOut is undefined.
2415 static int vdbeSorterMergeTreeBuild(
2416 VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
2417 MergeEngine **ppOut /* Write the MergeEngine here */
2419 MergeEngine *pMain = 0;
2420 int rc = SQLITE_OK;
2421 int iTask;
2423 #if SQLITE_MAX_WORKER_THREADS>0
2424 /* If the sorter uses more than one task, then create the top-level
2425 ** MergeEngine here. This MergeEngine will read data from exactly
2426 ** one PmaReader per sub-task. */
2427 assert( pSorter->bUseThreads || pSorter->nTask==1 );
2428 if( pSorter->nTask>1 ){
2429 pMain = vdbeMergeEngineNew(pSorter->nTask);
2430 if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
2432 #endif
2434 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
2435 SortSubtask *pTask = &pSorter->aTask[iTask];
2436 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
2437 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
2438 MergeEngine *pRoot = 0; /* Root node of tree for this task */
2439 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
2440 i64 iReadOff = 0;
2442 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
2443 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
2444 }else{
2445 int i;
2446 int iSeq = 0;
2447 pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
2448 if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
2449 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
2450 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
2451 int nReader; /* Number of level-0 PMAs to merge */
2453 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
2454 rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
2455 if( rc==SQLITE_OK ){
2456 rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
2461 if( rc==SQLITE_OK ){
2462 #if SQLITE_MAX_WORKER_THREADS>0
2463 if( pMain!=0 ){
2464 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
2465 }else
2466 #endif
2468 assert( pMain==0 );
2469 pMain = pRoot;
2471 }else{
2472 vdbeMergeEngineFree(pRoot);
2477 if( rc!=SQLITE_OK ){
2478 vdbeMergeEngineFree(pMain);
2479 pMain = 0;
2481 *ppOut = pMain;
2482 return rc;
2486 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
2487 ** on a sorter that has written two or more PMAs to temporary files. It sets
2488 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
2489 ** (for multi-threaded sorters) so that it can be used to iterate through
2490 ** all records stored in the sorter.
2492 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
2494 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
2495 int rc; /* Return code */
2496 SortSubtask *pTask0 = &pSorter->aTask[0];
2497 MergeEngine *pMain = 0;
2498 #if SQLITE_MAX_WORKER_THREADS
2499 sqlite3 *db = pTask0->pSorter->db;
2500 int i;
2501 SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
2502 for(i=0; i<pSorter->nTask; i++){
2503 pSorter->aTask[i].xCompare = xCompare;
2505 #endif
2507 rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
2508 if( rc==SQLITE_OK ){
2509 #if SQLITE_MAX_WORKER_THREADS
2510 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
2511 if( pSorter->bUseThreads ){
2512 int iTask;
2513 PmaReader *pReadr = 0;
2514 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
2515 rc = vdbeSortAllocUnpacked(pLast);
2516 if( rc==SQLITE_OK ){
2517 pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
2518 pSorter->pReader = pReadr;
2519 if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
2521 if( rc==SQLITE_OK ){
2522 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
2523 if( rc==SQLITE_OK ){
2524 vdbeIncrMergerSetThreads(pReadr->pIncr);
2525 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
2526 IncrMerger *pIncr;
2527 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
2528 vdbeIncrMergerSetThreads(pIncr);
2529 assert( pIncr->pTask!=pLast );
2532 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
2533 /* Check that:
2535 ** a) The incremental merge object is configured to use the
2536 ** right task, and
2537 ** b) If it is using task (nTask-1), it is configured to run
2538 ** in single-threaded mode. This is important, as the
2539 ** root merge (INCRINIT_ROOT) will be using the same task
2540 ** object.
2542 PmaReader *p = &pMain->aReadr[iTask];
2543 assert( p->pIncr==0 || (
2544 (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
2545 && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
2547 rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
2550 pMain = 0;
2552 if( rc==SQLITE_OK ){
2553 rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
2555 }else
2556 #endif
2558 rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
2559 pSorter->pMerger = pMain;
2560 pMain = 0;
2564 if( rc!=SQLITE_OK ){
2565 vdbeMergeEngineFree(pMain);
2567 return rc;
2572 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
2573 ** this function is called to prepare for iterating through the records
2574 ** in sorted order.
2576 int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
2577 VdbeSorter *pSorter;
2578 int rc = SQLITE_OK; /* Return code */
2580 assert( pCsr->eCurType==CURTYPE_SORTER );
2581 pSorter = pCsr->uc.pSorter;
2582 assert( pSorter );
2584 /* If no data has been written to disk, then do not do so now. Instead,
2585 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
2586 ** from the in-memory list. */
2587 if( pSorter->bUsePMA==0 ){
2588 if( pSorter->list.pList ){
2589 *pbEof = 0;
2590 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
2591 }else{
2592 *pbEof = 1;
2594 return rc;
2597 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
2598 ** function flushes the contents of memory to disk, it immediately always
2599 ** creates a new list consisting of a single key immediately afterwards.
2600 ** So the list is never empty at this point. */
2601 assert( pSorter->list.pList );
2602 rc = vdbeSorterFlushPMA(pSorter);
2604 /* Join all threads */
2605 rc = vdbeSorterJoinAll(pSorter, rc);
2607 vdbeSorterRewindDebug("rewind");
2609 /* Assuming no errors have occurred, set up a merger structure to
2610 ** incrementally read and merge all remaining PMAs. */
2611 assert( pSorter->pReader==0 );
2612 if( rc==SQLITE_OK ){
2613 rc = vdbeSorterSetupMerge(pSorter);
2614 *pbEof = 0;
2617 vdbeSorterRewindDebug("rewinddone");
2618 return rc;
2622 ** Advance to the next element in the sorter. Return value:
2624 ** SQLITE_OK success
2625 ** SQLITE_DONE end of data
2626 ** otherwise some kind of error.
2628 int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
2629 VdbeSorter *pSorter;
2630 int rc; /* Return code */
2632 assert( pCsr->eCurType==CURTYPE_SORTER );
2633 pSorter = pCsr->uc.pSorter;
2634 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
2635 if( pSorter->bUsePMA ){
2636 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
2637 assert( pSorter->bUseThreads==0 || pSorter->pReader );
2638 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
2639 #if SQLITE_MAX_WORKER_THREADS>0
2640 if( pSorter->bUseThreads ){
2641 rc = vdbePmaReaderNext(pSorter->pReader);
2642 if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
2643 }else
2644 #endif
2645 /*if( !pSorter->bUseThreads )*/ {
2646 int res = 0;
2647 assert( pSorter->pMerger!=0 );
2648 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
2649 rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
2650 if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
2652 }else{
2653 SorterRecord *pFree = pSorter->list.pList;
2654 pSorter->list.pList = pFree->u.pNext;
2655 pFree->u.pNext = 0;
2656 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
2657 rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
2659 return rc;
2663 ** Return a pointer to a buffer owned by the sorter that contains the
2664 ** current key.
2666 static void *vdbeSorterRowkey(
2667 const VdbeSorter *pSorter, /* Sorter object */
2668 int *pnKey /* OUT: Size of current key in bytes */
2670 void *pKey;
2671 if( pSorter->bUsePMA ){
2672 PmaReader *pReader;
2673 #if SQLITE_MAX_WORKER_THREADS>0
2674 if( pSorter->bUseThreads ){
2675 pReader = pSorter->pReader;
2676 }else
2677 #endif
2678 /*if( !pSorter->bUseThreads )*/{
2679 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
2681 *pnKey = pReader->nKey;
2682 pKey = pReader->aKey;
2683 }else{
2684 *pnKey = pSorter->list.pList->nVal;
2685 pKey = SRVAL(pSorter->list.pList);
2687 return pKey;
2691 ** Copy the current sorter key into the memory cell pOut.
2693 int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
2694 VdbeSorter *pSorter;
2695 void *pKey; int nKey; /* Sorter key to copy into pOut */
2697 assert( pCsr->eCurType==CURTYPE_SORTER );
2698 pSorter = pCsr->uc.pSorter;
2699 pKey = vdbeSorterRowkey(pSorter, &nKey);
2700 if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
2701 return SQLITE_NOMEM_BKPT;
2703 pOut->n = nKey;
2704 MemSetTypeFlag(pOut, MEM_Blob);
2705 memcpy(pOut->z, pKey, nKey);
2707 return SQLITE_OK;
2711 ** Compare the key in memory cell pVal with the key that the sorter cursor
2712 ** passed as the first argument currently points to. For the purposes of
2713 ** the comparison, ignore the rowid field at the end of each record.
2715 ** If the sorter cursor key contains any NULL values, consider it to be
2716 ** less than pVal. Even if pVal also contains NULL values.
2718 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
2719 ** Otherwise, set *pRes to a negative, zero or positive value if the
2720 ** key in pVal is smaller than, equal to or larger than the current sorter
2721 ** key.
2723 ** This routine forms the core of the OP_SorterCompare opcode, which in
2724 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
2726 int sqlite3VdbeSorterCompare(
2727 const VdbeCursor *pCsr, /* Sorter cursor */
2728 Mem *pVal, /* Value to compare to current sorter key */
2729 int nKeyCol, /* Compare this many columns */
2730 int *pRes /* OUT: Result of comparison */
2732 VdbeSorter *pSorter;
2733 UnpackedRecord *r2;
2734 KeyInfo *pKeyInfo;
2735 int i;
2736 void *pKey; int nKey; /* Sorter key to compare pVal with */
2738 assert( pCsr->eCurType==CURTYPE_SORTER );
2739 pSorter = pCsr->uc.pSorter;
2740 r2 = pSorter->pUnpacked;
2741 pKeyInfo = pCsr->pKeyInfo;
2742 if( r2==0 ){
2743 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
2744 if( r2==0 ) return SQLITE_NOMEM_BKPT;
2745 r2->nField = nKeyCol;
2747 assert( r2->nField==nKeyCol );
2749 pKey = vdbeSorterRowkey(pSorter, &nKey);
2750 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
2751 for(i=0; i<nKeyCol; i++){
2752 if( r2->aMem[i].flags & MEM_Null ){
2753 *pRes = -1;
2754 return SQLITE_OK;
2758 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
2759 return SQLITE_OK;