1 /* 2 ** 2001 September 15 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 implementations of the r-tree and r*-tree 13 ** algorithms packaged as an SQLite virtual table module. 14 */ 15 16 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) 17 18 /* 19 ** This file contains an implementation of a couple of different variants 20 ** of the r-tree algorithm. See the README file for further details. The 21 ** same data-structure is used for all, but the algorithms for insert and 22 ** delete operations vary. The variants used are selected at compile time 23 ** by defining the following symbols: 24 */ 25 26 /* Either, both or none of the following may be set to activate 27 ** r*tree variant algorithms. 28 */ 29 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0 30 #define VARIANT_RSTARTREE_REINSERT 1 31 32 /* 33 ** Exactly one of the following must be set to 1. 34 */ 35 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0 36 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0 37 #define VARIANT_RSTARTREE_SPLIT 1 38 39 #define VARIANT_GUTTMAN_SPLIT \ 40 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT) 41 42 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT 43 #define PickNext QuadraticPickNext 44 #define PickSeeds QuadraticPickSeeds 45 #define AssignCells splitNodeGuttman 46 #endif 47 #if VARIANT_GUTTMAN_LINEAR_SPLIT 48 #define PickNext LinearPickNext 49 #define PickSeeds LinearPickSeeds 50 #define AssignCells splitNodeGuttman 51 #endif 52 #if VARIANT_RSTARTREE_SPLIT 53 #define AssignCells splitNodeStartree 54 #endif 55 56 57 #ifndef SQLITE_CORE 58 #include "sqlite3ext.h" 59 SQLITE_EXTENSION_INIT1 60 #else 61 #include "sqlite3.h" 62 #endif 63 64 #include <string.h> 65 #include <assert.h> 66 67 #ifndef SQLITE_AMALGAMATION 68 typedef sqlite3_int64 i64; 69 typedef unsigned char u8; 70 typedef unsigned int u32; 71 #endif 72 73 typedef struct Rtree Rtree; 74 typedef struct RtreeCursor RtreeCursor; 75 typedef struct RtreeNode RtreeNode; 76 typedef struct RtreeCell RtreeCell; 77 typedef struct RtreeConstraint RtreeConstraint; 78 typedef union RtreeCoord RtreeCoord; 79 80 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ 81 #define RTREE_MAX_DIMENSIONS 5 82 83 /* Size of hash table Rtree.aHash. This hash table is not expected to 84 ** ever contain very many entries, so a fixed number of buckets is 85 ** used. 86 */ 87 #define HASHSIZE 128 88 89 /* 90 ** An rtree virtual-table object. 91 */ 92 struct Rtree { 93 sqlite3_vtab base; 94 sqlite3 *db; /* Host database connection */ 95 int iNodeSize; /* Size in bytes of each node in the node table */ 96 int nDim; /* Number of dimensions */ 97 int nBytesPerCell; /* Bytes consumed per cell */ 98 int iDepth; /* Current depth of the r-tree structure */ 99 char *zDb; /* Name of database containing r-tree table */ 100 char *zName; /* Name of r-tree table */ 101 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 102 int nBusy; /* Current number of users of this structure */ 103 104 /* List of nodes removed during a CondenseTree operation. List is 105 ** linked together via the pointer normally used for hash chains - 106 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 107 ** headed by the node (leaf nodes have RtreeNode.iNode==0). 108 */ 109 RtreeNode *pDeleted; 110 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ 111 112 /* Statements to read/write/delete a record from xxx_node */ 113 sqlite3_stmt *pReadNode; 114 sqlite3_stmt *pWriteNode; 115 sqlite3_stmt *pDeleteNode; 116 117 /* Statements to read/write/delete a record from xxx_rowid */ 118 sqlite3_stmt *pReadRowid; 119 sqlite3_stmt *pWriteRowid; 120 sqlite3_stmt *pDeleteRowid; 121 122 /* Statements to read/write/delete a record from xxx_parent */ 123 sqlite3_stmt *pReadParent; 124 sqlite3_stmt *pWriteParent; 125 sqlite3_stmt *pDeleteParent; 126 127 int eCoordType; 128 }; 129 130 /* Possible values for eCoordType: */ 131 #define RTREE_COORD_REAL32 0 132 #define RTREE_COORD_INT32 1 133 134 /* 135 ** The minimum number of cells allowed for a node is a third of the 136 ** maximum. In Gutman's notation: 137 ** 138 ** m = M/3 139 ** 140 ** If an R*-tree "Reinsert" operation is required, the same number of 141 ** cells are removed from the overfull node and reinserted into the tree. 142 */ 143 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) 144 #define RTREE_REINSERT(p) RTREE_MINCELLS(p) 145 #define RTREE_MAXCELLS 51 146 147 /* 148 ** An rtree cursor object. 149 */ 150 struct RtreeCursor { 151 sqlite3_vtab_cursor base; 152 RtreeNode *pNode; /* Node cursor is currently pointing at */ 153 int iCell; /* Index of current cell in pNode */ 154 int iStrategy; /* Copy of idxNum search parameter */ 155 int nConstraint; /* Number of entries in aConstraint */ 156 RtreeConstraint *aConstraint; /* Search constraints. */ 157 }; 158 159 union RtreeCoord { 160 float f; 161 int i; 162 }; 163 164 /* 165 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord 166 ** formatted as a double. This macro assumes that local variable pRtree points 167 ** to the Rtree structure associated with the RtreeCoord. 168 */ 169 #define DCOORD(coord) ( \ 170 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ 171 ((double)coord.f) : \ 172 ((double)coord.i) \ 173 ) 174 175 /* 176 ** A search constraint. 177 */ 178 struct RtreeConstraint { 179 int iCoord; /* Index of constrained coordinate */ 180 int op; /* Constraining operation */ 181 double rValue; /* Constraint value. */ 182 }; 183 184 /* Possible values for RtreeConstraint.op */ 185 #define RTREE_EQ 0x41 186 #define RTREE_LE 0x42 187 #define RTREE_LT 0x43 188 #define RTREE_GE 0x44 189 #define RTREE_GT 0x45 190 191 /* 192 ** An rtree structure node. 193 ** 194 ** Data format (RtreeNode.zData): 195 ** 196 ** 1. If the node is the root node (node 1), then the first 2 bytes 197 ** of the node contain the tree depth as a big-endian integer. 198 ** For non-root nodes, the first 2 bytes are left unused. 199 ** 200 ** 2. The next 2 bytes contain the number of entries currently 201 ** stored in the node. 202 ** 203 ** 3. The remainder of the node contains the node entries. Each entry 204 ** consists of a single 8-byte integer followed by an even number 205 ** of 4-byte coordinates. For leaf nodes the integer is the rowid 206 ** of a record. For internal nodes it is the node number of a 207 ** child page. 208 */ 209 struct RtreeNode { 210 RtreeNode *pParent; /* Parent node */ 211 i64 iNode; 212 int nRef; 213 int isDirty; 214 u8 *zData; 215 RtreeNode *pNext; /* Next node in this hash chain */ 216 }; 217 #define NCELL(pNode) readInt16(&(pNode)->zData[2]) 218 219 /* 220 ** Structure to store a deserialized rtree record. 221 */ 222 struct RtreeCell { 223 i64 iRowid; 224 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; 225 }; 226 227 #ifndef MAX 228 # define MAX(x,y) ((x) < (y) ? (y) : (x)) 229 #endif 230 #ifndef MIN 231 # define MIN(x,y) ((x) > (y) ? (y) : (x)) 232 #endif 233 234 /* 235 ** Functions to deserialize a 16 bit integer, 32 bit real number and 236 ** 64 bit integer. The deserialized value is returned. 237 */ 238 static int readInt16(u8 *p){ 239 return (p[0]<<8) + p[1]; 240 } 241 static void readCoord(u8 *p, RtreeCoord *pCoord){ 242 u32 i = ( 243 (((u32)p[0]) << 24) + 244 (((u32)p[1]) << 16) + 245 (((u32)p[2]) << 8) + 246 (((u32)p[3]) << 0) 247 ); 248 *(u32 *)pCoord = i; 249 } 250 static i64 readInt64(u8 *p){ 251 return ( 252 (((i64)p[0]) << 56) + 253 (((i64)p[1]) << 48) + 254 (((i64)p[2]) << 40) + 255 (((i64)p[3]) << 32) + 256 (((i64)p[4]) << 24) + 257 (((i64)p[5]) << 16) + 258 (((i64)p[6]) << 8) + 259 (((i64)p[7]) << 0) 260 ); 261 } 262 263 /* 264 ** Functions to serialize a 16 bit integer, 32 bit real number and 265 ** 64 bit integer. The value returned is the number of bytes written 266 ** to the argument buffer (always 2, 4 and 8 respectively). 267 */ 268 static int writeInt16(u8 *p, int i){ 269 p[0] = (i>> 8)&0xFF; 270 p[1] = (i>> 0)&0xFF; 271 return 2; 272 } 273 static int writeCoord(u8 *p, RtreeCoord *pCoord){ 274 u32 i; 275 assert( sizeof(RtreeCoord)==4 ); 276 assert( sizeof(u32)==4 ); 277 i = *(u32 *)pCoord; 278 p[0] = (i>>24)&0xFF; 279 p[1] = (i>>16)&0xFF; 280 p[2] = (i>> 8)&0xFF; 281 p[3] = (i>> 0)&0xFF; 282 return 4; 283 } 284 static int writeInt64(u8 *p, i64 i){ 285 p[0] = (i>>56)&0xFF; 286 p[1] = (i>>48)&0xFF; 287 p[2] = (i>>40)&0xFF; 288 p[3] = (i>>32)&0xFF; 289 p[4] = (i>>24)&0xFF; 290 p[5] = (i>>16)&0xFF; 291 p[6] = (i>> 8)&0xFF; 292 p[7] = (i>> 0)&0xFF; 293 return 8; 294 } 295 296 /* 297 ** Increment the reference count of node p. 298 */ 299 static void nodeReference(RtreeNode *p){ 300 if( p ){ 301 p->nRef++; 302 } 303 } 304 305 /* 306 ** Clear the content of node p (set all bytes to 0x00). 307 */ 308 static void nodeZero(Rtree *pRtree, RtreeNode *p){ 309 if( p ){ 310 memset(&p->zData[2], 0, pRtree->iNodeSize-2); 311 p->isDirty = 1; 312 } 313 } 314 315 /* 316 ** Given a node number iNode, return the corresponding key to use 317 ** in the Rtree.aHash table. 318 */ 319 static int nodeHash(i64 iNode){ 320 return ( 321 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 322 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0) 323 ) % HASHSIZE; 324 } 325 326 /* 327 ** Search the node hash table for node iNode. If found, return a pointer 328 ** to it. Otherwise, return 0. 329 */ 330 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ 331 RtreeNode *p; 332 assert( iNode!=0 ); 333 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); 334 return p; 335 } 336 337 /* 338 ** Add node pNode to the node hash table. 339 */ 340 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ 341 if( pNode ){ 342 int iHash; 343 assert( pNode->pNext==0 ); 344 iHash = nodeHash(pNode->iNode); 345 pNode->pNext = pRtree->aHash[iHash]; 346 pRtree->aHash[iHash] = pNode; 347 } 348 } 349 350 /* 351 ** Remove node pNode from the node hash table. 352 */ 353 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ 354 RtreeNode **pp; 355 if( pNode->iNode!=0 ){ 356 pp = &pRtree->aHash[nodeHash(pNode->iNode)]; 357 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } 358 *pp = pNode->pNext; 359 pNode->pNext = 0; 360 } 361 } 362 363 /* 364 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), 365 ** indicating that node has not yet been assigned a node number. It is 366 ** assigned a node number when nodeWrite() is called to write the 367 ** node contents out to the database. 368 */ 369 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){ 370 RtreeNode *pNode; 371 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); 372 if( pNode ){ 373 memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0)); 374 pNode->zData = (u8 *)&pNode[1]; 375 pNode->nRef = 1; 376 pNode->pParent = pParent; 377 pNode->isDirty = 1; 378 nodeReference(pParent); 379 } 380 return pNode; 381 } 382 383 /* 384 ** Obtain a reference to an r-tree node. 385 */ 386 static int 387 nodeAcquire( 388 Rtree *pRtree, /* R-tree structure */ 389 i64 iNode, /* Node number to load */ 390 RtreeNode *pParent, /* Either the parent node or NULL */ 391 RtreeNode **ppNode /* OUT: Acquired node */ 392 ){ 393 int rc; 394 RtreeNode *pNode; 395 396 /* Check if the requested node is already in the hash table. If so, 397 ** increase its reference count and return it. 398 */ 399 if( (pNode = nodeHashLookup(pRtree, iNode)) ){ 400 assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); 401 if( pParent && !pNode->pParent ){ 402 nodeReference(pParent); 403 pNode->pParent = pParent; 404 } 405 pNode->nRef++; 406 *ppNode = pNode; 407 return SQLITE_OK; 408 } 409 410 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); 411 if( !pNode ){ 412 *ppNode = 0; 413 return SQLITE_NOMEM; 414 } 415 pNode->pParent = pParent; 416 pNode->zData = (u8 *)&pNode[1]; 417 pNode->nRef = 1; 418 pNode->iNode = iNode; 419 pNode->isDirty = 0; 420 pNode->pNext = 0; 421 422 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); 423 rc = sqlite3_step(pRtree->pReadNode); 424 if( rc==SQLITE_ROW ){ 425 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); 426 assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize ); 427 memcpy(pNode->zData, zBlob, pRtree->iNodeSize); 428 nodeReference(pParent); 429 }else{ 430 sqlite3_free(pNode); 431 pNode = 0; 432 } 433 434 *ppNode = pNode; 435 rc = sqlite3_reset(pRtree->pReadNode); 436 437 if( rc==SQLITE_OK && iNode==1 ){ 438 pRtree->iDepth = readInt16(pNode->zData); 439 } 440 441 assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) ); 442 nodeHashInsert(pRtree, pNode); 443 444 return rc; 445 } 446 447 /* 448 ** Overwrite cell iCell of node pNode with the contents of pCell. 449 */ 450 static void nodeOverwriteCell( 451 Rtree *pRtree, 452 RtreeNode *pNode, 453 RtreeCell *pCell, 454 int iCell 455 ){ 456 int ii; 457 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; 458 p += writeInt64(p, pCell->iRowid); 459 for(ii=0; ii<(pRtree->nDim*2); ii++){ 460 p += writeCoord(p, &pCell->aCoord[ii]); 461 } 462 pNode->isDirty = 1; 463 } 464 465 /* 466 ** Remove cell the cell with index iCell from node pNode. 467 */ 468 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ 469 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; 470 u8 *pSrc = &pDst[pRtree->nBytesPerCell]; 471 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; 472 memmove(pDst, pSrc, nByte); 473 writeInt16(&pNode->zData[2], NCELL(pNode)-1); 474 pNode->isDirty = 1; 475 } 476 477 /* 478 ** Insert the contents of cell pCell into node pNode. If the insert 479 ** is successful, return SQLITE_OK. 480 ** 481 ** If there is not enough free space in pNode, return SQLITE_FULL. 482 */ 483 static int 484 nodeInsertCell( 485 Rtree *pRtree, 486 RtreeNode *pNode, 487 RtreeCell *pCell 488 ){ 489 int nCell; /* Current number of cells in pNode */ 490 int nMaxCell; /* Maximum number of cells for pNode */ 491 492 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; 493 nCell = NCELL(pNode); 494 495 assert(nCell<=nMaxCell); 496 497 if( nCell<nMaxCell ){ 498 nodeOverwriteCell(pRtree, pNode, pCell, nCell); 499 writeInt16(&pNode->zData[2], nCell+1); 500 pNode->isDirty = 1; 501 } 502 503 return (nCell==nMaxCell); 504 } 505 506 /* 507 ** If the node is dirty, write it out to the database. 508 */ 509 static int 510 nodeWrite(Rtree *pRtree, RtreeNode *pNode){ 511 int rc = SQLITE_OK; 512 if( pNode->isDirty ){ 513 sqlite3_stmt *p = pRtree->pWriteNode; 514 if( pNode->iNode ){ 515 sqlite3_bind_int64(p, 1, pNode->iNode); 516 }else{ 517 sqlite3_bind_null(p, 1); 518 } 519 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); 520 sqlite3_step(p); 521 pNode->isDirty = 0; 522 rc = sqlite3_reset(p); 523 if( pNode->iNode==0 && rc==SQLITE_OK ){ 524 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); 525 nodeHashInsert(pRtree, pNode); 526 } 527 } 528 return rc; 529 } 530 531 /* 532 ** Release a reference to a node. If the node is dirty and the reference 533 ** count drops to zero, the node data is written to the database. 534 */ 535 static int 536 nodeRelease(Rtree *pRtree, RtreeNode *pNode){ 537 int rc = SQLITE_OK; 538 if( pNode ){ 539 assert( pNode->nRef>0 ); 540 pNode->nRef--; 541 if( pNode->nRef==0 ){ 542 if( pNode->iNode==1 ){ 543 pRtree->iDepth = -1; 544 } 545 if( pNode->pParent ){ 546 rc = nodeRelease(pRtree, pNode->pParent); 547 } 548 if( rc==SQLITE_OK ){ 549 rc = nodeWrite(pRtree, pNode); 550 } 551 nodeHashDelete(pRtree, pNode); 552 sqlite3_free(pNode); 553 } 554 } 555 return rc; 556 } 557 558 /* 559 ** Return the 64-bit integer value associated with cell iCell of 560 ** node pNode. If pNode is a leaf node, this is a rowid. If it is 561 ** an internal node, then the 64-bit integer is a child page number. 562 */ 563 static i64 nodeGetRowid( 564 Rtree *pRtree, 565 RtreeNode *pNode, 566 int iCell 567 ){ 568 assert( iCell<NCELL(pNode) ); 569 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]); 570 } 571 572 /* 573 ** Return coordinate iCoord from cell iCell in node pNode. 574 */ 575 static void nodeGetCoord( 576 Rtree *pRtree, 577 RtreeNode *pNode, 578 int iCell, 579 int iCoord, 580 RtreeCoord *pCoord /* Space to write result to */ 581 ){ 582 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); 583 } 584 585 /* 586 ** Deserialize cell iCell of node pNode. Populate the structure pointed 587 ** to by pCell with the results. 588 */ 589 static void nodeGetCell( 590 Rtree *pRtree, 591 RtreeNode *pNode, 592 int iCell, 593 RtreeCell *pCell 594 ){ 595 int ii; 596 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); 597 for(ii=0; ii<pRtree->nDim*2; ii++){ 598 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]); 599 } 600 } 601 602 603 /* Forward declaration for the function that does the work of 604 ** the virtual table module xCreate() and xConnect() methods. 605 */ 606 static int rtreeInit( 607 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int 608 ); 609 610 /* 611 ** Rtree virtual table module xCreate method. 612 */ 613 static int rtreeCreate( 614 sqlite3 *db, 615 void *pAux, 616 int argc, const char *const*argv, 617 sqlite3_vtab **ppVtab, 618 char **pzErr 619 ){ 620 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); 621 } 622 623 /* 624 ** Rtree virtual table module xConnect method. 625 */ 626 static int rtreeConnect( 627 sqlite3 *db, 628 void *pAux, 629 int argc, const char *const*argv, 630 sqlite3_vtab **ppVtab, 631 char **pzErr 632 ){ 633 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); 634 } 635 636 /* 637 ** Increment the r-tree reference count. 638 */ 639 static void rtreeReference(Rtree *pRtree){ 640 pRtree->nBusy++; 641 } 642 643 /* 644 ** Decrement the r-tree reference count. When the reference count reaches 645 ** zero the structure is deleted. 646 */ 647 static void rtreeRelease(Rtree *pRtree){ 648 pRtree->nBusy--; 649 if( pRtree->nBusy==0 ){ 650 sqlite3_finalize(pRtree->pReadNode); 651 sqlite3_finalize(pRtree->pWriteNode); 652 sqlite3_finalize(pRtree->pDeleteNode); 653 sqlite3_finalize(pRtree->pReadRowid); 654 sqlite3_finalize(pRtree->pWriteRowid); 655 sqlite3_finalize(pRtree->pDeleteRowid); 656 sqlite3_finalize(pRtree->pReadParent); 657 sqlite3_finalize(pRtree->pWriteParent); 658 sqlite3_finalize(pRtree->pDeleteParent); 659 sqlite3_free(pRtree); 660 } 661 } 662 663 /* 664 ** Rtree virtual table module xDisconnect method. 665 */ 666 static int rtreeDisconnect(sqlite3_vtab *pVtab){ 667 rtreeRelease((Rtree *)pVtab); 668 return SQLITE_OK; 669 } 670 671 /* 672 ** Rtree virtual table module xDestroy method. 673 */ 674 static int rtreeDestroy(sqlite3_vtab *pVtab){ 675 Rtree *pRtree = (Rtree *)pVtab; 676 int rc; 677 char *zCreate = sqlite3_mprintf( 678 "DROP TABLE '%q'.'%q_node';" 679 "DROP TABLE '%q'.'%q_rowid';" 680 "DROP TABLE '%q'.'%q_parent';", 681 pRtree->zDb, pRtree->zName, 682 pRtree->zDb, pRtree->zName, 683 pRtree->zDb, pRtree->zName 684 ); 685 if( !zCreate ){ 686 rc = SQLITE_NOMEM; 687 }else{ 688 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); 689 sqlite3_free(zCreate); 690 } 691 if( rc==SQLITE_OK ){ 692 rtreeRelease(pRtree); 693 } 694 695 return rc; 696 } 697 698 /* 699 ** Rtree virtual table module xOpen method. 700 */ 701 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ 702 int rc = SQLITE_NOMEM; 703 RtreeCursor *pCsr; 704 705 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); 706 if( pCsr ){ 707 memset(pCsr, 0, sizeof(RtreeCursor)); 708 pCsr->base.pVtab = pVTab; 709 rc = SQLITE_OK; 710 } 711 *ppCursor = (sqlite3_vtab_cursor *)pCsr; 712 713 return rc; 714 } 715 716 /* 717 ** Rtree virtual table module xClose method. 718 */ 719 static int rtreeClose(sqlite3_vtab_cursor *cur){ 720 Rtree *pRtree = (Rtree *)(cur->pVtab); 721 int rc; 722 RtreeCursor *pCsr = (RtreeCursor *)cur; 723 sqlite3_free(pCsr->aConstraint); 724 rc = nodeRelease(pRtree, pCsr->pNode); 725 sqlite3_free(pCsr); 726 return rc; 727 } 728 729 /* 730 ** Rtree virtual table module xEof method. 731 ** 732 ** Return non-zero if the cursor does not currently point to a valid 733 ** record (i.e if the scan has finished), or zero otherwise. 734 */ 735 static int rtreeEof(sqlite3_vtab_cursor *cur){ 736 RtreeCursor *pCsr = (RtreeCursor *)cur; 737 return (pCsr->pNode==0); 738 } 739 740 /* 741 ** Cursor pCursor currently points to a cell in a non-leaf page. 742 ** Return true if the sub-tree headed by the cell is filtered 743 ** (excluded) by the constraints in the pCursor->aConstraint[] 744 ** array, or false otherwise. 745 */ 746 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){ 747 RtreeCell cell; 748 int ii; 749 int bRes = 0; 750 751 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); 752 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){ 753 RtreeConstraint *p = &pCursor->aConstraint[ii]; 754 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]); 755 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]); 756 757 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 758 || p->op==RTREE_GT || p->op==RTREE_EQ 759 ); 760 761 switch( p->op ){ 762 case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break; 763 case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break; 764 case RTREE_EQ: 765 bRes = (p->rValue>cell_max || p->rValue<cell_min); 766 break; 767 } 768 } 769 770 return bRes; 771 } 772 773 /* 774 ** Return true if the cell that cursor pCursor currently points to 775 ** would be filtered (excluded) by the constraints in the 776 ** pCursor->aConstraint[] array, or false otherwise. 777 ** 778 ** This function assumes that the cell is part of a leaf node. 779 */ 780 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){ 781 RtreeCell cell; 782 int ii; 783 784 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); 785 for(ii=0; ii<pCursor->nConstraint; ii++){ 786 RtreeConstraint *p = &pCursor->aConstraint[ii]; 787 double coord = DCOORD(cell.aCoord[p->iCoord]); 788 int res; 789 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 790 || p->op==RTREE_GT || p->op==RTREE_EQ 791 ); 792 switch( p->op ){ 793 case RTREE_LE: res = (coord<=p->rValue); break; 794 case RTREE_LT: res = (coord<p->rValue); break; 795 case RTREE_GE: res = (coord>=p->rValue); break; 796 case RTREE_GT: res = (coord>p->rValue); break; 797 case RTREE_EQ: res = (coord==p->rValue); break; 798 } 799 800 if( !res ) return 1; 801 } 802 803 return 0; 804 } 805 806 /* 807 ** Cursor pCursor currently points at a node that heads a sub-tree of 808 ** height iHeight (if iHeight==0, then the node is a leaf). Descend 809 ** to point to the left-most cell of the sub-tree that matches the 810 ** configured constraints. 811 */ 812 static int descendToCell( 813 Rtree *pRtree, 814 RtreeCursor *pCursor, 815 int iHeight, 816 int *pEof /* OUT: Set to true if cannot descend */ 817 ){ 818 int isEof; 819 int rc; 820 int ii; 821 RtreeNode *pChild; 822 sqlite3_int64 iRowid; 823 824 RtreeNode *pSavedNode = pCursor->pNode; 825 int iSavedCell = pCursor->iCell; 826 827 assert( iHeight>=0 ); 828 829 if( iHeight==0 ){ 830 isEof = testRtreeEntry(pRtree, pCursor); 831 }else{ 832 isEof = testRtreeCell(pRtree, pCursor); 833 } 834 if( isEof || iHeight==0 ){ 835 *pEof = isEof; 836 return SQLITE_OK; 837 } 838 839 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell); 840 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild); 841 if( rc!=SQLITE_OK ){ 842 return rc; 843 } 844 845 nodeRelease(pRtree, pCursor->pNode); 846 pCursor->pNode = pChild; 847 isEof = 1; 848 for(ii=0; isEof && ii<NCELL(pChild); ii++){ 849 pCursor->iCell = ii; 850 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof); 851 if( rc!=SQLITE_OK ){ 852 return rc; 853 } 854 } 855 856 if( isEof ){ 857 assert( pCursor->pNode==pChild ); 858 nodeReference(pSavedNode); 859 nodeRelease(pRtree, pChild); 860 pCursor->pNode = pSavedNode; 861 pCursor->iCell = iSavedCell; 862 } 863 864 *pEof = isEof; 865 return SQLITE_OK; 866 } 867 868 /* 869 ** One of the cells in node pNode is guaranteed to have a 64-bit 870 ** integer value equal to iRowid. Return the index of this cell. 871 */ 872 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){ 873 int ii; 874 for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){ 875 assert( ii<(NCELL(pNode)-1) ); 876 } 877 return ii; 878 } 879 880 /* 881 ** Return the index of the cell containing a pointer to node pNode 882 ** in its parent. If pNode is the root node, return -1. 883 */ 884 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){ 885 RtreeNode *pParent = pNode->pParent; 886 if( pParent ){ 887 return nodeRowidIndex(pRtree, pParent, pNode->iNode); 888 } 889 return -1; 890 } 891 892 /* 893 ** Rtree virtual table module xNext method. 894 */ 895 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ 896 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab); 897 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 898 int rc = SQLITE_OK; 899 900 if( pCsr->iStrategy==1 ){ 901 /* This "scan" is a direct lookup by rowid. There is no next entry. */ 902 nodeRelease(pRtree, pCsr->pNode); 903 pCsr->pNode = 0; 904 } 905 906 else if( pCsr->pNode ){ 907 /* Move to the next entry that matches the configured constraints. */ 908 int iHeight = 0; 909 while( pCsr->pNode ){ 910 RtreeNode *pNode = pCsr->pNode; 911 int nCell = NCELL(pNode); 912 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){ 913 int isEof; 914 rc = descendToCell(pRtree, pCsr, iHeight, &isEof); 915 if( rc!=SQLITE_OK || !isEof ){ 916 return rc; 917 } 918 } 919 pCsr->pNode = pNode->pParent; 920 pCsr->iCell = nodeParentIndex(pRtree, pNode); 921 nodeReference(pCsr->pNode); 922 nodeRelease(pRtree, pNode); 923 iHeight++; 924 } 925 } 926 927 return rc; 928 } 929 930 /* 931 ** Rtree virtual table module xRowid method. 932 */ 933 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ 934 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; 935 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 936 937 assert(pCsr->pNode); 938 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); 939 940 return SQLITE_OK; 941 } 942 943 /* 944 ** Rtree virtual table module xColumn method. 945 */ 946 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ 947 Rtree *pRtree = (Rtree *)cur->pVtab; 948 RtreeCursor *pCsr = (RtreeCursor *)cur; 949 950 if( i==0 ){ 951 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); 952 sqlite3_result_int64(ctx, iRowid); 953 }else{ 954 RtreeCoord c; 955 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c); 956 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 957 sqlite3_result_double(ctx, c.f); 958 }else{ 959 assert( pRtree->eCoordType==RTREE_COORD_INT32 ); 960 sqlite3_result_int(ctx, c.i); 961 } 962 } 963 964 return SQLITE_OK; 965 } 966 967 /* 968 ** Use nodeAcquire() to obtain the leaf node containing the record with 969 ** rowid iRowid. If successful, set *ppLeaf to point to the node and 970 ** return SQLITE_OK. If there is no such record in the table, set 971 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf 972 ** to zero and return an SQLite error code. 973 */ 974 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){ 975 int rc; 976 *ppLeaf = 0; 977 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); 978 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ 979 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); 980 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); 981 sqlite3_reset(pRtree->pReadRowid); 982 }else{ 983 rc = sqlite3_reset(pRtree->pReadRowid); 984 } 985 return rc; 986 } 987 988 989 /* 990 ** Rtree virtual table module xFilter method. 991 */ 992 static int rtreeFilter( 993 sqlite3_vtab_cursor *pVtabCursor, 994 int idxNum, const char *idxStr, 995 int argc, sqlite3_value **argv 996 ){ 997 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; 998 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 999 1000 RtreeNode *pRoot = 0; 1001 int ii; 1002 int rc = SQLITE_OK; 1003 1004 rtreeReference(pRtree); 1005 1006 sqlite3_free(pCsr->aConstraint); 1007 pCsr->aConstraint = 0; 1008 pCsr->iStrategy = idxNum; 1009 1010 if( idxNum==1 ){ 1011 /* Special case - lookup by rowid. */ 1012 RtreeNode *pLeaf; /* Leaf on which the required cell resides */ 1013 i64 iRowid = sqlite3_value_int64(argv[0]); 1014 rc = findLeafNode(pRtree, iRowid, &pLeaf); 1015 pCsr->pNode = pLeaf; 1016 if( pLeaf && rc==SQLITE_OK ){ 1017 pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid); 1018 } 1019 }else{ 1020 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 1021 ** with the configured constraints. 1022 */ 1023 if( argc>0 ){ 1024 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); 1025 pCsr->nConstraint = argc; 1026 if( !pCsr->aConstraint ){ 1027 rc = SQLITE_NOMEM; 1028 }else{ 1029 assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 ); 1030 for(ii=0; ii<argc; ii++){ 1031 RtreeConstraint *p = &pCsr->aConstraint[ii]; 1032 p->op = idxStr[ii*2]; 1033 p->iCoord = idxStr[ii*2+1]-'a'; 1034 p->rValue = sqlite3_value_double(argv[ii]); 1035 } 1036 } 1037 } 1038 1039 if( rc==SQLITE_OK ){ 1040 pCsr->pNode = 0; 1041 rc = nodeAcquire(pRtree, 1, 0, &pRoot); 1042 } 1043 if( rc==SQLITE_OK ){ 1044 int isEof = 1; 1045 int nCell = NCELL(pRoot); 1046 pCsr->pNode = pRoot; 1047 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){ 1048 assert( pCsr->pNode==pRoot ); 1049 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof); 1050 if( !isEof ){ 1051 break; 1052 } 1053 } 1054 if( rc==SQLITE_OK && isEof ){ 1055 assert( pCsr->pNode==pRoot ); 1056 nodeRelease(pRtree, pRoot); 1057 pCsr->pNode = 0; 1058 } 1059 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) ); 1060 } 1061 } 1062 1063 rtreeRelease(pRtree); 1064 return rc; 1065 } 1066 1067 /* 1068 ** Rtree virtual table module xBestIndex method. There are three 1069 ** table scan strategies to choose from (in order from most to 1070 ** least desirable): 1071 ** 1072 ** idxNum idxStr Strategy 1073 ** ------------------------------------------------ 1074 ** 1 Unused Direct lookup by rowid. 1075 ** 2 See below R-tree query. 1076 ** 3 Unused Full table scan. 1077 ** ------------------------------------------------ 1078 ** 1079 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy 1080 ** 2 is used, idxStr is formatted to contain 2 bytes for each 1081 ** constraint used. The first two bytes of idxStr correspond to 1082 ** the constraint in sqlite3_index_info.aConstraintUsage[] with 1083 ** (argvIndex==1) etc. 1084 ** 1085 ** The first of each pair of bytes in idxStr identifies the constraint 1086 ** operator as follows: 1087 ** 1088 ** Operator Byte Value 1089 ** ---------------------- 1090 ** = 0x41 ('A') 1091 ** <= 0x42 ('B') 1092 ** < 0x43 ('C') 1093 ** >= 0x44 ('D') 1094 ** > 0x45 ('E') 1095 ** ---------------------- 1096 ** 1097 ** The second of each pair of bytes identifies the coordinate column 1098 ** to which the constraint applies. The leftmost coordinate column 1099 ** is 'a', the second from the left 'b' etc. 1100 */ 1101 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ 1102 int rc = SQLITE_OK; 1103 int ii, cCol; 1104 1105 int iIdx = 0; 1106 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; 1107 memset(zIdxStr, 0, sizeof(zIdxStr)); 1108 1109 assert( pIdxInfo->idxStr==0 ); 1110 for(ii=0; ii<pIdxInfo->nConstraint; ii++){ 1111 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; 1112 1113 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ 1114 /* We have an equality constraint on the rowid. Use strategy 1. */ 1115 int jj; 1116 for(jj=0; jj<ii; jj++){ 1117 pIdxInfo->aConstraintUsage[jj].argvIndex = 0; 1118 pIdxInfo->aConstraintUsage[jj].omit = 0; 1119 } 1120 pIdxInfo->idxNum = 1; 1121 pIdxInfo->aConstraintUsage[ii].argvIndex = 1; 1122 pIdxInfo->aConstraintUsage[jj].omit = 1; 1123 1124 /* This strategy involves a two rowid lookups on an B-Tree structures 1125 ** and then a linear search of an R-Tree node. This should be 1126 ** considered almost as quick as a direct rowid lookup (for which 1127 ** sqlite uses an internal cost of 0.0). 1128 */ 1129 pIdxInfo->estimatedCost = 10.0; 1130 return SQLITE_OK; 1131 } 1132 1133 if( p->usable && p->iColumn>0 ){ 1134 u8 op = 0; 1135 switch( p->op ){ 1136 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; 1137 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; 1138 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; 1139 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; 1140 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; 1141 } 1142 if( op ){ 1143 /* Make sure this particular constraint has not been used before. 1144 ** If it has been used before, ignore it. 1145 ** 1146 ** A <= or < can be used if there is a prior >= or >. 1147 ** A >= or > can be used if there is a prior < or <=. 1148 ** A <= or < is disqualified if there is a prior <=, <, or ==. 1149 ** A >= or > is disqualified if there is a prior >=, >, or ==. 1150 ** A == is disqualifed if there is any prior constraint. 1151 */ 1152 int j, opmsk; 1153 static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 }; 1154 assert( compatible[RTREE_EQ & 7]==0 ); 1155 assert( compatible[RTREE_LT & 7]==1 ); 1156 assert( compatible[RTREE_LE & 7]==1 ); 1157 assert( compatible[RTREE_GT & 7]==2 ); 1158 assert( compatible[RTREE_GE & 7]==2 ); 1159 cCol = p->iColumn - 1 + 'a'; 1160 opmsk = compatible[op & 7]; 1161 for(j=0; j<iIdx; j+=2){ 1162 if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){ 1163 op = 0; 1164 break; 1165 } 1166 } 1167 } 1168 if( op ){ 1169 assert( iIdx<sizeof(zIdxStr)-1 ); 1170 zIdxStr[iIdx++] = op; 1171 zIdxStr[iIdx++] = cCol; 1172 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); 1173 pIdxInfo->aConstraintUsage[ii].omit = 1; 1174 } 1175 } 1176 } 1177 1178 pIdxInfo->idxNum = 2; 1179 pIdxInfo->needToFreeIdxStr = 1; 1180 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ 1181 return SQLITE_NOMEM; 1182 } 1183 assert( iIdx>=0 ); 1184 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1)); 1185 return rc; 1186 } 1187 1188 /* 1189 ** Return the N-dimensional volumn of the cell stored in *p. 1190 */ 1191 static float cellArea(Rtree *pRtree, RtreeCell *p){ 1192 float area = 1.0; 1193 int ii; 1194 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 1195 area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); 1196 } 1197 return area; 1198 } 1199 1200 /* 1201 ** Return the margin length of cell p. The margin length is the sum 1202 ** of the objects size in each dimension. 1203 */ 1204 static float cellMargin(Rtree *pRtree, RtreeCell *p){ 1205 float margin = 0.0; 1206 int ii; 1207 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 1208 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); 1209 } 1210 return margin; 1211 } 1212 1213 /* 1214 ** Store the union of cells p1 and p2 in p1. 1215 */ 1216 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ 1217 int ii; 1218 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 1219 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 1220 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); 1221 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); 1222 } 1223 }else{ 1224 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 1225 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); 1226 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); 1227 } 1228 } 1229 } 1230 1231 /* 1232 ** Return true if the area covered by p2 is a subset of the area covered 1233 ** by p1. False otherwise. 1234 */ 1235 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ 1236 int ii; 1237 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); 1238 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 1239 RtreeCoord *a1 = &p1->aCoord[ii]; 1240 RtreeCoord *a2 = &p2->aCoord[ii]; 1241 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 1242 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 1243 ){ 1244 return 0; 1245 } 1246 } 1247 return 1; 1248 } 1249 1250 /* 1251 ** Return the amount cell p would grow by if it were unioned with pCell. 1252 */ 1253 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ 1254 float area; 1255 RtreeCell cell; 1256 memcpy(&cell, p, sizeof(RtreeCell)); 1257 area = cellArea(pRtree, &cell); 1258 cellUnion(pRtree, &cell, pCell); 1259 return (cellArea(pRtree, &cell)-area); 1260 } 1261 1262 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT 1263 static float cellOverlap( 1264 Rtree *pRtree, 1265 RtreeCell *p, 1266 RtreeCell *aCell, 1267 int nCell, 1268 int iExclude 1269 ){ 1270 int ii; 1271 float overlap = 0.0; 1272 for(ii=0; ii<nCell; ii++){ 1273 if( ii!=iExclude ){ 1274 int jj; 1275 float o = 1.0; 1276 for(jj=0; jj<(pRtree->nDim*2); jj+=2){ 1277 double x1; 1278 double x2; 1279 1280 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); 1281 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); 1282 1283 if( x2<x1 ){ 1284 o = 0.0; 1285 break; 1286 }else{ 1287 o = o * (x2-x1); 1288 } 1289 } 1290 overlap += o; 1291 } 1292 } 1293 return overlap; 1294 } 1295 #endif 1296 1297 #if VARIANT_RSTARTREE_CHOOSESUBTREE 1298 static float cellOverlapEnlargement( 1299 Rtree *pRtree, 1300 RtreeCell *p, 1301 RtreeCell *pInsert, 1302 RtreeCell *aCell, 1303 int nCell, 1304 int iExclude 1305 ){ 1306 float before; 1307 float after; 1308 before = cellOverlap(pRtree, p, aCell, nCell, iExclude); 1309 cellUnion(pRtree, p, pInsert); 1310 after = cellOverlap(pRtree, p, aCell, nCell, iExclude); 1311 return after-before; 1312 } 1313 #endif 1314 1315 1316 /* 1317 ** This function implements the ChooseLeaf algorithm from Gutman[84]. 1318 ** ChooseSubTree in r*tree terminology. 1319 */ 1320 static int ChooseLeaf( 1321 Rtree *pRtree, /* Rtree table */ 1322 RtreeCell *pCell, /* Cell to insert into rtree */ 1323 int iHeight, /* Height of sub-tree rooted at pCell */ 1324 RtreeNode **ppLeaf /* OUT: Selected leaf page */ 1325 ){ 1326 int rc; 1327 int ii; 1328 RtreeNode *pNode; 1329 rc = nodeAcquire(pRtree, 1, 0, &pNode); 1330 1331 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){ 1332 int iCell; 1333 sqlite3_int64 iBest; 1334 1335 float fMinGrowth; 1336 float fMinArea; 1337 float fMinOverlap; 1338 1339 int nCell = NCELL(pNode); 1340 RtreeCell cell; 1341 RtreeNode *pChild; 1342 1343 RtreeCell *aCell = 0; 1344 1345 #if VARIANT_RSTARTREE_CHOOSESUBTREE 1346 if( ii==(pRtree->iDepth-1) ){ 1347 int jj; 1348 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell); 1349 if( !aCell ){ 1350 rc = SQLITE_NOMEM; 1351 nodeRelease(pRtree, pNode); 1352 pNode = 0; 1353 continue; 1354 } 1355 for(jj=0; jj<nCell; jj++){ 1356 nodeGetCell(pRtree, pNode, jj, &aCell[jj]); 1357 } 1358 } 1359 #endif 1360 1361 /* Select the child node which will be enlarged the least if pCell 1362 ** is inserted into it. Resolve ties by choosing the entry with 1363 ** the smallest area. 1364 */ 1365 for(iCell=0; iCell<nCell; iCell++){ 1366 float growth; 1367 float area; 1368 float overlap = 0.0; 1369 nodeGetCell(pRtree, pNode, iCell, &cell); 1370 growth = cellGrowth(pRtree, &cell, pCell); 1371 area = cellArea(pRtree, &cell); 1372 #if VARIANT_RSTARTREE_CHOOSESUBTREE 1373 if( ii==(pRtree->iDepth-1) ){ 1374 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell); 1375 } 1376 #endif 1377 if( (iCell==0) 1378 || (overlap<fMinOverlap) 1379 || (overlap==fMinOverlap && growth<fMinGrowth) 1380 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea) 1381 ){ 1382 fMinOverlap = overlap; 1383 fMinGrowth = growth; 1384 fMinArea = area; 1385 iBest = cell.iRowid; 1386 } 1387 } 1388 1389 sqlite3_free(aCell); 1390 rc = nodeAcquire(pRtree, iBest, pNode, &pChild); 1391 nodeRelease(pRtree, pNode); 1392 pNode = pChild; 1393 } 1394 1395 *ppLeaf = pNode; 1396 return rc; 1397 } 1398 1399 /* 1400 ** A cell with the same content as pCell has just been inserted into 1401 ** the node pNode. This function updates the bounding box cells in 1402 ** all ancestor elements. 1403 */ 1404 static void AdjustTree( 1405 Rtree *pRtree, /* Rtree table */ 1406 RtreeNode *pNode, /* Adjust ancestry of this node. */ 1407 RtreeCell *pCell /* This cell was just inserted */ 1408 ){ 1409 RtreeNode *p = pNode; 1410 while( p->pParent ){ 1411 RtreeCell cell; 1412 RtreeNode *pParent = p->pParent; 1413 int iCell = nodeParentIndex(pRtree, p); 1414 1415 nodeGetCell(pRtree, pParent, iCell, &cell); 1416 if( !cellContains(pRtree, &cell, pCell) ){ 1417 cellUnion(pRtree, &cell, pCell); 1418 nodeOverwriteCell(pRtree, pParent, &cell, iCell); 1419 } 1420 1421 p = pParent; 1422 } 1423 } 1424 1425 /* 1426 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table. 1427 */ 1428 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ 1429 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); 1430 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); 1431 sqlite3_step(pRtree->pWriteRowid); 1432 return sqlite3_reset(pRtree->pWriteRowid); 1433 } 1434 1435 /* 1436 ** Write mapping (iNode->iPar) to the <rtree>_parent table. 1437 */ 1438 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ 1439 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); 1440 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); 1441 sqlite3_step(pRtree->pWriteParent); 1442 return sqlite3_reset(pRtree->pWriteParent); 1443 } 1444 1445 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); 1446 1447 #if VARIANT_GUTTMAN_LINEAR_SPLIT 1448 /* 1449 ** Implementation of the linear variant of the PickNext() function from 1450 ** Guttman[84]. 1451 */ 1452 static RtreeCell *LinearPickNext( 1453 Rtree *pRtree, 1454 RtreeCell *aCell, 1455 int nCell, 1456 RtreeCell *pLeftBox, 1457 RtreeCell *pRightBox, 1458 int *aiUsed 1459 ){ 1460 int ii; 1461 for(ii=0; aiUsed[ii]; ii++); 1462 aiUsed[ii] = 1; 1463 return &aCell[ii]; 1464 } 1465 1466 /* 1467 ** Implementation of the linear variant of the PickSeeds() function from 1468 ** Guttman[84]. 1469 */ 1470 static void LinearPickSeeds( 1471 Rtree *pRtree, 1472 RtreeCell *aCell, 1473 int nCell, 1474 int *piLeftSeed, 1475 int *piRightSeed 1476 ){ 1477 int i; 1478 int iLeftSeed = 0; 1479 int iRightSeed = 1; 1480 float maxNormalInnerWidth = 0.0; 1481 1482 /* Pick two "seed" cells from the array of cells. The algorithm used 1483 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 1484 ** indices of the two seed cells in the array are stored in local 1485 ** variables iLeftSeek and iRightSeed. 1486 */ 1487 for(i=0; i<pRtree->nDim; i++){ 1488 float x1 = DCOORD(aCell[0].aCoord[i*2]); 1489 float x2 = DCOORD(aCell[0].aCoord[i*2+1]); 1490 float x3 = x1; 1491 float x4 = x2; 1492 int jj; 1493 1494 int iCellLeft = 0; 1495 int iCellRight = 0; 1496 1497 for(jj=1; jj<nCell; jj++){ 1498 float left = DCOORD(aCell[jj].aCoord[i*2]); 1499 float right = DCOORD(aCell[jj].aCoord[i*2+1]); 1500 1501 if( left<x1 ) x1 = left; 1502 if( right>x4 ) x4 = right; 1503 if( left>x3 ){ 1504 x3 = left; 1505 iCellRight = jj; 1506 } 1507 if( right<x2 ){ 1508 x2 = right; 1509 iCellLeft = jj; 1510 } 1511 } 1512 1513 if( x4!=x1 ){ 1514 float normalwidth = (x3 - x2) / (x4 - x1); 1515 if( normalwidth>maxNormalInnerWidth ){ 1516 iLeftSeed = iCellLeft; 1517 iRightSeed = iCellRight; 1518 } 1519 } 1520 } 1521 1522 *piLeftSeed = iLeftSeed; 1523 *piRightSeed = iRightSeed; 1524 } 1525 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */ 1526 1527 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT 1528 /* 1529 ** Implementation of the quadratic variant of the PickNext() function from 1530 ** Guttman[84]. 1531 */ 1532 static RtreeCell *QuadraticPickNext( 1533 Rtree *pRtree, 1534 RtreeCell *aCell, 1535 int nCell, 1536 RtreeCell *pLeftBox, 1537 RtreeCell *pRightBox, 1538 int *aiUsed 1539 ){ 1540 #define FABS(a) ((a)<0.0?-1.0*(a):(a)) 1541 1542 int iSelect = -1; 1543 float fDiff; 1544 int ii; 1545 for(ii=0; ii<nCell; ii++){ 1546 if( aiUsed[ii]==0 ){ 1547 float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]); 1548 float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]); 1549 float diff = FABS(right-left); 1550 if( iSelect<0 || diff>fDiff ){ 1551 fDiff = diff; 1552 iSelect = ii; 1553 } 1554 } 1555 } 1556 aiUsed[iSelect] = 1; 1557 return &aCell[iSelect]; 1558 } 1559 1560 /* 1561 ** Implementation of the quadratic variant of the PickSeeds() function from 1562 ** Guttman[84]. 1563 */ 1564 static void QuadraticPickSeeds( 1565 Rtree *pRtree, 1566 RtreeCell *aCell, 1567 int nCell, 1568 int *piLeftSeed, 1569 int *piRightSeed 1570 ){ 1571 int ii; 1572 int jj; 1573 1574 int iLeftSeed = 0; 1575 int iRightSeed = 1; 1576 float fWaste = 0.0; 1577 1578 for(ii=0; ii<nCell; ii++){ 1579 for(jj=ii+1; jj<nCell; jj++){ 1580 float right = cellArea(pRtree, &aCell[jj]); 1581 float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]); 1582 float waste = growth - right; 1583 1584 if( waste>fWaste ){ 1585 iLeftSeed = ii; 1586 iRightSeed = jj; 1587 fWaste = waste; 1588 } 1589 } 1590 } 1591 1592 *piLeftSeed = iLeftSeed; 1593 *piRightSeed = iRightSeed; 1594 } 1595 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */ 1596 1597 /* 1598 ** Arguments aIdx, aDistance and aSpare all point to arrays of size 1599 ** nIdx. The aIdx array contains the set of integers from 0 to 1600 ** (nIdx-1) in no particular order. This function sorts the values 1601 ** in aIdx according to the indexed values in aDistance. For 1602 ** example, assuming the inputs: 1603 ** 1604 ** aIdx = { 0, 1, 2, 3 } 1605 ** aDistance = { 5.0, 2.0, 7.0, 6.0 } 1606 ** 1607 ** this function sets the aIdx array to contain: 1608 ** 1609 ** aIdx = { 0, 1, 2, 3 } 1610 ** 1611 ** The aSpare array is used as temporary working space by the 1612 ** sorting algorithm. 1613 */ 1614 static void SortByDistance( 1615 int *aIdx, 1616 int nIdx, 1617 float *aDistance, 1618 int *aSpare 1619 ){ 1620 if( nIdx>1 ){ 1621 int iLeft = 0; 1622 int iRight = 0; 1623 1624 int nLeft = nIdx/2; 1625 int nRight = nIdx-nLeft; 1626 int *aLeft = aIdx; 1627 int *aRight = &aIdx[nLeft]; 1628 1629 SortByDistance(aLeft, nLeft, aDistance, aSpare); 1630 SortByDistance(aRight, nRight, aDistance, aSpare); 1631 1632 memcpy(aSpare, aLeft, sizeof(int)*nLeft); 1633 aLeft = aSpare; 1634 1635 while( iLeft<nLeft || iRight<nRight ){ 1636 if( iLeft==nLeft ){ 1637 aIdx[iLeft+iRight] = aRight[iRight]; 1638 iRight++; 1639 }else if( iRight==nRight ){ 1640 aIdx[iLeft+iRight] = aLeft[iLeft]; 1641 iLeft++; 1642 }else{ 1643 float fLeft = aDistance[aLeft[iLeft]]; 1644 float fRight = aDistance[aRight[iRight]]; 1645 if( fLeft<fRight ){ 1646 aIdx[iLeft+iRight] = aLeft[iLeft]; 1647 iLeft++; 1648 }else{ 1649 aIdx[iLeft+iRight] = aRight[iRight]; 1650 iRight++; 1651 } 1652 } 1653 } 1654 1655 #if 0 1656 /* Check that the sort worked */ 1657 { 1658 int jj; 1659 for(jj=1; jj<nIdx; jj++){ 1660 float left = aDistance[aIdx[jj-1]]; 1661 float right = aDistance[aIdx[jj]]; 1662 assert( left<=right ); 1663 } 1664 } 1665 #endif 1666 } 1667 } 1668 1669 /* 1670 ** Arguments aIdx, aCell and aSpare all point to arrays of size 1671 ** nIdx. The aIdx array contains the set of integers from 0 to 1672 ** (nIdx-1) in no particular order. This function sorts the values 1673 ** in aIdx according to dimension iDim of the cells in aCell. The 1674 ** minimum value of dimension iDim is considered first, the 1675 ** maximum used to break ties. 1676 ** 1677 ** The aSpare array is used as temporary working space by the 1678 ** sorting algorithm. 1679 */ 1680 static void SortByDimension( 1681 Rtree *pRtree, 1682 int *aIdx, 1683 int nIdx, 1684 int iDim, 1685 RtreeCell *aCell, 1686 int *aSpare 1687 ){ 1688 if( nIdx>1 ){ 1689 1690 int iLeft = 0; 1691 int iRight = 0; 1692 1693 int nLeft = nIdx/2; 1694 int nRight = nIdx-nLeft; 1695 int *aLeft = aIdx; 1696 int *aRight = &aIdx[nLeft]; 1697 1698 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); 1699 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); 1700 1701 memcpy(aSpare, aLeft, sizeof(int)*nLeft); 1702 aLeft = aSpare; 1703 while( iLeft<nLeft || iRight<nRight ){ 1704 double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]); 1705 double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]); 1706 double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]); 1707 double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]); 1708 if( (iLeft!=nLeft) && ((iRight==nRight) 1709 || (xleft1<xright1) 1710 || (xleft1==xright1 && xleft2<xright2) 1711 )){ 1712 aIdx[iLeft+iRight] = aLeft[iLeft]; 1713 iLeft++; 1714 }else{ 1715 aIdx[iLeft+iRight] = aRight[iRight]; 1716 iRight++; 1717 } 1718 } 1719 1720 #if 0 1721 /* Check that the sort worked */ 1722 { 1723 int jj; 1724 for(jj=1; jj<nIdx; jj++){ 1725 float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2]; 1726 float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1]; 1727 float xright1 = aCell[aIdx[jj]].aCoord[iDim*2]; 1728 float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1]; 1729 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) ); 1730 } 1731 } 1732 #endif 1733 } 1734 } 1735 1736 #if VARIANT_RSTARTREE_SPLIT 1737 /* 1738 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990]. 1739 */ 1740 static int splitNodeStartree( 1741 Rtree *pRtree, 1742 RtreeCell *aCell, 1743 int nCell, 1744 RtreeNode *pLeft, 1745 RtreeNode *pRight, 1746 RtreeCell *pBboxLeft, 1747 RtreeCell *pBboxRight 1748 ){ 1749 int **aaSorted; 1750 int *aSpare; 1751 int ii; 1752 1753 int iBestDim; 1754 int iBestSplit; 1755 float fBestMargin; 1756 1757 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int)); 1758 1759 aaSorted = (int **)sqlite3_malloc(nByte); 1760 if( !aaSorted ){ 1761 return SQLITE_NOMEM; 1762 } 1763 1764 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; 1765 memset(aaSorted, 0, nByte); 1766 for(ii=0; ii<pRtree->nDim; ii++){ 1767 int jj; 1768 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; 1769 for(jj=0; jj<nCell; jj++){ 1770 aaSorted[ii][jj] = jj; 1771 } 1772 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare); 1773 } 1774 1775 for(ii=0; ii<pRtree->nDim; ii++){ 1776 float margin = 0.0; 1777 float fBestOverlap; 1778 float fBestArea; 1779 int iBestLeft; 1780 int nLeft; 1781 1782 for( 1783 nLeft=RTREE_MINCELLS(pRtree); 1784 nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 1785 nLeft++ 1786 ){ 1787 RtreeCell left; 1788 RtreeCell right; 1789 int kk; 1790 float overlap; 1791 float area; 1792 1793 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); 1794 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); 1795 for(kk=1; kk<(nCell-1); kk++){ 1796 if( kk<nLeft ){ 1797 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]); 1798 }else{ 1799 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]); 1800 } 1801 } 1802 margin += cellMargin(pRtree, &left); 1803 margin += cellMargin(pRtree, &right); 1804 overlap = cellOverlap(pRtree, &left, &right, 1, -1); 1805 area = cellArea(pRtree, &left) + cellArea(pRtree, &right); 1806 if( (nLeft==RTREE_MINCELLS(pRtree)) 1807 || (overlap<fBestOverlap) 1808 || (overlap==fBestOverlap && area<fBestArea) 1809 ){ 1810 iBestLeft = nLeft; 1811 fBestOverlap = overlap; 1812 fBestArea = area; 1813 } 1814 } 1815 1816 if( ii==0 || margin<fBestMargin ){ 1817 iBestDim = ii; 1818 fBestMargin = margin; 1819 iBestSplit = iBestLeft; 1820 } 1821 } 1822 1823 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell)); 1824 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell)); 1825 for(ii=0; ii<nCell; ii++){ 1826 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight; 1827 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight; 1828 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]]; 1829 nodeInsertCell(pRtree, pTarget, pCell); 1830 cellUnion(pRtree, pBbox, pCell); 1831 } 1832 1833 sqlite3_free(aaSorted); 1834 return SQLITE_OK; 1835 } 1836 #endif 1837 1838 #if VARIANT_GUTTMAN_SPLIT 1839 /* 1840 ** Implementation of the regular R-tree SplitNode from Guttman[1984]. 1841 */ 1842 static int splitNodeGuttman( 1843 Rtree *pRtree, 1844 RtreeCell *aCell, 1845 int nCell, 1846 RtreeNode *pLeft, 1847 RtreeNode *pRight, 1848 RtreeCell *pBboxLeft, 1849 RtreeCell *pBboxRight 1850 ){ 1851 int iLeftSeed = 0; 1852 int iRightSeed = 1; 1853 int *aiUsed; 1854 int i; 1855 1856 aiUsed = sqlite3_malloc(sizeof(int)*nCell); 1857 if( !aiUsed ){ 1858 return SQLITE_NOMEM; 1859 } 1860 memset(aiUsed, 0, sizeof(int)*nCell); 1861 1862 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed); 1863 1864 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell)); 1865 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell)); 1866 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]); 1867 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]); 1868 aiUsed[iLeftSeed] = 1; 1869 aiUsed[iRightSeed] = 1; 1870 1871 for(i=nCell-2; i>0; i--){ 1872 RtreeCell *pNext; 1873 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed); 1874 float diff = 1875 cellGrowth(pRtree, pBboxLeft, pNext) - 1876 cellGrowth(pRtree, pBboxRight, pNext) 1877 ; 1878 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i) 1879 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i)) 1880 ){ 1881 nodeInsertCell(pRtree, pRight, pNext); 1882 cellUnion(pRtree, pBboxRight, pNext); 1883 }else{ 1884 nodeInsertCell(pRtree, pLeft, pNext); 1885 cellUnion(pRtree, pBboxLeft, pNext); 1886 } 1887 } 1888 1889 sqlite3_free(aiUsed); 1890 return SQLITE_OK; 1891 } 1892 #endif 1893 1894 static int updateMapping( 1895 Rtree *pRtree, 1896 i64 iRowid, 1897 RtreeNode *pNode, 1898 int iHeight 1899 ){ 1900 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); 1901 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); 1902 if( iHeight>0 ){ 1903 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); 1904 if( pChild ){ 1905 nodeRelease(pRtree, pChild->pParent); 1906 nodeReference(pNode); 1907 pChild->pParent = pNode; 1908 } 1909 } 1910 return xSetMapping(pRtree, iRowid, pNode->iNode); 1911 } 1912 1913 static int SplitNode( 1914 Rtree *pRtree, 1915 RtreeNode *pNode, 1916 RtreeCell *pCell, 1917 int iHeight 1918 ){ 1919 int i; 1920 int newCellIsRight = 0; 1921 1922 int rc = SQLITE_OK; 1923 int nCell = NCELL(pNode); 1924 RtreeCell *aCell; 1925 int *aiUsed; 1926 1927 RtreeNode *pLeft = 0; 1928 RtreeNode *pRight = 0; 1929 1930 RtreeCell leftbbox; 1931 RtreeCell rightbbox; 1932 1933 /* Allocate an array and populate it with a copy of pCell and 1934 ** all cells from node pLeft. Then zero the original node. 1935 */ 1936 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); 1937 if( !aCell ){ 1938 rc = SQLITE_NOMEM; 1939 goto splitnode_out; 1940 } 1941 aiUsed = (int *)&aCell[nCell+1]; 1942 memset(aiUsed, 0, sizeof(int)*(nCell+1)); 1943 for(i=0; i<nCell; i++){ 1944 nodeGetCell(pRtree, pNode, i, &aCell[i]); 1945 } 1946 nodeZero(pRtree, pNode); 1947 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell)); 1948 nCell++; 1949 1950 if( pNode->iNode==1 ){ 1951 pRight = nodeNew(pRtree, pNode, 1); 1952 pLeft = nodeNew(pRtree, pNode, 1); 1953 pRtree->iDepth++; 1954 pNode->isDirty = 1; 1955 writeInt16(pNode->zData, pRtree->iDepth); 1956 }else{ 1957 pLeft = pNode; 1958 pRight = nodeNew(pRtree, pLeft->pParent, 1); 1959 nodeReference(pLeft); 1960 } 1961 1962 if( !pLeft || !pRight ){ 1963 rc = SQLITE_NOMEM; 1964 goto splitnode_out; 1965 } 1966 1967 memset(pLeft->zData, 0, pRtree->iNodeSize); 1968 memset(pRight->zData, 0, pRtree->iNodeSize); 1969 1970 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); 1971 if( rc!=SQLITE_OK ){ 1972 goto splitnode_out; 1973 } 1974 1975 /* Ensure both child nodes have node numbers assigned to them. */ 1976 if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))) 1977 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) 1978 ){ 1979 goto splitnode_out; 1980 } 1981 1982 rightbbox.iRowid = pRight->iNode; 1983 leftbbox.iRowid = pLeft->iNode; 1984 1985 if( pNode->iNode==1 ){ 1986 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); 1987 if( rc!=SQLITE_OK ){ 1988 goto splitnode_out; 1989 } 1990 }else{ 1991 RtreeNode *pParent = pLeft->pParent; 1992 int iCell = nodeParentIndex(pRtree, pLeft); 1993 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); 1994 AdjustTree(pRtree, pParent, &leftbbox); 1995 } 1996 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ 1997 goto splitnode_out; 1998 } 1999 2000 for(i=0; i<NCELL(pRight); i++){ 2001 i64 iRowid = nodeGetRowid(pRtree, pRight, i); 2002 rc = updateMapping(pRtree, iRowid, pRight, iHeight); 2003 if( iRowid==pCell->iRowid ){ 2004 newCellIsRight = 1; 2005 } 2006 if( rc!=SQLITE_OK ){ 2007 goto splitnode_out; 2008 } 2009 } 2010 if( pNode->iNode==1 ){ 2011 for(i=0; i<NCELL(pLeft); i++){ 2012 i64 iRowid = nodeGetRowid(pRtree, pLeft, i); 2013 rc = updateMapping(pRtree, iRowid, pLeft, iHeight); 2014 if( rc!=SQLITE_OK ){ 2015 goto splitnode_out; 2016 } 2017 } 2018 }else if( newCellIsRight==0 ){ 2019 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight); 2020 } 2021 2022 if( rc==SQLITE_OK ){ 2023 rc = nodeRelease(pRtree, pRight); 2024 pRight = 0; 2025 } 2026 if( rc==SQLITE_OK ){ 2027 rc = nodeRelease(pRtree, pLeft); 2028 pLeft = 0; 2029 } 2030 2031 splitnode_out: 2032 nodeRelease(pRtree, pRight); 2033 nodeRelease(pRtree, pLeft); 2034 sqlite3_free(aCell); 2035 return rc; 2036 } 2037 2038 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ 2039 int rc = SQLITE_OK; 2040 if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){ 2041 sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode); 2042 if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){ 2043 i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0); 2044 rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent); 2045 }else{ 2046 rc = SQLITE_ERROR; 2047 } 2048 sqlite3_reset(pRtree->pReadParent); 2049 if( rc==SQLITE_OK ){ 2050 rc = fixLeafParent(pRtree, pLeaf->pParent); 2051 } 2052 } 2053 return rc; 2054 } 2055 2056 static int deleteCell(Rtree *, RtreeNode *, int, int); 2057 2058 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ 2059 int rc; 2060 RtreeNode *pParent; 2061 int iCell; 2062 2063 assert( pNode->nRef==1 ); 2064 2065 /* Remove the entry in the parent cell. */ 2066 iCell = nodeParentIndex(pRtree, pNode); 2067 pParent = pNode->pParent; 2068 pNode->pParent = 0; 2069 if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 2070 || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent)) 2071 ){ 2072 return rc; 2073 } 2074 2075 /* Remove the xxx_node entry. */ 2076 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); 2077 sqlite3_step(pRtree->pDeleteNode); 2078 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ 2079 return rc; 2080 } 2081 2082 /* Remove the xxx_parent entry. */ 2083 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); 2084 sqlite3_step(pRtree->pDeleteParent); 2085 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ 2086 return rc; 2087 } 2088 2089 /* Remove the node from the in-memory hash table and link it into 2090 ** the Rtree.pDeleted list. Its contents will be re-inserted later on. 2091 */ 2092 nodeHashDelete(pRtree, pNode); 2093 pNode->iNode = iHeight; 2094 pNode->pNext = pRtree->pDeleted; 2095 pNode->nRef++; 2096 pRtree->pDeleted = pNode; 2097 2098 return SQLITE_OK; 2099 } 2100 2101 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ 2102 RtreeNode *pParent = pNode->pParent; 2103 if( pParent ){ 2104 int ii; 2105 int nCell = NCELL(pNode); 2106 RtreeCell box; /* Bounding box for pNode */ 2107 nodeGetCell(pRtree, pNode, 0, &box); 2108 for(ii=1; ii<nCell; ii++){ 2109 RtreeCell cell; 2110 nodeGetCell(pRtree, pNode, ii, &cell); 2111 cellUnion(pRtree, &box, &cell); 2112 } 2113 box.iRowid = pNode->iNode; 2114 ii = nodeParentIndex(pRtree, pNode); 2115 nodeOverwriteCell(pRtree, pParent, &box, ii); 2116 fixBoundingBox(pRtree, pParent); 2117 } 2118 } 2119 2120 /* 2121 ** Delete the cell at index iCell of node pNode. After removing the 2122 ** cell, adjust the r-tree data structure if required. 2123 */ 2124 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ 2125 int rc; 2126 2127 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ 2128 return rc; 2129 } 2130 2131 /* Remove the cell from the node. This call just moves bytes around 2132 ** the in-memory node image, so it cannot fail. 2133 */ 2134 nodeDeleteCell(pRtree, pNode, iCell); 2135 2136 /* If the node is not the tree root and now has less than the minimum 2137 ** number of cells, remove it from the tree. Otherwise, update the 2138 ** cell in the parent node so that it tightly contains the updated 2139 ** node. 2140 */ 2141 if( pNode->iNode!=1 ){ 2142 RtreeNode *pParent = pNode->pParent; 2143 if( (pParent->iNode!=1 || NCELL(pParent)!=1) 2144 && (NCELL(pNode)<RTREE_MINCELLS(pRtree)) 2145 ){ 2146 rc = removeNode(pRtree, pNode, iHeight); 2147 }else{ 2148 fixBoundingBox(pRtree, pNode); 2149 } 2150 } 2151 2152 return rc; 2153 } 2154 2155 static int Reinsert( 2156 Rtree *pRtree, 2157 RtreeNode *pNode, 2158 RtreeCell *pCell, 2159 int iHeight 2160 ){ 2161 int *aOrder; 2162 int *aSpare; 2163 RtreeCell *aCell; 2164 float *aDistance; 2165 int nCell; 2166 float aCenterCoord[RTREE_MAX_DIMENSIONS]; 2167 int iDim; 2168 int ii; 2169 int rc = SQLITE_OK; 2170 2171 memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS); 2172 2173 nCell = NCELL(pNode)+1; 2174 2175 /* Allocate the buffers used by this operation. The allocation is 2176 ** relinquished before this function returns. 2177 */ 2178 aCell = (RtreeCell *)sqlite3_malloc(nCell * ( 2179 sizeof(RtreeCell) + /* aCell array */ 2180 sizeof(int) + /* aOrder array */ 2181 sizeof(int) + /* aSpare array */ 2182 sizeof(float) /* aDistance array */ 2183 )); 2184 if( !aCell ){ 2185 return SQLITE_NOMEM; 2186 } 2187 aOrder = (int *)&aCell[nCell]; 2188 aSpare = (int *)&aOrder[nCell]; 2189 aDistance = (float *)&aSpare[nCell]; 2190 2191 for(ii=0; ii<nCell; ii++){ 2192 if( ii==(nCell-1) ){ 2193 memcpy(&aCell[ii], pCell, sizeof(RtreeCell)); 2194 }else{ 2195 nodeGetCell(pRtree, pNode, ii, &aCell[ii]); 2196 } 2197 aOrder[ii] = ii; 2198 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2199 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); 2200 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); 2201 } 2202 } 2203 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2204 aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0); 2205 } 2206 2207 for(ii=0; ii<nCell; ii++){ 2208 aDistance[ii] = 0.0; 2209 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2210 float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 2211 DCOORD(aCell[ii].aCoord[iDim*2]); 2212 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); 2213 } 2214 } 2215 2216 SortByDistance(aOrder, nCell, aDistance, aSpare); 2217 nodeZero(pRtree, pNode); 2218 2219 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ 2220 RtreeCell *p = &aCell[aOrder[ii]]; 2221 nodeInsertCell(pRtree, pNode, p); 2222 if( p->iRowid==pCell->iRowid ){ 2223 if( iHeight==0 ){ 2224 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); 2225 }else{ 2226 rc = parentWrite(pRtree, p->iRowid, pNode->iNode); 2227 } 2228 } 2229 } 2230 if( rc==SQLITE_OK ){ 2231 fixBoundingBox(pRtree, pNode); 2232 } 2233 for(; rc==SQLITE_OK && ii<nCell; ii++){ 2234 /* Find a node to store this cell in. pNode->iNode currently contains 2235 ** the height of the sub-tree headed by the cell. 2236 */ 2237 RtreeNode *pInsert; 2238 RtreeCell *p = &aCell[aOrder[ii]]; 2239 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); 2240 if( rc==SQLITE_OK ){ 2241 int rc2; 2242 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); 2243 rc2 = nodeRelease(pRtree, pInsert); 2244 if( rc==SQLITE_OK ){ 2245 rc = rc2; 2246 } 2247 } 2248 } 2249 2250 sqlite3_free(aCell); 2251 return rc; 2252 } 2253 2254 /* 2255 ** Insert cell pCell into node pNode. Node pNode is the head of a 2256 ** subtree iHeight high (leaf nodes have iHeight==0). 2257 */ 2258 static int rtreeInsertCell( 2259 Rtree *pRtree, 2260 RtreeNode *pNode, 2261 RtreeCell *pCell, 2262 int iHeight 2263 ){ 2264 int rc = SQLITE_OK; 2265 if( iHeight>0 ){ 2266 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); 2267 if( pChild ){ 2268 nodeRelease(pRtree, pChild->pParent); 2269 nodeReference(pNode); 2270 pChild->pParent = pNode; 2271 } 2272 } 2273 if( nodeInsertCell(pRtree, pNode, pCell) ){ 2274 #if VARIANT_RSTARTREE_REINSERT 2275 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ 2276 rc = SplitNode(pRtree, pNode, pCell, iHeight); 2277 }else{ 2278 pRtree->iReinsertHeight = iHeight; 2279 rc = Reinsert(pRtree, pNode, pCell, iHeight); 2280 } 2281 #else 2282 rc = SplitNode(pRtree, pNode, pCell, iHeight); 2283 #endif 2284 }else{ 2285 AdjustTree(pRtree, pNode, pCell); 2286 if( iHeight==0 ){ 2287 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); 2288 }else{ 2289 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); 2290 } 2291 } 2292 return rc; 2293 } 2294 2295 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ 2296 int ii; 2297 int rc = SQLITE_OK; 2298 int nCell = NCELL(pNode); 2299 2300 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){ 2301 RtreeNode *pInsert; 2302 RtreeCell cell; 2303 nodeGetCell(pRtree, pNode, ii, &cell); 2304 2305 /* Find a node to store this cell in. pNode->iNode currently contains 2306 ** the height of the sub-tree headed by the cell. 2307 */ 2308 rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert); 2309 if( rc==SQLITE_OK ){ 2310 int rc2; 2311 rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode); 2312 rc2 = nodeRelease(pRtree, pInsert); 2313 if( rc==SQLITE_OK ){ 2314 rc = rc2; 2315 } 2316 } 2317 } 2318 return rc; 2319 } 2320 2321 /* 2322 ** Select a currently unused rowid for a new r-tree record. 2323 */ 2324 static int newRowid(Rtree *pRtree, i64 *piRowid){ 2325 int rc; 2326 sqlite3_bind_null(pRtree->pWriteRowid, 1); 2327 sqlite3_bind_null(pRtree->pWriteRowid, 2); 2328 sqlite3_step(pRtree->pWriteRowid); 2329 rc = sqlite3_reset(pRtree->pWriteRowid); 2330 *piRowid = sqlite3_last_insert_rowid(pRtree->db); 2331 return rc; 2332 } 2333 2334 #ifndef NDEBUG 2335 static int hashIsEmpty(Rtree *pRtree){ 2336 int ii; 2337 for(ii=0; ii<HASHSIZE; ii++){ 2338 assert( !pRtree->aHash[ii] ); 2339 } 2340 return 1; 2341 } 2342 #endif 2343 2344 /* 2345 ** The xUpdate method for rtree module virtual tables. 2346 */ 2347 static int rtreeUpdate( 2348 sqlite3_vtab *pVtab, 2349 int nData, 2350 sqlite3_value **azData, 2351 sqlite_int64 *pRowid 2352 ){ 2353 Rtree *pRtree = (Rtree *)pVtab; 2354 int rc = SQLITE_OK; 2355 2356 rtreeReference(pRtree); 2357 2358 assert(nData>=1); 2359 assert(hashIsEmpty(pRtree)); 2360 2361 /* If azData[0] is not an SQL NULL value, it is the rowid of a 2362 ** record to delete from the r-tree table. The following block does 2363 ** just that. 2364 */ 2365 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ 2366 i64 iDelete; /* The rowid to delete */ 2367 RtreeNode *pLeaf; /* Leaf node containing record iDelete */ 2368 int iCell; /* Index of iDelete cell in pLeaf */ 2369 RtreeNode *pRoot; 2370 2371 /* Obtain a reference to the root node to initialise Rtree.iDepth */ 2372 rc = nodeAcquire(pRtree, 1, 0, &pRoot); 2373 2374 /* Obtain a reference to the leaf node that contains the entry 2375 ** about to be deleted. 2376 */ 2377 if( rc==SQLITE_OK ){ 2378 iDelete = sqlite3_value_int64(azData[0]); 2379 rc = findLeafNode(pRtree, iDelete, &pLeaf); 2380 } 2381 2382 /* Delete the cell in question from the leaf node. */ 2383 if( rc==SQLITE_OK ){ 2384 int rc2; 2385 iCell = nodeRowidIndex(pRtree, pLeaf, iDelete); 2386 rc = deleteCell(pRtree, pLeaf, iCell, 0); 2387 rc2 = nodeRelease(pRtree, pLeaf); 2388 if( rc==SQLITE_OK ){ 2389 rc = rc2; 2390 } 2391 } 2392 2393 /* Delete the corresponding entry in the <rtree>_rowid table. */ 2394 if( rc==SQLITE_OK ){ 2395 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); 2396 sqlite3_step(pRtree->pDeleteRowid); 2397 rc = sqlite3_reset(pRtree->pDeleteRowid); 2398 } 2399 2400 /* Check if the root node now has exactly one child. If so, remove 2401 ** it, schedule the contents of the child for reinsertion and 2402 ** reduce the tree height by one. 2403 ** 2404 ** This is equivalent to copying the contents of the child into 2405 ** the root node (the operation that Gutman's paper says to perform 2406 ** in this scenario). 2407 */ 2408 if( rc==SQLITE_OK && pRtree->iDepth>0 ){ 2409 if( rc==SQLITE_OK && NCELL(pRoot)==1 ){ 2410 RtreeNode *pChild; 2411 i64 iChild = nodeGetRowid(pRtree, pRoot, 0); 2412 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); 2413 if( rc==SQLITE_OK ){ 2414 rc = removeNode(pRtree, pChild, pRtree->iDepth-1); 2415 } 2416 if( rc==SQLITE_OK ){ 2417 pRtree->iDepth--; 2418 writeInt16(pRoot->zData, pRtree->iDepth); 2419 pRoot->isDirty = 1; 2420 } 2421 } 2422 } 2423 2424 /* Re-insert the contents of any underfull nodes removed from the tree. */ 2425 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ 2426 if( rc==SQLITE_OK ){ 2427 rc = reinsertNodeContent(pRtree, pLeaf); 2428 } 2429 pRtree->pDeleted = pLeaf->pNext; 2430 sqlite3_free(pLeaf); 2431 } 2432 2433 /* Release the reference to the root node. */ 2434 if( rc==SQLITE_OK ){ 2435 rc = nodeRelease(pRtree, pRoot); 2436 }else{ 2437 nodeRelease(pRtree, pRoot); 2438 } 2439 } 2440 2441 /* If the azData[] array contains more than one element, elements 2442 ** (azData[2]..azData[argc-1]) contain a new record to insert into 2443 ** the r-tree structure. 2444 */ 2445 if( rc==SQLITE_OK && nData>1 ){ 2446 /* Insert a new record into the r-tree */ 2447 RtreeCell cell; 2448 int ii; 2449 RtreeNode *pLeaf; 2450 2451 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */ 2452 assert( nData==(pRtree->nDim*2 + 3) ); 2453 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 2454 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 2455 cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]); 2456 cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]); 2457 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ 2458 rc = SQLITE_CONSTRAINT; 2459 goto constraint; 2460 } 2461 } 2462 }else{ 2463 for(ii=0; ii<(pRtree->nDim*2); ii+=2){ 2464 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); 2465 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); 2466 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ 2467 rc = SQLITE_CONSTRAINT; 2468 goto constraint; 2469 } 2470 } 2471 } 2472 2473 /* Figure out the rowid of the new row. */ 2474 if( sqlite3_value_type(azData[2])==SQLITE_NULL ){ 2475 rc = newRowid(pRtree, &cell.iRowid); 2476 }else{ 2477 cell.iRowid = sqlite3_value_int64(azData[2]); 2478 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); 2479 if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){ 2480 sqlite3_reset(pRtree->pReadRowid); 2481 rc = SQLITE_CONSTRAINT; 2482 goto constraint; 2483 } 2484 rc = sqlite3_reset(pRtree->pReadRowid); 2485 } 2486 *pRowid = cell.iRowid; 2487 2488 if( rc==SQLITE_OK ){ 2489 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); 2490 } 2491 if( rc==SQLITE_OK ){ 2492 int rc2; 2493 pRtree->iReinsertHeight = -1; 2494 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); 2495 rc2 = nodeRelease(pRtree, pLeaf); 2496 if( rc==SQLITE_OK ){ 2497 rc = rc2; 2498 } 2499 } 2500 } 2501 2502 constraint: 2503 rtreeRelease(pRtree); 2504 return rc; 2505 } 2506 2507 /* 2508 ** The xRename method for rtree module virtual tables. 2509 */ 2510 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ 2511 Rtree *pRtree = (Rtree *)pVtab; 2512 int rc = SQLITE_NOMEM; 2513 char *zSql = sqlite3_mprintf( 2514 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" 2515 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" 2516 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" 2517 , pRtree->zDb, pRtree->zName, zNewName 2518 , pRtree->zDb, pRtree->zName, zNewName 2519 , pRtree->zDb, pRtree->zName, zNewName 2520 ); 2521 if( zSql ){ 2522 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); 2523 sqlite3_free(zSql); 2524 } 2525 return rc; 2526 } 2527 2528 static sqlite3_module rtreeModule = { 2529 0, /* iVersion */ 2530 rtreeCreate, /* xCreate - create a table */ 2531 rtreeConnect, /* xConnect - connect to an existing table */ 2532 rtreeBestIndex, /* xBestIndex - Determine search strategy */ 2533 rtreeDisconnect, /* xDisconnect - Disconnect from a table */ 2534 rtreeDestroy, /* xDestroy - Drop a table */ 2535 rtreeOpen, /* xOpen - open a cursor */ 2536 rtreeClose, /* xClose - close a cursor */ 2537 rtreeFilter, /* xFilter - configure scan constraints */ 2538 rtreeNext, /* xNext - advance a cursor */ 2539 rtreeEof, /* xEof */ 2540 rtreeColumn, /* xColumn - read data */ 2541 rtreeRowid, /* xRowid - read data */ 2542 rtreeUpdate, /* xUpdate - write data */ 2543 0, /* xBegin - begin transaction */ 2544 0, /* xSync - sync transaction */ 2545 0, /* xCommit - commit transaction */ 2546 0, /* xRollback - rollback transaction */ 2547 0, /* xFindFunction - function overloading */ 2548 rtreeRename /* xRename - rename the table */ 2549 }; 2550 2551 static int rtreeSqlInit( 2552 Rtree *pRtree, 2553 sqlite3 *db, 2554 const char *zDb, 2555 const char *zPrefix, 2556 int isCreate 2557 ){ 2558 int rc = SQLITE_OK; 2559 2560 #define N_STATEMENT 9 2561 static const char *azSql[N_STATEMENT] = { 2562 /* Read and write the xxx_node table */ 2563 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", 2564 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", 2565 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", 2566 2567 /* Read and write the xxx_rowid table */ 2568 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", 2569 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", 2570 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", 2571 2572 /* Read and write the xxx_parent table */ 2573 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", 2574 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", 2575 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" 2576 }; 2577 sqlite3_stmt **appStmt[N_STATEMENT]; 2578 int i; 2579 2580 pRtree->db = db; 2581 2582 if( isCreate ){ 2583 char *zCreate = sqlite3_mprintf( 2584 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" 2585 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" 2586 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);" 2587 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", 2588 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize 2589 ); 2590 if( !zCreate ){ 2591 return SQLITE_NOMEM; 2592 } 2593 rc = sqlite3_exec(db, zCreate, 0, 0, 0); 2594 sqlite3_free(zCreate); 2595 if( rc!=SQLITE_OK ){ 2596 return rc; 2597 } 2598 } 2599 2600 appStmt[0] = &pRtree->pReadNode; 2601 appStmt[1] = &pRtree->pWriteNode; 2602 appStmt[2] = &pRtree->pDeleteNode; 2603 appStmt[3] = &pRtree->pReadRowid; 2604 appStmt[4] = &pRtree->pWriteRowid; 2605 appStmt[5] = &pRtree->pDeleteRowid; 2606 appStmt[6] = &pRtree->pReadParent; 2607 appStmt[7] = &pRtree->pWriteParent; 2608 appStmt[8] = &pRtree->pDeleteParent; 2609 2610 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){ 2611 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix); 2612 if( zSql ){ 2613 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 2614 }else{ 2615 rc = SQLITE_NOMEM; 2616 } 2617 sqlite3_free(zSql); 2618 } 2619 2620 return rc; 2621 } 2622 2623 /* 2624 ** The second argument to this function contains the text of an SQL statement 2625 ** that returns a single integer value. The statement is compiled and executed 2626 ** using database connection db. If successful, the integer value returned 2627 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error 2628 ** code is returned and the value of *piVal after returning is not defined. 2629 */ 2630 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ 2631 int rc = SQLITE_NOMEM; 2632 if( zSql ){ 2633 sqlite3_stmt *pStmt = 0; 2634 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 2635 if( rc==SQLITE_OK ){ 2636 if( SQLITE_ROW==sqlite3_step(pStmt) ){ 2637 *piVal = sqlite3_column_int(pStmt, 0); 2638 } 2639 rc = sqlite3_finalize(pStmt); 2640 } 2641 } 2642 return rc; 2643 } 2644 2645 /* 2646 ** This function is called from within the xConnect() or xCreate() method to 2647 ** determine the node-size used by the rtree table being created or connected 2648 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned. 2649 ** Otherwise, an SQLite error code is returned. 2650 ** 2651 ** If this function is being called as part of an xConnect(), then the rtree 2652 ** table already exists. In this case the node-size is determined by inspecting 2653 ** the root node of the tree. 2654 ** 2655 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 2656 ** This ensures that each node is stored on a single database page. If the 2657 ** database page-size is so large that more than RTREE_MAXCELLS entries 2658 ** would fit in a single node, use a smaller node-size. 2659 */ 2660 static int getNodeSize( 2661 sqlite3 *db, /* Database handle */ 2662 Rtree *pRtree, /* Rtree handle */ 2663 int isCreate /* True for xCreate, false for xConnect */ 2664 ){ 2665 int rc; 2666 char *zSql; 2667 if( isCreate ){ 2668 int iPageSize; 2669 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); 2670 rc = getIntFromStmt(db, zSql, &iPageSize); 2671 if( rc==SQLITE_OK ){ 2672 pRtree->iNodeSize = iPageSize-64; 2673 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){ 2674 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; 2675 } 2676 } 2677 }else{ 2678 zSql = sqlite3_mprintf( 2679 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", 2680 pRtree->zDb, pRtree->zName 2681 ); 2682 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); 2683 } 2684 2685 sqlite3_free(zSql); 2686 return rc; 2687 } 2688 2689 /* 2690 ** This function is the implementation of both the xConnect and xCreate 2691 ** methods of the r-tree virtual table. 2692 ** 2693 ** argv[0] -> module name 2694 ** argv[1] -> database name 2695 ** argv[2] -> table name 2696 ** argv[...] -> column names... 2697 */ 2698 static int rtreeInit( 2699 sqlite3 *db, /* Database connection */ 2700 void *pAux, /* One of the RTREE_COORD_* constants */ 2701 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ 2702 sqlite3_vtab **ppVtab, /* OUT: New virtual table */ 2703 char **pzErr, /* OUT: Error message, if any */ 2704 int isCreate /* True for xCreate, false for xConnect */ 2705 ){ 2706 int rc = SQLITE_OK; 2707 Rtree *pRtree; 2708 int nDb; /* Length of string argv[1] */ 2709 int nName; /* Length of string argv[2] */ 2710 int eCoordType = (int)pAux; 2711 2712 const char *aErrMsg[] = { 2713 0, /* 0 */ 2714 "Wrong number of columns for an rtree table", /* 1 */ 2715 "Too few columns for an rtree table", /* 2 */ 2716 "Too many columns for an rtree table" /* 3 */ 2717 }; 2718 2719 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; 2720 if( aErrMsg[iErr] ){ 2721 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); 2722 return SQLITE_ERROR; 2723 } 2724 2725 /* Allocate the sqlite3_vtab structure */ 2726 nDb = strlen(argv[1]); 2727 nName = strlen(argv[2]); 2728 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); 2729 if( !pRtree ){ 2730 return SQLITE_NOMEM; 2731 } 2732 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); 2733 pRtree->nBusy = 1; 2734 pRtree->base.pModule = &rtreeModule; 2735 pRtree->zDb = (char *)&pRtree[1]; 2736 pRtree->zName = &pRtree->zDb[nDb+1]; 2737 pRtree->nDim = (argc-4)/2; 2738 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; 2739 pRtree->eCoordType = eCoordType; 2740 memcpy(pRtree->zDb, argv[1], nDb); 2741 memcpy(pRtree->zName, argv[2], nName); 2742 2743 /* Figure out the node size to use. */ 2744 rc = getNodeSize(db, pRtree, isCreate); 2745 2746 /* Create/Connect to the underlying relational database schema. If 2747 ** that is successful, call sqlite3_declare_vtab() to configure 2748 ** the r-tree table schema. 2749 */ 2750 if( rc==SQLITE_OK ){ 2751 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ 2752 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 2753 }else{ 2754 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); 2755 char *zTmp; 2756 int ii; 2757 for(ii=4; zSql && ii<argc; ii++){ 2758 zTmp = zSql; 2759 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]); 2760 sqlite3_free(zTmp); 2761 } 2762 if( zSql ){ 2763 zTmp = zSql; 2764 zSql = sqlite3_mprintf("%s);", zTmp); 2765 sqlite3_free(zTmp); 2766 } 2767 if( !zSql ){ 2768 rc = SQLITE_NOMEM; 2769 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ 2770 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 2771 } 2772 sqlite3_free(zSql); 2773 } 2774 } 2775 2776 if( rc==SQLITE_OK ){ 2777 *ppVtab = (sqlite3_vtab *)pRtree; 2778 }else{ 2779 rtreeRelease(pRtree); 2780 } 2781 return rc; 2782 } 2783 2784 2785 /* 2786 ** Implementation of a scalar function that decodes r-tree nodes to 2787 ** human readable strings. This can be used for debugging and analysis. 2788 ** 2789 ** The scalar function takes two arguments, a blob of data containing 2790 ** an r-tree node, and the number of dimensions the r-tree indexes. 2791 ** For a two-dimensional r-tree structure called "rt", to deserialize 2792 ** all nodes, a statement like: 2793 ** 2794 ** SELECT rtreenode(2, data) FROM rt_node; 2795 ** 2796 ** The human readable string takes the form of a Tcl list with one 2797 ** entry for each cell in the r-tree node. Each entry is itself a 2798 ** list, containing the 8-byte rowid/pageno followed by the 2799 ** <num-dimension>*2 coordinates. 2800 */ 2801 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ 2802 char *zText = 0; 2803 RtreeNode node; 2804 Rtree tree; 2805 int ii; 2806 2807 memset(&node, 0, sizeof(RtreeNode)); 2808 memset(&tree, 0, sizeof(Rtree)); 2809 tree.nDim = sqlite3_value_int(apArg[0]); 2810 tree.nBytesPerCell = 8 + 8 * tree.nDim; 2811 node.zData = (u8 *)sqlite3_value_blob(apArg[1]); 2812 2813 for(ii=0; ii<NCELL(&node); ii++){ 2814 char zCell[512]; 2815 int nCell = 0; 2816 RtreeCell cell; 2817 int jj; 2818 2819 nodeGetCell(&tree, &node, ii, &cell); 2820 sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid); 2821 nCell = strlen(zCell); 2822 for(jj=0; jj<tree.nDim*2; jj++){ 2823 sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f); 2824 nCell = strlen(zCell); 2825 } 2826 2827 if( zText ){ 2828 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell); 2829 sqlite3_free(zText); 2830 zText = zTextNew; 2831 }else{ 2832 zText = sqlite3_mprintf("{%s}", zCell); 2833 } 2834 } 2835 2836 sqlite3_result_text(ctx, zText, -1, sqlite3_free); 2837 } 2838 2839 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ 2840 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 2841 || sqlite3_value_bytes(apArg[0])<2 2842 ){ 2843 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 2844 }else{ 2845 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]); 2846 sqlite3_result_int(ctx, readInt16(zBlob)); 2847 } 2848 } 2849 2850 /* 2851 ** Register the r-tree module with database handle db. This creates the 2852 ** virtual table module "rtree" and the debugging/analysis scalar 2853 ** function "rtreenode". 2854 */ 2855 int sqlite3RtreeInit(sqlite3 *db){ 2856 int rc = SQLITE_OK; 2857 2858 if( rc==SQLITE_OK ){ 2859 int utf8 = SQLITE_UTF8; 2860 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0); 2861 } 2862 if( rc==SQLITE_OK ){ 2863 int utf8 = SQLITE_UTF8; 2864 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0); 2865 } 2866 if( rc==SQLITE_OK ){ 2867 void *c = (void *)RTREE_COORD_REAL32; 2868 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0); 2869 } 2870 if( rc==SQLITE_OK ){ 2871 void *c = (void *)RTREE_COORD_INT32; 2872 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0); 2873 } 2874 2875 return rc; 2876 } 2877 2878 #if !SQLITE_CORE 2879 int sqlite3_extension_init( 2880 sqlite3 *db, 2881 char **pzErrMsg, 2882 const sqlite3_api_routines *pApi 2883 ){ 2884 SQLITE_EXTENSION_INIT2(pApi) 2885 return sqlite3RtreeInit(db); 2886 } 2887 #endif 2888 2889 #endif 2890