vdbesort.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /*
  2. ** 2011 July 9
  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 (as may be required, for
  14. ** example, by CREATE INDEX statements on tables too large to fit in main
  15. ** memory).
  16. */
  17. #include "sqliteInt.h"
  18. #include "vdbeInt.h"
  19. typedef struct VdbeSorterIter VdbeSorterIter;
  20. typedef struct SorterRecord SorterRecord;
  21. typedef struct FileWriter FileWriter;
  22. /*
  23. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  24. **
  25. ** As keys are added to the sorter, they are written to disk in a series
  26. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  27. ** the same as the cache-size allowed for temporary databases. In order
  28. ** to allow the caller to extract keys from the sorter in sorted order,
  29. ** all PMAs currently stored on disk must be merged together. This comment
  30. ** describes the data structure used to do so. The structure supports
  31. ** merging any number of arrays in a single pass with no redundant comparison
  32. ** operations.
  33. **
  34. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  35. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  36. ** the purposes of the paragraphs below, we assume that the array is actually
  37. ** N elements in size, where N is the smallest power of 2 greater to or equal
  38. ** to the number of iterators being merged. The extra aIter[] elements are
  39. ** treated as if they are empty (always at EOF).
  40. **
  41. ** The aTree[] array is also N elements in size. The value of N is stored in
  42. ** the VdbeSorter.nTree variable.
  43. **
  44. ** The final (N/2) elements of aTree[] contain the results of comparing
  45. ** pairs of iterator keys together. Element i contains the result of
  46. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  47. ** aTree element is set to the index of it.
  48. **
  49. ** For the purposes of this comparison, EOF is considered greater than any
  50. ** other key value. If the keys are equal (only possible with two EOF
  51. ** values), it doesn't matter which index is stored.
  52. **
  53. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  54. ** above contains the index of the smallest of each block of 4 iterators.
  55. ** And so on. So that aTree[1] contains the index of the iterator that
  56. ** currently points to the smallest key value. aTree[0] is unused.
  57. **
  58. ** Example:
  59. **
  60. ** aIter[0] -> Banana
  61. ** aIter[1] -> Feijoa
  62. ** aIter[2] -> Elderberry
  63. ** aIter[3] -> Currant
  64. ** aIter[4] -> Grapefruit
  65. ** aIter[5] -> Apple
  66. ** aIter[6] -> Durian
  67. ** aIter[7] -> EOF
  68. **
  69. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  70. **
  71. ** The current element is "Apple" (the value of the key indicated by
  72. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  73. ** be advanced to the next key in its segment. Say the next key is
  74. ** "Eggplant":
  75. **
  76. ** aIter[5] -> Eggplant
  77. **
  78. ** The contents of aTree[] are updated first by comparing the new iterator
  79. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  80. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  81. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  82. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  83. ** so the value written into element 1 of the array is 0. As follows:
  84. **
  85. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  86. **
  87. ** In other words, each time we advance to the next sorter element, log2(N)
  88. ** key comparison operations are required, where N is the number of segments
  89. ** being merged (rounded up to the next power of 2).
  90. */
  91. struct VdbeSorter {
  92. i64 iWriteOff; /* Current write offset within file pTemp1 */
  93. i64 iReadOff; /* Current read offset within file pTemp1 */
  94. int nInMemory; /* Current size of pRecord list as PMA */
  95. int nTree; /* Used size of aTree/aIter (power of 2) */
  96. int nPMA; /* Number of PMAs stored in pTemp1 */
  97. int mnPmaSize; /* Minimum PMA size, in bytes */
  98. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  99. VdbeSorterIter *aIter; /* Array of iterators to merge */
  100. int *aTree; /* Current state of incremental merge */
  101. sqlite3_file *pTemp1; /* PMA file 1 */
  102. SorterRecord *pRecord; /* Head of in-memory record list */
  103. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  104. };
  105. /*
  106. ** The following type is an iterator for a PMA. It caches the current key in
  107. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  108. */
  109. struct VdbeSorterIter {
  110. i64 iReadOff; /* Current read offset */
  111. i64 iEof; /* 1 byte past EOF for this iterator */
  112. int nAlloc; /* Bytes of space at aAlloc */
  113. int nKey; /* Number of bytes in key */
  114. sqlite3_file *pFile; /* File iterator is reading from */
  115. u8 *aAlloc; /* Allocated space */
  116. u8 *aKey; /* Pointer to current key */
  117. u8 *aBuffer; /* Current read buffer */
  118. int nBuffer; /* Size of read buffer in bytes */
  119. };
  120. /*
  121. ** An instance of this structure is used to organize the stream of records
  122. ** being written to files by the merge-sort code into aligned, page-sized
  123. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  124. ** faster on many operating systems.
  125. */
  126. struct FileWriter {
  127. int eFWErr; /* Non-zero if in an error state */
  128. u8 *aBuffer; /* Pointer to write buffer */
  129. int nBuffer; /* Size of write buffer in bytes */
  130. int iBufStart; /* First byte of buffer to write */
  131. int iBufEnd; /* Last byte of buffer to write */
  132. i64 iWriteOff; /* Offset of start of buffer in file */
  133. sqlite3_file *pFile; /* File to write to */
  134. };
  135. /*
  136. ** A structure to store a single record. All in-memory records are connected
  137. ** together into a linked list headed at VdbeSorter.pRecord using the
  138. ** SorterRecord.pNext pointer.
  139. */
  140. struct SorterRecord {
  141. void *pVal;
  142. int nVal;
  143. SorterRecord *pNext;
  144. };
  145. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  146. #define SORTER_MIN_WORKING 10
  147. /* Maximum number of segments to merge in a single pass. */
  148. #define SORTER_MAX_MERGE_COUNT 16
  149. /*
  150. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  151. ** argument. All structure fields are set to zero before returning.
  152. */
  153. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  154. sqlite3DbFree(db, pIter->aAlloc);
  155. sqlite3DbFree(db, pIter->aBuffer);
  156. memset(pIter, 0, sizeof(VdbeSorterIter));
  157. }
  158. /*
  159. ** Read nByte bytes of data from the stream of data iterated by object p.
  160. ** If successful, set *ppOut to point to a buffer containing the data
  161. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  162. ** error code.
  163. **
  164. ** The buffer indicated by *ppOut may only be considered valid until the
  165. ** next call to this function.
  166. */
  167. static int vdbeSorterIterRead(
  168. sqlite3 *db, /* Database handle (for malloc) */
  169. VdbeSorterIter *p, /* Iterator */
  170. int nByte, /* Bytes of data to read */
  171. u8 **ppOut /* OUT: Pointer to buffer containing data */
  172. ){
  173. int iBuf; /* Offset within buffer to read from */
  174. int nAvail; /* Bytes of data available in buffer */
  175. assert( p->aBuffer );
  176. /* If there is no more data to be read from the buffer, read the next
  177. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  178. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  179. iBuf = p->iReadOff % p->nBuffer;
  180. if( iBuf==0 ){
  181. int nRead; /* Bytes to read from disk */
  182. int rc; /* sqlite3OsRead() return code */
  183. /* Determine how many bytes of data to read. */
  184. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  185. nRead = p->nBuffer;
  186. }else{
  187. nRead = (int)(p->iEof - p->iReadOff);
  188. }
  189. assert( nRead>0 );
  190. /* Read data from the file. Return early if an error occurs. */
  191. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  192. assert( rc!=SQLITE_IOERR_SHORT_READ );
  193. if( rc!=SQLITE_OK ) return rc;
  194. }
  195. nAvail = p->nBuffer - iBuf;
  196. if( nByte<=nAvail ){
  197. /* The requested data is available in the in-memory buffer. In this
  198. ** case there is no need to make a copy of the data, just return a
  199. ** pointer into the buffer to the caller. */
  200. *ppOut = &p->aBuffer[iBuf];
  201. p->iReadOff += nByte;
  202. }else{
  203. /* The requested data is not all available in the in-memory buffer.
  204. ** In this case, allocate space at p->aAlloc[] to copy the requested
  205. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  206. int nRem; /* Bytes remaining to copy */
  207. /* Extend the p->aAlloc[] allocation if required. */
  208. if( p->nAlloc<nByte ){
  209. int nNew = p->nAlloc*2;
  210. while( nByte>nNew ) nNew = nNew*2;
  211. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  212. if( !p->aAlloc ) return SQLITE_NOMEM;
  213. p->nAlloc = nNew;
  214. }
  215. /* Copy as much data as is available in the buffer into the start of
  216. ** p->aAlloc[]. */
  217. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  218. p->iReadOff += nAvail;
  219. nRem = nByte - nAvail;
  220. /* The following loop copies up to p->nBuffer bytes per iteration into
  221. ** the p->aAlloc[] buffer. */
  222. while( nRem>0 ){
  223. int rc; /* vdbeSorterIterRead() return code */
  224. int nCopy; /* Number of bytes to copy */
  225. u8 *aNext; /* Pointer to buffer to copy data from */
  226. nCopy = nRem;
  227. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  228. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  229. if( rc!=SQLITE_OK ) return rc;
  230. assert( aNext!=p->aAlloc );
  231. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  232. nRem -= nCopy;
  233. }
  234. *ppOut = p->aAlloc;
  235. }
  236. return SQLITE_OK;
  237. }
  238. /*
  239. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  240. ** the value read.
  241. */
  242. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  243. int iBuf;
  244. iBuf = p->iReadOff % p->nBuffer;
  245. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  246. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  247. }else{
  248. u8 aVarint[16], *a;
  249. int i = 0, rc;
  250. do{
  251. rc = vdbeSorterIterRead(db, p, 1, &a);
  252. if( rc ) return rc;
  253. aVarint[(i++)&0xf] = a[0];
  254. }while( (a[0]&0x80)!=0 );
  255. sqlite3GetVarint(aVarint, pnOut);
  256. }
  257. return SQLITE_OK;
  258. }
  259. /*
  260. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  261. ** no error occurs, or an SQLite error code if one does.
  262. */
  263. static int vdbeSorterIterNext(
  264. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  265. VdbeSorterIter *pIter /* Iterator to advance */
  266. ){
  267. int rc; /* Return Code */
  268. u64 nRec = 0; /* Size of record in bytes */
  269. if( pIter->iReadOff>=pIter->iEof ){
  270. /* This is an EOF condition */
  271. vdbeSorterIterZero(db, pIter);
  272. return SQLITE_OK;
  273. }
  274. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  275. if( rc==SQLITE_OK ){
  276. pIter->nKey = (int)nRec;
  277. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  278. }
  279. return rc;
  280. }
  281. /*
  282. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  283. ** starting at offset iStart and ending at offset iEof-1. This function
  284. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  285. ** PMA is empty).
  286. */
  287. static int vdbeSorterIterInit(
  288. sqlite3 *db, /* Database handle */
  289. const VdbeSorter *pSorter, /* Sorter object */
  290. i64 iStart, /* Start offset in pFile */
  291. VdbeSorterIter *pIter, /* Iterator to populate */
  292. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  293. ){
  294. int rc = SQLITE_OK;
  295. int nBuf;
  296. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  297. assert( pSorter->iWriteOff>iStart );
  298. assert( pIter->aAlloc==0 );
  299. assert( pIter->aBuffer==0 );
  300. pIter->pFile = pSorter->pTemp1;
  301. pIter->iReadOff = iStart;
  302. pIter->nAlloc = 128;
  303. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  304. pIter->nBuffer = nBuf;
  305. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  306. if( !pIter->aBuffer ){
  307. rc = SQLITE_NOMEM;
  308. }else{
  309. int iBuf;
  310. iBuf = iStart % nBuf;
  311. if( iBuf ){
  312. int nRead = nBuf - iBuf;
  313. if( (iStart + nRead) > pSorter->iWriteOff ){
  314. nRead = (int)(pSorter->iWriteOff - iStart);
  315. }
  316. rc = sqlite3OsRead(
  317. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  318. );
  319. assert( rc!=SQLITE_IOERR_SHORT_READ );
  320. }
  321. if( rc==SQLITE_OK ){
  322. u64 nByte; /* Size of PMA in bytes */
  323. pIter->iEof = pSorter->iWriteOff;
  324. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  325. pIter->iEof = pIter->iReadOff + nByte;
  326. *pnByte += nByte;
  327. }
  328. }
  329. if( rc==SQLITE_OK ){
  330. rc = vdbeSorterIterNext(db, pIter);
  331. }
  332. return rc;
  333. }
  334. /*
  335. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  336. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  337. ** used by the comparison. If an error occurs, return an SQLite error code.
  338. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  339. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  340. **
  341. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  342. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  343. ** is true and key1 contains even a single NULL value, it is considered to
  344. ** be less than key2. Even if key2 also contains NULL values.
  345. **
  346. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  347. ** has been allocated and contains an unpacked record that is used as key2.
  348. */
  349. static void vdbeSorterCompare(
  350. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  351. int bOmitRowid, /* Ignore rowid field at end of keys */
  352. const void *pKey1, int nKey1, /* Left side of comparison */
  353. const void *pKey2, int nKey2, /* Right side of comparison */
  354. int *pRes /* OUT: Result of comparison */
  355. ){
  356. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  357. VdbeSorter *pSorter = pCsr->pSorter;
  358. UnpackedRecord *r2 = pSorter->pUnpacked;
  359. int i;
  360. if( pKey2 ){
  361. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  362. }
  363. if( bOmitRowid ){
  364. r2->nField = pKeyInfo->nField;
  365. assert( r2->nField>0 );
  366. for(i=0; i<r2->nField; i++){
  367. if( r2->aMem[i].flags & MEM_Null ){
  368. *pRes = -1;
  369. return;
  370. }
  371. }
  372. r2->flags |= UNPACKED_PREFIX_MATCH;
  373. }
  374. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  375. }
  376. /*
  377. ** This function is called to compare two iterator keys when merging
  378. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  379. ** value to recalculate.
  380. */
  381. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  382. VdbeSorter *pSorter = pCsr->pSorter;
  383. int i1;
  384. int i2;
  385. int iRes;
  386. VdbeSorterIter *p1;
  387. VdbeSorterIter *p2;
  388. assert( iOut<pSorter->nTree && iOut>0 );
  389. if( iOut>=(pSorter->nTree/2) ){
  390. i1 = (iOut - pSorter->nTree/2) * 2;
  391. i2 = i1 + 1;
  392. }else{
  393. i1 = pSorter->aTree[iOut*2];
  394. i2 = pSorter->aTree[iOut*2+1];
  395. }
  396. p1 = &pSorter->aIter[i1];
  397. p2 = &pSorter->aIter[i2];
  398. if( p1->pFile==0 ){
  399. iRes = i2;
  400. }else if( p2->pFile==0 ){
  401. iRes = i1;
  402. }else{
  403. int res;
  404. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  405. vdbeSorterCompare(
  406. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  407. );
  408. if( res<=0 ){
  409. iRes = i1;
  410. }else{
  411. iRes = i2;
  412. }
  413. }
  414. pSorter->aTree[iOut] = iRes;
  415. return SQLITE_OK;
  416. }
  417. /*
  418. ** Initialize the temporary index cursor just opened as a sorter cursor.
  419. */
  420. int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  421. int pgsz; /* Page size of main database */
  422. int mxCache; /* Cache size */
  423. VdbeSorter *pSorter; /* The new sorter */
  424. char *d; /* Dummy */
  425. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  426. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  427. if( pSorter==0 ){
  428. return SQLITE_NOMEM;
  429. }
  430. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  431. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  432. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  433. if( !sqlite3TempInMemory(db) ){
  434. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  435. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  436. mxCache = db->aDb[0].pSchema->cache_size;
  437. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  438. pSorter->mxPmaSize = mxCache * pgsz;
  439. }
  440. return SQLITE_OK;
  441. }
  442. /*
  443. ** Free the list of sorted records starting at pRecord.
  444. */
  445. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  446. SorterRecord *p;
  447. SorterRecord *pNext;
  448. for(p=pRecord; p; p=pNext){
  449. pNext = p->pNext;
  450. sqlite3DbFree(db, p);
  451. }
  452. }
  453. /*
  454. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  455. */
  456. void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  457. VdbeSorter *pSorter = pCsr->pSorter;
  458. if( pSorter ){
  459. if( pSorter->aIter ){
  460. int i;
  461. for(i=0; i<pSorter->nTree; i++){
  462. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  463. }
  464. sqlite3DbFree(db, pSorter->aIter);
  465. }
  466. if( pSorter->pTemp1 ){
  467. sqlite3OsCloseFree(pSorter->pTemp1);
  468. }
  469. vdbeSorterRecordFree(db, pSorter->pRecord);
  470. sqlite3DbFree(db, pSorter->pUnpacked);
  471. sqlite3DbFree(db, pSorter);
  472. pCsr->pSorter = 0;
  473. }
  474. }
  475. /*
  476. ** Allocate space for a file-handle and open a temporary file. If successful,
  477. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  478. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  479. */
  480. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  481. int dummy;
  482. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  483. SQLITE_OPEN_TEMP_JOURNAL |
  484. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  485. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  486. );
  487. }
  488. /*
  489. ** Merge the two sorted lists p1 and p2 into a single list.
  490. ** Set *ppOut to the head of the new list.
  491. */
  492. static void vdbeSorterMerge(
  493. const VdbeCursor *pCsr, /* For pKeyInfo */
  494. SorterRecord *p1, /* First list to merge */
  495. SorterRecord *p2, /* Second list to merge */
  496. SorterRecord **ppOut /* OUT: Head of merged list */
  497. ){
  498. SorterRecord *pFinal = 0;
  499. SorterRecord **pp = &pFinal;
  500. void *pVal2 = p2 ? p2->pVal : 0;
  501. while( p1 && p2 ){
  502. int res;
  503. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  504. if( res<=0 ){
  505. *pp = p1;
  506. pp = &p1->pNext;
  507. p1 = p1->pNext;
  508. pVal2 = 0;
  509. }else{
  510. *pp = p2;
  511. pp = &p2->pNext;
  512. p2 = p2->pNext;
  513. if( p2==0 ) break;
  514. pVal2 = p2->pVal;
  515. }
  516. }
  517. *pp = p1 ? p1 : p2;
  518. *ppOut = pFinal;
  519. }
  520. /*
  521. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  522. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  523. ** occurs.
  524. */
  525. static int vdbeSorterSort(const VdbeCursor *pCsr){
  526. int i;
  527. SorterRecord **aSlot;
  528. SorterRecord *p;
  529. VdbeSorter *pSorter = pCsr->pSorter;
  530. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  531. if( !aSlot ){
  532. return SQLITE_NOMEM;
  533. }
  534. p = pSorter->pRecord;
  535. while( p ){
  536. SorterRecord *pNext = p->pNext;
  537. p->pNext = 0;
  538. for(i=0; aSlot[i]; i++){
  539. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  540. aSlot[i] = 0;
  541. }
  542. aSlot[i] = p;
  543. p = pNext;
  544. }
  545. p = 0;
  546. for(i=0; i<64; i++){
  547. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  548. }
  549. pSorter->pRecord = p;
  550. sqlite3_free(aSlot);
  551. return SQLITE_OK;
  552. }
  553. /*
  554. ** Initialize a file-writer object.
  555. */
  556. static void fileWriterInit(
  557. sqlite3 *db, /* Database (for malloc) */
  558. sqlite3_file *pFile, /* File to write to */
  559. FileWriter *p, /* Object to populate */
  560. i64 iStart /* Offset of pFile to begin writing at */
  561. ){
  562. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  563. memset(p, 0, sizeof(FileWriter));
  564. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  565. if( !p->aBuffer ){
  566. p->eFWErr = SQLITE_NOMEM;
  567. }else{
  568. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  569. p->iWriteOff = iStart - p->iBufStart;
  570. p->nBuffer = nBuf;
  571. p->pFile = pFile;
  572. }
  573. }
  574. /*
  575. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  576. ** if successful, or an SQLite error code if an error occurs.
  577. */
  578. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  579. int nRem = nData;
  580. while( nRem>0 && p->eFWErr==0 ){
  581. int nCopy = nRem;
  582. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  583. nCopy = p->nBuffer - p->iBufEnd;
  584. }
  585. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  586. p->iBufEnd += nCopy;
  587. if( p->iBufEnd==p->nBuffer ){
  588. p->eFWErr = sqlite3OsWrite(p->pFile,
  589. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  590. p->iWriteOff + p->iBufStart
  591. );
  592. p->iBufStart = p->iBufEnd = 0;
  593. p->iWriteOff += p->nBuffer;
  594. }
  595. assert( p->iBufEnd<p->nBuffer );
  596. nRem -= nCopy;
  597. }
  598. }
  599. /*
  600. ** Flush any buffered data to disk and clean up the file-writer object.
  601. ** The results of using the file-writer after this call are undefined.
  602. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  603. ** required. Otherwise, return an SQLite error code.
  604. **
  605. ** Before returning, set *piEof to the offset immediately following the
  606. ** last byte written to the file.
  607. */
  608. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  609. int rc;
  610. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  611. p->eFWErr = sqlite3OsWrite(p->pFile,
  612. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  613. p->iWriteOff + p->iBufStart
  614. );
  615. }
  616. *piEof = (p->iWriteOff + p->iBufEnd);
  617. sqlite3DbFree(db, p->aBuffer);
  618. rc = p->eFWErr;
  619. memset(p, 0, sizeof(FileWriter));
  620. return rc;
  621. }
  622. /*
  623. ** Write value iVal encoded as a varint to the file-write object. Return
  624. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  625. */
  626. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  627. int nByte;
  628. u8 aByte[10];
  629. nByte = sqlite3PutVarint(aByte, iVal);
  630. fileWriterWrite(p, aByte, nByte);
  631. }
  632. /*
  633. ** Write the current contents of the in-memory linked-list to a PMA. Return
  634. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  635. **
  636. ** The format of a PMA is:
  637. **
  638. ** * A varint. This varint contains the total number of bytes of content
  639. ** in the PMA (not including the varint itself).
  640. **
  641. ** * One or more records packed end-to-end in order of ascending keys.
  642. ** Each record consists of a varint followed by a blob of data (the
  643. ** key). The varint is the number of bytes in the blob of data.
  644. */
  645. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  646. int rc = SQLITE_OK; /* Return code */
  647. VdbeSorter *pSorter = pCsr->pSorter;
  648. FileWriter writer;
  649. memset(&writer, 0, sizeof(FileWriter));
  650. if( pSorter->nInMemory==0 ){
  651. assert( pSorter->pRecord==0 );
  652. return rc;
  653. }
  654. rc = vdbeSorterSort(pCsr);
  655. /* If the first temporary PMA file has not been opened, open it now. */
  656. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  657. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  658. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  659. assert( pSorter->iWriteOff==0 );
  660. assert( pSorter->nPMA==0 );
  661. }
  662. if( rc==SQLITE_OK ){
  663. SorterRecord *p;
  664. SorterRecord *pNext = 0;
  665. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  666. pSorter->nPMA++;
  667. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  668. for(p=pSorter->pRecord; p; p=pNext){
  669. pNext = p->pNext;
  670. fileWriterWriteVarint(&writer, p->nVal);
  671. fileWriterWrite(&writer, p->pVal, p->nVal);
  672. sqlite3DbFree(db, p);
  673. }
  674. pSorter->pRecord = p;
  675. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  676. }
  677. return rc;
  678. }
  679. /*
  680. ** Add a record to the sorter.
  681. */
  682. int sqlite3VdbeSorterWrite(
  683. sqlite3 *db, /* Database handle */
  684. const VdbeCursor *pCsr, /* Sorter cursor */
  685. Mem *pVal /* Memory cell containing record */
  686. ){
  687. VdbeSorter *pSorter = pCsr->pSorter;
  688. int rc = SQLITE_OK; /* Return Code */
  689. SorterRecord *pNew; /* New list element */
  690. assert( pSorter );
  691. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  692. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  693. if( pNew==0 ){
  694. rc = SQLITE_NOMEM;
  695. }else{
  696. pNew->pVal = (void *)&pNew[1];
  697. memcpy(pNew->pVal, pVal->z, pVal->n);
  698. pNew->nVal = pVal->n;
  699. pNew->pNext = pSorter->pRecord;
  700. pSorter->pRecord = pNew;
  701. }
  702. /* See if the contents of the sorter should now be written out. They
  703. ** are written out when either of the following are true:
  704. **
  705. ** * The total memory allocated for the in-memory list is greater
  706. ** than (page-size * cache-size), or
  707. **
  708. ** * The total memory allocated for the in-memory list is greater
  709. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  710. */
  711. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  712. (pSorter->nInMemory>pSorter->mxPmaSize)
  713. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  714. )){
  715. #ifdef SQLITE_DEBUG
  716. i64 nExpect = pSorter->iWriteOff
  717. + sqlite3VarintLen(pSorter->nInMemory)
  718. + pSorter->nInMemory;
  719. #endif
  720. rc = vdbeSorterListToPMA(db, pCsr);
  721. pSorter->nInMemory = 0;
  722. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  723. }
  724. return rc;
  725. }
  726. /*
  727. ** Helper function for sqlite3VdbeSorterRewind().
  728. */
  729. static int vdbeSorterInitMerge(
  730. sqlite3 *db, /* Database handle */
  731. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  732. i64 *pnByte /* Sum of bytes in all opened PMAs */
  733. ){
  734. VdbeSorter *pSorter = pCsr->pSorter;
  735. int rc = SQLITE_OK; /* Return code */
  736. int i; /* Used to iterator through aIter[] */
  737. i64 nByte = 0; /* Total bytes in all opened PMAs */
  738. /* Initialize the iterators. */
  739. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  740. VdbeSorterIter *pIter = &pSorter->aIter[i];
  741. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  742. pSorter->iReadOff = pIter->iEof;
  743. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  744. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  745. }
  746. /* Initialize the aTree[] array. */
  747. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  748. rc = vdbeSorterDoCompare(pCsr, i);
  749. }
  750. *pnByte = nByte;
  751. return rc;
  752. }
  753. /*
  754. ** Once the sorter has been populated, this function is called to prepare
  755. ** for iterating through its contents in sorted order.
  756. */
  757. int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  758. VdbeSorter *pSorter = pCsr->pSorter;
  759. int rc; /* Return code */
  760. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  761. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  762. int nIter; /* Number of iterators used */
  763. int nByte; /* Bytes of space required for aIter/aTree */
  764. int N = 2; /* Power of 2 >= nIter */
  765. assert( pSorter );
  766. /* If no data has been written to disk, then do not do so now. Instead,
  767. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  768. ** from the in-memory list. */
  769. if( pSorter->nPMA==0 ){
  770. *pbEof = !pSorter->pRecord;
  771. assert( pSorter->aTree==0 );
  772. return vdbeSorterSort(pCsr);
  773. }
  774. /* Write the current in-memory list to a PMA. */
  775. rc = vdbeSorterListToPMA(db, pCsr);
  776. if( rc!=SQLITE_OK ) return rc;
  777. /* Allocate space for aIter[] and aTree[]. */
  778. nIter = pSorter->nPMA;
  779. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  780. assert( nIter>0 );
  781. while( N<nIter ) N += N;
  782. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  783. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  784. if( !pSorter->aIter ) return SQLITE_NOMEM;
  785. pSorter->aTree = (int *)&pSorter->aIter[N];
  786. pSorter->nTree = N;
  787. do {
  788. int iNew; /* Index of new, merged, PMA */
  789. for(iNew=0;
  790. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  791. iNew++
  792. ){
  793. int rc2; /* Return code from fileWriterFinish() */
  794. FileWriter writer; /* Object used to write to disk */
  795. i64 nWrite; /* Number of bytes in new PMA */
  796. memset(&writer, 0, sizeof(FileWriter));
  797. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  798. ** initialize an iterator for each of them and break out of the loop.
  799. ** These iterators will be incrementally merged as the VDBE layer calls
  800. ** sqlite3VdbeSorterNext().
  801. **
  802. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  803. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  804. ** are merged into a single PMA that is written to file pTemp2.
  805. */
  806. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  807. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  808. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  809. break;
  810. }
  811. /* Open the second temp file, if it is not already open. */
  812. if( pTemp2==0 ){
  813. assert( iWrite2==0 );
  814. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  815. }
  816. if( rc==SQLITE_OK ){
  817. int bEof = 0;
  818. fileWriterInit(db, pTemp2, &writer, iWrite2);
  819. fileWriterWriteVarint(&writer, nWrite);
  820. while( rc==SQLITE_OK && bEof==0 ){
  821. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  822. assert( pIter->pFile );
  823. fileWriterWriteVarint(&writer, pIter->nKey);
  824. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  825. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  826. }
  827. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  828. if( rc==SQLITE_OK ) rc = rc2;
  829. }
  830. }
  831. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  832. break;
  833. }else{
  834. sqlite3_file *pTmp = pSorter->pTemp1;
  835. pSorter->nPMA = iNew;
  836. pSorter->pTemp1 = pTemp2;
  837. pTemp2 = pTmp;
  838. pSorter->iWriteOff = iWrite2;
  839. pSorter->iReadOff = 0;
  840. iWrite2 = 0;
  841. }
  842. }while( rc==SQLITE_OK );
  843. if( pTemp2 ){
  844. sqlite3OsCloseFree(pTemp2);
  845. }
  846. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  847. return rc;
  848. }
  849. /*
  850. ** Advance to the next element in the sorter.
  851. */
  852. int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  853. VdbeSorter *pSorter = pCsr->pSorter;
  854. int rc; /* Return code */
  855. if( pSorter->aTree ){
  856. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  857. int i; /* Index of aTree[] to recalculate */
  858. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  859. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  860. rc = vdbeSorterDoCompare(pCsr, i);
  861. }
  862. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  863. }else{
  864. SorterRecord *pFree = pSorter->pRecord;
  865. pSorter->pRecord = pFree->pNext;
  866. pFree->pNext = 0;
  867. vdbeSorterRecordFree(db, pFree);
  868. *pbEof = !pSorter->pRecord;
  869. rc = SQLITE_OK;
  870. }
  871. return rc;
  872. }
  873. /*
  874. ** Return a pointer to a buffer owned by the sorter that contains the
  875. ** current key.
  876. */
  877. static void *vdbeSorterRowkey(
  878. const VdbeSorter *pSorter, /* Sorter object */
  879. int *pnKey /* OUT: Size of current key in bytes */
  880. ){
  881. void *pKey;
  882. if( pSorter->aTree ){
  883. VdbeSorterIter *pIter;
  884. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  885. *pnKey = pIter->nKey;
  886. pKey = pIter->aKey;
  887. }else{
  888. *pnKey = pSorter->pRecord->nVal;
  889. pKey = pSorter->pRecord->pVal;
  890. }
  891. return pKey;
  892. }
  893. /*
  894. ** Copy the current sorter key into the memory cell pOut.
  895. */
  896. int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  897. VdbeSorter *pSorter = pCsr->pSorter;
  898. void *pKey; int nKey; /* Sorter key to copy into pOut */
  899. pKey = vdbeSorterRowkey(pSorter, &nKey);
  900. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  901. return SQLITE_NOMEM;
  902. }
  903. pOut->n = nKey;
  904. MemSetTypeFlag(pOut, MEM_Blob);
  905. memcpy(pOut->z, pKey, nKey);
  906. return SQLITE_OK;
  907. }
  908. /*
  909. ** Compare the key in memory cell pVal with the key that the sorter cursor
  910. ** passed as the first argument currently points to. For the purposes of
  911. ** the comparison, ignore the rowid field at the end of each record.
  912. **
  913. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  914. ** Otherwise, set *pRes to a negative, zero or positive value if the
  915. ** key in pVal is smaller than, equal to or larger than the current sorter
  916. ** key.
  917. */
  918. int sqlite3VdbeSorterCompare(
  919. const VdbeCursor *pCsr, /* Sorter cursor */
  920. Mem *pVal, /* Value to compare to current sorter key */
  921. int *pRes /* OUT: Result of comparison */
  922. ){
  923. VdbeSorter *pSorter = pCsr->pSorter;
  924. void *pKey; int nKey; /* Sorter key to compare pVal with */
  925. pKey = vdbeSorterRowkey(pSorter, &nKey);
  926. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  927. return SQLITE_OK;
  928. }