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. (Sometimes 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 66 /* 67 ** Target size for allocation chunks. 68 */ 69 #define ROWSET_ALLOCATION_SIZE 1024 70 71 /* 72 ** The number of rowset entries per allocation chunk. 73 */ 74 #define ROWSET_ENTRY_PER_CHUNK \ 75 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry)) 76 77 /* 78 ** Each entry in a RowSet is an instance of the following object. 79 ** 80 ** This same object is reused to store a linked list of trees of RowSetEntry 81 ** objects. In that alternative use, pRight points to the next entry 82 ** in the list, pLeft points to the tree, and v is unused. The 83 ** RowSet.pForest value points to the head of this forest list. 84 */ 85 struct RowSetEntry { 86 i64 v; /* ROWID value for this entry */ 87 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */ 88 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */ 89 }; 90 91 /* 92 ** RowSetEntry objects are allocated in large chunks (instances of the 93 ** following structure) to reduce memory allocation overhead. The 94 ** chunks are kept on a linked list so that they can be deallocated 95 ** when the RowSet is destroyed. 96 */ 97 struct RowSetChunk { 98 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */ 99 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */ 100 }; 101 102 /* 103 ** A RowSet in an instance of the following structure. 104 ** 105 ** A typedef of this structure if found in sqliteInt.h. 106 */ 107 struct RowSet { 108 struct RowSetChunk *pChunk; /* List of all chunk allocations */ 109 sqlite3 *db; /* The database connection */ 110 struct RowSetEntry *pEntry; /* List of entries using pRight */ 111 struct RowSetEntry *pLast; /* Last entry on the pEntry list */ 112 struct RowSetEntry *pFresh; /* Source of new entry objects */ 113 struct RowSetEntry *pForest; /* List of binary trees of entries */ 114 u16 nFresh; /* Number of objects on pFresh */ 115 u16 rsFlags; /* Various flags */ 116 int iBatch; /* Current insert batch */ 117 }; 118 119 /* 120 ** Allowed values for RowSet.rsFlags 121 */ 122 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */ 123 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */ 124 125 /* 126 ** Turn bulk memory into a RowSet object. N bytes of memory 127 ** are available at pSpace. The db pointer is used as a memory context 128 ** for any subsequent allocations that need to occur. 129 ** Return a pointer to the new RowSet object. 130 ** 131 ** It must be the case that N is sufficient to make a Rowset. If not 132 ** an assertion fault occurs. 133 ** 134 ** If N is larger than the minimum, use the surplus as an initial 135 ** allocation of entries available to be filled. 136 */ 137 RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ 138 RowSet *p; 139 assert( N >= ROUND8(sizeof(*p)) ); 140 p = pSpace; 141 p->pChunk = 0; 142 p->db = db; 143 p->pEntry = 0; 144 p->pLast = 0; 145 p->pForest = 0; 146 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p); 147 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry)); 148 p->rsFlags = ROWSET_SORTED; 149 p->iBatch = 0; 150 return p; 151 } 152 153 /* 154 ** Deallocate all chunks from a RowSet. This frees all memory that 155 ** the RowSet has allocated over its lifetime. This routine is 156 ** the destructor for the RowSet. 157 */ 158 void sqlite3RowSetClear(RowSet *p){ 159 struct RowSetChunk *pChunk, *pNextChunk; 160 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){ 161 pNextChunk = pChunk->pNextChunk; 162 sqlite3DbFree(p->db, pChunk); 163 } 164 p->pChunk = 0; 165 p->nFresh = 0; 166 p->pEntry = 0; 167 p->pLast = 0; 168 p->pForest = 0; 169 p->rsFlags = ROWSET_SORTED; 170 } 171 172 /* 173 ** Allocate a new RowSetEntry object that is associated with the 174 ** given RowSet. Return a pointer to the new and completely uninitialized 175 ** objected. 176 ** 177 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this 178 ** routine returns NULL. 179 */ 180 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ 181 assert( p!=0 ); 182 if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/ 183 /* We could allocate a fresh RowSetEntry each time one is needed, but it 184 ** is more efficient to pull a preallocated entry from the pool */ 185 struct RowSetChunk *pNew; 186 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); 187 if( pNew==0 ){ 188 return 0; 189 } 190 pNew->pNextChunk = p->pChunk; 191 p->pChunk = pNew; 192 p->pFresh = pNew->aEntry; 193 p->nFresh = ROWSET_ENTRY_PER_CHUNK; 194 } 195 p->nFresh--; 196 return p->pFresh++; 197 } 198 199 /* 200 ** Insert a new value into a RowSet. 201 ** 202 ** The mallocFailed flag of the database connection is set if a 203 ** memory allocation fails. 204 */ 205 void sqlite3RowSetInsert(RowSet *p, i64 rowid){ 206 struct RowSetEntry *pEntry; /* The new entry */ 207 struct RowSetEntry *pLast; /* The last prior entry */ 208 209 /* This routine is never called after sqlite3RowSetNext() */ 210 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); 211 212 pEntry = rowSetEntryAlloc(p); 213 if( pEntry==0 ) return; 214 pEntry->v = rowid; 215 pEntry->pRight = 0; 216 pLast = p->pLast; 217 if( pLast ){ 218 if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/ 219 /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags 220 ** where possible */ 221 p->rsFlags &= ~ROWSET_SORTED; 222 } 223 pLast->pRight = pEntry; 224 }else{ 225 p->pEntry = pEntry; 226 } 227 p->pLast = pEntry; 228 } 229 230 /* 231 ** Merge two lists of RowSetEntry objects. Remove duplicates. 232 ** 233 ** The input lists are connected via pRight pointers and are 234 ** assumed to each already be in sorted order. 235 */ 236 static struct RowSetEntry *rowSetEntryMerge( 237 struct RowSetEntry *pA, /* First sorted list to be merged */ 238 struct RowSetEntry *pB /* Second sorted list to be merged */ 239 ){ 240 struct RowSetEntry head; 241 struct RowSetEntry *pTail; 242 243 pTail = &head; 244 while( pA && pB ){ 245 assert( pA->pRight==0 || pA->v<=pA->pRight->v ); 246 assert( pB->pRight==0 || pB->v<=pB->pRight->v ); 247 if( pA->v<pB->v ){ 248 pTail->pRight = pA; 249 pA = pA->pRight; 250 pTail = pTail->pRight; 251 }else if( pB->v<pA->v ){ 252 pTail->pRight = pB; 253 pB = pB->pRight; 254 pTail = pTail->pRight; 255 }else{ 256 pA = pA->pRight; 257 } 258 } 259 if( pA ){ 260 assert( pA->pRight==0 || pA->v<=pA->pRight->v ); 261 pTail->pRight = pA; 262 }else{ 263 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v ); 264 pTail->pRight = pB; 265 } 266 return head.pRight; 267 } 268 269 /* 270 ** Sort all elements on the list of RowSetEntry objects into order of 271 ** increasing v. 272 */ 273 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){ 274 unsigned int i; 275 struct RowSetEntry *pNext, *aBucket[40]; 276 277 memset(aBucket, 0, sizeof(aBucket)); 278 while( pIn ){ 279 pNext = pIn->pRight; 280 pIn->pRight = 0; 281 for(i=0; aBucket[i]; i++){ 282 pIn = rowSetEntryMerge(aBucket[i], pIn); 283 aBucket[i] = 0; 284 } 285 aBucket[i] = pIn; 286 pIn = pNext; 287 } 288 pIn = 0; 289 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){ 290 pIn = rowSetEntryMerge(pIn, aBucket[i]); 291 } 292 return pIn; 293 } 294 295 296 /* 297 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects. 298 ** Convert this tree into a linked list connected by the pRight pointers 299 ** and return pointers to the first and last elements of the new list. 300 */ 301 static void rowSetTreeToList( 302 struct RowSetEntry *pIn, /* Root of the input tree */ 303 struct RowSetEntry **ppFirst, /* Write head of the output list here */ 304 struct RowSetEntry **ppLast /* Write tail of the output list here */ 305 ){ 306 assert( pIn!=0 ); 307 if( pIn->pLeft ){ 308 struct RowSetEntry *p; 309 rowSetTreeToList(pIn->pLeft, ppFirst, &p); 310 p->pRight = pIn; 311 }else{ 312 *ppFirst = pIn; 313 } 314 if( pIn->pRight ){ 315 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast); 316 }else{ 317 *ppLast = pIn; 318 } 319 assert( (*ppLast)->pRight==0 ); 320 } 321 322 323 /* 324 ** Convert a sorted list of elements (connected by pRight) into a binary 325 ** tree with depth of iDepth. A depth of 1 means the tree contains a single 326 ** node taken from the head of *ppList. A depth of 2 means a tree with 327 ** three nodes. And so forth. 328 ** 329 ** Use as many entries from the input list as required and update the 330 ** *ppList to point to the unused elements of the list. If the input 331 ** list contains too few elements, then construct an incomplete tree 332 ** and leave *ppList set to NULL. 333 ** 334 ** Return a pointer to the root of the constructed binary tree. 335 */ 336 static struct RowSetEntry *rowSetNDeepTree( 337 struct RowSetEntry **ppList, 338 int iDepth 339 ){ 340 struct RowSetEntry *p; /* Root of the new tree */ 341 struct RowSetEntry *pLeft; /* Left subtree */ 342 if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/ 343 /* Prevent unnecessary deep recursion when we run out of entries */ 344 return 0; 345 } 346 if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/ 347 /* This branch causes a *balanced* tree to be generated. A valid tree 348 ** is still generated without this branch, but the tree is wildly 349 ** unbalanced and inefficient. */ 350 pLeft = rowSetNDeepTree(ppList, iDepth-1); 351 p = *ppList; 352 if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/ 353 /* It is safe to always return here, but the resulting tree 354 ** would be unbalanced */ 355 return pLeft; 356 } 357 p->pLeft = pLeft; 358 *ppList = p->pRight; 359 p->pRight = rowSetNDeepTree(ppList, iDepth-1); 360 }else{ 361 p = *ppList; 362 *ppList = p->pRight; 363 p->pLeft = p->pRight = 0; 364 } 365 return p; 366 } 367 368 /* 369 ** Convert a sorted list of elements into a binary tree. Make the tree 370 ** as deep as it needs to be in order to contain the entire list. 371 */ 372 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){ 373 int iDepth; /* Depth of the tree so far */ 374 struct RowSetEntry *p; /* Current tree root */ 375 struct RowSetEntry *pLeft; /* Left subtree */ 376 377 assert( pList!=0 ); 378 p = pList; 379 pList = p->pRight; 380 p->pLeft = p->pRight = 0; 381 for(iDepth=1; pList; iDepth++){ 382 pLeft = p; 383 p = pList; 384 pList = p->pRight; 385 p->pLeft = pLeft; 386 p->pRight = rowSetNDeepTree(&pList, iDepth); 387 } 388 return p; 389 } 390 391 /* 392 ** Take all the entries on p->pEntry and on the trees in p->pForest and 393 ** sort them all together into one big ordered list on p->pEntry. 394 ** 395 ** This routine should only be called once in the life of a RowSet. 396 */ 397 static void rowSetToList(RowSet *p){ 398 399 /* This routine is called only once */ 400 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); 401 402 if( (p->rsFlags & ROWSET_SORTED)==0 ){ 403 p->pEntry = rowSetEntrySort(p->pEntry); 404 } 405 406 /* While this module could theoretically support it, sqlite3RowSetNext() 407 ** is never called after sqlite3RowSetText() for the same RowSet. So 408 ** there is never a forest to deal with. Should this change, simply 409 ** remove the assert() and the #if 0. */ 410 assert( p->pForest==0 ); 411 #if 0 412 while( p->pForest ){ 413 struct RowSetEntry *pTree = p->pForest->pLeft; 414 if( pTree ){ 415 struct RowSetEntry *pHead, *pTail; 416 rowSetTreeToList(pTree, &pHead, &pTail); 417 p->pEntry = rowSetEntryMerge(p->pEntry, pHead); 418 } 419 p->pForest = p->pForest->pRight; 420 } 421 #endif 422 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */ 423 } 424 425 /* 426 ** Extract the smallest element from the RowSet. 427 ** Write the element into *pRowid. Return 1 on success. Return 428 ** 0 if the RowSet is already empty. 429 ** 430 ** After this routine has been called, the sqlite3RowSetInsert() 431 ** routine may not be called again. 432 */ 433 int sqlite3RowSetNext(RowSet *p, i64 *pRowid){ 434 assert( p!=0 ); 435 436 /* Merge the forest into a single sorted list on first call */ 437 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p); 438 439 /* Return the next entry on the list */ 440 if( p->pEntry ){ 441 *pRowid = p->pEntry->v; 442 p->pEntry = p->pEntry->pRight; 443 if( p->pEntry==0 ){ 444 sqlite3RowSetClear(p); 445 } 446 return 1; 447 }else{ 448 return 0; 449 } 450 } 451 452 /* 453 ** Check to see if element iRowid was inserted into the rowset as 454 ** part of any insert batch prior to iBatch. Return 1 or 0. 455 ** 456 ** If this is the first test of a new batch and if there exist entries 457 ** on pRowSet->pEntry, then sort those entries into the forest at 458 ** pRowSet->pForest so that they can be tested. 459 */ 460 int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){ 461 struct RowSetEntry *p, *pTree; 462 463 /* This routine is never called after sqlite3RowSetNext() */ 464 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 ); 465 466 /* Sort entries into the forest on the first test of a new batch 467 */ 468 if( iBatch!=pRowSet->iBatch ){ 469 p = pRowSet->pEntry; 470 if( p ){ 471 struct RowSetEntry **ppPrevTree = &pRowSet->pForest; 472 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ 473 p = rowSetEntrySort(p); 474 } 475 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ 476 ppPrevTree = &pTree->pRight; 477 if( pTree->pLeft==0 ){ 478 pTree->pLeft = rowSetListToTree(p); 479 break; 480 }else{ 481 struct RowSetEntry *pAux, *pTail; 482 rowSetTreeToList(pTree->pLeft, &pAux, &pTail); 483 pTree->pLeft = 0; 484 p = rowSetEntryMerge(pAux, p); 485 } 486 } 487 if( pTree==0 ){ 488 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet); 489 if( pTree ){ 490 pTree->v = 0; 491 pTree->pRight = 0; 492 pTree->pLeft = rowSetListToTree(p); 493 } 494 } 495 pRowSet->pEntry = 0; 496 pRowSet->pLast = 0; 497 pRowSet->rsFlags |= ROWSET_SORTED; 498 } 499 pRowSet->iBatch = iBatch; 500 } 501 502 /* Test to see if the iRowid value appears anywhere in the forest. 503 ** Return 1 if it does and 0 if not. 504 */ 505 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){ 506 p = pTree->pLeft; 507 while( p ){ 508 if( p->v<iRowid ){ 509 p = p->pRight; 510 }else if( p->v>iRowid ){ 511 p = p->pLeft; 512 }else{ 513 return 1; 514 } 515 } 516 } 517 return 0; 518 } 519