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