rowset.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. ** 2008 December 3
  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. **
  13. ** This module implements an object we call a "RowSet".
  14. **
  15. ** The RowSet object is a collection of rowids. Rowids
  16. ** are inserted into the RowSet in an arbitrary order. Inserts
  17. ** can be intermixed with tests to see if a given rowid has been
  18. ** previously inserted into the RowSet.
  19. **
  20. ** After all inserts are finished, it is possible to extract the
  21. ** elements of the RowSet in sorted order. Once this extraction
  22. ** process has started, no new elements may be inserted.
  23. **
  24. ** Hence, the primitive operations for a RowSet are:
  25. **
  26. ** CREATE
  27. ** INSERT
  28. ** TEST
  29. ** SMALLEST
  30. ** DESTROY
  31. **
  32. ** The CREATE and DESTROY primitives are the constructor and destructor,
  33. ** obviously. The INSERT primitive adds a new element to the RowSet.
  34. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  35. ** extracts the least value from the RowSet.
  36. **
  37. ** The INSERT primitive might allocate additional memory. Memory is
  38. ** allocated in chunks so most INSERTs do no allocation. There is an
  39. ** upper bound on the size of allocated memory. No memory is freed
  40. ** until DESTROY.
  41. **
  42. ** The TEST primitive includes a "batch" number. The TEST primitive
  43. ** will only see elements that were inserted before the last change
  44. ** in the batch number. In other words, if an INSERT occurs between
  45. ** two TESTs where the TESTs have the same batch nubmer, then the
  46. ** value added by the INSERT will not be visible to the second TEST.
  47. ** The initial batch number is zero, so if the very first TEST contains
  48. ** a non-zero batch number, it will see all prior INSERTs.
  49. **
  50. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  51. ** that is attempted.
  52. **
  53. ** The cost of an INSERT is roughly constant. (Sometime new memory
  54. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  55. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  56. ** The cost of a TEST using the same batch number is O(logN). The cost
  57. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  58. ** primitives are constant time. The cost of DESTROY is O(N).
  59. **
  60. ** There is an added cost of O(N) when switching between TEST and
  61. ** SMALLEST primitives.
  62. */
  63. #include "sqliteInt.h"
  64. /*
  65. ** Target size for allocation chunks.
  66. */
  67. #define ROWSET_ALLOCATION_SIZE 1024
  68. /*
  69. ** The number of rowset entries per allocation chunk.
  70. */
  71. #define ROWSET_ENTRY_PER_CHUNK \
  72. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  73. /*
  74. ** Each entry in a RowSet is an instance of the following object.
  75. **
  76. ** This same object is reused to store a linked list of trees of RowSetEntry
  77. ** objects. In that alternative use, pRight points to the next entry
  78. ** in the list, pLeft points to the tree, and v is unused. The
  79. ** RowSet.pForest value points to the head of this forest list.
  80. */
  81. struct RowSetEntry {
  82. i64 v; /* ROWID value for this entry */
  83. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  84. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  85. };
  86. /*
  87. ** RowSetEntry objects are allocated in large chunks (instances of the
  88. ** following structure) to reduce memory allocation overhead. The
  89. ** chunks are kept on a linked list so that they can be deallocated
  90. ** when the RowSet is destroyed.
  91. */
  92. struct RowSetChunk {
  93. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  94. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  95. };
  96. /*
  97. ** A RowSet in an instance of the following structure.
  98. **
  99. ** A typedef of this structure if found in sqliteInt.h.
  100. */
  101. struct RowSet {
  102. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  103. sqlite3 *db; /* The database connection */
  104. struct RowSetEntry *pEntry; /* List of entries using pRight */
  105. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  106. struct RowSetEntry *pFresh; /* Source of new entry objects */
  107. struct RowSetEntry *pForest; /* List of binary trees of entries */
  108. u16 nFresh; /* Number of objects on pFresh */
  109. u8 rsFlags; /* Various flags */
  110. u8 iBatch; /* Current insert batch */
  111. };
  112. /*
  113. ** Allowed values for RowSet.rsFlags
  114. */
  115. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  116. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  117. /*
  118. ** Turn bulk memory into a RowSet object. N bytes of memory
  119. ** are available at pSpace. The db pointer is used as a memory context
  120. ** for any subsequent allocations that need to occur.
  121. ** Return a pointer to the new RowSet object.
  122. **
  123. ** It must be the case that N is sufficient to make a Rowset. If not
  124. ** an assertion fault occurs.
  125. **
  126. ** If N is larger than the minimum, use the surplus as an initial
  127. ** allocation of entries available to be filled.
  128. */
  129. RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  130. RowSet *p;
  131. assert( N >= ROUND8(sizeof(*p)) );
  132. p = pSpace;
  133. p->pChunk = 0;
  134. p->db = db;
  135. p->pEntry = 0;
  136. p->pLast = 0;
  137. p->pForest = 0;
  138. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  139. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  140. p->rsFlags = ROWSET_SORTED;
  141. p->iBatch = 0;
  142. return p;
  143. }
  144. /*
  145. ** Deallocate all chunks from a RowSet. This frees all memory that
  146. ** the RowSet has allocated over its lifetime. This routine is
  147. ** the destructor for the RowSet.
  148. */
  149. void sqlite3RowSetClear(RowSet *p){
  150. struct RowSetChunk *pChunk, *pNextChunk;
  151. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  152. pNextChunk = pChunk->pNextChunk;
  153. sqlite3DbFree(p->db, pChunk);
  154. }
  155. p->pChunk = 0;
  156. p->nFresh = 0;
  157. p->pEntry = 0;
  158. p->pLast = 0;
  159. p->pForest = 0;
  160. p->rsFlags = ROWSET_SORTED;
  161. }
  162. /*
  163. ** Allocate a new RowSetEntry object that is associated with the
  164. ** given RowSet. Return a pointer to the new and completely uninitialized
  165. ** objected.
  166. **
  167. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  168. ** routine returns NULL.
  169. */
  170. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  171. assert( p!=0 );
  172. if( p->nFresh==0 ){
  173. struct RowSetChunk *pNew;
  174. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  175. if( pNew==0 ){
  176. return 0;
  177. }
  178. pNew->pNextChunk = p->pChunk;
  179. p->pChunk = pNew;
  180. p->pFresh = pNew->aEntry;
  181. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  182. }
  183. p->nFresh--;
  184. return p->pFresh++;
  185. }
  186. /*
  187. ** Insert a new value into a RowSet.
  188. **
  189. ** The mallocFailed flag of the database connection is set if a
  190. ** memory allocation fails.
  191. */
  192. void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  193. struct RowSetEntry *pEntry; /* The new entry */
  194. struct RowSetEntry *pLast; /* The last prior entry */
  195. /* This routine is never called after sqlite3RowSetNext() */
  196. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  197. pEntry = rowSetEntryAlloc(p);
  198. if( pEntry==0 ) return;
  199. pEntry->v = rowid;
  200. pEntry->pRight = 0;
  201. pLast = p->pLast;
  202. if( pLast ){
  203. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  204. p->rsFlags &= ~ROWSET_SORTED;
  205. }
  206. pLast->pRight = pEntry;
  207. }else{
  208. p->pEntry = pEntry;
  209. }
  210. p->pLast = pEntry;
  211. }
  212. /*
  213. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  214. **
  215. ** The input lists are connected via pRight pointers and are
  216. ** assumed to each already be in sorted order.
  217. */
  218. static struct RowSetEntry *rowSetEntryMerge(
  219. struct RowSetEntry *pA, /* First sorted list to be merged */
  220. struct RowSetEntry *pB /* Second sorted list to be merged */
  221. ){
  222. struct RowSetEntry head;
  223. struct RowSetEntry *pTail;
  224. pTail = &head;
  225. while( pA && pB ){
  226. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  227. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  228. if( pA->v<pB->v ){
  229. pTail->pRight = pA;
  230. pA = pA->pRight;
  231. pTail = pTail->pRight;
  232. }else if( pB->v<pA->v ){
  233. pTail->pRight = pB;
  234. pB = pB->pRight;
  235. pTail = pTail->pRight;
  236. }else{
  237. pA = pA->pRight;
  238. }
  239. }
  240. if( pA ){
  241. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  242. pTail->pRight = pA;
  243. }else{
  244. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  245. pTail->pRight = pB;
  246. }
  247. return head.pRight;
  248. }
  249. /*
  250. ** Sort all elements on the list of RowSetEntry objects into order of
  251. ** increasing v.
  252. */
  253. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  254. unsigned int i;
  255. struct RowSetEntry *pNext, *aBucket[40];
  256. memset(aBucket, 0, sizeof(aBucket));
  257. while( pIn ){
  258. pNext = pIn->pRight;
  259. pIn->pRight = 0;
  260. for(i=0; aBucket[i]; i++){
  261. pIn = rowSetEntryMerge(aBucket[i], pIn);
  262. aBucket[i] = 0;
  263. }
  264. aBucket[i] = pIn;
  265. pIn = pNext;
  266. }
  267. pIn = 0;
  268. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  269. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  270. }
  271. return pIn;
  272. }
  273. /*
  274. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  275. ** Convert this tree into a linked list connected by the pRight pointers
  276. ** and return pointers to the first and last elements of the new list.
  277. */
  278. static void rowSetTreeToList(
  279. struct RowSetEntry *pIn, /* Root of the input tree */
  280. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  281. struct RowSetEntry **ppLast /* Write tail of the output list here */
  282. ){
  283. assert( pIn!=0 );
  284. if( pIn->pLeft ){
  285. struct RowSetEntry *p;
  286. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  287. p->pRight = pIn;
  288. }else{
  289. *ppFirst = pIn;
  290. }
  291. if( pIn->pRight ){
  292. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  293. }else{
  294. *ppLast = pIn;
  295. }
  296. assert( (*ppLast)->pRight==0 );
  297. }
  298. /*
  299. ** Convert a sorted list of elements (connected by pRight) into a binary
  300. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  301. ** node taken from the head of *ppList. A depth of 2 means a tree with
  302. ** three nodes. And so forth.
  303. **
  304. ** Use as many entries from the input list as required and update the
  305. ** *ppList to point to the unused elements of the list. If the input
  306. ** list contains too few elements, then construct an incomplete tree
  307. ** and leave *ppList set to NULL.
  308. **
  309. ** Return a pointer to the root of the constructed binary tree.
  310. */
  311. static struct RowSetEntry *rowSetNDeepTree(
  312. struct RowSetEntry **ppList,
  313. int iDepth
  314. ){
  315. struct RowSetEntry *p; /* Root of the new tree */
  316. struct RowSetEntry *pLeft; /* Left subtree */
  317. if( *ppList==0 ){
  318. return 0;
  319. }
  320. if( iDepth==1 ){
  321. p = *ppList;
  322. *ppList = p->pRight;
  323. p->pLeft = p->pRight = 0;
  324. return p;
  325. }
  326. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  327. p = *ppList;
  328. if( p==0 ){
  329. return pLeft;
  330. }
  331. p->pLeft = pLeft;
  332. *ppList = p->pRight;
  333. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  334. return p;
  335. }
  336. /*
  337. ** Convert a sorted list of elements into a binary tree. Make the tree
  338. ** as deep as it needs to be in order to contain the entire list.
  339. */
  340. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  341. int iDepth; /* Depth of the tree so far */
  342. struct RowSetEntry *p; /* Current tree root */
  343. struct RowSetEntry *pLeft; /* Left subtree */
  344. assert( pList!=0 );
  345. p = pList;
  346. pList = p->pRight;
  347. p->pLeft = p->pRight = 0;
  348. for(iDepth=1; pList; iDepth++){
  349. pLeft = p;
  350. p = pList;
  351. pList = p->pRight;
  352. p->pLeft = pLeft;
  353. p->pRight = rowSetNDeepTree(&pList, iDepth);
  354. }
  355. return p;
  356. }
  357. /*
  358. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  359. ** sort them all together into one big ordered list on p->pEntry.
  360. **
  361. ** This routine should only be called once in the life of a RowSet.
  362. */
  363. static void rowSetToList(RowSet *p){
  364. /* This routine is called only once */
  365. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  366. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  367. p->pEntry = rowSetEntrySort(p->pEntry);
  368. }
  369. /* While this module could theoretically support it, sqlite3RowSetNext()
  370. ** is never called after sqlite3RowSetText() for the same RowSet. So
  371. ** there is never a forest to deal with. Should this change, simply
  372. ** remove the assert() and the #if 0. */
  373. assert( p->pForest==0 );
  374. #if 0
  375. while( p->pForest ){
  376. struct RowSetEntry *pTree = p->pForest->pLeft;
  377. if( pTree ){
  378. struct RowSetEntry *pHead, *pTail;
  379. rowSetTreeToList(pTree, &pHead, &pTail);
  380. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  381. }
  382. p->pForest = p->pForest->pRight;
  383. }
  384. #endif
  385. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  386. }
  387. /*
  388. ** Extract the smallest element from the RowSet.
  389. ** Write the element into *pRowid. Return 1 on success. Return
  390. ** 0 if the RowSet is already empty.
  391. **
  392. ** After this routine has been called, the sqlite3RowSetInsert()
  393. ** routine may not be called again.
  394. */
  395. int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  396. assert( p!=0 );
  397. /* Merge the forest into a single sorted list on first call */
  398. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  399. /* Return the next entry on the list */
  400. if( p->pEntry ){
  401. *pRowid = p->pEntry->v;
  402. p->pEntry = p->pEntry->pRight;
  403. if( p->pEntry==0 ){
  404. sqlite3RowSetClear(p);
  405. }
  406. return 1;
  407. }else{
  408. return 0;
  409. }
  410. }
  411. /*
  412. ** Check to see if element iRowid was inserted into the rowset as
  413. ** part of any insert batch prior to iBatch. Return 1 or 0.
  414. **
  415. ** If this is the first test of a new batch and if there exist entires
  416. ** on pRowSet->pEntry, then sort those entires into the forest at
  417. ** pRowSet->pForest so that they can be tested.
  418. */
  419. int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  420. struct RowSetEntry *p, *pTree;
  421. /* This routine is never called after sqlite3RowSetNext() */
  422. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  423. /* Sort entries into the forest on the first test of a new batch
  424. */
  425. if( iBatch!=pRowSet->iBatch ){
  426. p = pRowSet->pEntry;
  427. if( p ){
  428. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  429. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  430. p = rowSetEntrySort(p);
  431. }
  432. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  433. ppPrevTree = &pTree->pRight;
  434. if( pTree->pLeft==0 ){
  435. pTree->pLeft = rowSetListToTree(p);
  436. break;
  437. }else{
  438. struct RowSetEntry *pAux, *pTail;
  439. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  440. pTree->pLeft = 0;
  441. p = rowSetEntryMerge(pAux, p);
  442. }
  443. }
  444. if( pTree==0 ){
  445. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  446. if( pTree ){
  447. pTree->v = 0;
  448. pTree->pRight = 0;
  449. pTree->pLeft = rowSetListToTree(p);
  450. }
  451. }
  452. pRowSet->pEntry = 0;
  453. pRowSet->pLast = 0;
  454. pRowSet->rsFlags |= ROWSET_SORTED;
  455. }
  456. pRowSet->iBatch = iBatch;
  457. }
  458. /* Test to see if the iRowid value appears anywhere in the forest.
  459. ** Return 1 if it does and 0 if not.
  460. */
  461. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  462. p = pTree->pLeft;
  463. while( p ){
  464. if( p->v<iRowid ){
  465. p = p->pRight;
  466. }else if( p->v>iRowid ){
  467. p = p->pLeft;
  468. }else{
  469. return 1;
  470. }
  471. }
  472. }
  473. return 0;
  474. }