Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/vdbesort.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / vdbesort.c` 2947 lines ยท 103607 bytes Raw Blame History 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. 10 ** 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. 16 ** 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. 20 ** 21 ** Here is the (internal, non-API) interface between this module and the 22 ** rest of the SQLite system: 23 ** 24 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object. 25 ** 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. 33 ** 34 ** sqlite3VdbeSorterRewind() Sort all content previously added. 35 ** Position the read cursor on the 36 ** first sorted element. 37 ** 38 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted 39 ** element. 40 ** 41 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the 42 ** row currently under the read cursor. 43 ** 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. 50 ** 51 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim 52 ** all resources. 53 ** 54 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This 55 ** is like Close() followed by Init() only 56 ** much faster. 57 ** 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. 61 ** 62 ** Init() 63 ** for each record: Write() 64 ** Rewind() 65 ** Rowkey()/Compare() 66 ** Next() 67 ** Close() 68 ** 69 ** Algorithm: 70 ** 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. 77 ** 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. 84 ** 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" multiplied by 89 ** that returned by "PRAGMA main.cache_size", in bytes. 90 ** 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. 99 ** 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. 104 ** 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. 108 ** 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 retrieved from the sorter by the VDBE. The 112 ** MergeEngine object, described in further detail below, performs this 113 ** merge. 114 ** 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. 120 ** 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. 123 ** 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. 130 ** 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. 137 */ 138 #include "sqliteInt.h" 139 #include "vdbeInt.h" 140 141 /* 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. 145 */ 146 #if 0 147 # define SQLITE_DEBUG_SORTER_THREADS 1 148 #endif 149 150 /* 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. 154 */ 155 #define SQLITE_MAX_PMASZ (1<<29) 156 157 /* 158 ** Private objects used by the sorter 159 */ 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 */ 168 169 /* 170 ** A container for a temp file handle and the current amount of data 171 ** stored in the file. 172 */ 173 struct SorterFile { 174 sqlite3_file *pFd; /* File handle */ 175 i64 iEof; /* Bytes of data stored in pFd */ 176 }; 177 178 /* 179 ** An in-memory list of objects to be sorted. 180 ** 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. 185 */ 186 struct SorterList { 187 SorterRecord *pList; /* Linked list of records */ 188 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */ 189 i64 szPMA; /* Size of pList as PMA in bytes */ 190 }; 191 192 /* 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. 197 ** 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). 205 ** 206 ** The aTree[] array is also N elements in size. The value of N is stored in 207 ** the MergeEngine.nTree variable. 208 ** 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. 213 ** 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. 217 ** 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. 222 ** 223 ** Example: 224 ** 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 233 ** 234 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 } 235 ** 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": 240 ** 241 ** aReadr[5] -> Eggplant 242 ** 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 (Bananafile2. And instead of using a 396 ** background thread to prepare data for the PmaReader, with a single 397 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with 398 ** keys from pMerger by the calling thread whenever the PmaReader runs out 399 ** of data. 400 */ 401 struct IncrMerger { 402 SortSubtask *pTask; /* Task that owns this merger */ 403 MergeEngine *pMerger; /* Merge engine thread reads data from */ 404 i64 iStartOff; /* Offset to start writing file at */ 405 int mxSz; /* Maximum bytes of data to store */ 406 int bEof; /* Set to true when merge is finished */ 407 int bUseThread; /* True to use a bg thread for this object */ 408 SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */ 409 }; 410 411 /* 412 ** An instance of this object is used for writing a PMA. 413 ** 414 ** The PMA is written one record at a time. Each record is of an arbitrary 415 ** size. But I/O is more efficient if it occurs in page-sized blocks where 416 ** each block is aligned on a page boundary. This object caches writes to 417 ** the PMA so that aligned, page-size blocks are written. 418 */ 419 struct PmaWriter { 420 int eFWErr; /* Non-zero if in an error state */ 421 u8 *aBuffer; /* Pointer to write buffer */ 422 int nBuffer; /* Size of write buffer in bytes */ 423 int iBufStart; /* First byte of buffer to write */ 424 int iBufEnd; /* Last byte of buffer to write */ 425 i64 iWriteOff; /* Offset of start of buffer in file */ 426 sqlite3_file *pFd; /* File handle to write to */ 427 u64 nPmaSpill; /* Total number of bytes written */ 428 }; 429 430 /* 431 ** This object is the header on a single record while that record is being 432 ** held in memory and prior to being written out as part of a PMA. 433 ** 434 ** How the linked list is connected depends on how memory is being managed 435 ** by this module. If using a separate allocation for each in-memory record 436 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the 437 ** SorterRecord.u.pNext pointers. 438 ** 439 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0), 440 ** then while records are being accumulated the list is linked using the 441 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may 442 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM 443 ** has finished passing records to the sorter, or when the in-memory buffer 444 ** is full, the list is sorted. As part of the sorting process, it is 445 ** converted to use the SorterRecord.u.pNext pointers. See function 446 ** vdbeSorterSort() for details. 447 */ 448 struct SorterRecord { 449 int nVal; /* Size of the record in bytes */ 450 union { 451 SorterRecord *pNext; /* Pointer to next record in list */ 452 int iNext; /* Offset within aMemory of next record */ 453 } u; 454 /* The data for the record immediately follows this header */ 455 }; 456 457 /* Return a pointer to the buffer containing the record data for SorterRecord 458 ** object p. Should be used as if: 459 ** 460 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; } 461 */ 462 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1)) 463 464 465 /* Maximum number of PMAs that a single MergeEngine can merge */ 466 #define SORTER_MAX_MERGE_COUNT 16 467 468 static int vdbeIncrSwap(IncrMerger*); 469 static void vdbeIncrFree(IncrMerger *); 470 471 /* 472 ** Free all memory belonging to the PmaReader object passed as the 473 ** argument. All structure fields are set to zero before returning. 474 */ 475 static void vdbePmaReaderClear(PmaReader *pReadr){ 476 sqlite3_free(pReadr->aAlloc); 477 sqlite3_free(pReadr->aBuffer); 478 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); 479 vdbeIncrFree(pReadr->pIncr); 480 memset(pReadr, 0, sizeof(PmaReader)); 481 } 482 483 /* 484 ** Read the next nByte bytes of data from the PMA p. 485 ** If successful, set *ppOut to point to a buffer containing the data 486 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite 487 ** error code. 488 ** 489 ** The buffer returned in *ppOut is only valid until the 490 ** next call to this function. 491 */ 492 static int vdbePmaReadBlob( 493 PmaReader *p, /* PmaReader from which to take the blob */ 494 int nByte, /* Bytes of data to read */ 495 u8 **ppOut /* OUT: Pointer to buffer containing data */ 496 ){ 497 int iBuf; /* Offset within buffer to read from */ 498 int nAvail; /* Bytes of data available in buffer */ 499 500 if( p->aMap ){ 501 *ppOut = &p->aMap[p->iReadOff]; 502 p->iReadOff += nByte; 503 return SQLITE_OK; 504 } 505 506 assert( p->aBuffer ); 507 508 /* If there is no more data to be read from the buffer, read the next 509 ** p->nBuffer bytes of data from the file into it. Or, if there are less 510 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */ 511 iBuf = p->iReadOff % p->nBuffer; 512 if( iBuf==0 ){ 513 int nRead; /* Bytes to read from disk */ 514 int rc; /* sqlite3OsRead() return code */ 515 516 /* Determine how many bytes of data to read. */ 517 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){ 518 nRead = p->nBuffer; 519 }else{ 520 nRead = (int)(p->iEof - p->iReadOff); 521 } 522 assert( nRead>0 ); 523 524 /* Readr data from the file. Return early if an error occurs. */ 525 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff); 526 assert( rc!=SQLITE_IOERR_SHORT_READ ); 527 if( rc!=SQLITE_OK ) return rc; 528 } 529 nAvail = p->nBuffer - iBuf; 530 531 if( nByte<=nAvail ){ 532 /* The requested data is available in the in-memory buffer. In this 533 ** case there is no need to make a copy of the data, just return a 534 ** pointer into the buffer to the caller. */ 535 *ppOut = &p->aBuffer[iBuf]; 536 p->iReadOff += nByte; 537 }else{ 538 /* The requested data is not all available in the in-memory buffer. 539 ** In this case, allocate space at p->aAlloc[] to copy the requested 540 ** range into. Then return a copy of pointer p->aAlloc to the caller. */ 541 int nRem; /* Bytes remaining to copy */ 542 543 /* Extend the p->aAlloc[] allocation if required. */ 544 if( p->nAllocnAlloc); 547 while( nByte>nNew ) nNew = nNew*2; 548 aNew = sqlite3Realloc(p->aAlloc, nNew); 549 if( !aNew ) return SQLITE_NOMEM_BKPT; 550 p->nAlloc = nNew; 551 p->aAlloc = aNew; 552 } 553 554 /* Copy as much data as is available in the buffer into the start of 555 ** p->aAlloc[]. */ 556 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail); 557 p->iReadOff += nAvail; 558 nRem = nByte - nAvail; 559 560 /* The following loop copies up to p->nBuffer bytes per iteration into 561 ** the p->aAlloc[] buffer. */ 562 while( nRem>0 ){ 563 int rc; /* vdbePmaReadBlob() return code */ 564 int nCopy; /* Number of bytes to copy */ 565 u8 *aNext = 0; /* Pointer to buffer to copy data from */ 566 567 nCopy = nRem; 568 if( nRem>p->nBuffer ) nCopy = p->nBuffer; 569 rc = vdbePmaReadBlob(p, nCopy, &aNext); 570 if( rc!=SQLITE_OK ) return rc; 571 assert( aNext!=p->aAlloc ); 572 assert( aNext!=0 ); 573 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy); 574 nRem -= nCopy; 575 } 576 577 *ppOut = p->aAlloc; 578 } 579 580 return SQLITE_OK; 581 } 582 583 /* 584 ** Read a varint from the stream of data accessed by p. Set *pnOut to 585 ** the value read. 586 */ 587 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){ 588 int iBuf; 589 590 if( p->aMap ){ 591 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut); 592 }else{ 593 iBuf = p->iReadOff % p->nBuffer; 594 if( iBuf && (p->nBuffer-iBuf)>=9 ){ 595 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut); 596 }else{ 597 u8 aVarint[16], *a; 598 int i = 0, rc; 599 do{ 600 rc = vdbePmaReadBlob(p, 1, &a); 601 if( rc ) return rc; 602 aVarint[(i++)&0xf] = a[0]; 603 }while( (a[0]&0x80)!=0 ); 604 sqlite3GetVarint(aVarint, pnOut); 605 } 606 } 607 608 return SQLITE_OK; 609 } 610 611 /* 612 ** Attempt to memory map file pFile. If successful, set *pp to point to the 613 ** new mapping and return SQLITE_OK. If the mapping is not attempted 614 ** (because the file is too large or the VFS layer is configured not to use 615 ** mmap), return SQLITE_OK and set *pp to NULL. 616 ** 617 ** Or, if an error occurs, return an SQLite error code. The final value of 618 ** *pp is undefined in this case. 619 */ 620 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){ 621 int rc = SQLITE_OK; 622 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){ 623 sqlite3_file *pFd = pFile->pFd; 624 if( pFd->pMethods->iVersion>=3 ){ 625 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp); 626 testcase( rc!=SQLITE_OK ); 627 } 628 } 629 return rc; 630 } 631 632 /* 633 ** Attach PmaReader pReadr to file pFile (if it is not already attached to 634 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK 635 ** if successful, or an SQLite error code if an error occurs. 636 */ 637 static int vdbePmaReaderSeek( 638 SortSubtask *pTask, /* Task context */ 639 PmaReader *pReadr, /* Reader whose cursor is to be moved */ 640 SorterFile *pFile, /* Sorter file to read from */ 641 i64 iOff /* Offset in pFile */ 642 ){ 643 int rc = SQLITE_OK; 644 645 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 ); 646 647 if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ; 648 if( pReadr->aMap ){ 649 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap); 650 pReadr->aMap = 0; 651 } 652 pReadr->iReadOff = iOff; 653 pReadr->iEof = pFile->iEof; 654 pReadr->pFd = pFile->pFd; 655 656 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap); 657 if( rc==SQLITE_OK && pReadr->aMap==0 ){ 658 int pgsz = pTask->pSorter->pgsz; 659 int iBuf = pReadr->iReadOff % pgsz; 660 if( pReadr->aBuffer==0 ){ 661 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz); 662 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT; 663 pReadr->nBuffer = pgsz; 664 } 665 if( rc==SQLITE_OK && iBuf ){ 666 int nRead = pgsz - iBuf; 667 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){ 668 nRead = (int)(pReadr->iEof - pReadr->iReadOff); 669 } 670 rc = sqlite3OsRead( 671 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff 672 ); 673 testcase( rc!=SQLITE_OK ); 674 } 675 } 676 677 return rc; 678 } 679 680 /* 681 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if 682 ** no error occurs, or an SQLite error code if one does. 683 */ 684 static int vdbePmaReaderNext(PmaReader *pReadr){ 685 int rc = SQLITE_OK; /* Return Code */ 686 u64 nRec = 0; /* Size of record in bytes */ 687 688 689 if( pReadr->iReadOff>=pReadr->iEof ){ 690 IncrMerger *pIncr = pReadr->pIncr; 691 int bEof = 1; 692 if( pIncr ){ 693 rc = vdbeIncrSwap(pIncr); 694 if( rc==SQLITE_OK && pIncr->bEof==0 ){ 695 rc = vdbePmaReaderSeek( 696 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff 697 ); 698 bEof = 0; 699 } 700 } 701 702 if( bEof ){ 703 /* This is an EOF condition */ 704 vdbePmaReaderClear(pReadr); 705 testcase( rc!=SQLITE_OK ); 706 return rc; 707 } 708 } 709 710 if( rc==SQLITE_OK ){ 711 rc = vdbePmaReadVarint(pReadr, &nRec); 712 } 713 if( rc==SQLITE_OK ){ 714 pReadr->nKey = (int)nRec; 715 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey); 716 testcase( rc!=SQLITE_OK ); 717 } 718 719 return rc; 720 } 721 722 /* 723 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile 724 ** starting at offset iStart and ending at offset iEof-1. This function 725 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 726 ** PMA is empty). 727 ** 728 ** If the pnByte parameter is NULL, then it is assumed that the file 729 ** contains a single PMA, and that that PMA omits the initial length varint. 730 */ 731 static int vdbePmaReaderInit( 732 SortSubtask *pTask, /* Task context */ 733 SorterFile *pFile, /* Sorter file to read from */ 734 i64 iStart, /* Start offset in pFile */ 735 PmaReader *pReadr, /* PmaReader to populate */ 736 i64 *pnByte /* IN/OUT: Increment this value by PMA size */ 737 ){ 738 int rc; 739 740 assert( pFile->iEof>iStart ); 741 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 ); 742 assert( pReadr->aBuffer==0 ); 743 assert( pReadr->aMap==0 ); 744 745 rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart); 746 if( rc==SQLITE_OK ){ 747 u64 nByte = 0; /* Size of PMA in bytes */ 748 rc = vdbePmaReadVarint(pReadr, &nByte); 749 pReadr->iEof = pReadr->iReadOff + nByte; 750 *pnByte += nByte; 751 } 752 753 if( rc==SQLITE_OK ){ 754 rc = vdbePmaReaderNext(pReadr); 755 } 756 return rc; 757 } 758 759 /* 760 ** A version of vdbeSorterCompare() that assumes that it has already been 761 ** determined that the first field of key1 is equal to the first field of 762 ** key2. 763 */ 764 static int vdbeSorterCompareTail( 765 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 766 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 767 const void *pKey1, int nKey1, /* Left side of comparison */ 768 const void *pKey2, int nKey2 /* Right side of comparison */ 769 ){ 770 UnpackedRecord *r2 = pTask->pUnpacked; 771 if( *pbKey2Cached==0 ){ 772 sqlite3VdbeRecordUnpack(nKey2, pKey2, r2); 773 *pbKey2Cached = 1; 774 } 775 return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1); 776 } 777 778 /* 779 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 780 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences 781 ** used by the comparison. Return the result of the comparison. 782 ** 783 ** If IN/OUT parameter *pbKey2Cached is true when this function is called, 784 ** it is assumed that (pTask->pUnpacked) contains the unpacked version 785 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked 786 ** version of key2 and *pbKey2Cached set to true before returning. 787 ** 788 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set 789 ** to SQLITE_NOMEM. 790 */ 791 static int vdbeSorterCompare( 792 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 793 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 794 const void *pKey1, int nKey1, /* Left side of comparison */ 795 const void *pKey2, int nKey2 /* Right side of comparison */ 796 ){ 797 UnpackedRecord *r2 = pTask->pUnpacked; 798 if( !*pbKey2Cached ){ 799 sqlite3VdbeRecordUnpack(nKey2, pKey2, r2); 800 *pbKey2Cached = 1; 801 } 802 return sqlite3VdbeRecordCompare(nKey1, pKey1, r2); 803 } 804 805 /* 806 ** A specially optimized version of vdbeSorterCompare() that assumes that 807 ** the first field of each key is a TEXT value and that the collation 808 ** sequence to compare them with is BINARY. 809 */ 810 static int vdbeSorterCompareText( 811 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 812 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 813 const void *pKey1, int nKey1, /* Left side of comparison */ 814 const void *pKey2, int nKey2 /* Right side of comparison */ 815 ){ 816 const u8 * const p1 = (const u8 * const)pKey1; 817 const u8 * const p2 = (const u8 * const)pKey2; 818 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ 819 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ 820 821 int n1; 822 int n2; 823 int res; 824 825 getVarint32NR(&p1[1], n1); 826 getVarint32NR(&p2[1], n2); 827 res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2); 828 if( res==0 ){ 829 res = n1 - n2; 830 } 831 832 if( res==0 ){ 833 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ 834 res = vdbeSorterCompareTail( 835 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 836 ); 837 } 838 }else{ 839 assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); 840 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); 841 if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ 842 res = res * -1; 843 } 844 } 845 846 return res; 847 } 848 849 /* 850 ** A specially optimized version of vdbeSorterCompare() that assumes that 851 ** the first field of each key is an INTEGER value. 852 */ 853 static int vdbeSorterCompareInt( 854 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 855 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 856 const void *pKey1, int nKey1, /* Left side of comparison */ 857 const void *pKey2, int nKey2 /* Right side of comparison */ 858 ){ 859 const u8 * const p1 = (const u8 * const)pKey1; 860 const u8 * const p2 = (const u8 * const)pKey2; 861 const int s1 = p1[1]; /* Left hand serial type */ 862 const int s2 = p2[1]; /* Right hand serial type */ 863 const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */ 864 const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */ 865 int res; /* Return value */ 866 867 assert( (s1>0 && s1<7) || s1==8 || s1==9 ); 868 assert( (s2>0 && s2<7) || s2==8 || s2==9 ); 869 870 if( s1==s2 ){ 871 /* The two values have the same sign. Compare using memcmp(). */ 872 static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 }; 873 const u8 n = aLen[s1]; 874 int i; 875 res = 0; 876 for(i=0; i7 && s2>7 ){ 885 res = s1 - s2; 886 }else{ 887 if( s2>7 ){ 888 res = +1; 889 }else if( s1>7 ){ 890 res = -1; 891 }else{ 892 res = s1 - s2; 893 } 894 assert( res!=0 ); 895 896 if( res>0 ){ 897 if( *v1 & 0x80 ) res = -1; 898 }else{ 899 if( *v2 & 0x80 ) res = +1; 900 } 901 } 902 903 assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); 904 if( res==0 ){ 905 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ 906 res = vdbeSorterCompareTail( 907 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 908 ); 909 } 910 }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ 911 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); 912 res = res * -1; 913 } 914 915 return res; 916 } 917 918 /* Helper function for vdbeSorterCompareReal(). 919 ** 920 ** The first elements of both pKey1 and pKey2 have been decoded into double 921 ** values r1 and r2. Do the comparison between those keys and return the 922 ** result. If r1==r2, break the tie with a comparison of subsequent elements 923 ** from each key. 924 */ 925 static int vdbeSorterFinishRealCompare( 926 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 927 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 928 const void *pKey1, int nKey1, /* Left side of comparison */ 929 const void *pKey2, int nKey2, /* Right side of comparison */ 930 double r1, /* REAL value of first element of pKey1 */ 931 double r2 /* REAL value of first element of pKey2 */ 932 ){ 933 int res; 934 if( r1r2 ){ 937 res = +1; 938 }else{ 939 res = 0; 940 } 941 assert( pTask->pSorter->pKeyInfo->aSortFlags!=0 ); 942 if( res==0 ){ 943 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){ 944 res = vdbeSorterCompareTail( 945 pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2 946 ); 947 } 948 }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){ 949 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) ); 950 res = res * -1; 951 } 952 return res; 953 } 954 955 /* Helper function for vdbeSorterCompareReal(). 956 ** 957 ** Buffer p[] is a record where the first term is guaranteed to be either 958 ** a floating-point value, or an integer stand-in for a floating point 959 ** value (a MEM_IntReal). Whatever its format, extract the value and 960 ** return it. 961 */ 962 static double vdbeSorterGetReal(const u8 *p){ 963 double r; /* the return value */ 964 965 assert( p[0]<0x80 ); /* 1-byte headers: nAllField<13 */ 966 assert( p[1]>0 && p[1]<10 ); /* first fields proven numeric */ 967 968 if( p[1]==7 ){ 969 u64 x = sqlite3Get8byte(p + p[0]); 970 swapMixedEndianFloat(x); 971 assert( !IsNaN(x) ); 972 memcpy(&r, &x, sizeof(r)); 973 }else{ 974 Mem m; 975 m.u.i = 0; 976 sqlite3VdbeSerialGet(p + p[0], p[1], &m); 977 assert( m.flags==MEM_Int ); 978 r = (double)m.u.i; 979 } 980 return r; 981 } 982 983 /* Helper function for vdbeSorterCompareReal() 984 ** 985 ** This routine handles the case of comparing two floating-point values 986 ** where one or both of the floating-point are represented by integers. 987 ** In other words, where one both is an MEM_RealInt. 988 ** 989 ** This subroutine is factored out from vdbeSorterCompareReal() for 990 ** efficiency. If inlined into vdbeSorterCompareReal(), this routine 991 ** will use extra stack space and consume CPU cycles setting up and 992 ** breaking down that stack space, even if in the common case where 993 ** this path is not used. 994 */ 995 static SQLITE_NOINLINE int vdbeSorterCompareRealInt( 996 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 997 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 998 const void *pKey1, int nKey1, /* Left side of comparison */ 999 const void *pKey2, int nKey2 /* Right side of comparison */ 1000 ){ 1001 const u8 * const p1 = (const u8 * const)pKey1; 1002 const u8 * const p2 = (const u8 * const)pKey2; 1003 if( p1[1]==6 || p2[1]==6 ){ 1004 /* 64-bit integer values cannot be represented exactly by a double so 1005 ** must be handled by the generalized comparison function. */ 1006 return vdbeSorterCompare(pTask, 1007 pbKey2Cached, pKey1,nKey1, pKey2,nKey2); 1008 }else{ 1009 double r1 = vdbeSorterGetReal(p1); 1010 double r2 = vdbeSorterGetReal(p2); 1011 return vdbeSorterFinishRealCompare(pTask,pbKey2Cached, 1012 pKey1,nKey1,pKey2,nKey2,r1,r2); 1013 } 1014 } 1015 1016 /* 1017 ** Comparison function optimized for the case where the first term 1018 ** of both keys are either MEM_Real or MEM_RealInt. 1019 ** 1020 ** See also vdbeSorterCompareInt() for MEM_Int values and 1021 ** vdbeSorterCompareText() for MEM_Str values. The general 1022 ** case is vdbeSorterCompare() which handles anything, but is slower. 1023 */ 1024 static int vdbeSorterCompareReal( 1025 SortSubtask *pTask, /* Subtask context (for pKeyInfo) */ 1026 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */ 1027 const void *pKey1, int nKey1, /* Left side of comparison */ 1028 const void *pKey2, int nKey2 /* Right side of comparison */ 1029 ){ 1030 const u8*const p1 = (const u8*const)pKey1; /* Left key record */ 1031 const u8*const p2 = (const u8*const)pKey2; /* Right key record */ 1032 u64 x; /* A real value stored as an integer */ 1033 double r1; /* First element of pKey1 */ 1034 double r2; /* First element of pKey2 */ 1035 1036 assert( p1[0]<0x80 && p2[0]<0x80 ); /* 1-byte headers: nAllField<13 */ 1037 assert( p1[1]>0 && p1[1]<10 ); /* first field guaranteed numeric */ 1038 assert( p2[1]>0 && p2[1]<10 ); /* first field guaranteed numeric */ 1039 1040 if( p1[1]!=7 || p2[1]!=7 ){ 1041 /* One or both floating point values are stored as INTEGER. This might 1042 ** be because of the MEM_RealInt encoding. Try to optimize that case. */ 1043 return vdbeSorterCompareRealInt(pTask, 1044 pbKey2Cached, pKey1,nKey1, pKey2,nKey2 1045 ); 1046 } 1047 assert( p1[0]<=nKey1-8 && p2[0]<=nKey2-8 ); 1048 1049 x = sqlite3Get8byte(p1 + *p1); 1050 swapMixedEndianFloat(x); 1051 assert( !IsNaN(x) ); 1052 memcpy(&r1, &x, sizeof(r1)); 1053 x = sqlite3Get8byte(p2 + *p2); 1054 swapMixedEndianFloat(x); 1055 assert( !IsNaN(x) ); 1056 memcpy(&r2, &x, sizeof(r2)); 1057 return vdbeSorterFinishRealCompare(pTask, 1058 pbKey2Cached, pKey1,nKey1, pKey2,nKey2, r1, r2 1059 ); 1060 } 1061 1062 /* 1063 ** Initialize the temporary index cursor just opened as a sorter cursor. 1064 ** 1065 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField) 1066 ** to determine the number of fields that should be compared from the 1067 ** records being sorted. However, if the value passed as argument nField 1068 ** is non-zero and the sorter is able to guarantee a stable sort, nField 1069 ** is used instead. This is used when sorting records for a CREATE INDEX 1070 ** statement. In this case, keys are always delivered to the sorter in 1071 ** order of the primary key, which happens to be make up the final part 1072 ** of the records being sorted. So if the sort is stable, there is never 1073 ** any reason to compare PK fields and they can be ignored for a small 1074 ** performance boost. 1075 ** 1076 ** The sorter can guarantee a stable sort when running in single-threaded 1077 ** mode, but not in multi-threaded mode. 1078 ** 1079 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. 1080 */ 1081 int sqlite3VdbeSorterInit( 1082 sqlite3 *db, /* Database connection (for malloc()) */ 1083 int nField, /* Number of key fields in each record */ 1084 VdbeCursor *pCsr /* Cursor that holds the new sorter */ 1085 ){ 1086 int pgsz; /* Page size of main database */ 1087 int i; /* Used to iterate through aTask[] */ 1088 VdbeSorter *pSorter; /* The new sorter */ 1089 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */ 1090 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */ 1091 i64 sz; /* Size of pSorter in bytes */ 1092 int rc = SQLITE_OK; 1093 #if SQLITE_MAX_WORKER_THREADS==0 1094 # define nWorker 0 1095 #else 1096 int nWorker; 1097 #endif 1098 1099 /* Initialize the upper limit on the number of worker threads */ 1100 #if SQLITE_MAX_WORKER_THREADS>0 1101 if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){ 1102 nWorker = 0; 1103 }else{ 1104 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS]; 1105 } 1106 #endif 1107 1108 /* Do not allow the total number of threads (main thread + all workers) 1109 ** to exceed the maximum merge count */ 1110 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT 1111 if( nWorker>=SORTER_MAX_MERGE_COUNT ){ 1112 nWorker = SORTER_MAX_MERGE_COUNT-1; 1113 } 1114 #endif 1115 1116 assert( pCsr->pKeyInfo ); 1117 assert( !pCsr->isEphemeral ); 1118 assert( pCsr->eCurType==CURTYPE_SORTER ); 1119 assert( sizeof(KeyInfo) + UMXV(pCsr->pKeyInfo->nKeyField)*sizeof(CollSeq*) 1120 < 0x7fffffff ); 1121 assert( pCsr->pKeyInfo->nKeyField<=pCsr->pKeyInfo->nAllField ); 1122 szKeyInfo = SZ_KEYINFO(pCsr->pKeyInfo->nAllField); 1123 sz = SZ_VDBESORTER(nWorker+1); 1124 1125 pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo); 1126 pCsr->uc.pSorter = pSorter; 1127 if( pSorter==0 ){ 1128 rc = SQLITE_NOMEM_BKPT; 1129 }else{ 1130 Btree *pBt = db->aDb[0].pBt; 1131 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz); 1132 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo); 1133 pKeyInfo->db = 0; 1134 if( nField && nWorker==0 ){ 1135 pKeyInfo->nKeyField = nField; 1136 assert( nField<=pCsr->pKeyInfo->nAllField ); 1137 } 1138 /* It is OK that pKeyInfo reuses the aSortFlags field from pCsr->pKeyInfo, 1139 ** since the pCsr->pKeyInfo->aSortFlags[] array is invariant and lives 1140 ** longer that pSorter. */ 1141 assert( pKeyInfo->aSortFlags==pCsr->pKeyInfo->aSortFlags ); 1142 sqlite3BtreeEnter(pBt); 1143 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt); 1144 sqlite3BtreeLeave(pBt); 1145 pSorter->nTask = nWorker + 1; 1146 pSorter->iPrev = (u8)(nWorker - 1); 1147 pSorter->bUseThreads = (pSorter->nTask>1); 1148 pSorter->db = db; 1149 for(i=0; inTask; i++){ 1150 SortSubtask *pTask = &pSorter->aTask[i]; 1151 pTask->pSorter = pSorter; 1152 } 1153 1154 if( !sqlite3TempInMemory(db) ){ 1155 i64 mxCache; /* Cache size in bytes*/ 1156 u32 szPma = sqlite3GlobalConfig.szPma; 1157 pSorter->mnPmaSize = szPma * pgsz; 1158 1159 mxCache = db->aDb[0].pSchema->cache_size; 1160 if( mxCache<0 ){ 1161 /* A negative cache-size value C indicates that the cache is abs(C) 1162 ** KiB in size. */ 1163 mxCache = mxCache * -1024; 1164 }else{ 1165 mxCache = mxCache * pgsz; 1166 } 1167 mxCache = MIN(mxCache, SQLITE_MAX_PMASZ); 1168 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache); 1169 1170 /* Avoid large memory allocations if the application has requested 1171 ** SQLITE_CONFIG_SMALL_MALLOC. */ 1172 if( sqlite3GlobalConfig.bSmallMalloc==0 ){ 1173 assert( pSorter->iMemory==0 ); 1174 pSorter->nMemory = pgsz; 1175 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz); 1176 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT; 1177 } 1178 } 1179 1180 if( pKeyInfo->nAllField<13 1181 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl) 1182 && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0 1183 ){ 1184 pSorter->typeMask = SORTER_TYPE_INTEGER|SORTER_TYPE_TEXT|SORTER_TYPE_REAL; 1185 } 1186 } 1187 1188 return rc; 1189 } 1190 #undef nWorker /* Defined at the top of this function */ 1191 1192 /* 1193 ** Free the list of sorted records starting at pRecord. 1194 */ 1195 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){ 1196 SorterRecord *p; 1197 SorterRecord *pNext; 1198 for(p=pRecord; p; p=pNext){ 1199 pNext = p->u.pNext; 1200 sqlite3DbFree(db, p); 1201 } 1202 } 1203 1204 /* 1205 ** Free all resources owned by the object indicated by argument pTask. All 1206 ** fields of *pTask are zeroed before returning. 1207 */ 1208 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){ 1209 sqlite3DbFree(db, pTask->pUnpacked); 1210 #if SQLITE_MAX_WORKER_THREADS>0 1211 /* pTask->list.aMemory can only be non-zero if it was handed memory 1212 ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */ 1213 if( pTask->list.aMemory ){ 1214 sqlite3_free(pTask->list.aMemory); 1215 }else 1216 #endif 1217 { 1218 assert( pTask->list.aMemory==0 ); 1219 vdbeSorterRecordFree(0, pTask->list.pList); 1220 } 1221 if( pTask->file.pFd ){ 1222 sqlite3OsCloseFree(pTask->file.pFd); 1223 } 1224 if( pTask->file2.pFd ){ 1225 sqlite3OsCloseFree(pTask->file2.pFd); 1226 } 1227 memset(pTask, 0, sizeof(SortSubtask)); 1228 } 1229 1230 #ifdef SQLITE_DEBUG_SORTER_THREADS 1231 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){ 1232 i64 t; 1233 int iTask = (pTask - pTask->pSorter->aTask); 1234 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); 1235 fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent); 1236 } 1237 static void vdbeSorterRewindDebug(const char *zEvent){ 1238 i64 t = 0; 1239 sqlite3_vfs *pVfs = sqlite3_vfs_find(0); 1240 if( ALWAYS(pVfs) ) sqlite3OsCurrentTimeInt64(pVfs, &t); 1241 fprintf(stderr, "%lld:X %s\n", t, zEvent); 1242 } 1243 static void vdbeSorterPopulateDebug( 1244 SortSubtask *pTask, 1245 const char *zEvent 1246 ){ 1247 i64 t; 1248 int iTask = (pTask - pTask->pSorter->aTask); 1249 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); 1250 fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent); 1251 } 1252 static void vdbeSorterBlockDebug( 1253 SortSubtask *pTask, 1254 int bBlocked, 1255 const char *zEvent 1256 ){ 1257 if( bBlocked ){ 1258 i64 t; 1259 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t); 1260 fprintf(stderr, "%lld:main %s\n", t, zEvent); 1261 } 1262 } 1263 #else 1264 # define vdbeSorterWorkDebug(x,y) 1265 # define vdbeSorterRewindDebug(y) 1266 # define vdbeSorterPopulateDebug(x,y) 1267 # define vdbeSorterBlockDebug(x,y,z) 1268 #endif 1269 1270 #if SQLITE_MAX_WORKER_THREADS>0 1271 /* 1272 ** Join thread pTask->thread. 1273 */ 1274 static int vdbeSorterJoinThread(SortSubtask *pTask){ 1275 int rc = SQLITE_OK; 1276 if( pTask->pThread ){ 1277 #ifdef SQLITE_DEBUG_SORTER_THREADS 1278 int bDone = pTask->bDone; 1279 #endif 1280 void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR); 1281 vdbeSorterBlockDebug(pTask, !bDone, "enter"); 1282 (void)sqlite3ThreadJoin(pTask->pThread, &pRet); 1283 vdbeSorterBlockDebug(pTask, !bDone, "exit"); 1284 rc = SQLITE_PTR_TO_INT(pRet); 1285 assert( pTask->bDone==1 ); 1286 pTask->bDone = 0; 1287 pTask->pThread = 0; 1288 } 1289 return rc; 1290 } 1291 1292 /* 1293 ** Launch a background thread to run xTask(pIn). 1294 */ 1295 static int vdbeSorterCreateThread( 1296 SortSubtask *pTask, /* Thread will use this task object */ 1297 void *(*xTask)(void*), /* Routine to run in a separate thread */ 1298 void *pIn /* Argument passed into xTask() */ 1299 ){ 1300 assert( pTask->pThread==0 && pTask->bDone==0 ); 1301 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn); 1302 } 1303 1304 /* 1305 ** Join all outstanding threads launched by SorterWrite() to create 1306 ** level-0 PMAs. 1307 */ 1308 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){ 1309 int rc = rcin; 1310 int i; 1311 1312 /* This function is always called by the main user thread. 1313 ** 1314 ** If this function is being called after SorterRewind() has been called, 1315 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread 1316 ** is currently attempt to join one of the other threads. To avoid a race 1317 ** condition where this thread also attempts to join the same object, join 1318 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */ 1319 for(i=pSorter->nTask-1; i>=0; i--){ 1320 SortSubtask *pTask = &pSorter->aTask[i]; 1321 int rc2 = vdbeSorterJoinThread(pTask); 1322 if( rc==SQLITE_OK ) rc = rc2; 1323 } 1324 return rc; 1325 } 1326 #else 1327 # define vdbeSorterJoinAll(x,rcin) (rcin) 1328 # define vdbeSorterJoinThread(pTask) SQLITE_OK 1329 #endif 1330 1331 /* 1332 ** Allocate a new MergeEngine object capable of handling up to 1333 ** nReader PmaReader inputs. 1334 ** 1335 ** nReader is automatically rounded up to the next power of two. 1336 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up. 1337 */ 1338 static MergeEngine *vdbeMergeEngineNew(int nReader){ 1339 int N = 2; /* Smallest power of two >= nReader */ 1340 i64 nByte; /* Total bytes of space to allocate */ 1341 MergeEngine *pNew; /* Pointer to allocated object to return */ 1342 1343 assert( nReader<=SORTER_MAX_MERGE_COUNT ); 1344 1345 while( NnTree = N; 1351 pNew->pTask = 0; 1352 pNew->aReadr = (PmaReader*)&pNew[1]; 1353 pNew->aTree = (int*)&pNew->aReadr[N]; 1354 } 1355 return pNew; 1356 } 1357 1358 /* 1359 ** Free the MergeEngine object passed as the only argument. 1360 */ 1361 static void vdbeMergeEngineFree(MergeEngine *pMerger){ 1362 int i; 1363 if( pMerger ){ 1364 for(i=0; inTree; i++){ 1365 vdbePmaReaderClear(&pMerger->aReadr[i]); 1366 } 1367 } 1368 sqlite3_free(pMerger); 1369 } 1370 1371 /* 1372 ** Free all resources associated with the IncrMerger object indicated by 1373 ** the first argument. 1374 */ 1375 static void vdbeIncrFree(IncrMerger *pIncr){ 1376 if( pIncr ){ 1377 #if SQLITE_MAX_WORKER_THREADS>0 1378 if( pIncr->bUseThread ){ 1379 vdbeSorterJoinThread(pIncr->pTask); 1380 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd); 1381 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd); 1382 } 1383 #endif 1384 vdbeMergeEngineFree(pIncr->pMerger); 1385 sqlite3_free(pIncr); 1386 } 1387 } 1388 1389 /* 1390 ** Reset a sorting cursor back to its original empty state. 1391 */ 1392 void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){ 1393 int i; 1394 (void)vdbeSorterJoinAll(pSorter, SQLITE_OK); 1395 assert( pSorter->bUseThreads || pSorter->pReader==0 ); 1396 #if SQLITE_MAX_WORKER_THREADS>0 1397 if( pSorter->pReader ){ 1398 vdbePmaReaderClear(pSorter->pReader); 1399 sqlite3DbFree(db, pSorter->pReader); 1400 pSorter->pReader = 0; 1401 } 1402 #endif 1403 vdbeMergeEngineFree(pSorter->pMerger); 1404 pSorter->pMerger = 0; 1405 for(i=0; inTask; i++){ 1406 SortSubtask *pTask = &pSorter->aTask[i]; 1407 vdbeSortSubtaskCleanup(db, pTask); 1408 pTask->pSorter = pSorter; 1409 } 1410 if( pSorter->list.aMemory==0 ){ 1411 vdbeSorterRecordFree(0, pSorter->list.pList); 1412 } 1413 pSorter->list.pList = 0; 1414 pSorter->list.szPMA = 0; 1415 pSorter->bUsePMA = 0; 1416 pSorter->iMemory = 0; 1417 pSorter->mxKeysize = 0; 1418 sqlite3DbFree(db, pSorter->pUnpacked); 1419 pSorter->pUnpacked = 0; 1420 } 1421 1422 /* 1423 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines. 1424 */ 1425 void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){ 1426 VdbeSorter *pSorter; 1427 assert( pCsr->eCurType==CURTYPE_SORTER ); 1428 pSorter = pCsr->uc.pSorter; 1429 if( pSorter ){ 1430 /* Increment db->nSpill by the total number of bytes of data written 1431 ** to temp files by this sort operation. */ 1432 int ii; 1433 for(ii=0; iinTask; ii++){ 1434 db->nSpill += pSorter->aTask[ii].nSpill; 1435 } 1436 sqlite3VdbeSorterReset(db, pSorter); 1437 sqlite3_free(pSorter->list.aMemory); 1438 sqlite3DbFree(db, pSorter); 1439 pCsr->uc.pSorter = 0; 1440 } 1441 } 1442 1443 #if SQLITE_MAX_MMAP_SIZE>0 1444 /* 1445 ** The first argument is a file-handle open on a temporary file. The file 1446 ** is guaranteed to be nByte bytes or smaller in size. This function 1447 ** attempts to extend the file to nByte bytes in size and to ensure that 1448 ** the VFS has memory mapped it. 1449 ** 1450 ** Whether or not the file does end up memory mapped of course depends on 1451 ** the specific VFS implementation. 1452 */ 1453 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){ 1454 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){ 1455 void *p = 0; 1456 int chunksize = 4*1024; 1457 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize); 1458 sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte); 1459 sqlite3OsFetch(pFd, 0, (int)nByte, &p); 1460 if( p ) sqlite3OsUnfetch(pFd, 0, p); 1461 } 1462 } 1463 #else 1464 # define vdbeSorterExtendFile(x,y,z) 1465 #endif 1466 1467 /* 1468 ** Allocate space for a file-handle and open a temporary file. If successful, 1469 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK. 1470 ** Otherwise, set *ppFd to 0 and return an SQLite error code. 1471 */ 1472 static int vdbeSorterOpenTempFile( 1473 sqlite3 *db, /* Database handle doing sort */ 1474 i64 nExtend, /* Attempt to extend file to this size */ 1475 sqlite3_file **ppFd 1476 ){ 1477 int rc; 1478 if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS; 1479 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd, 1480 SQLITE_OPEN_TEMP_JOURNAL | 1481 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | 1482 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc 1483 ); 1484 if( rc==SQLITE_OK ){ 1485 i64 max = SQLITE_MAX_MMAP_SIZE; 1486 sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max); 1487 if( nExtend>0 ){ 1488 vdbeSorterExtendFile(db, *ppFd, nExtend); 1489 } 1490 } 1491 return rc; 1492 } 1493 1494 /* 1495 ** If it has not already been allocated, allocate the UnpackedRecord 1496 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 1497 ** if no allocation was required), or SQLITE_NOMEM otherwise. 1498 */ 1499 static int vdbeSortAllocUnpacked(SortSubtask *pTask){ 1500 if( pTask->pUnpacked==0 ){ 1501 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo); 1502 if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT; 1503 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField; 1504 pTask->pUnpacked->errCode = 0; 1505 } 1506 return SQLITE_OK; 1507 } 1508 1509 1510 /* 1511 ** Merge the two sorted lists p1 and p2 into a single list. 1512 */ 1513 static SorterRecord *vdbeSorterMerge( 1514 SortSubtask *pTask, /* Calling thread context */ 1515 SorterRecord *p1, /* First list to merge */ 1516 SorterRecord *p2 /* Second list to merge */ 1517 ){ 1518 SorterRecord *pFinal = 0; 1519 SorterRecord **pp = &pFinal; 1520 int bCached = 0; 1521 1522 assert( p1!=0 && p2!=0 ); 1523 for(;;){ 1524 int res; 1525 res = pTask->xCompare( 1526 pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal 1527 ); 1528 1529 if( res<=0 ){ 1530 *pp = p1; 1531 pp = &p1->u.pNext; 1532 p1 = p1->u.pNext; 1533 if( p1==0 ){ 1534 *pp = p2; 1535 break; 1536 } 1537 }else{ 1538 *pp = p2; 1539 pp = &p2->u.pNext; 1540 p2 = p2->u.pNext; 1541 bCached = 0; 1542 if( p2==0 ){ 1543 *pp = p1; 1544 break; 1545 } 1546 } 1547 } 1548 return pFinal; 1549 } 1550 1551 /* 1552 ** Return the SorterCompare function to compare values collected by the 1553 ** sorter object passed as the only argument. 1554 */ 1555 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){ 1556 if( p->typeMask & SORTER_TYPE_INTEGER ){ 1557 return vdbeSorterCompareInt; 1558 }else if( p->typeMask & SORTER_TYPE_TEXT ){ 1559 return vdbeSorterCompareText; 1560 }else if( p->typeMask & SORTER_TYPE_REAL ){ 1561 return vdbeSorterCompareReal; 1562 } 1563 return vdbeSorterCompare; 1564 } 1565 1566 /* 1567 ** Sort the linked list of records headed at pTask->pList. Return 1568 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 1569 ** an error occurs. 1570 */ 1571 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){ 1572 int i; 1573 SorterRecord *p; 1574 int rc; 1575 SorterRecord *aSlot[64]; 1576 1577 rc = vdbeSortAllocUnpacked(pTask); 1578 if( rc!=SQLITE_OK ) return rc; 1579 1580 p = pList->pList; 1581 pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); 1582 memset(aSlot, 0, sizeof(aSlot)); 1583 1584 while( p ){ 1585 SorterRecord *pNext; 1586 if( pList->aMemory ){ 1587 if( (u8*)p==pList->aMemory ){ 1588 pNext = 0; 1589 }else{ 1590 assert( p->u.iNextaMemory) ); 1591 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext]; 1592 } 1593 }else{ 1594 pNext = p->u.pNext; 1595 } 1596 1597 p->u.pNext = 0; 1598 for(i=0; aSlot[i]; i++){ 1599 p = vdbeSorterMerge(pTask, p, aSlot[i]); 1600 /* ,--Each aSlot[] holds twice as much as the previous. So we cannot use 1601 ** | up all 64 aSlots[] with only a 64-bit address space. 1602 ** v */ 1603 assert( ipList = p; 1616 1617 assert( pTask->pUnpacked->errCode==SQLITE_OK 1618 || pTask->pUnpacked->errCode==SQLITE_NOMEM 1619 ); 1620 return pTask->pUnpacked->errCode; 1621 } 1622 1623 /* 1624 ** Initialize a PMA-writer object. 1625 */ 1626 static void vdbePmaWriterInit( 1627 sqlite3_file *pFd, /* File handle to write to */ 1628 PmaWriter *p, /* Object to populate */ 1629 int nBuf, /* Buffer size */ 1630 i64 iStart /* Offset of pFd to begin writing at */ 1631 ){ 1632 memset(p, 0, sizeof(PmaWriter)); 1633 p->aBuffer = (u8*)sqlite3Malloc(nBuf); 1634 if( !p->aBuffer ){ 1635 p->eFWErr = SQLITE_NOMEM_BKPT; 1636 }else{ 1637 p->iBufEnd = p->iBufStart = (iStart % nBuf); 1638 p->iWriteOff = iStart - p->iBufStart; 1639 p->nBuffer = nBuf; 1640 p->pFd = pFd; 1641 } 1642 } 1643 1644 /* 1645 ** Write nData bytes of data to the PMA. Return SQLITE_OK 1646 ** if successful, or an SQLite error code if an error occurs. 1647 */ 1648 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){ 1649 int nRem = nData; 1650 while( nRem>0 && p->eFWErr==0 ){ 1651 int nCopy = nRem; 1652 if( nCopy>(p->nBuffer - p->iBufEnd) ){ 1653 nCopy = p->nBuffer - p->iBufEnd; 1654 } 1655 1656 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy); 1657 p->iBufEnd += nCopy; 1658 if( p->iBufEnd==p->nBuffer ){ 1659 p->eFWErr = sqlite3OsWrite(p->pFd, 1660 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 1661 p->iWriteOff + p->iBufStart 1662 ); 1663 p->nPmaSpill += (p->iBufEnd - p->iBufStart); 1664 p->iBufStart = p->iBufEnd = 0; 1665 p->iWriteOff += p->nBuffer; 1666 } 1667 assert( p->iBufEndnBuffer ); 1668 1669 nRem -= nCopy; 1670 } 1671 } 1672 1673 /* 1674 ** Flush any buffered data to disk and clean up the PMA-writer object. 1675 ** The results of using the PMA-writer after this call are undefined. 1676 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 1677 ** required. Otherwise, return an SQLite error code. 1678 ** 1679 ** Before returning, set *piEof to the offset immediately following the 1680 ** last byte written to the file. Also, increment (*pnSpill) by the total 1681 ** number of bytes written to the file. 1682 */ 1683 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof, u64 *pnSpill){ 1684 int rc; 1685 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){ 1686 p->eFWErr = sqlite3OsWrite(p->pFd, 1687 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 1688 p->iWriteOff + p->iBufStart 1689 ); 1690 p->nPmaSpill += (p->iBufEnd - p->iBufStart); 1691 } 1692 *piEof = (p->iWriteOff + p->iBufEnd); 1693 *pnSpill += p->nPmaSpill; 1694 sqlite3_free(p->aBuffer); 1695 rc = p->eFWErr; 1696 memset(p, 0, sizeof(PmaWriter)); 1697 return rc; 1698 } 1699 1700 /* 1701 ** Write value iVal encoded as a varint to the PMA. Return 1702 ** SQLITE_OK if successful, or an SQLite error code if an error occurs. 1703 */ 1704 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){ 1705 int nByte; 1706 u8 aByte[10]; 1707 nByte = sqlite3PutVarint(aByte, iVal); 1708 vdbePmaWriteBlob(p, aByte, nByte); 1709 } 1710 1711 /* 1712 ** Write the current contents of in-memory linked-list pList to a level-0 1713 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 1714 ** successful, or an SQLite error code otherwise. 1715 ** 1716 ** The format of a PMA is: 1717 ** 1718 ** * A varint. This varint contains the total number of bytes of content 1719 ** in the PMA (not including the varint itself). 1720 ** 1721 ** * One or more records packed end-to-end in order of ascending keys. 1722 ** Each record consists of a varint followed by a blob of data (the 1723 ** key). The varint is the number of bytes in the blob of data. 1724 */ 1725 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){ 1726 sqlite3 *db = pTask->pSorter->db; 1727 int rc = SQLITE_OK; /* Return code */ 1728 PmaWriter writer; /* Object used to write to the file */ 1729 1730 #ifdef SQLITE_DEBUG 1731 /* Set iSz to the expected size of file pTask->file after writing the PMA. 1732 ** This is used by an assert() statement at the end of this function. */ 1733 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof; 1734 #endif 1735 1736 vdbeSorterWorkDebug(pTask, "enter"); 1737 memset(&writer, 0, sizeof(PmaWriter)); 1738 assert( pList->szPMA>0 ); 1739 1740 /* If the first temporary PMA file has not been opened, open it now. */ 1741 if( pTask->file.pFd==0 ){ 1742 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd); 1743 assert( rc!=SQLITE_OK || pTask->file.pFd ); 1744 assert( pTask->file.iEof==0 ); 1745 assert( pTask->nPMA==0 ); 1746 } 1747 1748 /* Try to get the file to memory map */ 1749 if( rc==SQLITE_OK ){ 1750 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9); 1751 } 1752 1753 /* Sort the list */ 1754 if( rc==SQLITE_OK ){ 1755 rc = vdbeSorterSort(pTask, pList); 1756 } 1757 1758 if( rc==SQLITE_OK ){ 1759 SorterRecord *p; 1760 SorterRecord *pNext = 0; 1761 1762 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz, 1763 pTask->file.iEof); 1764 pTask->nPMA++; 1765 vdbePmaWriteVarint(&writer, pList->szPMA); 1766 for(p=pList->pList; p; p=pNext){ 1767 pNext = p->u.pNext; 1768 vdbePmaWriteVarint(&writer, p->nVal); 1769 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal); 1770 if( pList->aMemory==0 ) sqlite3_free(p); 1771 } 1772 pList->pList = p; 1773 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof, &pTask->nSpill); 1774 } 1775 1776 vdbeSorterWorkDebug(pTask, "exit"); 1777 assert( rc!=SQLITE_OK || pList->pList==0 ); 1778 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz ); 1779 return rc; 1780 } 1781 1782 /* 1783 ** Advance the MergeEngine to its next entry. 1784 ** Set *pbEof to true there is no next entry because 1785 ** the MergeEngine has reached the end of all its inputs. 1786 ** 1787 ** Return SQLITE_OK if successful or an error code if an error occurs. 1788 */ 1789 static int vdbeMergeEngineStep( 1790 MergeEngine *pMerger, /* The merge engine to advance to the next row */ 1791 int *pbEof /* Set TRUE at EOF. Set false for more content */ 1792 ){ 1793 int rc; 1794 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */ 1795 SortSubtask *pTask = pMerger->pTask; 1796 1797 /* Advance the current PmaReader */ 1798 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]); 1799 1800 /* Update contents of aTree[] */ 1801 if( rc==SQLITE_OK ){ 1802 int i; /* Index of aTree[] to recalculate */ 1803 PmaReader *pReadr1; /* First PmaReader to compare */ 1804 PmaReader *pReadr2; /* Second PmaReader to compare */ 1805 int bCached = 0; 1806 1807 /* Find the first two PmaReaders to compare. The one that was just 1808 ** advanced (iPrev) and the one next to it in the array. */ 1809 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)]; 1810 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)]; 1811 1812 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){ 1813 /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */ 1814 int iRes; 1815 if( pReadr1->pFd==0 ){ 1816 iRes = +1; 1817 }else if( pReadr2->pFd==0 ){ 1818 iRes = -1; 1819 }else{ 1820 iRes = pTask->xCompare(pTask, &bCached, 1821 pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey 1822 ); 1823 } 1824 1825 /* If pReadr1 contained the smaller value, set aTree[i] to its index. 1826 ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this 1827 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set 1828 ** pKey2 to point to the record belonging to pReadr2. 1829 ** 1830 ** Alternatively, if pReadr2 contains the smaller of the two values, 1831 ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare() 1832 ** was actually called above, then pTask->pUnpacked now contains 1833 ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent 1834 ** vdbeSorterCompare() from decoding pReadr2 again. 1835 ** 1836 ** If the two values were equal, then the value from the oldest 1837 ** PMA should be considered smaller. The VdbeSorter.aReadr[] array 1838 ** is sorted from oldest to newest, so pReadr1 contains older values 1839 ** than pReadr2 iff (pReadr1aTree[i] = (int)(pReadr1 - pMerger->aReadr); 1842 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; 1843 bCached = 0; 1844 }else{ 1845 if( pReadr1->pFd ) bCached = 0; 1846 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr); 1847 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ]; 1848 } 1849 } 1850 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0); 1851 } 1852 1853 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc); 1854 } 1855 1856 #if SQLITE_MAX_WORKER_THREADS>0 1857 /* 1858 ** The main routine for background threads that write level-0 PMAs. 1859 */ 1860 static void *vdbeSorterFlushThread(void *pCtx){ 1861 SortSubtask *pTask = (SortSubtask*)pCtx; 1862 int rc; /* Return code */ 1863 assert( pTask->bDone==0 ); 1864 rc = vdbeSorterListToPMA(pTask, &pTask->list); 1865 pTask->bDone = 1; 1866 return SQLITE_INT_TO_PTR(rc); 1867 } 1868 #endif /* SQLITE_MAX_WORKER_THREADS>0 */ 1869 1870 /* 1871 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly 1872 ** using a background thread. 1873 */ 1874 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){ 1875 #if SQLITE_MAX_WORKER_THREADS==0 1876 pSorter->bUsePMA = 1; 1877 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list); 1878 #else 1879 int rc = SQLITE_OK; 1880 int i; 1881 SortSubtask *pTask = 0; /* Thread context used to create new PMA */ 1882 int nWorker = (pSorter->nTask-1); 1883 1884 /* Set the flag to indicate that at least one PMA has been written. 1885 ** Or will be, anyhow. */ 1886 pSorter->bUsePMA = 1; 1887 1888 /* Select a sub-task to sort and flush the current list of in-memory 1889 ** records to disk. If the sorter is running in multi-threaded mode, 1890 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if 1891 ** the background thread from a sub-tasks previous turn is still running, 1892 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy, 1893 ** fall back to using the final sub-task. The first (pSorter->nTask-1) 1894 ** sub-tasks are preferred as they use background threads - the final 1895 ** sub-task uses the main thread. */ 1896 for(i=0; iiPrev + i + 1) % nWorker; 1898 pTask = &pSorter->aTask[iTest]; 1899 if( pTask->bDone ){ 1900 rc = vdbeSorterJoinThread(pTask); 1901 } 1902 if( rc!=SQLITE_OK || pTask->pThread==0 ) break; 1903 } 1904 1905 if( rc==SQLITE_OK ){ 1906 if( i==nWorker ){ 1907 /* Use the foreground thread for this operation */ 1908 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list); 1909 }else{ 1910 /* Launch a background thread for this operation */ 1911 u8 *aMem; 1912 void *pCtx; 1913 1914 assert( pTask!=0 ); 1915 assert( pTask->pThread==0 && pTask->bDone==0 ); 1916 assert( pTask->list.pList==0 ); 1917 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); 1918 1919 aMem = pTask->list.aMemory; 1920 pCtx = (void*)pTask; 1921 pSorter->iPrev = (u8)(pTask - pSorter->aTask); 1922 pTask->list = pSorter->list; 1923 pSorter->list.pList = 0; 1924 pSorter->list.szPMA = 0; 1925 if( aMem ){ 1926 pSorter->list.aMemory = aMem; 1927 pSorter->nMemory = sqlite3MallocSize(aMem); 1928 }else if( pSorter->list.aMemory ){ 1929 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory); 1930 if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT; 1931 } 1932 1933 rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx); 1934 } 1935 } 1936 1937 return rc; 1938 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */ 1939 } 1940 1941 /* 1942 ** Add a record to the sorter. 1943 */ 1944 int sqlite3VdbeSorterWrite( 1945 const VdbeCursor *pCsr, /* Sorter cursor */ 1946 Mem *pVal /* Memory cell containing record */ 1947 ){ 1948 VdbeSorter *pSorter; 1949 int rc = SQLITE_OK; /* Return Code */ 1950 SorterRecord *pNew; /* New list element */ 1951 int bFlush; /* True to flush contents of memory to PMA */ 1952 i64 nReq; /* Bytes of memory required */ 1953 i64 nPMA; /* Bytes of PMA space required */ 1954 int t; /* serial type of first record field */ 1955 1956 assert( pCsr->eCurType==CURTYPE_SORTER ); 1957 pSorter = pCsr->uc.pSorter; 1958 getVarint32NR((const u8*)&pVal->z[1], t); 1959 if( t>0 && t<10 ){ 1960 if( t==7 ){ 1961 pSorter->typeMask &= SORTER_TYPE_REAL; 1962 }else{ 1963 pSorter->typeMask &= (SORTER_TYPE_INTEGER|SORTER_TYPE_REAL); 1964 } 1965 }else if( t>10 && (t & 0x01) ){ 1966 pSorter->typeMask &= SORTER_TYPE_TEXT; 1967 }else{ 1968 pSorter->typeMask = 0; 1969 } 1970 1971 assert( pSorter ); 1972 1973 /* Figure out whether or not the current contents of memory should be 1974 ** flushed to a PMA before continuing. If so, do so. 1975 ** 1976 ** If using the single large allocation mode (pSorter->aMemory!=0), then 1977 ** flush the contents of memory to a new PMA if (a) at least one value is 1978 ** already in memory and (b) the new value will not fit in memory. 1979 ** 1980 ** Or, if using separate allocations for each record, flush the contents 1981 ** of memory to a PMA if either of the following are true: 1982 ** 1983 ** * The total memory allocated for the in-memory list is greater 1984 ** than (page-size * cache-size), or 1985 ** 1986 ** * The total memory allocated for the in-memory list is greater 1987 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true. 1988 */ 1989 nReq = pVal->n + sizeof(SorterRecord); 1990 nPMA = pVal->n + sqlite3VarintLen(pVal->n); 1991 if( pSorter->mxPmaSize ){ 1992 if( pSorter->list.aMemory ){ 1993 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize; 1994 }else{ 1995 bFlush = ( 1996 (pSorter->list.szPMA > pSorter->mxPmaSize) 1997 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull()) 1998 ); 1999 } 2000 if( bFlush ){ 2001 rc = vdbeSorterFlushPMA(pSorter); 2002 pSorter->list.szPMA = 0; 2003 pSorter->iMemory = 0; 2004 assert( rc!=SQLITE_OK || pSorter->list.pList==0 ); 2005 } 2006 } 2007 2008 pSorter->list.szPMA += nPMA; 2009 if( nPMA>pSorter->mxKeysize ){ 2010 pSorter->mxKeysize = nPMA; 2011 } 2012 2013 if( pSorter->list.aMemory ){ 2014 int nMin = pSorter->iMemory + nReq; 2015 2016 if( nMin>pSorter->nMemory ){ 2017 u8 *aNew; 2018 sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory; 2019 int iListOff = -1; 2020 if( pSorter->list.pList ){ 2021 iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; 2022 } 2023 while( nNew < nMin ) nNew = nNew*2; 2024 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; 2025 if( nNew < nMin ) nNew = nMin; 2026 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew); 2027 if( !aNew ) return SQLITE_NOMEM_BKPT; 2028 if( iListOff>=0 ){ 2029 pSorter->list.pList = (SorterRecord*)&aNew[iListOff]; 2030 } 2031 pSorter->list.aMemory = aNew; 2032 pSorter->nMemory = nNew; 2033 } 2034 2035 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory]; 2036 pSorter->iMemory += ROUND8(nReq); 2037 if( pSorter->list.pList ){ 2038 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory); 2039 } 2040 }else{ 2041 pNew = (SorterRecord *)sqlite3Malloc(nReq); 2042 if( pNew==0 ){ 2043 return SQLITE_NOMEM_BKPT; 2044 } 2045 pNew->u.pNext = pSorter->list.pList; 2046 } 2047 2048 memcpy(SRVAL(pNew), pVal->z, pVal->n); 2049 pNew->nVal = pVal->n; 2050 pSorter->list.pList = pNew; 2051 2052 return rc; 2053 } 2054 2055 /* 2056 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format 2057 ** of the data stored in aFile[1] is the same as that used by regular PMAs, 2058 ** except that the number-of-bytes varint is omitted from the start. 2059 */ 2060 static int vdbeIncrPopulate(IncrMerger *pIncr){ 2061 int rc = SQLITE_OK; 2062 int rc2; 2063 i64 iStart = pIncr->iStartOff; 2064 SorterFile *pOut = &pIncr->aFile[1]; 2065 SortSubtask *pTask = pIncr->pTask; 2066 MergeEngine *pMerger = pIncr->pMerger; 2067 PmaWriter writer; 2068 assert( pIncr->bEof==0 ); 2069 2070 vdbeSorterPopulateDebug(pTask, "enter"); 2071 2072 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart); 2073 while( rc==SQLITE_OK ){ 2074 int dummy; 2075 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ]; 2076 int nKey = pReader->nKey; 2077 i64 iEof = writer.iWriteOff + writer.iBufEnd; 2078 2079 /* Check if the output file is full or if the input has been exhausted. 2080 ** In either case exit the loop. */ 2081 if( pReader->pFd==0 ) break; 2082 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break; 2083 2084 /* Write the next key to the output. */ 2085 vdbePmaWriteVarint(&writer, nKey); 2086 vdbePmaWriteBlob(&writer, pReader->aKey, nKey); 2087 assert( pIncr->pMerger->pTask==pTask ); 2088 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy); 2089 } 2090 2091 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof, &pTask->nSpill); 2092 if( rc==SQLITE_OK ) rc = rc2; 2093 vdbeSorterPopulateDebug(pTask, "exit"); 2094 return rc; 2095 } 2096 2097 #if SQLITE_MAX_WORKER_THREADS>0 2098 /* 2099 ** The main routine for background threads that populate aFile[1] of 2100 ** multi-threaded IncrMerger objects. 2101 */ 2102 static void *vdbeIncrPopulateThread(void *pCtx){ 2103 IncrMerger *pIncr = (IncrMerger*)pCtx; 2104 void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) ); 2105 pIncr->pTask->bDone = 1; 2106 return pRet; 2107 } 2108 2109 /* 2110 ** Launch a background thread to populate aFile[1] of pIncr. 2111 */ 2112 static int vdbeIncrBgPopulate(IncrMerger *pIncr){ 2113 void *p = (void*)pIncr; 2114 assert( pIncr->bUseThread ); 2115 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p); 2116 } 2117 #endif 2118 2119 /* 2120 ** This function is called when the PmaReader corresponding to pIncr has 2121 ** finished reading the contents of aFile[0]. Its purpose is to "refill" 2122 ** aFile[0] such that the PmaReader should start rereading it from the 2123 ** beginning. 2124 ** 2125 ** For single-threaded objects, this is accomplished by literally reading 2126 ** keys from pIncr->pMerger and repopulating aFile[0]. 2127 ** 2128 ** For multi-threaded objects, all that is required is to wait until the 2129 ** background thread is finished (if it is not already) and then swap 2130 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not 2131 ** been exhausted, this function also launches a new background thread 2132 ** to populate the new aFile[1]. 2133 ** 2134 ** SQLITE_OK is returned on success, or an SQLite error code otherwise. 2135 */ 2136 static int vdbeIncrSwap(IncrMerger *pIncr){ 2137 int rc = SQLITE_OK; 2138 2139 #if SQLITE_MAX_WORKER_THREADS>0 2140 if( pIncr->bUseThread ){ 2141 rc = vdbeSorterJoinThread(pIncr->pTask); 2142 2143 if( rc==SQLITE_OK ){ 2144 SorterFile f0 = pIncr->aFile[0]; 2145 pIncr->aFile[0] = pIncr->aFile[1]; 2146 pIncr->aFile[1] = f0; 2147 } 2148 2149 if( rc==SQLITE_OK ){ 2150 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ 2151 pIncr->bEof = 1; 2152 }else{ 2153 rc = vdbeIncrBgPopulate(pIncr); 2154 } 2155 } 2156 }else 2157 #endif 2158 { 2159 rc = vdbeIncrPopulate(pIncr); 2160 pIncr->aFile[0] = pIncr->aFile[1]; 2161 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){ 2162 pIncr->bEof = 1; 2163 } 2164 } 2165 2166 return rc; 2167 } 2168 2169 /* 2170 ** Allocate and return a new IncrMerger object to read data from pMerger. 2171 ** 2172 ** If an OOM condition is encountered, return NULL. In this case free the 2173 ** pMerger argument before returning. 2174 */ 2175 static int vdbeIncrMergerNew( 2176 SortSubtask *pTask, /* The thread that will be using the new IncrMerger */ 2177 MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */ 2178 IncrMerger **ppOut /* Write the new IncrMerger here */ 2179 ){ 2180 int rc = SQLITE_OK; 2181 IncrMerger *pIncr = *ppOut = (IncrMerger*) 2182 (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr))); 2183 if( pIncr ){ 2184 pIncr->pMerger = pMerger; 2185 pIncr->pTask = pTask; 2186 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2); 2187 pTask->file2.iEof += pIncr->mxSz; 2188 }else{ 2189 vdbeMergeEngineFree(pMerger); 2190 rc = SQLITE_NOMEM_BKPT; 2191 } 2192 assert( *ppOut!=0 || rc!=SQLITE_OK ); 2193 return rc; 2194 } 2195 2196 #if SQLITE_MAX_WORKER_THREADS>0 2197 /* 2198 ** Set the "use-threads" flag on object pIncr. 2199 */ 2200 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){ 2201 pIncr->bUseThread = 1; 2202 pIncr->pTask->file2.iEof -= pIncr->mxSz; 2203 } 2204 #endif /* SQLITE_MAX_WORKER_THREADS>0 */ 2205 2206 2207 2208 /* 2209 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the 2210 ** two PmaReaders that feed that entry. Neither of the PmaReaders 2211 ** are advanced. This routine merely does the comparison. 2212 */ 2213 static void vdbeMergeEngineCompare( 2214 MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */ 2215 int iOut /* Store the result in pMerger->aTree[iOut] */ 2216 ){ 2217 int i1; 2218 int i2; 2219 int iRes; 2220 PmaReader *p1; 2221 PmaReader *p2; 2222 2223 assert( iOutnTree && iOut>0 ); 2224 2225 if( iOut>=(pMerger->nTree/2) ){ 2226 i1 = (iOut - pMerger->nTree/2) * 2; 2227 i2 = i1 + 1; 2228 }else{ 2229 i1 = pMerger->aTree[iOut*2]; 2230 i2 = pMerger->aTree[iOut*2+1]; 2231 } 2232 2233 p1 = &pMerger->aReadr[i1]; 2234 p2 = &pMerger->aReadr[i2]; 2235 2236 if( p1->pFd==0 ){ 2237 iRes = i2; 2238 }else if( p2->pFd==0 ){ 2239 iRes = i1; 2240 }else{ 2241 SortSubtask *pTask = pMerger->pTask; 2242 int bCached = 0; 2243 int res; 2244 assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */ 2245 res = pTask->xCompare( 2246 pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey 2247 ); 2248 if( res<=0 ){ 2249 iRes = i1; 2250 }else{ 2251 iRes = i2; 2252 } 2253 } 2254 2255 pMerger->aTree[iOut] = iRes; 2256 } 2257 2258 /* 2259 ** Allowed values for the eMode parameter to vdbeMergeEngineInit() 2260 ** and vdbePmaReaderIncrMergeInit(). 2261 ** 2262 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when 2263 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used 2264 ** when there exists one or more separate worker threads. 2265 */ 2266 #define INCRINIT_NORMAL 0 2267 #define INCRINIT_TASK 1 2268 #define INCRINIT_ROOT 2 2269 2270 /* 2271 ** Forward reference required as the vdbeIncrMergeInit() and 2272 ** vdbePmaReaderIncrInit() routines are called mutually recursively when 2273 ** building a merge tree. 2274 */ 2275 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode); 2276 2277 /* 2278 ** Initialize the MergeEngine object passed as the second argument. Once this 2279 ** function returns, the first key of merged data may be read from the 2280 ** MergeEngine object in the usual fashion. 2281 ** 2282 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge 2283 ** objects attached to the PmaReader objects that the merger reads from have 2284 ** already been populated, but that they have not yet populated aFile[0] and 2285 ** set the PmaReader objects up to read from it. In this case all that is 2286 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at 2287 ** its first key. 2288 ** 2289 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 2290 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 2291 ** to pMerger. 2292 ** 2293 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. 2294 */ 2295 static int vdbeMergeEngineInit( 2296 SortSubtask *pTask, /* Thread that will run pMerger */ 2297 MergeEngine *pMerger, /* MergeEngine to initialize */ 2298 int eMode /* One of the INCRINIT_XXX constants */ 2299 ){ 2300 int rc = SQLITE_OK; /* Return code */ 2301 int i; /* For looping over PmaReader objects */ 2302 int nTree; /* Number of subtrees to merge */ 2303 2304 /* Failure to allocate the merge would have been detected prior to 2305 ** invoking this routine */ 2306 assert( pMerger!=0 ); 2307 2308 /* eMode is always INCRINIT_NORMAL in single-threaded mode */ 2309 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); 2310 2311 /* Verify that the MergeEngine is assigned to a single thread */ 2312 assert( pMerger->pTask==0 ); 2313 pMerger->pTask = pTask; 2314 2315 nTree = pMerger->nTree; 2316 for(i=0; i0 && eMode==INCRINIT_ROOT ){ 2318 /* PmaReaders should be normally initialized in order, as if they are 2319 ** reading from the same temp file this makes for more linear file IO. 2320 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is 2321 ** in use it will block the vdbePmaReaderNext() call while it uses 2322 ** the main thread to fill its buffer. So calling PmaReaderNext() 2323 ** on this PmaReader before any of the multi-threaded PmaReaders takes 2324 ** better advantage of multi-processor hardware. */ 2325 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]); 2326 }else{ 2327 rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL); 2328 } 2329 if( rc!=SQLITE_OK ) return rc; 2330 } 2331 2332 for(i=pMerger->nTree-1; i>0; i--){ 2333 vdbeMergeEngineCompare(pMerger, i); 2334 } 2335 return pTask->pUnpacked->errCode; 2336 } 2337 2338 /* 2339 ** The PmaReader passed as the first argument is guaranteed to be an 2340 ** incremental-reader (pReadr->pIncr!=0). This function serves to open 2341 ** and/or initialize the temp file related fields of the IncrMerge 2342 ** object at (pReadr->pIncr). 2343 ** 2344 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders 2345 ** in the sub-tree headed by pReadr are also initialized. Data is then 2346 ** loaded into the buffers belonging to pReadr and it is set to point to 2347 ** the first key in its range. 2348 ** 2349 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed 2350 ** to be a multi-threaded PmaReader and this function is being called in a 2351 ** background thread. In this case all PmaReaders in the sub-tree are 2352 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to 2353 ** pReadr is populated. However, pReadr itself is not set up to point 2354 ** to its first key. A call to vdbePmaReaderNext() is still required to do 2355 ** that. 2356 ** 2357 ** The reason this function does not call vdbePmaReaderNext() immediately 2358 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has 2359 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since 2360 ** this entire function is being run by thread (pTask->thread), that will 2361 ** lead to the current background thread attempting to join itself. 2362 ** 2363 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed 2364 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all 2365 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK). 2366 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and 2367 ** the current PmaReader set to point to the first key in its range. 2368 ** 2369 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. 2370 */ 2371 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){ 2372 int rc = SQLITE_OK; 2373 IncrMerger *pIncr = pReadr->pIncr; 2374 SortSubtask *pTask = pIncr->pTask; 2375 sqlite3 *db = pTask->pSorter->db; 2376 2377 /* eMode is always INCRINIT_NORMAL in single-threaded mode */ 2378 assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL ); 2379 2380 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode); 2381 2382 /* Set up the required files for pIncr. A multi-threaded IncrMerge object 2383 ** requires two temp files to itself, whereas a single-threaded object 2384 ** only requires a region of pTask->file2. */ 2385 if( rc==SQLITE_OK ){ 2386 int mxSz = pIncr->mxSz; 2387 #if SQLITE_MAX_WORKER_THREADS>0 2388 if( pIncr->bUseThread ){ 2389 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd); 2390 if( rc==SQLITE_OK ){ 2391 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd); 2392 } 2393 }else 2394 #endif 2395 /*if( !pIncr->bUseThread )*/{ 2396 if( pTask->file2.pFd==0 ){ 2397 assert( pTask->file2.iEof>0 ); 2398 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd); 2399 pTask->file2.iEof = 0; 2400 } 2401 if( rc==SQLITE_OK ){ 2402 pIncr->aFile[1].pFd = pTask->file2.pFd; 2403 pIncr->iStartOff = pTask->file2.iEof; 2404 pTask->file2.iEof += mxSz; 2405 } 2406 } 2407 } 2408 2409 #if SQLITE_MAX_WORKER_THREADS>0 2410 if( rc==SQLITE_OK && pIncr->bUseThread ){ 2411 /* Use the current thread to populate aFile[1], even though this 2412 ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object, 2413 ** then this function is already running in background thread 2414 ** pIncr->pTask->thread. 2415 ** 2416 ** If this is the INCRINIT_ROOT object, then it is running in the 2417 ** main VDBE thread. But that is Ok, as that thread cannot return 2418 ** control to the VDBE or proceed with anything useful until the 2419 ** first results are ready from this merger object anyway. 2420 */ 2421 assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK ); 2422 rc = vdbeIncrPopulate(pIncr); 2423 } 2424 #endif 2425 2426 if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){ 2427 rc = vdbePmaReaderNext(pReadr); 2428 } 2429 2430 return rc; 2431 } 2432 2433 #if SQLITE_MAX_WORKER_THREADS>0 2434 /* 2435 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in 2436 ** background threads. 2437 */ 2438 static void *vdbePmaReaderBgIncrInit(void *pCtx){ 2439 PmaReader *pReader = (PmaReader*)pCtx; 2440 void *pRet = SQLITE_INT_TO_PTR( 2441 vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK) 2442 ); 2443 pReader->pIncr->pTask->bDone = 1; 2444 return pRet; 2445 } 2446 #endif 2447 2448 /* 2449 ** If the PmaReader passed as the first argument is not an incremental-reader 2450 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes 2451 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to 2452 ** this routine to initialize the incremental merge. 2453 ** 2454 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), 2455 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit(). 2456 ** Or, if the IncrMerger is single threaded, the same function is called 2457 ** using the current thread. 2458 */ 2459 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){ 2460 IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */ 2461 int rc = SQLITE_OK; /* Return code */ 2462 if( pIncr ){ 2463 #if SQLITE_MAX_WORKER_THREADS>0 2464 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK ); 2465 if( pIncr->bUseThread ){ 2466 void *pCtx = (void*)pReadr; 2467 rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx); 2468 }else 2469 #endif 2470 { 2471 rc = vdbePmaReaderIncrMergeInit(pReadr, eMode); 2472 } 2473 } 2474 return rc; 2475 } 2476 2477 /* 2478 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0 2479 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to 2480 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut 2481 ** to NULL and return an SQLite error code. 2482 ** 2483 ** When this function is called, *piOffset is set to the offset of the 2484 ** first PMA to read from pTask->file. Assuming no error occurs, it is 2485 ** set to the offset immediately following the last byte of the last 2486 ** PMA before returning. If an error does occur, then the final value of 2487 ** *piOffset is undefined. 2488 */ 2489 static int vdbeMergeEngineLevel0( 2490 SortSubtask *pTask, /* Sorter task to read from */ 2491 int nPMA, /* Number of PMAs to read */ 2492 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */ 2493 MergeEngine **ppOut /* OUT: New merge-engine */ 2494 ){ 2495 MergeEngine *pNew; /* Merge engine to return */ 2496 i64 iOff = *piOffset; 2497 int i; 2498 int rc = SQLITE_OK; 2499 2500 *ppOut = pNew = vdbeMergeEngineNew(nPMA); 2501 if( pNew==0 ) rc = SQLITE_NOMEM_BKPT; 2502 2503 for(i=0; iaReadr[i]; 2506 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy); 2507 iOff = pReadr->iEof; 2508 } 2509 2510 if( rc!=SQLITE_OK ){ 2511 vdbeMergeEngineFree(pNew); 2512 *ppOut = 0; 2513 } 2514 *piOffset = iOff; 2515 return rc; 2516 } 2517 2518 /* 2519 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of 2520 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes. 2521 ** 2522 ** i.e. 2523 ** 2524 ** nPMA<=16 -> TreeDepth() == 0 2525 ** nPMA<=256 -> TreeDepth() == 1 2526 ** nPMA<=65536 -> TreeDepth() == 2 2527 */ 2528 static int vdbeSorterTreeDepth(int nPMA){ 2529 int nDepth = 0; 2530 i64 nDiv = SORTER_MAX_MERGE_COUNT; 2531 while( nDiv < (i64)nPMA ){ 2532 nDiv = nDiv * SORTER_MAX_MERGE_COUNT; 2533 nDepth++; 2534 } 2535 return nDepth; 2536 } 2537 2538 /* 2539 ** pRoot is the root of an incremental merge-tree with depth nDepth (according 2540 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the 2541 ** tree, counting from zero. This function adds pLeaf to the tree. 2542 ** 2543 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error 2544 ** code is returned and pLeaf is freed. 2545 */ 2546 static int vdbeSorterAddToTree( 2547 SortSubtask *pTask, /* Task context */ 2548 int nDepth, /* Depth of tree according to TreeDepth() */ 2549 int iSeq, /* Sequence number of leaf within tree */ 2550 MergeEngine *pRoot, /* Root of tree */ 2551 MergeEngine *pLeaf /* Leaf to add to tree */ 2552 ){ 2553 int rc = SQLITE_OK; 2554 int nDiv = 1; 2555 int i; 2556 MergeEngine *p = pRoot; 2557 IncrMerger *pIncr; 2558 2559 rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr); 2560 2561 for(i=1; iaReadr[iIter]; 2568 2569 if( pReadr->pIncr==0 ){ 2570 MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); 2571 if( pNew==0 ){ 2572 rc = SQLITE_NOMEM_BKPT; 2573 }else{ 2574 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr); 2575 } 2576 } 2577 if( rc==SQLITE_OK ){ 2578 p = pReadr->pIncr->pMerger; 2579 nDiv = nDiv / SORTER_MAX_MERGE_COUNT; 2580 } 2581 } 2582 2583 if( rc==SQLITE_OK ){ 2584 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr; 2585 }else{ 2586 vdbeIncrFree(pIncr); 2587 } 2588 return rc; 2589 } 2590 2591 /* 2592 ** This function is called as part of a SorterRewind() operation on a sorter 2593 ** that has already written two or more level-0 PMAs to one or more temp 2594 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 2595 ** can be used to incrementally merge all PMAs on disk. 2596 ** 2597 ** If successful, SQLITE_OK is returned and *ppOut set to point to the 2598 ** MergeEngine object at the root of the tree before returning. Or, if an 2599 ** error occurs, an SQLite error code is returned and the final value 2600 ** of *ppOut is undefined. 2601 */ 2602 static int vdbeSorterMergeTreeBuild( 2603 VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */ 2604 MergeEngine **ppOut /* Write the MergeEngine here */ 2605 ){ 2606 MergeEngine *pMain = 0; 2607 int rc = SQLITE_OK; 2608 int iTask; 2609 2610 #if SQLITE_MAX_WORKER_THREADS>0 2611 /* If the sorter uses more than one task, then create the top-level 2612 ** MergeEngine here. This MergeEngine will read data from exactly 2613 ** one PmaReader per sub-task. */ 2614 assert( pSorter->bUseThreads || pSorter->nTask==1 ); 2615 if( pSorter->nTask>1 ){ 2616 pMain = vdbeMergeEngineNew(pSorter->nTask); 2617 if( pMain==0 ) rc = SQLITE_NOMEM_BKPT; 2618 } 2619 #endif 2620 2621 for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ 2622 SortSubtask *pTask = &pSorter->aTask[iTask]; 2623 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 ); 2624 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){ 2625 MergeEngine *pRoot = 0; /* Root node of tree for this task */ 2626 int nDepth = vdbeSorterTreeDepth(pTask->nPMA); 2627 i64 iReadOff = 0; 2628 2629 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){ 2630 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot); 2631 }else{ 2632 int i; 2633 int iSeq = 0; 2634 pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT); 2635 if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT; 2636 for(i=0; inPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){ 2637 MergeEngine *pMerger = 0; /* New level-0 PMA merger */ 2638 int nReader; /* Number of level-0 PMAs to merge */ 2639 2640 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT); 2641 rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger); 2642 if( rc==SQLITE_OK ){ 2643 rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger); 2644 } 2645 } 2646 } 2647 2648 if( rc==SQLITE_OK ){ 2649 #if SQLITE_MAX_WORKER_THREADS>0 2650 if( pMain!=0 ){ 2651 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr); 2652 }else 2653 #endif 2654 { 2655 assert( pMain==0 ); 2656 pMain = pRoot; 2657 } 2658 }else{ 2659 vdbeMergeEngineFree(pRoot); 2660 } 2661 } 2662 } 2663 2664 if( rc!=SQLITE_OK ){ 2665 vdbeMergeEngineFree(pMain); 2666 pMain = 0; 2667 } 2668 *ppOut = pMain; 2669 return rc; 2670 } 2671 2672 /* 2673 ** This function is called as part of an sqlite3VdbeSorterRewind() operation 2674 ** on a sorter that has written two or more PMAs to temporary files. It sets 2675 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader 2676 ** (for multi-threaded sorters) so that it can be used to iterate through 2677 ** all records stored in the sorter. 2678 ** 2679 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise. 2680 */ 2681 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){ 2682 int rc; /* Return code */ 2683 SortSubtask *pTask0 = &pSorter->aTask[0]; 2684 MergeEngine *pMain = 0; 2685 #if SQLITE_MAX_WORKER_THREADS 2686 sqlite3 *db = pTask0->pSorter->db; 2687 int i; 2688 SorterCompare xCompare = vdbeSorterGetCompare(pSorter); 2689 for(i=0; inTask; i++){ 2690 pSorter->aTask[i].xCompare = xCompare; 2691 } 2692 #endif 2693 2694 rc = vdbeSorterMergeTreeBuild(pSorter, &pMain); 2695 if( rc==SQLITE_OK ){ 2696 #if SQLITE_MAX_WORKER_THREADS 2697 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 ); 2698 if( pSorter->bUseThreads ){ 2699 int iTask; 2700 PmaReader *pReadr = 0; 2701 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1]; 2702 rc = vdbeSortAllocUnpacked(pLast); 2703 if( rc==SQLITE_OK ){ 2704 pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader)); 2705 pSorter->pReader = pReadr; 2706 if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT; 2707 } 2708 if( rc==SQLITE_OK ){ 2709 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr); 2710 if( rc==SQLITE_OK ){ 2711 vdbeIncrMergerSetThreads(pReadr->pIncr); 2712 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){ 2713 IncrMerger *pIncr; 2714 if( (pIncr = pMain->aReadr[iTask].pIncr) ){ 2715 vdbeIncrMergerSetThreads(pIncr); 2716 assert( pIncr->pTask!=pLast ); 2717 } 2718 } 2719 for(iTask=0; rc==SQLITE_OK && iTasknTask; iTask++){ 2720 /* Check that: 2721 ** 2722 ** a) The incremental merge object is configured to use the 2723 ** right task, and 2724 ** b) If it is using task (nTask-1), it is configured to run 2725 ** in single-threaded mode. This is important, as the 2726 ** root merge (INCRINIT_ROOT) will be using the same task 2727 ** object. 2728 */ 2729 PmaReader *p = &pMain->aReadr[iTask]; 2730 assert( p->pIncr==0 || ( 2731 (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */ 2732 && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */ 2733 )); 2734 rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK); 2735 } 2736 } 2737 pMain = 0; 2738 } 2739 if( rc==SQLITE_OK ){ 2740 rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT); 2741 } 2742 }else 2743 #endif 2744 { 2745 rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL); 2746 pSorter->pMerger = pMain; 2747 pMain = 0; 2748 } 2749 } 2750 2751 if( rc!=SQLITE_OK ){ 2752 vdbeMergeEngineFree(pMain); 2753 } 2754 return rc; 2755 } 2756 2757 2758 /* 2759 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite, 2760 ** this function is called to prepare for iterating through the records 2761 ** in sorted order. 2762 */ 2763 int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){ 2764 VdbeSorter *pSorter; 2765 int rc = SQLITE_OK; /* Return code */ 2766 2767 assert( pCsr->eCurType==CURTYPE_SORTER ); 2768 pSorter = pCsr->uc.pSorter; 2769 assert( pSorter ); 2770 2771 /* If no data has been written to disk, then do not do so now. Instead, 2772 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly 2773 ** from the in-memory list. */ 2774 if( pSorter->bUsePMA==0 ){ 2775 if( pSorter->list.pList ){ 2776 *pbEof = 0; 2777 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list); 2778 }else{ 2779 *pbEof = 1; 2780 } 2781 return rc; 2782 } 2783 2784 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 2785 ** function flushes the contents of memory to disk, it immediately always 2786 ** creates a new list consisting of a single key immediately afterwards. 2787 ** So the list is never empty at this point. */ 2788 assert( pSorter->list.pList ); 2789 rc = vdbeSorterFlushPMA(pSorter); 2790 2791 /* Join all threads */ 2792 rc = vdbeSorterJoinAll(pSorter, rc); 2793 2794 vdbeSorterRewindDebug("rewind"); 2795 2796 /* Assuming no errors have occurred, set up a merger structure to 2797 ** incrementally read and merge all remaining PMAs. */ 2798 assert( pSorter->pReader==0 ); 2799 if( rc==SQLITE_OK ){ 2800 rc = vdbeSorterSetupMerge(pSorter); 2801 *pbEof = 0; 2802 } 2803 2804 vdbeSorterRewindDebug("rewinddone"); 2805 return rc; 2806 } 2807 2808 /* 2809 ** Advance to the next element in the sorter. Return value: 2810 ** 2811 ** SQLITE_OK success 2812 ** SQLITE_DONE end of data 2813 ** otherwise some kind of error. 2814 */ 2815 int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){ 2816 VdbeSorter *pSorter; 2817 int rc; /* Return code */ 2818 2819 assert( pCsr->eCurType==CURTYPE_SORTER ); 2820 pSorter = pCsr->uc.pSorter; 2821 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) ); 2822 if( pSorter->bUsePMA ){ 2823 assert( pSorter->pReader==0 || pSorter->pMerger==0 ); 2824 assert( pSorter->bUseThreads==0 || pSorter->pReader ); 2825 assert( pSorter->bUseThreads==1 || pSorter->pMerger ); 2826 #if SQLITE_MAX_WORKER_THREADS>0 2827 if( pSorter->bUseThreads ){ 2828 rc = vdbePmaReaderNext(pSorter->pReader); 2829 if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE; 2830 }else 2831 #endif 2832 /*if( !pSorter->bUseThreads )*/ { 2833 int res = 0; 2834 assert( pSorter->pMerger!=0 ); 2835 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) ); 2836 rc = vdbeMergeEngineStep(pSorter->pMerger, &res); 2837 if( rc==SQLITE_OK && res ) rc = SQLITE_DONE; 2838 } 2839 }else{ 2840 SorterRecord *pFree = pSorter->list.pList; 2841 pSorter->list.pList = pFree->u.pNext; 2842 pFree->u.pNext = 0; 2843 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree); 2844 rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE; 2845 } 2846 return rc; 2847 } 2848 2849 /* 2850 ** Return a pointer to a buffer owned by the sorter that contains the 2851 ** current key. 2852 */ 2853 static void *vdbeSorterRowkey( 2854 const VdbeSorter *pSorter, /* Sorter object */ 2855 int *pnKey /* OUT: Size of current key in bytes */ 2856 ){ 2857 void *pKey; 2858 if( pSorter->bUsePMA ){ 2859 PmaReader *pReader; 2860 #if SQLITE_MAX_WORKER_THREADS>0 2861 if( pSorter->bUseThreads ){ 2862 pReader = pSorter->pReader; 2863 }else 2864 #endif 2865 /*if( !pSorter->bUseThreads )*/{ 2866 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]]; 2867 } 2868 *pnKey = pReader->nKey; 2869 pKey = pReader->aKey; 2870 }else{ 2871 *pnKey = pSorter->list.pList->nVal; 2872 pKey = SRVAL(pSorter->list.pList); 2873 } 2874 return pKey; 2875 } 2876 2877 /* 2878 ** Copy the current sorter key into the memory cell pOut. 2879 */ 2880 int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){ 2881 VdbeSorter *pSorter; 2882 void *pKey; int nKey; /* Sorter key to copy into pOut */ 2883 2884 assert( pCsr->eCurType==CURTYPE_SORTER ); 2885 pSorter = pCsr->uc.pSorter; 2886 pKey = vdbeSorterRowkey(pSorter, &nKey); 2887 if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){ 2888 return SQLITE_NOMEM_BKPT; 2889 } 2890 pOut->n = nKey; 2891 MemSetTypeFlag(pOut, MEM_Blob); 2892 memcpy(pOut->z, pKey, nKey); 2893 2894 return SQLITE_OK; 2895 } 2896 2897 /* 2898 ** Compare the key in memory cell pVal with the key that the sorter cursor 2899 ** passed as the first argument currently points to. For the purposes of 2900 ** the comparison, ignore the rowid field at the end of each record. 2901 ** 2902 ** If the sorter cursor key contains any NULL values, consider it to be 2903 ** less than pVal. Even if pVal also contains NULL values. 2904 ** 2905 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM). 2906 ** Otherwise, set *pRes to a negative, zero or positive value if the 2907 ** key in pVal is smaller than, equal to or larger than the current sorter 2908 ** key. 2909 ** 2910 ** This routine forms the core of the OP_SorterCompare opcode, which in 2911 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX. 2912 */ 2913 int sqlite3VdbeSorterCompare( 2914 const VdbeCursor *pCsr, /* Sorter cursor */ 2915 Mem *pVal, /* Value to compare to current sorter key */ 2916 int nKeyCol, /* Compare this many columns */ 2917 int *pRes /* OUT: Result of comparison */ 2918 ){ 2919 VdbeSorter *pSorter; 2920 UnpackedRecord *r2; 2921 KeyInfo *pKeyInfo; 2922 int i; 2923 void *pKey; int nKey; /* Sorter key to compare pVal with */ 2924 2925 assert( pCsr->eCurType==CURTYPE_SORTER ); 2926 pSorter = pCsr->uc.pSorter; 2927 r2 = pSorter->pUnpacked; 2928 pKeyInfo = pCsr->pKeyInfo; 2929 if( r2==0 ){ 2930 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo); 2931 if( r2==0 ) return SQLITE_NOMEM_BKPT; 2932 r2->nField = nKeyCol; 2933 } 2934 assert( r2->nField==nKeyCol ); 2935 2936 pKey = vdbeSorterRowkey(pSorter, &nKey); 2937 sqlite3VdbeRecordUnpack(nKey, pKey, r2); 2938 for(i=0; iaMem[i].flags & MEM_Null ){ 2940 *pRes = -1; 2941 return SQLITE_OK; 2942 } 2943 } 2944 2945 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2); 2946 return SQLITE_OK; 2947 }