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. If the r-tree contains auxiliary columns, those are stored 35 ** on the end of the %_rowid table. 36 ** 37 ** The root node of an r-tree always exists, even if the r-tree table is 38 ** empty. The nodeno of the root node is always 1. All other nodes in the 39 ** table must be the same size as the root node. The content of each node 40 ** is formatted as follows: 41 ** 42 ** 1. If the node is the root node (node 1), then the first 2 bytes 43 ** of the node contain the tree depth as a big-endian integer. 44 ** For non-root nodes, the first 2 bytes are left unused. 45 ** 46 ** 2. The next 2 bytes contain the number of entries currently 47 ** stored in the node. 48 ** 49 ** 3. The remainder of the node contains the node entries. Each entry 50 ** consists of a single 8-byte integer followed by an even number 51 ** of 4-byte coordinates. For leaf nodes the integer is the rowid 52 ** of a record. For internal nodes it is the node number of a 53 ** child page. 54 */ 55 56 #if !defined(SQLITE_CORE) \ 57 || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE)) 58 59 #ifndef SQLITE_CORE 60 #include "sqlite3ext.h" 61 SQLITE_EXTENSION_INIT1 62 #else 63 #include "sqlite3.h" 64 #endif 65 int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */ 66 67 #ifndef SQLITE_AMALGAMATION 68 #include "sqlite3rtree.h" 69 typedef sqlite3_int64 i64; 70 typedef sqlite3_uint64 u64; 71 typedef unsigned char u8; 72 typedef unsigned short u16; 73 typedef unsigned int u32; 74 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 75 # define NDEBUG 1 76 #endif 77 #if defined(NDEBUG) && defined(SQLITE_DEBUG) 78 # undef NDEBUG 79 #endif 80 #endif 81 82 #include <string.h> 83 #include <stdio.h> 84 #include <assert.h> 85 #include <stdlib.h> 86 87 /* The following macro is used to suppress compiler warnings. 88 */ 89 #ifndef UNUSED_PARAMETER 90 # define UNUSED_PARAMETER(x) (void)(x) 91 #endif 92 93 typedef struct Rtree Rtree; 94 typedef struct RtreeCursor RtreeCursor; 95 typedef struct RtreeNode RtreeNode; 96 typedef struct RtreeCell RtreeCell; 97 typedef struct RtreeConstraint RtreeConstraint; 98 typedef struct RtreeMatchArg RtreeMatchArg; 99 typedef struct RtreeGeomCallback RtreeGeomCallback; 100 typedef union RtreeCoord RtreeCoord; 101 typedef struct RtreeSearchPoint RtreeSearchPoint; 102 103 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ 104 #define RTREE_MAX_DIMENSIONS 5 105 106 /* Maximum number of auxiliary columns */ 107 #define RTREE_MAX_AUX_COLUMN 100 108 109 /* Size of hash table Rtree.aHash. This hash table is not expected to 110 ** ever contain very many entries, so a fixed number of buckets is 111 ** used. 112 */ 113 #define HASHSIZE 97 114 115 /* The xBestIndex method of this virtual table requires an estimate of 116 ** the number of rows in the virtual table to calculate the costs of 117 ** various strategies. If possible, this estimate is loaded from the 118 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum). 119 ** Otherwise, if no sqlite_stat1 entry is available, use 120 ** RTREE_DEFAULT_ROWEST. 121 */ 122 #define RTREE_DEFAULT_ROWEST 1048576 123 #define RTREE_MIN_ROWEST 100 124 125 /* 126 ** An rtree virtual-table object. 127 */ 128 struct Rtree { 129 sqlite3_vtab base; /* Base class. Must be first */ 130 sqlite3 *db; /* Host database connection */ 131 int iNodeSize; /* Size in bytes of each node in the node table */ 132 u8 nDim; /* Number of dimensions */ 133 u8 nDim2; /* Twice the number of dimensions */ 134 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */ 135 u8 nBytesPerCell; /* Bytes consumed per cell */ 136 u8 inWrTrans; /* True if inside write transaction */ 137 u8 nAux; /* # of auxiliary columns in %_rowid */ 138 u8 nAuxNotNull; /* Number of initial not-null aux columns */ 139 #ifdef SQLITE_DEBUG 140 u8 bCorrupt; /* Shadow table corruption detected */ 141 #endif 142 int iDepth; /* Current depth of the r-tree structure */ 143 char *zDb; /* Name of database containing r-tree table */ 144 char *zName; /* Name of r-tree table */ 145 u32 nBusy; /* Current number of users of this structure */ 146 i64 nRowEst; /* Estimated number of rows in this table */ 147 u32 nCursor; /* Number of open cursors */ 148 u32 nNodeRef; /* Number RtreeNodes with positive nRef */ 149 char *zReadAuxSql; /* SQL for statement to read aux data */ 150 151 /* List of nodes removed during a CondenseTree operation. List is 152 ** linked together via the pointer normally used for hash chains - 153 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 154 ** headed by the node (leaf nodes have RtreeNode.iNode==0). 155 */ 156 RtreeNode *pDeleted; 157 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ 158 159 /* Blob I/O on xxx_node */ 160 sqlite3_blob *pNodeBlob; 161 162 /* Statements to read/write/delete a record from xxx_node */ 163 sqlite3_stmt *pWriteNode; 164 sqlite3_stmt *pDeleteNode; 165 166 /* Statements to read/write/delete a record from xxx_rowid */ 167 sqlite3_stmt *pReadRowid; 168 sqlite3_stmt *pWriteRowid; 169 sqlite3_stmt *pDeleteRowid; 170 171 /* Statements to read/write/delete a record from xxx_parent */ 172 sqlite3_stmt *pReadParent; 173 sqlite3_stmt *pWriteParent; 174 sqlite3_stmt *pDeleteParent; 175 176 /* Statement for writing to the "aux:" fields, if there are any */ 177 sqlite3_stmt *pWriteAux; 178 179 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 180 }; 181 182 /* Possible values for Rtree.eCoordType: */ 183 #define RTREE_COORD_REAL32 0 184 #define RTREE_COORD_INT32 1 185 186 /* 187 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will 188 ** only deal with integer coordinates. No floating point operations 189 ** will be done. 190 */ 191 #ifdef SQLITE_RTREE_INT_ONLY 192 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */ 193 typedef int RtreeValue; /* Low accuracy coordinate */ 194 # define RTREE_ZERO 0 195 #else 196 typedef double RtreeDValue; /* High accuracy coordinate */ 197 typedef float RtreeValue; /* Low accuracy coordinate */ 198 # define RTREE_ZERO 0.0 199 #endif 200 201 /* 202 ** Set the Rtree.bCorrupt flag 203 */ 204 #ifdef SQLITE_DEBUG 205 # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1) 206 #else 207 # define RTREE_IS_CORRUPT(X) 208 #endif 209 210 /* 211 ** When doing a search of an r-tree, instances of the following structure 212 ** record intermediate results from the tree walk. 213 ** 214 ** The id is always a node-id. For iLevel>=1 the id is the node-id of 215 ** the node that the RtreeSearchPoint represents. When iLevel==0, however, 216 ** the id is of the parent node and the cell that RtreeSearchPoint 217 ** represents is the iCell-th entry in the parent node. 218 */ 219 struct RtreeSearchPoint { 220 RtreeDValue rScore; /* The score for this node. Smallest goes first. */ 221 sqlite3_int64 id; /* Node ID */ 222 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */ 223 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */ 224 u8 iCell; /* Cell index within the node */ 225 }; 226 227 /* 228 ** The minimum number of cells allowed for a node is a third of the 229 ** maximum. In Gutman's notation: 230 ** 231 ** m = M/3 232 ** 233 ** If an R*-tree "Reinsert" operation is required, the same number of 234 ** cells are removed from the overfull node and reinserted into the tree. 235 */ 236 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) 237 #define RTREE_REINSERT(p) RTREE_MINCELLS(p) 238 #define RTREE_MAXCELLS 51 239 240 /* 241 ** The smallest possible node-size is (512-64)==448 bytes. And the largest 242 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates). 243 ** Therefore all non-root nodes must contain at least 3 entries. Since 244 ** 3^40 is greater than 2^64, an r-tree structure always has a depth of 245 ** 40 or less. 246 */ 247 #define RTREE_MAX_DEPTH 40 248 249 250 /* 251 ** Number of entries in the cursor RtreeNode cache. The first entry is 252 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining 253 ** entries cache the RtreeNode for the first elements of the priority queue. 254 */ 255 #define RTREE_CACHE_SZ 5 256 257 /* 258 ** An rtree cursor object. 259 */ 260 struct RtreeCursor { 261 sqlite3_vtab_cursor base; /* Base class. Must be first */ 262 u8 atEOF; /* True if at end of search */ 263 u8 bPoint; /* True if sPoint is valid */ 264 u8 bAuxValid; /* True if pReadAux is valid */ 265 int iStrategy; /* Copy of idxNum search parameter */ 266 int nConstraint; /* Number of entries in aConstraint */ 267 RtreeConstraint *aConstraint; /* Search constraints. */ 268 int nPointAlloc; /* Number of slots allocated for aPoint[] */ 269 int nPoint; /* Number of slots used in aPoint[] */ 270 int mxLevel; /* iLevel value for root of the tree */ 271 RtreeSearchPoint *aPoint; /* Priority queue for search points */ 272 sqlite3_stmt *pReadAux; /* Statement to read aux-data */ 273 RtreeSearchPoint sPoint; /* Cached next search point */ 274 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */ 275 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */ 276 }; 277 278 /* Return the Rtree of a RtreeCursor */ 279 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab)) 280 281 /* 282 ** A coordinate can be either a floating point number or a integer. All 283 ** coordinates within a single R-Tree are always of the same time. 284 */ 285 union RtreeCoord { 286 RtreeValue f; /* Floating point value */ 287 int i; /* Integer value */ 288 u32 u; /* Unsigned for byte-order conversions */ 289 }; 290 291 /* 292 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord 293 ** formatted as a RtreeDValue (double or int64). This macro assumes that local 294 ** variable pRtree points to the Rtree structure associated with the 295 ** RtreeCoord. 296 */ 297 #ifdef SQLITE_RTREE_INT_ONLY 298 # define DCOORD(coord) ((RtreeDValue)coord.i) 299 #else 300 # define DCOORD(coord) ( \ 301 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ 302 ((double)coord.f) : \ 303 ((double)coord.i) \ 304 ) 305 #endif 306 307 /* 308 ** A search constraint. 309 */ 310 struct RtreeConstraint { 311 int iCoord; /* Index of constrained coordinate */ 312 int op; /* Constraining operation */ 313 union { 314 RtreeDValue rValue; /* Constraint value. */ 315 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*); 316 int (*xQueryFunc)(sqlite3_rtree_query_info*); 317 } u; 318 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */ 319 }; 320 321 /* Possible values for RtreeConstraint.op */ 322 #define RTREE_EQ 0x41 /* A */ 323 #define RTREE_LE 0x42 /* B */ 324 #define RTREE_LT 0x43 /* C */ 325 #define RTREE_GE 0x44 /* D */ 326 #define RTREE_GT 0x45 /* E */ 327 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */ 328 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */ 329 330 /* Special operators available only on cursors. Needs to be consecutive 331 ** with the normal values above, but must be less than RTREE_MATCH. These 332 ** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or 333 ** x<'xyz' (RTREE_TRUE) */ 334 #define RTREE_TRUE 0x3f /* ? */ 335 #define RTREE_FALSE 0x40 /* @ */ 336 337 /* 338 ** An rtree structure node. 339 */ 340 struct RtreeNode { 341 RtreeNode *pParent; /* Parent node */ 342 i64 iNode; /* The node number */ 343 int nRef; /* Number of references to this node */ 344 int isDirty; /* True if the node needs to be written to disk */ 345 u8 *zData; /* Content of the node, as should be on disk */ 346 RtreeNode *pNext; /* Next node in this hash collision chain */ 347 }; 348 349 /* Return the number of cells in a node */ 350 #define NCELL(pNode) readInt16(&(pNode)->zData[2]) 351 352 /* 353 ** A single cell from a node, deserialized 354 */ 355 struct RtreeCell { 356 i64 iRowid; /* Node or entry ID */ 357 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */ 358 }; 359 360 361 /* 362 ** This object becomes the sqlite3_user_data() for the SQL functions 363 ** that are created by sqlite3_rtree_geometry_callback() and 364 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH 365 ** operators in order to constrain a search. 366 ** 367 ** xGeom and xQueryFunc are the callback functions. Exactly one of 368 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the 369 ** SQL function was created using sqlite3_rtree_geometry_callback() or 370 ** sqlite3_rtree_query_callback(). 371 ** 372 ** This object is deleted automatically by the destructor mechanism in 373 ** sqlite3_create_function_v2(). 374 */ 375 struct RtreeGeomCallback { 376 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*); 377 int (*xQueryFunc)(sqlite3_rtree_query_info*); 378 void (*xDestructor)(void*); 379 void *pContext; 380 }; 381 382 /* 383 ** An instance of this structure (in the form of a BLOB) is returned by 384 ** the SQL functions that sqlite3_rtree_geometry_callback() and 385 ** sqlite3_rtree_query_callback() create, and is read as the right-hand 386 ** operand to the MATCH operator of an R-Tree. 387 */ 388 struct RtreeMatchArg { 389 u32 iSize; /* Size of this object */ 390 RtreeGeomCallback cb; /* Info about the callback functions */ 391 int nParam; /* Number of parameters to the SQL function */ 392 sqlite3_value **apSqlParam; /* Original SQL parameter values */ 393 RtreeDValue aParam[1]; /* Values for parameters to the SQL function */ 394 }; 395 396 #ifndef MAX 397 # define MAX(x,y) ((x) < (y) ? (y) : (x)) 398 #endif 399 #ifndef MIN 400 # define MIN(x,y) ((x) > (y) ? (y) : (x)) 401 #endif 402 403 /* What version of GCC is being used. 0 means GCC is not being used . 404 ** Note that the GCC_VERSION macro will also be set correctly when using 405 ** clang, since clang works hard to be gcc compatible. So the gcc 406 ** optimizations will also work when compiling with clang. 407 */ 408 #ifndef GCC_VERSION 409 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) 410 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) 411 #else 412 # define GCC_VERSION 0 413 #endif 414 #endif 415 416 /* The testcase() macro should already be defined in the amalgamation. If 417 ** it is not, make it a no-op. 418 */ 419 #ifndef SQLITE_AMALGAMATION 420 # define testcase(X) 421 #endif 422 423 /* 424 ** Make sure that the compiler intrinsics we desire are enabled when 425 ** compiling with an appropriate version of MSVC unless prevented by 426 ** the SQLITE_DISABLE_INTRINSIC define. 427 */ 428 #if !defined(SQLITE_DISABLE_INTRINSIC) 429 # if defined(_MSC_VER) && _MSC_VER>=1400 430 # if !defined(_WIN32_WCE) 431 # include <intrin.h> 432 # pragma intrinsic(_byteswap_ulong) 433 # pragma intrinsic(_byteswap_uint64) 434 # else 435 # include <cmnintrin.h> 436 # endif 437 # endif 438 #endif 439 440 /* 441 ** Macros to determine whether the machine is big or little endian, 442 ** and whether or not that determination is run-time or compile-time. 443 ** 444 ** For best performance, an attempt is made to guess at the byte-order 445 ** using C-preprocessor macros. If that is unsuccessful, or if 446 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined 447 ** at run-time. 448 */ 449 #ifndef SQLITE_BYTEORDER 450 #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \ 451 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \ 452 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \ 453 defined(__arm__) 454 # define SQLITE_BYTEORDER 1234 455 #elif defined(sparc) || defined(__ppc__) 456 # define SQLITE_BYTEORDER 4321 457 #else 458 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */ 459 #endif 460 #endif 461 462 463 /* What version of MSVC is being used. 0 means MSVC is not being used */ 464 #ifndef MSVC_VERSION 465 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) 466 # define MSVC_VERSION _MSC_VER 467 #else 468 # define MSVC_VERSION 0 469 #endif 470 #endif 471 472 /* 473 ** Functions to deserialize a 16 bit integer, 32 bit real number and 474 ** 64 bit integer. The deserialized value is returned. 475 */ 476 static int readInt16(u8 *p){ 477 return (p[0]<<8) + p[1]; 478 } 479 static void readCoord(u8 *p, RtreeCoord *pCoord){ 480 assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ 481 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 482 pCoord->u = _byteswap_ulong(*(u32*)p); 483 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 484 pCoord->u = __builtin_bswap32(*(u32*)p); 485 #elif SQLITE_BYTEORDER==4321 486 pCoord->u = *(u32*)p; 487 #else 488 pCoord->u = ( 489 (((u32)p[0]) << 24) + 490 (((u32)p[1]) << 16) + 491 (((u32)p[2]) << 8) + 492 (((u32)p[3]) << 0) 493 ); 494 #endif 495 } 496 static i64 readInt64(u8 *p){ 497 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 498 u64 x; 499 memcpy(&x, p, 8); 500 return (i64)_byteswap_uint64(x); 501 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 502 u64 x; 503 memcpy(&x, p, 8); 504 return (i64)__builtin_bswap64(x); 505 #elif SQLITE_BYTEORDER==4321 506 i64 x; 507 memcpy(&x, p, 8); 508 return x; 509 #else 510 return (i64)( 511 (((u64)p[0]) << 56) + 512 (((u64)p[1]) << 48) + 513 (((u64)p[2]) << 40) + 514 (((u64)p[3]) << 32) + 515 (((u64)p[4]) << 24) + 516 (((u64)p[5]) << 16) + 517 (((u64)p[6]) << 8) + 518 (((u64)p[7]) << 0) 519 ); 520 #endif 521 } 522 523 /* 524 ** Functions to serialize a 16 bit integer, 32 bit real number and 525 ** 64 bit integer. The value returned is the number of bytes written 526 ** to the argument buffer (always 2, 4 and 8 respectively). 527 */ 528 static void writeInt16(u8 *p, int i){ 529 p[0] = (i>> 8)&0xFF; 530 p[1] = (i>> 0)&0xFF; 531 } 532 static int writeCoord(u8 *p, RtreeCoord *pCoord){ 533 u32 i; 534 assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */ 535 assert( sizeof(RtreeCoord)==4 ); 536 assert( sizeof(u32)==4 ); 537 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 538 i = __builtin_bswap32(pCoord->u); 539 memcpy(p, &i, 4); 540 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 541 i = _byteswap_ulong(pCoord->u); 542 memcpy(p, &i, 4); 543 #elif SQLITE_BYTEORDER==4321 544 i = pCoord->u; 545 memcpy(p, &i, 4); 546 #else 547 i = pCoord->u; 548 p[0] = (i>>24)&0xFF; 549 p[1] = (i>>16)&0xFF; 550 p[2] = (i>> 8)&0xFF; 551 p[3] = (i>> 0)&0xFF; 552 #endif 553 return 4; 554 } 555 static int writeInt64(u8 *p, i64 i){ 556 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 557 i = (i64)__builtin_bswap64((u64)i); 558 memcpy(p, &i, 8); 559 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 560 i = (i64)_byteswap_uint64((u64)i); 561 memcpy(p, &i, 8); 562 #elif SQLITE_BYTEORDER==4321 563 memcpy(p, &i, 8); 564 #else 565 p[0] = (i>>56)&0xFF; 566 p[1] = (i>>48)&0xFF; 567 p[2] = (i>>40)&0xFF; 568 p[3] = (i>>32)&0xFF; 569 p[4] = (i>>24)&0xFF; 570 p[5] = (i>>16)&0xFF; 571 p[6] = (i>> 8)&0xFF; 572 p[7] = (i>> 0)&0xFF; 573 #endif 574 return 8; 575 } 576 577 /* 578 ** Increment the reference count of node p. 579 */ 580 static void nodeReference(RtreeNode *p){ 581 if( p ){ 582 assert( p->nRef>0 ); 583 p->nRef++; 584 } 585 } 586 587 /* 588 ** Clear the content of node p (set all bytes to 0x00). 589 */ 590 static void nodeZero(Rtree *pRtree, RtreeNode *p){ 591 memset(&p->zData[2], 0, pRtree->iNodeSize-2); 592 p->isDirty = 1; 593 } 594 595 /* 596 ** Given a node number iNode, return the corresponding key to use 597 ** in the Rtree.aHash table. 598 */ 599 static unsigned int nodeHash(i64 iNode){ 600 return ((unsigned)iNode) % HASHSIZE; 601 } 602 603 /* 604 ** Search the node hash table for node iNode. If found, return a pointer 605 ** to it. Otherwise, return 0. 606 */ 607 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ 608 RtreeNode *p; 609 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); 610 return p; 611 } 612 613 /* 614 ** Add node pNode to the node hash table. 615 */ 616 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ 617 int iHash; 618 assert( pNode->pNext==0 ); 619 iHash = nodeHash(pNode->iNode); 620 pNode->pNext = pRtree->aHash[iHash]; 621 pRtree->aHash[iHash] = pNode; 622 } 623 624 /* 625 ** Remove node pNode from the node hash table. 626 */ 627 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ 628 RtreeNode **pp; 629 if( pNode->iNode!=0 ){ 630 pp = &pRtree->aHash[nodeHash(pNode->iNode)]; 631 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } 632 *pp = pNode->pNext; 633 pNode->pNext = 0; 634 } 635 } 636 637 /* 638 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), 639 ** indicating that node has not yet been assigned a node number. It is 640 ** assigned a node number when nodeWrite() is called to write the 641 ** node contents out to the database. 642 */ 643 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){ 644 RtreeNode *pNode; 645 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize); 646 if( pNode ){ 647 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); 648 pNode->zData = (u8 *)&pNode[1]; 649 pNode->nRef = 1; 650 pRtree->nNodeRef++; 651 pNode->pParent = pParent; 652 pNode->isDirty = 1; 653 nodeReference(pParent); 654 } 655 return pNode; 656 } 657 658 /* 659 ** Clear the Rtree.pNodeBlob object 660 */ 661 static void nodeBlobReset(Rtree *pRtree){ 662 if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){ 663 sqlite3_blob *pBlob = pRtree->pNodeBlob; 664 pRtree->pNodeBlob = 0; 665 sqlite3_blob_close(pBlob); 666 } 667 } 668 669 /* 670 ** Check to see if pNode is the same as pParent or any of the parents 671 ** of pParent. 672 */ 673 static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){ 674 do{ 675 if( pNode==pParent ) return 1; 676 pParent = pParent->pParent; 677 }while( pParent ); 678 return 0; 679 } 680 681 /* 682 ** Obtain a reference to an r-tree node. 683 */ 684 static int nodeAcquire( 685 Rtree *pRtree, /* R-tree structure */ 686 i64 iNode, /* Node number to load */ 687 RtreeNode *pParent, /* Either the parent node or NULL */ 688 RtreeNode **ppNode /* OUT: Acquired node */ 689 ){ 690 int rc = SQLITE_OK; 691 RtreeNode *pNode = 0; 692 693 /* Check if the requested node is already in the hash table. If so, 694 ** increase its reference count and return it. 695 */ 696 if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){ 697 if( pParent && !pNode->pParent ){ 698 if( nodeInParentChain(pNode, pParent) ){ 699 RTREE_IS_CORRUPT(pRtree); 700 return SQLITE_CORRUPT_VTAB; 701 } 702 pParent->nRef++; 703 pNode->pParent = pParent; 704 }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){ 705 RTREE_IS_CORRUPT(pRtree); 706 return SQLITE_CORRUPT_VTAB; 707 } 708 pNode->nRef++; 709 *ppNode = pNode; 710 return SQLITE_OK; 711 } 712 713 if( pRtree->pNodeBlob ){ 714 sqlite3_blob *pBlob = pRtree->pNodeBlob; 715 pRtree->pNodeBlob = 0; 716 rc = sqlite3_blob_reopen(pBlob, iNode); 717 pRtree->pNodeBlob = pBlob; 718 if( rc ){ 719 nodeBlobReset(pRtree); 720 if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM; 721 } 722 } 723 if( pRtree->pNodeBlob==0 ){ 724 char *zTab = sqlite3_mprintf("%s_node", pRtree->zName); 725 if( zTab==0 ) return SQLITE_NOMEM; 726 rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0, 727 &pRtree->pNodeBlob); 728 sqlite3_free(zTab); 729 } 730 if( rc ){ 731 nodeBlobReset(pRtree); 732 *ppNode = 0; 733 /* If unable to open an sqlite3_blob on the desired row, that can only 734 ** be because the shadow tables hold erroneous data. */ 735 if( rc==SQLITE_ERROR ){ 736 rc = SQLITE_CORRUPT_VTAB; 737 RTREE_IS_CORRUPT(pRtree); 738 } 739 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){ 740 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize); 741 if( !pNode ){ 742 rc = SQLITE_NOMEM; 743 }else{ 744 pNode->pParent = pParent; 745 pNode->zData = (u8 *)&pNode[1]; 746 pNode->nRef = 1; 747 pRtree->nNodeRef++; 748 pNode->iNode = iNode; 749 pNode->isDirty = 0; 750 pNode->pNext = 0; 751 rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData, 752 pRtree->iNodeSize, 0); 753 } 754 } 755 756 /* If the root node was just loaded, set pRtree->iDepth to the height 757 ** of the r-tree structure. A height of zero means all data is stored on 758 ** the root node. A height of one means the children of the root node 759 ** are the leaves, and so on. If the depth as specified on the root node 760 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt. 761 */ 762 if( pNode && rc==SQLITE_OK && iNode==1 ){ 763 pRtree->iDepth = readInt16(pNode->zData); 764 if( pRtree->iDepth>RTREE_MAX_DEPTH ){ 765 rc = SQLITE_CORRUPT_VTAB; 766 RTREE_IS_CORRUPT(pRtree); 767 } 768 } 769 770 /* If no error has occurred so far, check if the "number of entries" 771 ** field on the node is too large. If so, set the return code to 772 ** SQLITE_CORRUPT_VTAB. 773 */ 774 if( pNode && rc==SQLITE_OK ){ 775 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){ 776 rc = SQLITE_CORRUPT_VTAB; 777 RTREE_IS_CORRUPT(pRtree); 778 } 779 } 780 781 if( rc==SQLITE_OK ){ 782 if( pNode!=0 ){ 783 nodeReference(pParent); 784 nodeHashInsert(pRtree, pNode); 785 }else{ 786 rc = SQLITE_CORRUPT_VTAB; 787 RTREE_IS_CORRUPT(pRtree); 788 } 789 *ppNode = pNode; 790 }else{ 791 if( pNode ){ 792 pRtree->nNodeRef--; 793 sqlite3_free(pNode); 794 } 795 *ppNode = 0; 796 } 797 798 return rc; 799 } 800 801 /* 802 ** Overwrite cell iCell of node pNode with the contents of pCell. 803 */ 804 static void nodeOverwriteCell( 805 Rtree *pRtree, /* The overall R-Tree */ 806 RtreeNode *pNode, /* The node into which the cell is to be written */ 807 RtreeCell *pCell, /* The cell to write */ 808 int iCell /* Index into pNode into which pCell is written */ 809 ){ 810 int ii; 811 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; 812 p += writeInt64(p, pCell->iRowid); 813 for(ii=0; ii<pRtree->nDim2; ii++){ 814 p += writeCoord(p, &pCell->aCoord[ii]); 815 } 816 pNode->isDirty = 1; 817 } 818 819 /* 820 ** Remove the cell with index iCell from node pNode. 821 */ 822 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ 823 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; 824 u8 *pSrc = &pDst[pRtree->nBytesPerCell]; 825 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; 826 memmove(pDst, pSrc, nByte); 827 writeInt16(&pNode->zData[2], NCELL(pNode)-1); 828 pNode->isDirty = 1; 829 } 830 831 /* 832 ** Insert the contents of cell pCell into node pNode. If the insert 833 ** is successful, return SQLITE_OK. 834 ** 835 ** If there is not enough free space in pNode, return SQLITE_FULL. 836 */ 837 static int nodeInsertCell( 838 Rtree *pRtree, /* The overall R-Tree */ 839 RtreeNode *pNode, /* Write new cell into this node */ 840 RtreeCell *pCell /* The cell to be inserted */ 841 ){ 842 int nCell; /* Current number of cells in pNode */ 843 int nMaxCell; /* Maximum number of cells for pNode */ 844 845 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; 846 nCell = NCELL(pNode); 847 848 assert( nCell<=nMaxCell ); 849 if( nCell<nMaxCell ){ 850 nodeOverwriteCell(pRtree, pNode, pCell, nCell); 851 writeInt16(&pNode->zData[2], nCell+1); 852 pNode->isDirty = 1; 853 } 854 855 return (nCell==nMaxCell); 856 } 857 858 /* 859 ** If the node is dirty, write it out to the database. 860 */ 861 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){ 862 int rc = SQLITE_OK; 863 if( pNode->isDirty ){ 864 sqlite3_stmt *p = pRtree->pWriteNode; 865 if( pNode->iNode ){ 866 sqlite3_bind_int64(p, 1, pNode->iNode); 867 }else{ 868 sqlite3_bind_null(p, 1); 869 } 870 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); 871 sqlite3_step(p); 872 pNode->isDirty = 0; 873 rc = sqlite3_reset(p); 874 sqlite3_bind_null(p, 2); 875 if( pNode->iNode==0 && rc==SQLITE_OK ){ 876 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); 877 nodeHashInsert(pRtree, pNode); 878 } 879 } 880 return rc; 881 } 882 883 /* 884 ** Release a reference to a node. If the node is dirty and the reference 885 ** count drops to zero, the node data is written to the database. 886 */ 887 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){ 888 int rc = SQLITE_OK; 889 if( pNode ){ 890 assert( pNode->nRef>0 ); 891 assert( pRtree->nNodeRef>0 ); 892 pNode->nRef--; 893 if( pNode->nRef==0 ){ 894 pRtree->nNodeRef--; 895 if( pNode->iNode==1 ){ 896 pRtree->iDepth = -1; 897 } 898 if( pNode->pParent ){ 899 rc = nodeRelease(pRtree, pNode->pParent); 900 } 901 if( rc==SQLITE_OK ){ 902 rc = nodeWrite(pRtree, pNode); 903 } 904 nodeHashDelete(pRtree, pNode); 905 sqlite3_free(pNode); 906 } 907 } 908 return rc; 909 } 910 911 /* 912 ** Return the 64-bit integer value associated with cell iCell of 913 ** node pNode. If pNode is a leaf node, this is a rowid. If it is 914 ** an internal node, then the 64-bit integer is a child page number. 915 */ 916 static i64 nodeGetRowid( 917 Rtree *pRtree, /* The overall R-Tree */ 918 RtreeNode *pNode, /* The node from which to extract the ID */ 919 int iCell /* The cell index from which to extract the ID */ 920 ){ 921 assert( iCell<NCELL(pNode) ); 922 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]); 923 } 924 925 /* 926 ** Return coordinate iCoord from cell iCell in node pNode. 927 */ 928 static void nodeGetCoord( 929 Rtree *pRtree, /* The overall R-Tree */ 930 RtreeNode *pNode, /* The node from which to extract a coordinate */ 931 int iCell, /* The index of the cell within the node */ 932 int iCoord, /* Which coordinate to extract */ 933 RtreeCoord *pCoord /* OUT: Space to write result to */ 934 ){ 935 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); 936 } 937 938 /* 939 ** Deserialize cell iCell of node pNode. Populate the structure pointed 940 ** to by pCell with the results. 941 */ 942 static void nodeGetCell( 943 Rtree *pRtree, /* The overall R-Tree */ 944 RtreeNode *pNode, /* The node containing the cell to be read */ 945 int iCell, /* Index of the cell within the node */ 946 RtreeCell *pCell /* OUT: Write the cell contents here */ 947 ){ 948 u8 *pData; 949 RtreeCoord *pCoord; 950 int ii = 0; 951 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); 952 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell); 953 pCoord = pCell->aCoord; 954 do{ 955 readCoord(pData, &pCoord[ii]); 956 readCoord(pData+4, &pCoord[ii+1]); 957 pData += 8; 958 ii += 2; 959 }while( ii<pRtree->nDim2 ); 960 } 961 962 963 /* Forward declaration for the function that does the work of 964 ** the virtual table module xCreate() and xConnect() methods. 965 */ 966 static int rtreeInit( 967 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int 968 ); 969 970 /* 971 ** Rtree virtual table module xCreate method. 972 */ 973 static int rtreeCreate( 974 sqlite3 *db, 975 void *pAux, 976 int argc, const char *const*argv, 977 sqlite3_vtab **ppVtab, 978 char **pzErr 979 ){ 980 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1); 981 } 982 983 /* 984 ** Rtree virtual table module xConnect method. 985 */ 986 static int rtreeConnect( 987 sqlite3 *db, 988 void *pAux, 989 int argc, const char *const*argv, 990 sqlite3_vtab **ppVtab, 991 char **pzErr 992 ){ 993 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0); 994 } 995 996 /* 997 ** Increment the r-tree reference count. 998 */ 999 static void rtreeReference(Rtree *pRtree){ 1000 pRtree->nBusy++; 1001 } 1002 1003 /* 1004 ** Decrement the r-tree reference count. When the reference count reaches 1005 ** zero the structure is deleted. 1006 */ 1007 static void rtreeRelease(Rtree *pRtree){ 1008 pRtree->nBusy--; 1009 if( pRtree->nBusy==0 ){ 1010 pRtree->inWrTrans = 0; 1011 assert( pRtree->nCursor==0 ); 1012 nodeBlobReset(pRtree); 1013 assert( pRtree->nNodeRef==0 || pRtree->bCorrupt ); 1014 sqlite3_finalize(pRtree->pWriteNode); 1015 sqlite3_finalize(pRtree->pDeleteNode); 1016 sqlite3_finalize(pRtree->pReadRowid); 1017 sqlite3_finalize(pRtree->pWriteRowid); 1018 sqlite3_finalize(pRtree->pDeleteRowid); 1019 sqlite3_finalize(pRtree->pReadParent); 1020 sqlite3_finalize(pRtree->pWriteParent); 1021 sqlite3_finalize(pRtree->pDeleteParent); 1022 sqlite3_finalize(pRtree->pWriteAux); 1023 sqlite3_free(pRtree->zReadAuxSql); 1024 sqlite3_free(pRtree); 1025 } 1026 } 1027 1028 /* 1029 ** Rtree virtual table module xDisconnect method. 1030 */ 1031 static int rtreeDisconnect(sqlite3_vtab *pVtab){ 1032 rtreeRelease((Rtree *)pVtab); 1033 return SQLITE_OK; 1034 } 1035 1036 /* 1037 ** Rtree virtual table module xDestroy method. 1038 */ 1039 static int rtreeDestroy(sqlite3_vtab *pVtab){ 1040 Rtree *pRtree = (Rtree *)pVtab; 1041 int rc; 1042 char *zCreate = sqlite3_mprintf( 1043 "DROP TABLE '%q'.'%q_node';" 1044 "DROP TABLE '%q'.'%q_rowid';" 1045 "DROP TABLE '%q'.'%q_parent';", 1046 pRtree->zDb, pRtree->zName, 1047 pRtree->zDb, pRtree->zName, 1048 pRtree->zDb, pRtree->zName 1049 ); 1050 if( !zCreate ){ 1051 rc = SQLITE_NOMEM; 1052 }else{ 1053 nodeBlobReset(pRtree); 1054 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); 1055 sqlite3_free(zCreate); 1056 } 1057 if( rc==SQLITE_OK ){ 1058 rtreeRelease(pRtree); 1059 } 1060 1061 return rc; 1062 } 1063 1064 /* 1065 ** Rtree virtual table module xOpen method. 1066 */ 1067 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ 1068 int rc = SQLITE_NOMEM; 1069 Rtree *pRtree = (Rtree *)pVTab; 1070 RtreeCursor *pCsr; 1071 1072 pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor)); 1073 if( pCsr ){ 1074 memset(pCsr, 0, sizeof(RtreeCursor)); 1075 pCsr->base.pVtab = pVTab; 1076 rc = SQLITE_OK; 1077 pRtree->nCursor++; 1078 } 1079 *ppCursor = (sqlite3_vtab_cursor *)pCsr; 1080 1081 return rc; 1082 } 1083 1084 1085 /* 1086 ** Reset a cursor back to its initial state. 1087 */ 1088 static void resetCursor(RtreeCursor *pCsr){ 1089 Rtree *pRtree = (Rtree *)(pCsr->base.pVtab); 1090 int ii; 1091 sqlite3_stmt *pStmt; 1092 if( pCsr->aConstraint ){ 1093 int i; /* Used to iterate through constraint array */ 1094 for(i=0; i<pCsr->nConstraint; i++){ 1095 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo; 1096 if( pInfo ){ 1097 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser); 1098 sqlite3_free(pInfo); 1099 } 1100 } 1101 sqlite3_free(pCsr->aConstraint); 1102 pCsr->aConstraint = 0; 1103 } 1104 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]); 1105 sqlite3_free(pCsr->aPoint); 1106 pStmt = pCsr->pReadAux; 1107 memset(pCsr, 0, sizeof(RtreeCursor)); 1108 pCsr->base.pVtab = (sqlite3_vtab*)pRtree; 1109 pCsr->pReadAux = pStmt; 1110 1111 } 1112 1113 /* 1114 ** Rtree virtual table module xClose method. 1115 */ 1116 static int rtreeClose(sqlite3_vtab_cursor *cur){ 1117 Rtree *pRtree = (Rtree *)(cur->pVtab); 1118 RtreeCursor *pCsr = (RtreeCursor *)cur; 1119 assert( pRtree->nCursor>0 ); 1120 resetCursor(pCsr); 1121 sqlite3_finalize(pCsr->pReadAux); 1122 sqlite3_free(pCsr); 1123 pRtree->nCursor--; 1124 nodeBlobReset(pRtree); 1125 return SQLITE_OK; 1126 } 1127 1128 /* 1129 ** Rtree virtual table module xEof method. 1130 ** 1131 ** Return non-zero if the cursor does not currently point to a valid 1132 ** record (i.e if the scan has finished), or zero otherwise. 1133 */ 1134 static int rtreeEof(sqlite3_vtab_cursor *cur){ 1135 RtreeCursor *pCsr = (RtreeCursor *)cur; 1136 return pCsr->atEOF; 1137 } 1138 1139 /* 1140 ** Convert raw bits from the on-disk RTree record into a coordinate value. 1141 ** The on-disk format is big-endian and needs to be converted for little- 1142 ** endian platforms. The on-disk record stores integer coordinates if 1143 ** eInt is true and it stores 32-bit floating point records if eInt is 1144 ** false. a[] is the four bytes of the on-disk record to be decoded. 1145 ** Store the results in "r". 1146 ** 1147 ** There are five versions of this macro. The last one is generic. The 1148 ** other four are various architectures-specific optimizations. 1149 */ 1150 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 1151 #define RTREE_DECODE_COORD(eInt, a, r) { \ 1152 RtreeCoord c; /* Coordinate decoded */ \ 1153 c.u = _byteswap_ulong(*(u32*)a); \ 1154 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ 1155 } 1156 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 1157 #define RTREE_DECODE_COORD(eInt, a, r) { \ 1158 RtreeCoord c; /* Coordinate decoded */ \ 1159 c.u = __builtin_bswap32(*(u32*)a); \ 1160 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ 1161 } 1162 #elif SQLITE_BYTEORDER==1234 1163 #define RTREE_DECODE_COORD(eInt, a, r) { \ 1164 RtreeCoord c; /* Coordinate decoded */ \ 1165 memcpy(&c.u,a,4); \ 1166 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \ 1167 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \ 1168 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ 1169 } 1170 #elif SQLITE_BYTEORDER==4321 1171 #define RTREE_DECODE_COORD(eInt, a, r) { \ 1172 RtreeCoord c; /* Coordinate decoded */ \ 1173 memcpy(&c.u,a,4); \ 1174 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ 1175 } 1176 #else 1177 #define RTREE_DECODE_COORD(eInt, a, r) { \ 1178 RtreeCoord c; /* Coordinate decoded */ \ 1179 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \ 1180 +((u32)a[2]<<8) + a[3]; \ 1181 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \ 1182 } 1183 #endif 1184 1185 /* 1186 ** Check the RTree node or entry given by pCellData and p against the MATCH 1187 ** constraint pConstraint. 1188 */ 1189 static int rtreeCallbackConstraint( 1190 RtreeConstraint *pConstraint, /* The constraint to test */ 1191 int eInt, /* True if RTree holding integer coordinates */ 1192 u8 *pCellData, /* Raw cell content */ 1193 RtreeSearchPoint *pSearch, /* Container of this cell */ 1194 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */ 1195 int *peWithin /* OUT: visibility of the cell */ 1196 ){ 1197 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */ 1198 int nCoord = pInfo->nCoord; /* No. of coordinates */ 1199 int rc; /* Callback return code */ 1200 RtreeCoord c; /* Translator union */ 1201 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */ 1202 1203 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY ); 1204 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 ); 1205 1206 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){ 1207 pInfo->iRowid = readInt64(pCellData); 1208 } 1209 pCellData += 8; 1210 #ifndef SQLITE_RTREE_INT_ONLY 1211 if( eInt==0 ){ 1212 switch( nCoord ){ 1213 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f; 1214 readCoord(pCellData+32, &c); aCoord[8] = c.f; 1215 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f; 1216 readCoord(pCellData+24, &c); aCoord[6] = c.f; 1217 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f; 1218 readCoord(pCellData+16, &c); aCoord[4] = c.f; 1219 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f; 1220 readCoord(pCellData+8, &c); aCoord[2] = c.f; 1221 default: readCoord(pCellData+4, &c); aCoord[1] = c.f; 1222 readCoord(pCellData, &c); aCoord[0] = c.f; 1223 } 1224 }else 1225 #endif 1226 { 1227 switch( nCoord ){ 1228 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i; 1229 readCoord(pCellData+32, &c); aCoord[8] = c.i; 1230 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i; 1231 readCoord(pCellData+24, &c); aCoord[6] = c.i; 1232 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i; 1233 readCoord(pCellData+16, &c); aCoord[4] = c.i; 1234 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i; 1235 readCoord(pCellData+8, &c); aCoord[2] = c.i; 1236 default: readCoord(pCellData+4, &c); aCoord[1] = c.i; 1237 readCoord(pCellData, &c); aCoord[0] = c.i; 1238 } 1239 } 1240 if( pConstraint->op==RTREE_MATCH ){ 1241 int eWithin = 0; 1242 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo, 1243 nCoord, aCoord, &eWithin); 1244 if( eWithin==0 ) *peWithin = NOT_WITHIN; 1245 *prScore = RTREE_ZERO; 1246 }else{ 1247 pInfo->aCoord = aCoord; 1248 pInfo->iLevel = pSearch->iLevel - 1; 1249 pInfo->rScore = pInfo->rParentScore = pSearch->rScore; 1250 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin; 1251 rc = pConstraint->u.xQueryFunc(pInfo); 1252 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin; 1253 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){ 1254 *prScore = pInfo->rScore; 1255 } 1256 } 1257 return rc; 1258 } 1259 1260 /* 1261 ** Check the internal RTree node given by pCellData against constraint p. 1262 ** If this constraint cannot be satisfied by any child within the node, 1263 ** set *peWithin to NOT_WITHIN. 1264 */ 1265 static void rtreeNonleafConstraint( 1266 RtreeConstraint *p, /* The constraint to test */ 1267 int eInt, /* True if RTree holds integer coordinates */ 1268 u8 *pCellData, /* Raw cell content as appears on disk */ 1269 int *peWithin /* Adjust downward, as appropriate */ 1270 ){ 1271 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */ 1272 1273 /* p->iCoord might point to either a lower or upper bound coordinate 1274 ** in a coordinate pair. But make pCellData point to the lower bound. 1275 */ 1276 pCellData += 8 + 4*(p->iCoord&0xfe); 1277 1278 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 1279 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE 1280 || p->op==RTREE_FALSE ); 1281 assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ 1282 switch( p->op ){ 1283 case RTREE_TRUE: return; /* Always satisfied */ 1284 case RTREE_FALSE: break; /* Never satisfied */ 1285 case RTREE_LE: 1286 case RTREE_LT: 1287 case RTREE_EQ: 1288 RTREE_DECODE_COORD(eInt, pCellData, val); 1289 /* val now holds the lower bound of the coordinate pair */ 1290 if( p->u.rValue>=val ) return; 1291 if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */ 1292 /* Fall through for the RTREE_EQ case */ 1293 1294 default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */ 1295 pCellData += 4; 1296 RTREE_DECODE_COORD(eInt, pCellData, val); 1297 /* val now holds the upper bound of the coordinate pair */ 1298 if( p->u.rValue<=val ) return; 1299 } 1300 *peWithin = NOT_WITHIN; 1301 } 1302 1303 /* 1304 ** Check the leaf RTree cell given by pCellData against constraint p. 1305 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN. 1306 ** If the constraint is satisfied, leave *peWithin unchanged. 1307 ** 1308 ** The constraint is of the form: xN op $val 1309 ** 1310 ** The op is given by p->op. The xN is p->iCoord-th coordinate in 1311 ** pCellData. $val is given by p->u.rValue. 1312 */ 1313 static void rtreeLeafConstraint( 1314 RtreeConstraint *p, /* The constraint to test */ 1315 int eInt, /* True if RTree holds integer coordinates */ 1316 u8 *pCellData, /* Raw cell content as appears on disk */ 1317 int *peWithin /* Adjust downward, as appropriate */ 1318 ){ 1319 RtreeDValue xN; /* Coordinate value converted to a double */ 1320 1321 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 1322 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE 1323 || p->op==RTREE_FALSE ); 1324 pCellData += 8 + p->iCoord*4; 1325 assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ 1326 RTREE_DECODE_COORD(eInt, pCellData, xN); 1327 switch( p->op ){ 1328 case RTREE_TRUE: return; /* Always satisfied */ 1329 case RTREE_FALSE: break; /* Never satisfied */ 1330 case RTREE_LE: if( xN <= p->u.rValue ) return; break; 1331 case RTREE_LT: if( xN < p->u.rValue ) return; break; 1332 case RTREE_GE: if( xN >= p->u.rValue ) return; break; 1333 case RTREE_GT: if( xN > p->u.rValue ) return; break; 1334 default: if( xN == p->u.rValue ) return; break; 1335 } 1336 *peWithin = NOT_WITHIN; 1337 } 1338 1339 /* 1340 ** One of the cells in node pNode is guaranteed to have a 64-bit 1341 ** integer value equal to iRowid. Return the index of this cell. 1342 */ 1343 static int nodeRowidIndex( 1344 Rtree *pRtree, 1345 RtreeNode *pNode, 1346 i64 iRowid, 1347 int *piIndex 1348 ){ 1349 int ii; 1350 int nCell = NCELL(pNode); 1351 assert( nCell<200 ); 1352 for(ii=0; ii<nCell; ii++){ 1353 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){ 1354 *piIndex = ii; 1355 return SQLITE_OK; 1356 } 1357 } 1358 RTREE_IS_CORRUPT(pRtree); 1359 return SQLITE_CORRUPT_VTAB; 1360 } 1361 1362 /* 1363 ** Return the index of the cell containing a pointer to node pNode 1364 ** in its parent. If pNode is the root node, return -1. 1365 */ 1366 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){ 1367 RtreeNode *pParent = pNode->pParent; 1368 if( pParent ){ 1369 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex); 1370 } 1371 *piIndex = -1; 1372 return SQLITE_OK; 1373 } 1374 1375 /* 1376 ** Compare two search points. Return negative, zero, or positive if the first 1377 ** is less than, equal to, or greater than the second. 1378 ** 1379 ** The rScore is the primary key. Smaller rScore values come first. 1380 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller 1381 ** iLevel values coming first. In this way, if rScore is the same for all 1382 ** SearchPoints, then iLevel becomes the deciding factor and the result 1383 ** is a depth-first search, which is the desired default behavior. 1384 */ 1385 static int rtreeSearchPointCompare( 1386 const RtreeSearchPoint *pA, 1387 const RtreeSearchPoint *pB 1388 ){ 1389 if( pA->rScore<pB->rScore ) return -1; 1390 if( pA->rScore>pB->rScore ) return +1; 1391 if( pA->iLevel<pB->iLevel ) return -1; 1392 if( pA->iLevel>pB->iLevel ) return +1; 1393 return 0; 1394 } 1395 1396 /* 1397 ** Interchange two search points in a cursor. 1398 */ 1399 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){ 1400 RtreeSearchPoint t = p->aPoint[i]; 1401 assert( i<j ); 1402 p->aPoint[i] = p->aPoint[j]; 1403 p->aPoint[j] = t; 1404 i++; j++; 1405 if( i<RTREE_CACHE_SZ ){ 1406 if( j>=RTREE_CACHE_SZ ){ 1407 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); 1408 p->aNode[i] = 0; 1409 }else{ 1410 RtreeNode *pTemp = p->aNode[i]; 1411 p->aNode[i] = p->aNode[j]; 1412 p->aNode[j] = pTemp; 1413 } 1414 } 1415 } 1416 1417 /* 1418 ** Return the search point with the lowest current score. 1419 */ 1420 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){ 1421 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0; 1422 } 1423 1424 /* 1425 ** Get the RtreeNode for the search point with the lowest score. 1426 */ 1427 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){ 1428 sqlite3_int64 id; 1429 int ii = 1 - pCur->bPoint; 1430 assert( ii==0 || ii==1 ); 1431 assert( pCur->bPoint || pCur->nPoint ); 1432 if( pCur->aNode[ii]==0 ){ 1433 assert( pRC!=0 ); 1434 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id; 1435 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]); 1436 } 1437 return pCur->aNode[ii]; 1438 } 1439 1440 /* 1441 ** Push a new element onto the priority queue 1442 */ 1443 static RtreeSearchPoint *rtreeEnqueue( 1444 RtreeCursor *pCur, /* The cursor */ 1445 RtreeDValue rScore, /* Score for the new search point */ 1446 u8 iLevel /* Level for the new search point */ 1447 ){ 1448 int i, j; 1449 RtreeSearchPoint *pNew; 1450 if( pCur->nPoint>=pCur->nPointAlloc ){ 1451 int nNew = pCur->nPointAlloc*2 + 8; 1452 pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0])); 1453 if( pNew==0 ) return 0; 1454 pCur->aPoint = pNew; 1455 pCur->nPointAlloc = nNew; 1456 } 1457 i = pCur->nPoint++; 1458 pNew = pCur->aPoint + i; 1459 pNew->rScore = rScore; 1460 pNew->iLevel = iLevel; 1461 assert( iLevel<=RTREE_MAX_DEPTH ); 1462 while( i>0 ){ 1463 RtreeSearchPoint *pParent; 1464 j = (i-1)/2; 1465 pParent = pCur->aPoint + j; 1466 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break; 1467 rtreeSearchPointSwap(pCur, j, i); 1468 i = j; 1469 pNew = pParent; 1470 } 1471 return pNew; 1472 } 1473 1474 /* 1475 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return 1476 ** NULL if malloc fails. 1477 */ 1478 static RtreeSearchPoint *rtreeSearchPointNew( 1479 RtreeCursor *pCur, /* The cursor */ 1480 RtreeDValue rScore, /* Score for the new search point */ 1481 u8 iLevel /* Level for the new search point */ 1482 ){ 1483 RtreeSearchPoint *pNew, *pFirst; 1484 pFirst = rtreeSearchPointFirst(pCur); 1485 pCur->anQueue[iLevel]++; 1486 if( pFirst==0 1487 || pFirst->rScore>rScore 1488 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel) 1489 ){ 1490 if( pCur->bPoint ){ 1491 int ii; 1492 pNew = rtreeEnqueue(pCur, rScore, iLevel); 1493 if( pNew==0 ) return 0; 1494 ii = (int)(pNew - pCur->aPoint) + 1; 1495 if( ii<RTREE_CACHE_SZ ){ 1496 assert( pCur->aNode[ii]==0 ); 1497 pCur->aNode[ii] = pCur->aNode[0]; 1498 }else{ 1499 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]); 1500 } 1501 pCur->aNode[0] = 0; 1502 *pNew = pCur->sPoint; 1503 } 1504 pCur->sPoint.rScore = rScore; 1505 pCur->sPoint.iLevel = iLevel; 1506 pCur->bPoint = 1; 1507 return &pCur->sPoint; 1508 }else{ 1509 return rtreeEnqueue(pCur, rScore, iLevel); 1510 } 1511 } 1512 1513 #if 0 1514 /* Tracing routines for the RtreeSearchPoint queue */ 1515 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){ 1516 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); } 1517 printf(" %d.%05lld.%02d %g %d", 1518 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin 1519 ); 1520 idx++; 1521 if( idx<RTREE_CACHE_SZ ){ 1522 printf(" %p\n", pCur->aNode[idx]); 1523 }else{ 1524 printf("\n"); 1525 } 1526 } 1527 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){ 1528 int ii; 1529 printf("=== %9s ", zPrefix); 1530 if( pCur->bPoint ){ 1531 tracePoint(&pCur->sPoint, -1, pCur); 1532 } 1533 for(ii=0; ii<pCur->nPoint; ii++){ 1534 if( ii>0 || pCur->bPoint ) printf(" "); 1535 tracePoint(&pCur->aPoint[ii], ii, pCur); 1536 } 1537 } 1538 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B) 1539 #else 1540 # define RTREE_QUEUE_TRACE(A,B) /* no-op */ 1541 #endif 1542 1543 /* Remove the search point with the lowest current score. 1544 */ 1545 static void rtreeSearchPointPop(RtreeCursor *p){ 1546 int i, j, k, n; 1547 i = 1 - p->bPoint; 1548 assert( i==0 || i==1 ); 1549 if( p->aNode[i] ){ 1550 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]); 1551 p->aNode[i] = 0; 1552 } 1553 if( p->bPoint ){ 1554 p->anQueue[p->sPoint.iLevel]--; 1555 p->bPoint = 0; 1556 }else if( p->nPoint ){ 1557 p->anQueue[p->aPoint[0].iLevel]--; 1558 n = --p->nPoint; 1559 p->aPoint[0] = p->aPoint[n]; 1560 if( n<RTREE_CACHE_SZ-1 ){ 1561 p->aNode[1] = p->aNode[n+1]; 1562 p->aNode[n+1] = 0; 1563 } 1564 i = 0; 1565 while( (j = i*2+1)<n ){ 1566 k = j+1; 1567 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){ 1568 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){ 1569 rtreeSearchPointSwap(p, i, k); 1570 i = k; 1571 }else{ 1572 break; 1573 } 1574 }else{ 1575 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){ 1576 rtreeSearchPointSwap(p, i, j); 1577 i = j; 1578 }else{ 1579 break; 1580 } 1581 } 1582 } 1583 } 1584 } 1585 1586 1587 /* 1588 ** Continue the search on cursor pCur until the front of the queue 1589 ** contains an entry suitable for returning as a result-set row, 1590 ** or until the RtreeSearchPoint queue is empty, indicating that the 1591 ** query has completed. 1592 */ 1593 static int rtreeStepToLeaf(RtreeCursor *pCur){ 1594 RtreeSearchPoint *p; 1595 Rtree *pRtree = RTREE_OF_CURSOR(pCur); 1596 RtreeNode *pNode; 1597 int eWithin; 1598 int rc = SQLITE_OK; 1599 int nCell; 1600 int nConstraint = pCur->nConstraint; 1601 int ii; 1602 int eInt; 1603 RtreeSearchPoint x; 1604 1605 eInt = pRtree->eCoordType==RTREE_COORD_INT32; 1606 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){ 1607 u8 *pCellData; 1608 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); 1609 if( rc ) return rc; 1610 nCell = NCELL(pNode); 1611 assert( nCell<200 ); 1612 pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell); 1613 while( p->iCell<nCell ){ 1614 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1; 1615 eWithin = FULLY_WITHIN; 1616 for(ii=0; ii<nConstraint; ii++){ 1617 RtreeConstraint *pConstraint = pCur->aConstraint + ii; 1618 if( pConstraint->op>=RTREE_MATCH ){ 1619 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p, 1620 &rScore, &eWithin); 1621 if( rc ) return rc; 1622 }else if( p->iLevel==1 ){ 1623 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin); 1624 }else{ 1625 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin); 1626 } 1627 if( eWithin==NOT_WITHIN ){ 1628 p->iCell++; 1629 pCellData += pRtree->nBytesPerCell; 1630 break; 1631 } 1632 } 1633 if( eWithin==NOT_WITHIN ) continue; 1634 p->iCell++; 1635 x.iLevel = p->iLevel - 1; 1636 if( x.iLevel ){ 1637 x.id = readInt64(pCellData); 1638 for(ii=0; ii<pCur->nPoint; ii++){ 1639 if( pCur->aPoint[ii].id==x.id ){ 1640 RTREE_IS_CORRUPT(pRtree); 1641 return SQLITE_CORRUPT_VTAB; 1642 } 1643 } 1644 x.iCell = 0; 1645 }else{ 1646 x.id = p->id; 1647 x.iCell = p->iCell - 1; 1648 } 1649 if( p->iCell>=nCell ){ 1650 RTREE_QUEUE_TRACE(pCur, "POP-S:"); 1651 rtreeSearchPointPop(pCur); 1652 } 1653 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO; 1654 p = rtreeSearchPointNew(pCur, rScore, x.iLevel); 1655 if( p==0 ) return SQLITE_NOMEM; 1656 p->eWithin = (u8)eWithin; 1657 p->id = x.id; 1658 p->iCell = x.iCell; 1659 RTREE_QUEUE_TRACE(pCur, "PUSH-S:"); 1660 break; 1661 } 1662 if( p->iCell>=nCell ){ 1663 RTREE_QUEUE_TRACE(pCur, "POP-Se:"); 1664 rtreeSearchPointPop(pCur); 1665 } 1666 } 1667 pCur->atEOF = p==0; 1668 return SQLITE_OK; 1669 } 1670 1671 /* 1672 ** Rtree virtual table module xNext method. 1673 */ 1674 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ 1675 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 1676 int rc = SQLITE_OK; 1677 1678 /* Move to the next entry that matches the configured constraints. */ 1679 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:"); 1680 if( pCsr->bAuxValid ){ 1681 pCsr->bAuxValid = 0; 1682 sqlite3_reset(pCsr->pReadAux); 1683 } 1684 rtreeSearchPointPop(pCsr); 1685 rc = rtreeStepToLeaf(pCsr); 1686 return rc; 1687 } 1688 1689 /* 1690 ** Rtree virtual table module xRowid method. 1691 */ 1692 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ 1693 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 1694 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); 1695 int rc = SQLITE_OK; 1696 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); 1697 if( rc==SQLITE_OK && p ){ 1698 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell); 1699 } 1700 return rc; 1701 } 1702 1703 /* 1704 ** Rtree virtual table module xColumn method. 1705 */ 1706 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ 1707 Rtree *pRtree = (Rtree *)cur->pVtab; 1708 RtreeCursor *pCsr = (RtreeCursor *)cur; 1709 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr); 1710 RtreeCoord c; 1711 int rc = SQLITE_OK; 1712 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc); 1713 1714 if( rc ) return rc; 1715 if( p==0 ) return SQLITE_OK; 1716 if( i==0 ){ 1717 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell)); 1718 }else if( i<=pRtree->nDim2 ){ 1719 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c); 1720 #ifndef SQLITE_RTREE_INT_ONLY 1721 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 1722 sqlite3_result_double(ctx, c.f); 1723 }else 1724 #endif 1725 { 1726 assert( pRtree->eCoordType==RTREE_COORD_INT32 ); 1727 sqlite3_result_int(ctx, c.i); 1728 } 1729 }else{ 1730 if( !pCsr->bAuxValid ){ 1731 if( pCsr->pReadAux==0 ){ 1732 rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0, 1733 &pCsr->pReadAux, 0); 1734 if( rc ) return rc; 1735 } 1736 sqlite3_bind_int64(pCsr->pReadAux, 1, 1737 nodeGetRowid(pRtree, pNode, p->iCell)); 1738 rc = sqlite3_step(pCsr->pReadAux); 1739 if( rc==SQLITE_ROW ){ 1740 pCsr->bAuxValid = 1; 1741 }else{ 1742 sqlite3_reset(pCsr->pReadAux); 1743 if( rc==SQLITE_DONE ) rc = SQLITE_OK; 1744 return rc; 1745 } 1746 } 1747 sqlite3_result_value(ctx, 1748 sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1)); 1749 } 1750 return SQLITE_OK; 1751 } 1752 1753 /* 1754 ** Use nodeAcquire() to obtain the leaf node containing the record with 1755 ** rowid iRowid. If successful, set *ppLeaf to point to the node and 1756 ** return SQLITE_OK. If there is no such record in the table, set 1757 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf 1758 ** to zero and return an SQLite error code. 1759 */ 1760 static int findLeafNode( 1761 Rtree *pRtree, /* RTree to search */ 1762 i64 iRowid, /* The rowid searching for */ 1763 RtreeNode **ppLeaf, /* Write the node here */ 1764 sqlite3_int64 *piNode /* Write the node-id here */ 1765 ){ 1766 int rc; 1767 *ppLeaf = 0; 1768 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); 1769 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ 1770 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); 1771 if( piNode ) *piNode = iNode; 1772 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); 1773 sqlite3_reset(pRtree->pReadRowid); 1774 }else{ 1775 rc = sqlite3_reset(pRtree->pReadRowid); 1776 } 1777 return rc; 1778 } 1779 1780 /* 1781 ** This function is called to configure the RtreeConstraint object passed 1782 ** as the second argument for a MATCH constraint. The value passed as the 1783 ** first argument to this function is the right-hand operand to the MATCH 1784 ** operator. 1785 */ 1786 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){ 1787 RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */ 1788 sqlite3_rtree_query_info *pInfo; /* Callback information */ 1789 1790 pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg"); 1791 if( pSrc==0 ) return SQLITE_ERROR; 1792 pInfo = (sqlite3_rtree_query_info*) 1793 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize ); 1794 if( !pInfo ) return SQLITE_NOMEM; 1795 memset(pInfo, 0, sizeof(*pInfo)); 1796 pBlob = (RtreeMatchArg*)&pInfo[1]; 1797 memcpy(pBlob, pSrc, pSrc->iSize); 1798 pInfo->pContext = pBlob->cb.pContext; 1799 pInfo->nParam = pBlob->nParam; 1800 pInfo->aParam = pBlob->aParam; 1801 pInfo->apSqlParam = pBlob->apSqlParam; 1802 1803 if( pBlob->cb.xGeom ){ 1804 pCons->u.xGeom = pBlob->cb.xGeom; 1805 }else{ 1806 pCons->op = RTREE_QUERY; 1807 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc; 1808 } 1809 pCons->pInfo = pInfo; 1810 return SQLITE_OK; 1811 } 1812 1813 /* 1814 ** Rtree virtual table module xFilter method. 1815 */ 1816 static int rtreeFilter( 1817 sqlite3_vtab_cursor *pVtabCursor, 1818 int idxNum, const char *idxStr, 1819 int argc, sqlite3_value **argv 1820 ){ 1821 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; 1822 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; 1823 RtreeNode *pRoot = 0; 1824 int ii; 1825 int rc = SQLITE_OK; 1826 int iCell = 0; 1827 1828 rtreeReference(pRtree); 1829 1830 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */ 1831 resetCursor(pCsr); 1832 1833 pCsr->iStrategy = idxNum; 1834 if( idxNum==1 ){ 1835 /* Special case - lookup by rowid. */ 1836 RtreeNode *pLeaf; /* Leaf on which the required cell resides */ 1837 RtreeSearchPoint *p; /* Search point for the leaf */ 1838 i64 iRowid = sqlite3_value_int64(argv[0]); 1839 i64 iNode = 0; 1840 int eType = sqlite3_value_numeric_type(argv[0]); 1841 if( eType==SQLITE_INTEGER 1842 || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid) 1843 ){ 1844 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode); 1845 }else{ 1846 rc = SQLITE_OK; 1847 pLeaf = 0; 1848 } 1849 if( rc==SQLITE_OK && pLeaf!=0 ){ 1850 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0); 1851 assert( p!=0 ); /* Always returns pCsr->sPoint */ 1852 pCsr->aNode[0] = pLeaf; 1853 p->id = iNode; 1854 p->eWithin = PARTLY_WITHIN; 1855 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell); 1856 p->iCell = (u8)iCell; 1857 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:"); 1858 }else{ 1859 pCsr->atEOF = 1; 1860 } 1861 }else{ 1862 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 1863 ** with the configured constraints. 1864 */ 1865 rc = nodeAcquire(pRtree, 1, 0, &pRoot); 1866 if( rc==SQLITE_OK && argc>0 ){ 1867 pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc); 1868 pCsr->nConstraint = argc; 1869 if( !pCsr->aConstraint ){ 1870 rc = SQLITE_NOMEM; 1871 }else{ 1872 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc); 1873 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1)); 1874 assert( (idxStr==0 && argc==0) 1875 || (idxStr && (int)strlen(idxStr)==argc*2) ); 1876 for(ii=0; ii<argc; ii++){ 1877 RtreeConstraint *p = &pCsr->aConstraint[ii]; 1878 int eType = sqlite3_value_numeric_type(argv[ii]); 1879 p->op = idxStr[ii*2]; 1880 p->iCoord = idxStr[ii*2+1]-'0'; 1881 if( p->op>=RTREE_MATCH ){ 1882 /* A MATCH operator. The right-hand-side must be a blob that 1883 ** can be cast into an RtreeMatchArg object. One created using 1884 ** an sqlite3_rtree_geometry_callback() SQL user function. 1885 */ 1886 rc = deserializeGeometry(argv[ii], p); 1887 if( rc!=SQLITE_OK ){ 1888 break; 1889 } 1890 p->pInfo->nCoord = pRtree->nDim2; 1891 p->pInfo->anQueue = pCsr->anQueue; 1892 p->pInfo->mxLevel = pRtree->iDepth + 1; 1893 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ 1894 #ifdef SQLITE_RTREE_INT_ONLY 1895 p->u.rValue = sqlite3_value_int64(argv[ii]); 1896 #else 1897 p->u.rValue = sqlite3_value_double(argv[ii]); 1898 #endif 1899 }else{ 1900 p->u.rValue = RTREE_ZERO; 1901 if( eType==SQLITE_NULL ){ 1902 p->op = RTREE_FALSE; 1903 }else if( p->op==RTREE_LT || p->op==RTREE_LE ){ 1904 p->op = RTREE_TRUE; 1905 }else{ 1906 p->op = RTREE_FALSE; 1907 } 1908 } 1909 } 1910 } 1911 } 1912 if( rc==SQLITE_OK ){ 1913 RtreeSearchPoint *pNew; 1914 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1)); 1915 if( pNew==0 ) return SQLITE_NOMEM; 1916 pNew->id = 1; 1917 pNew->iCell = 0; 1918 pNew->eWithin = PARTLY_WITHIN; 1919 assert( pCsr->bPoint==1 ); 1920 pCsr->aNode[0] = pRoot; 1921 pRoot = 0; 1922 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:"); 1923 rc = rtreeStepToLeaf(pCsr); 1924 } 1925 } 1926 1927 nodeRelease(pRtree, pRoot); 1928 rtreeRelease(pRtree); 1929 return rc; 1930 } 1931 1932 /* 1933 ** Rtree virtual table module xBestIndex method. There are three 1934 ** table scan strategies to choose from (in order from most to 1935 ** least desirable): 1936 ** 1937 ** idxNum idxStr Strategy 1938 ** ------------------------------------------------ 1939 ** 1 Unused Direct lookup by rowid. 1940 ** 2 See below R-tree query or full-table scan. 1941 ** ------------------------------------------------ 1942 ** 1943 ** If strategy 1 is used, then idxStr is not meaningful. If strategy 1944 ** 2 is used, idxStr is formatted to contain 2 bytes for each 1945 ** constraint used. The first two bytes of idxStr correspond to 1946 ** the constraint in sqlite3_index_info.aConstraintUsage[] with 1947 ** (argvIndex==1) etc. 1948 ** 1949 ** The first of each pair of bytes in idxStr identifies the constraint 1950 ** operator as follows: 1951 ** 1952 ** Operator Byte Value 1953 ** ---------------------- 1954 ** = 0x41 ('A') 1955 ** <= 0x42 ('B') 1956 ** < 0x43 ('C') 1957 ** >= 0x44 ('D') 1958 ** > 0x45 ('E') 1959 ** MATCH 0x46 ('F') 1960 ** ---------------------- 1961 ** 1962 ** The second of each pair of bytes identifies the coordinate column 1963 ** to which the constraint applies. The leftmost coordinate column 1964 ** is 'a', the second from the left 'b' etc. 1965 */ 1966 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ 1967 Rtree *pRtree = (Rtree*)tab; 1968 int rc = SQLITE_OK; 1969 int ii; 1970 int bMatch = 0; /* True if there exists a MATCH constraint */ 1971 i64 nRow; /* Estimated rows returned by this scan */ 1972 1973 int iIdx = 0; 1974 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; 1975 memset(zIdxStr, 0, sizeof(zIdxStr)); 1976 1977 /* Check if there exists a MATCH constraint - even an unusable one. If there 1978 ** is, do not consider the lookup-by-rowid plan as using such a plan would 1979 ** require the VDBE to evaluate the MATCH constraint, which is not currently 1980 ** possible. */ 1981 for(ii=0; ii<pIdxInfo->nConstraint; ii++){ 1982 if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){ 1983 bMatch = 1; 1984 } 1985 } 1986 1987 assert( pIdxInfo->idxStr==0 ); 1988 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){ 1989 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; 1990 1991 if( bMatch==0 && p->usable 1992 && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ 1993 ){ 1994 /* We have an equality constraint on the rowid. Use strategy 1. */ 1995 int jj; 1996 for(jj=0; jj<ii; jj++){ 1997 pIdxInfo->aConstraintUsage[jj].argvIndex = 0; 1998 pIdxInfo->aConstraintUsage[jj].omit = 0; 1999 } 2000 pIdxInfo->idxNum = 1; 2001 pIdxInfo->aConstraintUsage[ii].argvIndex = 1; 2002 pIdxInfo->aConstraintUsage[jj].omit = 1; 2003 2004 /* This strategy involves a two rowid lookups on an B-Tree structures 2005 ** and then a linear search of an R-Tree node. This should be 2006 ** considered almost as quick as a direct rowid lookup (for which 2007 ** sqlite uses an internal cost of 0.0). It is expected to return 2008 ** a single row. 2009 */ 2010 pIdxInfo->estimatedCost = 30.0; 2011 pIdxInfo->estimatedRows = 1; 2012 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE; 2013 return SQLITE_OK; 2014 } 2015 2016 if( p->usable 2017 && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2) 2018 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) 2019 ){ 2020 u8 op; 2021 switch( p->op ){ 2022 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; 2023 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; 2024 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; 2025 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; 2026 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; 2027 case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break; 2028 default: op = 0; break; 2029 } 2030 if( op ){ 2031 zIdxStr[iIdx++] = op; 2032 zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0'); 2033 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2); 2034 pIdxInfo->aConstraintUsage[ii].omit = 1; 2035 } 2036 } 2037 } 2038 2039 pIdxInfo->idxNum = 2; 2040 pIdxInfo->needToFreeIdxStr = 1; 2041 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ 2042 return SQLITE_NOMEM; 2043 } 2044 2045 nRow = pRtree->nRowEst >> (iIdx/2); 2046 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow; 2047 pIdxInfo->estimatedRows = nRow; 2048 2049 return rc; 2050 } 2051 2052 /* 2053 ** Return the N-dimensional volumn of the cell stored in *p. 2054 */ 2055 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){ 2056 RtreeDValue area = (RtreeDValue)1; 2057 assert( pRtree->nDim>=1 && pRtree->nDim<=5 ); 2058 #ifndef SQLITE_RTREE_INT_ONLY 2059 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 2060 switch( pRtree->nDim ){ 2061 case 5: area = p->aCoord[9].f - p->aCoord[8].f; 2062 case 4: area *= p->aCoord[7].f - p->aCoord[6].f; 2063 case 3: area *= p->aCoord[5].f - p->aCoord[4].f; 2064 case 2: area *= p->aCoord[3].f - p->aCoord[2].f; 2065 default: area *= p->aCoord[1].f - p->aCoord[0].f; 2066 } 2067 }else 2068 #endif 2069 { 2070 switch( pRtree->nDim ){ 2071 case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i; 2072 case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i; 2073 case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i; 2074 case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i; 2075 default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i; 2076 } 2077 } 2078 return area; 2079 } 2080 2081 /* 2082 ** Return the margin length of cell p. The margin length is the sum 2083 ** of the objects size in each dimension. 2084 */ 2085 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){ 2086 RtreeDValue margin = 0; 2087 int ii = pRtree->nDim2 - 2; 2088 do{ 2089 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); 2090 ii -= 2; 2091 }while( ii>=0 ); 2092 return margin; 2093 } 2094 2095 /* 2096 ** Store the union of cells p1 and p2 in p1. 2097 */ 2098 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ 2099 int ii = 0; 2100 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 2101 do{ 2102 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); 2103 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); 2104 ii += 2; 2105 }while( ii<pRtree->nDim2 ); 2106 }else{ 2107 do{ 2108 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); 2109 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); 2110 ii += 2; 2111 }while( ii<pRtree->nDim2 ); 2112 } 2113 } 2114 2115 /* 2116 ** Return true if the area covered by p2 is a subset of the area covered 2117 ** by p1. False otherwise. 2118 */ 2119 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ 2120 int ii; 2121 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32); 2122 for(ii=0; ii<pRtree->nDim2; ii+=2){ 2123 RtreeCoord *a1 = &p1->aCoord[ii]; 2124 RtreeCoord *a2 = &p2->aCoord[ii]; 2125 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 2126 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 2127 ){ 2128 return 0; 2129 } 2130 } 2131 return 1; 2132 } 2133 2134 /* 2135 ** Return the amount cell p would grow by if it were unioned with pCell. 2136 */ 2137 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ 2138 RtreeDValue area; 2139 RtreeCell cell; 2140 memcpy(&cell, p, sizeof(RtreeCell)); 2141 area = cellArea(pRtree, &cell); 2142 cellUnion(pRtree, &cell, pCell); 2143 return (cellArea(pRtree, &cell)-area); 2144 } 2145 2146 static RtreeDValue cellOverlap( 2147 Rtree *pRtree, 2148 RtreeCell *p, 2149 RtreeCell *aCell, 2150 int nCell 2151 ){ 2152 int ii; 2153 RtreeDValue overlap = RTREE_ZERO; 2154 for(ii=0; ii<nCell; ii++){ 2155 int jj; 2156 RtreeDValue o = (RtreeDValue)1; 2157 for(jj=0; jj<pRtree->nDim2; jj+=2){ 2158 RtreeDValue x1, x2; 2159 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); 2160 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); 2161 if( x2<x1 ){ 2162 o = (RtreeDValue)0; 2163 break; 2164 }else{ 2165 o = o * (x2-x1); 2166 } 2167 } 2168 overlap += o; 2169 } 2170 return overlap; 2171 } 2172 2173 2174 /* 2175 ** This function implements the ChooseLeaf algorithm from Gutman[84]. 2176 ** ChooseSubTree in r*tree terminology. 2177 */ 2178 static int ChooseLeaf( 2179 Rtree *pRtree, /* Rtree table */ 2180 RtreeCell *pCell, /* Cell to insert into rtree */ 2181 int iHeight, /* Height of sub-tree rooted at pCell */ 2182 RtreeNode **ppLeaf /* OUT: Selected leaf page */ 2183 ){ 2184 int rc; 2185 int ii; 2186 RtreeNode *pNode = 0; 2187 rc = nodeAcquire(pRtree, 1, 0, &pNode); 2188 2189 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){ 2190 int iCell; 2191 sqlite3_int64 iBest = 0; 2192 2193 RtreeDValue fMinGrowth = RTREE_ZERO; 2194 RtreeDValue fMinArea = RTREE_ZERO; 2195 2196 int nCell = NCELL(pNode); 2197 RtreeCell cell; 2198 RtreeNode *pChild; 2199 2200 RtreeCell *aCell = 0; 2201 2202 /* Select the child node which will be enlarged the least if pCell 2203 ** is inserted into it. Resolve ties by choosing the entry with 2204 ** the smallest area. 2205 */ 2206 for(iCell=0; iCell<nCell; iCell++){ 2207 int bBest = 0; 2208 RtreeDValue growth; 2209 RtreeDValue area; 2210 nodeGetCell(pRtree, pNode, iCell, &cell); 2211 growth = cellGrowth(pRtree, &cell, pCell); 2212 area = cellArea(pRtree, &cell); 2213 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){ 2214 bBest = 1; 2215 } 2216 if( bBest ){ 2217 fMinGrowth = growth; 2218 fMinArea = area; 2219 iBest = cell.iRowid; 2220 } 2221 } 2222 2223 sqlite3_free(aCell); 2224 rc = nodeAcquire(pRtree, iBest, pNode, &pChild); 2225 nodeRelease(pRtree, pNode); 2226 pNode = pChild; 2227 } 2228 2229 *ppLeaf = pNode; 2230 return rc; 2231 } 2232 2233 /* 2234 ** A cell with the same content as pCell has just been inserted into 2235 ** the node pNode. This function updates the bounding box cells in 2236 ** all ancestor elements. 2237 */ 2238 static int AdjustTree( 2239 Rtree *pRtree, /* Rtree table */ 2240 RtreeNode *pNode, /* Adjust ancestry of this node. */ 2241 RtreeCell *pCell /* This cell was just inserted */ 2242 ){ 2243 RtreeNode *p = pNode; 2244 int cnt = 0; 2245 while( p->pParent ){ 2246 RtreeNode *pParent = p->pParent; 2247 RtreeCell cell; 2248 int iCell; 2249 2250 if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){ 2251 RTREE_IS_CORRUPT(pRtree); 2252 return SQLITE_CORRUPT_VTAB; 2253 } 2254 2255 nodeGetCell(pRtree, pParent, iCell, &cell); 2256 if( !cellContains(pRtree, &cell, pCell) ){ 2257 cellUnion(pRtree, &cell, pCell); 2258 nodeOverwriteCell(pRtree, pParent, &cell, iCell); 2259 } 2260 2261 p = pParent; 2262 } 2263 return SQLITE_OK; 2264 } 2265 2266 /* 2267 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table. 2268 */ 2269 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ 2270 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); 2271 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); 2272 sqlite3_step(pRtree->pWriteRowid); 2273 return sqlite3_reset(pRtree->pWriteRowid); 2274 } 2275 2276 /* 2277 ** Write mapping (iNode->iPar) to the <rtree>_parent table. 2278 */ 2279 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ 2280 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); 2281 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); 2282 sqlite3_step(pRtree->pWriteParent); 2283 return sqlite3_reset(pRtree->pWriteParent); 2284 } 2285 2286 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); 2287 2288 2289 /* 2290 ** Arguments aIdx, aDistance and aSpare all point to arrays of size 2291 ** nIdx. The aIdx array contains the set of integers from 0 to 2292 ** (nIdx-1) in no particular order. This function sorts the values 2293 ** in aIdx according to the indexed values in aDistance. For 2294 ** example, assuming the inputs: 2295 ** 2296 ** aIdx = { 0, 1, 2, 3 } 2297 ** aDistance = { 5.0, 2.0, 7.0, 6.0 } 2298 ** 2299 ** this function sets the aIdx array to contain: 2300 ** 2301 ** aIdx = { 0, 1, 2, 3 } 2302 ** 2303 ** The aSpare array is used as temporary working space by the 2304 ** sorting algorithm. 2305 */ 2306 static void SortByDistance( 2307 int *aIdx, 2308 int nIdx, 2309 RtreeDValue *aDistance, 2310 int *aSpare 2311 ){ 2312 if( nIdx>1 ){ 2313 int iLeft = 0; 2314 int iRight = 0; 2315 2316 int nLeft = nIdx/2; 2317 int nRight = nIdx-nLeft; 2318 int *aLeft = aIdx; 2319 int *aRight = &aIdx[nLeft]; 2320 2321 SortByDistance(aLeft, nLeft, aDistance, aSpare); 2322 SortByDistance(aRight, nRight, aDistance, aSpare); 2323 2324 memcpy(aSpare, aLeft, sizeof(int)*nLeft); 2325 aLeft = aSpare; 2326 2327 while( iLeft<nLeft || iRight<nRight ){ 2328 if( iLeft==nLeft ){ 2329 aIdx[iLeft+iRight] = aRight[iRight]; 2330 iRight++; 2331 }else if( iRight==nRight ){ 2332 aIdx[iLeft+iRight] = aLeft[iLeft]; 2333 iLeft++; 2334 }else{ 2335 RtreeDValue fLeft = aDistance[aLeft[iLeft]]; 2336 RtreeDValue fRight = aDistance[aRight[iRight]]; 2337 if( fLeft<fRight ){ 2338 aIdx[iLeft+iRight] = aLeft[iLeft]; 2339 iLeft++; 2340 }else{ 2341 aIdx[iLeft+iRight] = aRight[iRight]; 2342 iRight++; 2343 } 2344 } 2345 } 2346 2347 #if 0 2348 /* Check that the sort worked */ 2349 { 2350 int jj; 2351 for(jj=1; jj<nIdx; jj++){ 2352 RtreeDValue left = aDistance[aIdx[jj-1]]; 2353 RtreeDValue right = aDistance[aIdx[jj]]; 2354 assert( left<=right ); 2355 } 2356 } 2357 #endif 2358 } 2359 } 2360 2361 /* 2362 ** Arguments aIdx, aCell and aSpare all point to arrays of size 2363 ** nIdx. The aIdx array contains the set of integers from 0 to 2364 ** (nIdx-1) in no particular order. This function sorts the values 2365 ** in aIdx according to dimension iDim of the cells in aCell. The 2366 ** minimum value of dimension iDim is considered first, the 2367 ** maximum used to break ties. 2368 ** 2369 ** The aSpare array is used as temporary working space by the 2370 ** sorting algorithm. 2371 */ 2372 static void SortByDimension( 2373 Rtree *pRtree, 2374 int *aIdx, 2375 int nIdx, 2376 int iDim, 2377 RtreeCell *aCell, 2378 int *aSpare 2379 ){ 2380 if( nIdx>1 ){ 2381 2382 int iLeft = 0; 2383 int iRight = 0; 2384 2385 int nLeft = nIdx/2; 2386 int nRight = nIdx-nLeft; 2387 int *aLeft = aIdx; 2388 int *aRight = &aIdx[nLeft]; 2389 2390 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); 2391 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); 2392 2393 memcpy(aSpare, aLeft, sizeof(int)*nLeft); 2394 aLeft = aSpare; 2395 while( iLeft<nLeft || iRight<nRight ){ 2396 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]); 2397 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]); 2398 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]); 2399 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]); 2400 if( (iLeft!=nLeft) && ((iRight==nRight) 2401 || (xleft1<xright1) 2402 || (xleft1==xright1 && xleft2<xright2) 2403 )){ 2404 aIdx[iLeft+iRight] = aLeft[iLeft]; 2405 iLeft++; 2406 }else{ 2407 aIdx[iLeft+iRight] = aRight[iRight]; 2408 iRight++; 2409 } 2410 } 2411 2412 #if 0 2413 /* Check that the sort worked */ 2414 { 2415 int jj; 2416 for(jj=1; jj<nIdx; jj++){ 2417 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2]; 2418 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1]; 2419 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2]; 2420 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1]; 2421 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) ); 2422 } 2423 } 2424 #endif 2425 } 2426 } 2427 2428 /* 2429 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990]. 2430 */ 2431 static int splitNodeStartree( 2432 Rtree *pRtree, 2433 RtreeCell *aCell, 2434 int nCell, 2435 RtreeNode *pLeft, 2436 RtreeNode *pRight, 2437 RtreeCell *pBboxLeft, 2438 RtreeCell *pBboxRight 2439 ){ 2440 int **aaSorted; 2441 int *aSpare; 2442 int ii; 2443 2444 int iBestDim = 0; 2445 int iBestSplit = 0; 2446 RtreeDValue fBestMargin = RTREE_ZERO; 2447 2448 sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int)); 2449 2450 aaSorted = (int **)sqlite3_malloc64(nByte); 2451 if( !aaSorted ){ 2452 return SQLITE_NOMEM; 2453 } 2454 2455 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; 2456 memset(aaSorted, 0, nByte); 2457 for(ii=0; ii<pRtree->nDim; ii++){ 2458 int jj; 2459 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; 2460 for(jj=0; jj<nCell; jj++){ 2461 aaSorted[ii][jj] = jj; 2462 } 2463 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare); 2464 } 2465 2466 for(ii=0; ii<pRtree->nDim; ii++){ 2467 RtreeDValue margin = RTREE_ZERO; 2468 RtreeDValue fBestOverlap = RTREE_ZERO; 2469 RtreeDValue fBestArea = RTREE_ZERO; 2470 int iBestLeft = 0; 2471 int nLeft; 2472 2473 for( 2474 nLeft=RTREE_MINCELLS(pRtree); 2475 nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 2476 nLeft++ 2477 ){ 2478 RtreeCell left; 2479 RtreeCell right; 2480 int kk; 2481 RtreeDValue overlap; 2482 RtreeDValue area; 2483 2484 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); 2485 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); 2486 for(kk=1; kk<(nCell-1); kk++){ 2487 if( kk<nLeft ){ 2488 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]); 2489 }else{ 2490 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]); 2491 } 2492 } 2493 margin += cellMargin(pRtree, &left); 2494 margin += cellMargin(pRtree, &right); 2495 overlap = cellOverlap(pRtree, &left, &right, 1); 2496 area = cellArea(pRtree, &left) + cellArea(pRtree, &right); 2497 if( (nLeft==RTREE_MINCELLS(pRtree)) 2498 || (overlap<fBestOverlap) 2499 || (overlap==fBestOverlap && area<fBestArea) 2500 ){ 2501 iBestLeft = nLeft; 2502 fBestOverlap = overlap; 2503 fBestArea = area; 2504 } 2505 } 2506 2507 if( ii==0 || margin<fBestMargin ){ 2508 iBestDim = ii; 2509 fBestMargin = margin; 2510 iBestSplit = iBestLeft; 2511 } 2512 } 2513 2514 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell)); 2515 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell)); 2516 for(ii=0; ii<nCell; ii++){ 2517 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight; 2518 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight; 2519 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]]; 2520 nodeInsertCell(pRtree, pTarget, pCell); 2521 cellUnion(pRtree, pBbox, pCell); 2522 } 2523 2524 sqlite3_free(aaSorted); 2525 return SQLITE_OK; 2526 } 2527 2528 2529 static int updateMapping( 2530 Rtree *pRtree, 2531 i64 iRowid, 2532 RtreeNode *pNode, 2533 int iHeight 2534 ){ 2535 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); 2536 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); 2537 if( iHeight>0 ){ 2538 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); 2539 if( pChild ){ 2540 nodeRelease(pRtree, pChild->pParent); 2541 nodeReference(pNode); 2542 pChild->pParent = pNode; 2543 } 2544 } 2545 return xSetMapping(pRtree, iRowid, pNode->iNode); 2546 } 2547 2548 static int SplitNode( 2549 Rtree *pRtree, 2550 RtreeNode *pNode, 2551 RtreeCell *pCell, 2552 int iHeight 2553 ){ 2554 int i; 2555 int newCellIsRight = 0; 2556 2557 int rc = SQLITE_OK; 2558 int nCell = NCELL(pNode); 2559 RtreeCell *aCell; 2560 int *aiUsed; 2561 2562 RtreeNode *pLeft = 0; 2563 RtreeNode *pRight = 0; 2564 2565 RtreeCell leftbbox; 2566 RtreeCell rightbbox; 2567 2568 /* Allocate an array and populate it with a copy of pCell and 2569 ** all cells from node pLeft. Then zero the original node. 2570 */ 2571 aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); 2572 if( !aCell ){ 2573 rc = SQLITE_NOMEM; 2574 goto splitnode_out; 2575 } 2576 aiUsed = (int *)&aCell[nCell+1]; 2577 memset(aiUsed, 0, sizeof(int)*(nCell+1)); 2578 for(i=0; i<nCell; i++){ 2579 nodeGetCell(pRtree, pNode, i, &aCell[i]); 2580 } 2581 nodeZero(pRtree, pNode); 2582 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell)); 2583 nCell++; 2584 2585 if( pNode->iNode==1 ){ 2586 pRight = nodeNew(pRtree, pNode); 2587 pLeft = nodeNew(pRtree, pNode); 2588 pRtree->iDepth++; 2589 pNode->isDirty = 1; 2590 writeInt16(pNode->zData, pRtree->iDepth); 2591 }else{ 2592 pLeft = pNode; 2593 pRight = nodeNew(pRtree, pLeft->pParent); 2594 pLeft->nRef++; 2595 } 2596 2597 if( !pLeft || !pRight ){ 2598 rc = SQLITE_NOMEM; 2599 goto splitnode_out; 2600 } 2601 2602 memset(pLeft->zData, 0, pRtree->iNodeSize); 2603 memset(pRight->zData, 0, pRtree->iNodeSize); 2604 2605 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, 2606 &leftbbox, &rightbbox); 2607 if( rc!=SQLITE_OK ){ 2608 goto splitnode_out; 2609 } 2610 2611 /* Ensure both child nodes have node numbers assigned to them by calling 2612 ** nodeWrite(). Node pRight always needs a node number, as it was created 2613 ** by nodeNew() above. But node pLeft sometimes already has a node number. 2614 ** In this case avoid the all to nodeWrite(). 2615 */ 2616 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) 2617 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) 2618 ){ 2619 goto splitnode_out; 2620 } 2621 2622 rightbbox.iRowid = pRight->iNode; 2623 leftbbox.iRowid = pLeft->iNode; 2624 2625 if( pNode->iNode==1 ){ 2626 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); 2627 if( rc!=SQLITE_OK ){ 2628 goto splitnode_out; 2629 } 2630 }else{ 2631 RtreeNode *pParent = pLeft->pParent; 2632 int iCell; 2633 rc = nodeParentIndex(pRtree, pLeft, &iCell); 2634 if( rc==SQLITE_OK ){ 2635 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); 2636 rc = AdjustTree(pRtree, pParent, &leftbbox); 2637 } 2638 if( rc!=SQLITE_OK ){ 2639 goto splitnode_out; 2640 } 2641 } 2642 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ 2643 goto splitnode_out; 2644 } 2645 2646 for(i=0; i<NCELL(pRight); i++){ 2647 i64 iRowid = nodeGetRowid(pRtree, pRight, i); 2648 rc = updateMapping(pRtree, iRowid, pRight, iHeight); 2649 if( iRowid==pCell->iRowid ){ 2650 newCellIsRight = 1; 2651 } 2652 if( rc!=SQLITE_OK ){ 2653 goto splitnode_out; 2654 } 2655 } 2656 if( pNode->iNode==1 ){ 2657 for(i=0; i<NCELL(pLeft); i++){ 2658 i64 iRowid = nodeGetRowid(pRtree, pLeft, i); 2659 rc = updateMapping(pRtree, iRowid, pLeft, iHeight); 2660 if( rc!=SQLITE_OK ){ 2661 goto splitnode_out; 2662 } 2663 } 2664 }else if( newCellIsRight==0 ){ 2665 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight); 2666 } 2667 2668 if( rc==SQLITE_OK ){ 2669 rc = nodeRelease(pRtree, pRight); 2670 pRight = 0; 2671 } 2672 if( rc==SQLITE_OK ){ 2673 rc = nodeRelease(pRtree, pLeft); 2674 pLeft = 0; 2675 } 2676 2677 splitnode_out: 2678 nodeRelease(pRtree, pRight); 2679 nodeRelease(pRtree, pLeft); 2680 sqlite3_free(aCell); 2681 return rc; 2682 } 2683 2684 /* 2685 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 2686 ** still NULL, load all ancestor nodes of pLeaf into memory and populate 2687 ** the pLeaf->pParent chain all the way up to the root node. 2688 ** 2689 ** This operation is required when a row is deleted (or updated - an update 2690 ** is implemented as a delete followed by an insert). SQLite provides the 2691 ** rowid of the row to delete, which can be used to find the leaf on which 2692 ** the entry resides (argument pLeaf). Once the leaf is located, this 2693 ** function is called to determine its ancestry. 2694 */ 2695 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ 2696 int rc = SQLITE_OK; 2697 RtreeNode *pChild = pLeaf; 2698 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){ 2699 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */ 2700 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode); 2701 rc = sqlite3_step(pRtree->pReadParent); 2702 if( rc==SQLITE_ROW ){ 2703 RtreeNode *pTest; /* Used to test for reference loops */ 2704 i64 iNode; /* Node number of parent node */ 2705 2706 /* Before setting pChild->pParent, test that we are not creating a 2707 ** loop of references (as we would if, say, pChild==pParent). We don't 2708 ** want to do this as it leads to a memory leak when trying to delete 2709 ** the referenced counted node structures. 2710 */ 2711 iNode = sqlite3_column_int64(pRtree->pReadParent, 0); 2712 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent); 2713 if( !pTest ){ 2714 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent); 2715 } 2716 } 2717 rc = sqlite3_reset(pRtree->pReadParent); 2718 if( rc==SQLITE_OK ) rc = rc2; 2719 if( rc==SQLITE_OK && !pChild->pParent ){ 2720 RTREE_IS_CORRUPT(pRtree); 2721 rc = SQLITE_CORRUPT_VTAB; 2722 } 2723 pChild = pChild->pParent; 2724 } 2725 return rc; 2726 } 2727 2728 static int deleteCell(Rtree *, RtreeNode *, int, int); 2729 2730 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ 2731 int rc; 2732 int rc2; 2733 RtreeNode *pParent = 0; 2734 int iCell; 2735 2736 assert( pNode->nRef==1 ); 2737 2738 /* Remove the entry in the parent cell. */ 2739 rc = nodeParentIndex(pRtree, pNode, &iCell); 2740 if( rc==SQLITE_OK ){ 2741 pParent = pNode->pParent; 2742 pNode->pParent = 0; 2743 rc = deleteCell(pRtree, pParent, iCell, iHeight+1); 2744 } 2745 rc2 = nodeRelease(pRtree, pParent); 2746 if( rc==SQLITE_OK ){ 2747 rc = rc2; 2748 } 2749 if( rc!=SQLITE_OK ){ 2750 return rc; 2751 } 2752 2753 /* Remove the xxx_node entry. */ 2754 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); 2755 sqlite3_step(pRtree->pDeleteNode); 2756 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ 2757 return rc; 2758 } 2759 2760 /* Remove the xxx_parent entry. */ 2761 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); 2762 sqlite3_step(pRtree->pDeleteParent); 2763 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ 2764 return rc; 2765 } 2766 2767 /* Remove the node from the in-memory hash table and link it into 2768 ** the Rtree.pDeleted list. Its contents will be re-inserted later on. 2769 */ 2770 nodeHashDelete(pRtree, pNode); 2771 pNode->iNode = iHeight; 2772 pNode->pNext = pRtree->pDeleted; 2773 pNode->nRef++; 2774 pRtree->pDeleted = pNode; 2775 2776 return SQLITE_OK; 2777 } 2778 2779 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ 2780 RtreeNode *pParent = pNode->pParent; 2781 int rc = SQLITE_OK; 2782 if( pParent ){ 2783 int ii; 2784 int nCell = NCELL(pNode); 2785 RtreeCell box; /* Bounding box for pNode */ 2786 nodeGetCell(pRtree, pNode, 0, &box); 2787 for(ii=1; ii<nCell; ii++){ 2788 RtreeCell cell; 2789 nodeGetCell(pRtree, pNode, ii, &cell); 2790 cellUnion(pRtree, &box, &cell); 2791 } 2792 box.iRowid = pNode->iNode; 2793 rc = nodeParentIndex(pRtree, pNode, &ii); 2794 if( rc==SQLITE_OK ){ 2795 nodeOverwriteCell(pRtree, pParent, &box, ii); 2796 rc = fixBoundingBox(pRtree, pParent); 2797 } 2798 } 2799 return rc; 2800 } 2801 2802 /* 2803 ** Delete the cell at index iCell of node pNode. After removing the 2804 ** cell, adjust the r-tree data structure if required. 2805 */ 2806 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ 2807 RtreeNode *pParent; 2808 int rc; 2809 2810 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ 2811 return rc; 2812 } 2813 2814 /* Remove the cell from the node. This call just moves bytes around 2815 ** the in-memory node image, so it cannot fail. 2816 */ 2817 nodeDeleteCell(pRtree, pNode, iCell); 2818 2819 /* If the node is not the tree root and now has less than the minimum 2820 ** number of cells, remove it from the tree. Otherwise, update the 2821 ** cell in the parent node so that it tightly contains the updated 2822 ** node. 2823 */ 2824 pParent = pNode->pParent; 2825 assert( pParent || pNode->iNode==1 ); 2826 if( pParent ){ 2827 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){ 2828 rc = removeNode(pRtree, pNode, iHeight); 2829 }else{ 2830 rc = fixBoundingBox(pRtree, pNode); 2831 } 2832 } 2833 2834 return rc; 2835 } 2836 2837 static int Reinsert( 2838 Rtree *pRtree, 2839 RtreeNode *pNode, 2840 RtreeCell *pCell, 2841 int iHeight 2842 ){ 2843 int *aOrder; 2844 int *aSpare; 2845 RtreeCell *aCell; 2846 RtreeDValue *aDistance; 2847 int nCell; 2848 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS]; 2849 int iDim; 2850 int ii; 2851 int rc = SQLITE_OK; 2852 int n; 2853 2854 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS); 2855 2856 nCell = NCELL(pNode)+1; 2857 n = (nCell+1)&(~1); 2858 2859 /* Allocate the buffers used by this operation. The allocation is 2860 ** relinquished before this function returns. 2861 */ 2862 aCell = (RtreeCell *)sqlite3_malloc64(n * ( 2863 sizeof(RtreeCell) + /* aCell array */ 2864 sizeof(int) + /* aOrder array */ 2865 sizeof(int) + /* aSpare array */ 2866 sizeof(RtreeDValue) /* aDistance array */ 2867 )); 2868 if( !aCell ){ 2869 return SQLITE_NOMEM; 2870 } 2871 aOrder = (int *)&aCell[n]; 2872 aSpare = (int *)&aOrder[n]; 2873 aDistance = (RtreeDValue *)&aSpare[n]; 2874 2875 for(ii=0; ii<nCell; ii++){ 2876 if( ii==(nCell-1) ){ 2877 memcpy(&aCell[ii], pCell, sizeof(RtreeCell)); 2878 }else{ 2879 nodeGetCell(pRtree, pNode, ii, &aCell[ii]); 2880 } 2881 aOrder[ii] = ii; 2882 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2883 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); 2884 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); 2885 } 2886 } 2887 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2888 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2)); 2889 } 2890 2891 for(ii=0; ii<nCell; ii++){ 2892 aDistance[ii] = RTREE_ZERO; 2893 for(iDim=0; iDim<pRtree->nDim; iDim++){ 2894 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 2895 DCOORD(aCell[ii].aCoord[iDim*2])); 2896 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); 2897 } 2898 } 2899 2900 SortByDistance(aOrder, nCell, aDistance, aSpare); 2901 nodeZero(pRtree, pNode); 2902 2903 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ 2904 RtreeCell *p = &aCell[aOrder[ii]]; 2905 nodeInsertCell(pRtree, pNode, p); 2906 if( p->iRowid==pCell->iRowid ){ 2907 if( iHeight==0 ){ 2908 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); 2909 }else{ 2910 rc = parentWrite(pRtree, p->iRowid, pNode->iNode); 2911 } 2912 } 2913 } 2914 if( rc==SQLITE_OK ){ 2915 rc = fixBoundingBox(pRtree, pNode); 2916 } 2917 for(; rc==SQLITE_OK && ii<nCell; ii++){ 2918 /* Find a node to store this cell in. pNode->iNode currently contains 2919 ** the height of the sub-tree headed by the cell. 2920 */ 2921 RtreeNode *pInsert; 2922 RtreeCell *p = &aCell[aOrder[ii]]; 2923 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); 2924 if( rc==SQLITE_OK ){ 2925 int rc2; 2926 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); 2927 rc2 = nodeRelease(pRtree, pInsert); 2928 if( rc==SQLITE_OK ){ 2929 rc = rc2; 2930 } 2931 } 2932 } 2933 2934 sqlite3_free(aCell); 2935 return rc; 2936 } 2937 2938 /* 2939 ** Insert cell pCell into node pNode. Node pNode is the head of a 2940 ** subtree iHeight high (leaf nodes have iHeight==0). 2941 */ 2942 static int rtreeInsertCell( 2943 Rtree *pRtree, 2944 RtreeNode *pNode, 2945 RtreeCell *pCell, 2946 int iHeight 2947 ){ 2948 int rc = SQLITE_OK; 2949 if( iHeight>0 ){ 2950 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); 2951 if( pChild ){ 2952 nodeRelease(pRtree, pChild->pParent); 2953 nodeReference(pNode); 2954 pChild->pParent = pNode; 2955 } 2956 } 2957 if( nodeInsertCell(pRtree, pNode, pCell) ){ 2958 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ 2959 rc = SplitNode(pRtree, pNode, pCell, iHeight); 2960 }else{ 2961 pRtree->iReinsertHeight = iHeight; 2962 rc = Reinsert(pRtree, pNode, pCell, iHeight); 2963 } 2964 }else{ 2965 rc = AdjustTree(pRtree, pNode, pCell); 2966 if( rc==SQLITE_OK ){ 2967 if( iHeight==0 ){ 2968 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); 2969 }else{ 2970 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); 2971 } 2972 } 2973 } 2974 return rc; 2975 } 2976 2977 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ 2978 int ii; 2979 int rc = SQLITE_OK; 2980 int nCell = NCELL(pNode); 2981 2982 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){ 2983 RtreeNode *pInsert; 2984 RtreeCell cell; 2985 nodeGetCell(pRtree, pNode, ii, &cell); 2986 2987 /* Find a node to store this cell in. pNode->iNode currently contains 2988 ** the height of the sub-tree headed by the cell. 2989 */ 2990 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert); 2991 if( rc==SQLITE_OK ){ 2992 int rc2; 2993 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode); 2994 rc2 = nodeRelease(pRtree, pInsert); 2995 if( rc==SQLITE_OK ){ 2996 rc = rc2; 2997 } 2998 } 2999 } 3000 return rc; 3001 } 3002 3003 /* 3004 ** Select a currently unused rowid for a new r-tree record. 3005 */ 3006 static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){ 3007 int rc; 3008 sqlite3_bind_null(pRtree->pWriteRowid, 1); 3009 sqlite3_bind_null(pRtree->pWriteRowid, 2); 3010 sqlite3_step(pRtree->pWriteRowid); 3011 rc = sqlite3_reset(pRtree->pWriteRowid); 3012 *piRowid = sqlite3_last_insert_rowid(pRtree->db); 3013 return rc; 3014 } 3015 3016 /* 3017 ** Remove the entry with rowid=iDelete from the r-tree structure. 3018 */ 3019 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){ 3020 int rc; /* Return code */ 3021 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */ 3022 int iCell; /* Index of iDelete cell in pLeaf */ 3023 RtreeNode *pRoot = 0; /* Root node of rtree structure */ 3024 3025 3026 /* Obtain a reference to the root node to initialize Rtree.iDepth */ 3027 rc = nodeAcquire(pRtree, 1, 0, &pRoot); 3028 3029 /* Obtain a reference to the leaf node that contains the entry 3030 ** about to be deleted. 3031 */ 3032 if( rc==SQLITE_OK ){ 3033 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0); 3034 } 3035 3036 #ifdef CORRUPT_DB 3037 assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB ); 3038 #endif 3039 3040 /* Delete the cell in question from the leaf node. */ 3041 if( rc==SQLITE_OK && pLeaf ){ 3042 int rc2; 3043 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell); 3044 if( rc==SQLITE_OK ){ 3045 rc = deleteCell(pRtree, pLeaf, iCell, 0); 3046 } 3047 rc2 = nodeRelease(pRtree, pLeaf); 3048 if( rc==SQLITE_OK ){ 3049 rc = rc2; 3050 } 3051 } 3052 3053 /* Delete the corresponding entry in the <rtree>_rowid table. */ 3054 if( rc==SQLITE_OK ){ 3055 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); 3056 sqlite3_step(pRtree->pDeleteRowid); 3057 rc = sqlite3_reset(pRtree->pDeleteRowid); 3058 } 3059 3060 /* Check if the root node now has exactly one child. If so, remove 3061 ** it, schedule the contents of the child for reinsertion and 3062 ** reduce the tree height by one. 3063 ** 3064 ** This is equivalent to copying the contents of the child into 3065 ** the root node (the operation that Gutman's paper says to perform 3066 ** in this scenario). 3067 */ 3068 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){ 3069 int rc2; 3070 RtreeNode *pChild = 0; 3071 i64 iChild = nodeGetRowid(pRtree, pRoot, 0); 3072 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); 3073 if( rc==SQLITE_OK ){ 3074 rc = removeNode(pRtree, pChild, pRtree->iDepth-1); 3075 } 3076 rc2 = nodeRelease(pRtree, pChild); 3077 if( rc==SQLITE_OK ) rc = rc2; 3078 if( rc==SQLITE_OK ){ 3079 pRtree->iDepth--; 3080 writeInt16(pRoot->zData, pRtree->iDepth); 3081 pRoot->isDirty = 1; 3082 } 3083 } 3084 3085 /* Re-insert the contents of any underfull nodes removed from the tree. */ 3086 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ 3087 if( rc==SQLITE_OK ){ 3088 rc = reinsertNodeContent(pRtree, pLeaf); 3089 } 3090 pRtree->pDeleted = pLeaf->pNext; 3091 pRtree->nNodeRef--; 3092 sqlite3_free(pLeaf); 3093 } 3094 3095 /* Release the reference to the root node. */ 3096 if( rc==SQLITE_OK ){ 3097 rc = nodeRelease(pRtree, pRoot); 3098 }else{ 3099 nodeRelease(pRtree, pRoot); 3100 } 3101 3102 return rc; 3103 } 3104 3105 /* 3106 ** Rounding constants for float->double conversion. 3107 */ 3108 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */ 3109 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */ 3110 3111 #if !defined(SQLITE_RTREE_INT_ONLY) 3112 /* 3113 ** Convert an sqlite3_value into an RtreeValue (presumably a float) 3114 ** while taking care to round toward negative or positive, respectively. 3115 */ 3116 static RtreeValue rtreeValueDown(sqlite3_value *v){ 3117 double d = sqlite3_value_double(v); 3118 float f = (float)d; 3119 if( f>d ){ 3120 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS)); 3121 } 3122 return f; 3123 } 3124 static RtreeValue rtreeValueUp(sqlite3_value *v){ 3125 double d = sqlite3_value_double(v); 3126 float f = (float)d; 3127 if( f<d ){ 3128 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY)); 3129 } 3130 return f; 3131 } 3132 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */ 3133 3134 /* 3135 ** A constraint has failed while inserting a row into an rtree table. 3136 ** Assuming no OOM error occurs, this function sets the error message 3137 ** (at pRtree->base.zErrMsg) to an appropriate value and returns 3138 ** SQLITE_CONSTRAINT. 3139 ** 3140 ** Parameter iCol is the index of the leftmost column involved in the 3141 ** constraint failure. If it is 0, then the constraint that failed is 3142 ** the unique constraint on the id column. Otherwise, it is the rtree 3143 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed. 3144 ** 3145 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT. 3146 */ 3147 static int rtreeConstraintError(Rtree *pRtree, int iCol){ 3148 sqlite3_stmt *pStmt = 0; 3149 char *zSql; 3150 int rc; 3151 3152 assert( iCol==0 || iCol%2 ); 3153 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName); 3154 if( zSql ){ 3155 rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0); 3156 }else{ 3157 rc = SQLITE_NOMEM; 3158 } 3159 sqlite3_free(zSql); 3160 3161 if( rc==SQLITE_OK ){ 3162 if( iCol==0 ){ 3163 const char *zCol = sqlite3_column_name(pStmt, 0); 3164 pRtree->base.zErrMsg = sqlite3_mprintf( 3165 "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol 3166 ); 3167 }else{ 3168 const char *zCol1 = sqlite3_column_name(pStmt, iCol); 3169 const char *zCol2 = sqlite3_column_name(pStmt, iCol+1); 3170 pRtree->base.zErrMsg = sqlite3_mprintf( 3171 "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2 3172 ); 3173 } 3174 } 3175 3176 sqlite3_finalize(pStmt); 3177 return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc); 3178 } 3179 3180 3181 3182 /* 3183 ** The xUpdate method for rtree module virtual tables. 3184 */ 3185 static int rtreeUpdate( 3186 sqlite3_vtab *pVtab, 3187 int nData, 3188 sqlite3_value **aData, 3189 sqlite_int64 *pRowid 3190 ){ 3191 Rtree *pRtree = (Rtree *)pVtab; 3192 int rc = SQLITE_OK; 3193 RtreeCell cell; /* New cell to insert if nData>1 */ 3194 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */ 3195 3196 if( pRtree->nNodeRef ){ 3197 /* Unable to write to the btree while another cursor is reading from it, 3198 ** since the write might do a rebalance which would disrupt the read 3199 ** cursor. */ 3200 return SQLITE_LOCKED_VTAB; 3201 } 3202 rtreeReference(pRtree); 3203 assert(nData>=1); 3204 3205 cell.iRowid = 0; /* Used only to suppress a compiler warning */ 3206 3207 /* Constraint handling. A write operation on an r-tree table may return 3208 ** SQLITE_CONSTRAINT for two reasons: 3209 ** 3210 ** 1. A duplicate rowid value, or 3211 ** 2. The supplied data violates the "x2>=x1" constraint. 3212 ** 3213 ** In the first case, if the conflict-handling mode is REPLACE, then 3214 ** the conflicting row can be removed before proceeding. In the second 3215 ** case, SQLITE_CONSTRAINT must be returned regardless of the 3216 ** conflict-handling mode specified by the user. 3217 */ 3218 if( nData>1 ){ 3219 int ii; 3220 int nn = nData - 4; 3221 3222 if( nn > pRtree->nDim2 ) nn = pRtree->nDim2; 3223 /* Populate the cell.aCoord[] array. The first coordinate is aData[3]. 3224 ** 3225 ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared 3226 ** with "column" that are interpreted as table constraints. 3227 ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5)); 3228 ** This problem was discovered after years of use, so we silently ignore 3229 ** these kinds of misdeclared tables to avoid breaking any legacy. 3230 */ 3231 3232 #ifndef SQLITE_RTREE_INT_ONLY 3233 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ 3234 for(ii=0; ii<nn; ii+=2){ 3235 cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]); 3236 cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]); 3237 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ 3238 rc = rtreeConstraintError(pRtree, ii+1); 3239 goto constraint; 3240 } 3241 } 3242 }else 3243 #endif 3244 { 3245 for(ii=0; ii<nn; ii+=2){ 3246 cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]); 3247 cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]); 3248 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ 3249 rc = rtreeConstraintError(pRtree, ii+1); 3250 goto constraint; 3251 } 3252 } 3253 } 3254 3255 /* If a rowid value was supplied, check if it is already present in 3256 ** the table. If so, the constraint has failed. */ 3257 if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){ 3258 cell.iRowid = sqlite3_value_int64(aData[2]); 3259 if( sqlite3_value_type(aData[0])==SQLITE_NULL 3260 || sqlite3_value_int64(aData[0])!=cell.iRowid 3261 ){ 3262 int steprc; 3263 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); 3264 steprc = sqlite3_step(pRtree->pReadRowid); 3265 rc = sqlite3_reset(pRtree->pReadRowid); 3266 if( SQLITE_ROW==steprc ){ 3267 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){ 3268 rc = rtreeDeleteRowid(pRtree, cell.iRowid); 3269 }else{ 3270 rc = rtreeConstraintError(pRtree, 0); 3271 goto constraint; 3272 } 3273 } 3274 } 3275 bHaveRowid = 1; 3276 } 3277 } 3278 3279 /* If aData[0] is not an SQL NULL value, it is the rowid of a 3280 ** record to delete from the r-tree table. The following block does 3281 ** just that. 3282 */ 3283 if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){ 3284 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0])); 3285 } 3286 3287 /* If the aData[] array contains more than one element, elements 3288 ** (aData[2]..aData[argc-1]) contain a new record to insert into 3289 ** the r-tree structure. 3290 */ 3291 if( rc==SQLITE_OK && nData>1 ){ 3292 /* Insert the new record into the r-tree */ 3293 RtreeNode *pLeaf = 0; 3294 3295 /* Figure out the rowid of the new row. */ 3296 if( bHaveRowid==0 ){ 3297 rc = rtreeNewRowid(pRtree, &cell.iRowid); 3298 } 3299 *pRowid = cell.iRowid; 3300 3301 if( rc==SQLITE_OK ){ 3302 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); 3303 } 3304 if( rc==SQLITE_OK ){ 3305 int rc2; 3306 pRtree->iReinsertHeight = -1; 3307 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); 3308 rc2 = nodeRelease(pRtree, pLeaf); 3309 if( rc==SQLITE_OK ){ 3310 rc = rc2; 3311 } 3312 } 3313 if( rc==SQLITE_OK && pRtree->nAux ){ 3314 sqlite3_stmt *pUp = pRtree->pWriteAux; 3315 int jj; 3316 sqlite3_bind_int64(pUp, 1, *pRowid); 3317 for(jj=0; jj<pRtree->nAux; jj++){ 3318 sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]); 3319 } 3320 sqlite3_step(pUp); 3321 rc = sqlite3_reset(pUp); 3322 } 3323 } 3324 3325 constraint: 3326 rtreeRelease(pRtree); 3327 return rc; 3328 } 3329 3330 /* 3331 ** Called when a transaction starts. 3332 */ 3333 static int rtreeBeginTransaction(sqlite3_vtab *pVtab){ 3334 Rtree *pRtree = (Rtree *)pVtab; 3335 assert( pRtree->inWrTrans==0 ); 3336 pRtree->inWrTrans++; 3337 return SQLITE_OK; 3338 } 3339 3340 /* 3341 ** Called when a transaction completes (either by COMMIT or ROLLBACK). 3342 ** The sqlite3_blob object should be released at this point. 3343 */ 3344 static int rtreeEndTransaction(sqlite3_vtab *pVtab){ 3345 Rtree *pRtree = (Rtree *)pVtab; 3346 pRtree->inWrTrans = 0; 3347 nodeBlobReset(pRtree); 3348 return SQLITE_OK; 3349 } 3350 3351 /* 3352 ** The xRename method for rtree module virtual tables. 3353 */ 3354 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ 3355 Rtree *pRtree = (Rtree *)pVtab; 3356 int rc = SQLITE_NOMEM; 3357 char *zSql = sqlite3_mprintf( 3358 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" 3359 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" 3360 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" 3361 , pRtree->zDb, pRtree->zName, zNewName 3362 , pRtree->zDb, pRtree->zName, zNewName 3363 , pRtree->zDb, pRtree->zName, zNewName 3364 ); 3365 if( zSql ){ 3366 nodeBlobReset(pRtree); 3367 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); 3368 sqlite3_free(zSql); 3369 } 3370 return rc; 3371 } 3372 3373 /* 3374 ** The xSavepoint method. 3375 ** 3376 ** This module does not need to do anything to support savepoints. However, 3377 ** it uses this hook to close any open blob handle. This is done because a 3378 ** DROP TABLE command - which fortunately always opens a savepoint - cannot 3379 ** succeed if there are any open blob handles. i.e. if the blob handle were 3380 ** not closed here, the following would fail: 3381 ** 3382 ** BEGIN; 3383 ** INSERT INTO rtree... 3384 ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED 3385 ** COMMIT; 3386 */ 3387 static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){ 3388 Rtree *pRtree = (Rtree *)pVtab; 3389 u8 iwt = pRtree->inWrTrans; 3390 UNUSED_PARAMETER(iSavepoint); 3391 pRtree->inWrTrans = 0; 3392 nodeBlobReset(pRtree); 3393 pRtree->inWrTrans = iwt; 3394 return SQLITE_OK; 3395 } 3396 3397 /* 3398 ** This function populates the pRtree->nRowEst variable with an estimate 3399 ** of the number of rows in the virtual table. If possible, this is based 3400 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST. 3401 */ 3402 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){ 3403 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'"; 3404 char *zSql; 3405 sqlite3_stmt *p; 3406 int rc; 3407 i64 nRow = 0; 3408 3409 rc = sqlite3_table_column_metadata( 3410 db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0 3411 ); 3412 if( rc!=SQLITE_OK ){ 3413 pRtree->nRowEst = RTREE_DEFAULT_ROWEST; 3414 return rc==SQLITE_ERROR ? SQLITE_OK : rc; 3415 } 3416 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName); 3417 if( zSql==0 ){ 3418 rc = SQLITE_NOMEM; 3419 }else{ 3420 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0); 3421 if( rc==SQLITE_OK ){ 3422 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0); 3423 rc = sqlite3_finalize(p); 3424 }else if( rc!=SQLITE_NOMEM ){ 3425 rc = SQLITE_OK; 3426 } 3427 3428 if( rc==SQLITE_OK ){ 3429 if( nRow==0 ){ 3430 pRtree->nRowEst = RTREE_DEFAULT_ROWEST; 3431 }else{ 3432 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST); 3433 } 3434 } 3435 sqlite3_free(zSql); 3436 } 3437 3438 return rc; 3439 } 3440 3441 3442 /* 3443 ** Return true if zName is the extension on one of the shadow tables used 3444 ** by this module. 3445 */ 3446 static int rtreeShadowName(const char *zName){ 3447 static const char *azName[] = { 3448 "node", "parent", "rowid" 3449 }; 3450 unsigned int i; 3451 for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){ 3452 if( sqlite3_stricmp(zName, azName[i])==0 ) return 1; 3453 } 3454 return 0; 3455 } 3456 3457 static sqlite3_module rtreeModule = { 3458 3, /* iVersion */ 3459 rtreeCreate, /* xCreate - create a table */ 3460 rtreeConnect, /* xConnect - connect to an existing table */ 3461 rtreeBestIndex, /* xBestIndex - Determine search strategy */ 3462 rtreeDisconnect, /* xDisconnect - Disconnect from a table */ 3463 rtreeDestroy, /* xDestroy - Drop a table */ 3464 rtreeOpen, /* xOpen - open a cursor */ 3465 rtreeClose, /* xClose - close a cursor */ 3466 rtreeFilter, /* xFilter - configure scan constraints */ 3467 rtreeNext, /* xNext - advance a cursor */ 3468 rtreeEof, /* xEof */ 3469 rtreeColumn, /* xColumn - read data */ 3470 rtreeRowid, /* xRowid - read data */ 3471 rtreeUpdate, /* xUpdate - write data */ 3472 rtreeBeginTransaction, /* xBegin - begin transaction */ 3473 rtreeEndTransaction, /* xSync - sync transaction */ 3474 rtreeEndTransaction, /* xCommit - commit transaction */ 3475 rtreeEndTransaction, /* xRollback - rollback transaction */ 3476 0, /* xFindFunction - function overloading */ 3477 rtreeRename, /* xRename - rename the table */ 3478 rtreeSavepoint, /* xSavepoint */ 3479 0, /* xRelease */ 3480 0, /* xRollbackTo */ 3481 rtreeShadowName /* xShadowName */ 3482 }; 3483 3484 static int rtreeSqlInit( 3485 Rtree *pRtree, 3486 sqlite3 *db, 3487 const char *zDb, 3488 const char *zPrefix, 3489 int isCreate 3490 ){ 3491 int rc = SQLITE_OK; 3492 3493 #define N_STATEMENT 8 3494 static const char *azSql[N_STATEMENT] = { 3495 /* Write the xxx_node table */ 3496 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)", 3497 "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1", 3498 3499 /* Read and write the xxx_rowid table */ 3500 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1", 3501 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)", 3502 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1", 3503 3504 /* Read and write the xxx_parent table */ 3505 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1", 3506 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)", 3507 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1" 3508 }; 3509 sqlite3_stmt **appStmt[N_STATEMENT]; 3510 int i; 3511 const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB; 3512 3513 pRtree->db = db; 3514 3515 if( isCreate ){ 3516 char *zCreate; 3517 sqlite3_str *p = sqlite3_str_new(db); 3518 int ii; 3519 sqlite3_str_appendf(p, 3520 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno", 3521 zDb, zPrefix); 3522 for(ii=0; ii<pRtree->nAux; ii++){ 3523 sqlite3_str_appendf(p,",a%d",ii); 3524 } 3525 sqlite3_str_appendf(p, 3526 ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);", 3527 zDb, zPrefix); 3528 sqlite3_str_appendf(p, 3529 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);", 3530 zDb, zPrefix); 3531 sqlite3_str_appendf(p, 3532 "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))", 3533 zDb, zPrefix, pRtree->iNodeSize); 3534 zCreate = sqlite3_str_finish(p); 3535 if( !zCreate ){ 3536 return SQLITE_NOMEM; 3537 } 3538 rc = sqlite3_exec(db, zCreate, 0, 0, 0); 3539 sqlite3_free(zCreate); 3540 if( rc!=SQLITE_OK ){ 3541 return rc; 3542 } 3543 } 3544 3545 appStmt[0] = &pRtree->pWriteNode; 3546 appStmt[1] = &pRtree->pDeleteNode; 3547 appStmt[2] = &pRtree->pReadRowid; 3548 appStmt[3] = &pRtree->pWriteRowid; 3549 appStmt[4] = &pRtree->pDeleteRowid; 3550 appStmt[5] = &pRtree->pReadParent; 3551 appStmt[6] = &pRtree->pWriteParent; 3552 appStmt[7] = &pRtree->pDeleteParent; 3553 3554 rc = rtreeQueryStat1(db, pRtree); 3555 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){ 3556 char *zSql; 3557 const char *zFormat; 3558 if( i!=3 || pRtree->nAux==0 ){ 3559 zFormat = azSql[i]; 3560 }else { 3561 /* An UPSERT is very slightly slower than REPLACE, but it is needed 3562 ** if there are auxiliary columns */ 3563 zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)" 3564 "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno"; 3565 } 3566 zSql = sqlite3_mprintf(zFormat, zDb, zPrefix); 3567 if( zSql ){ 3568 rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); 3569 }else{ 3570 rc = SQLITE_NOMEM; 3571 } 3572 sqlite3_free(zSql); 3573 } 3574 if( pRtree->nAux ){ 3575 pRtree->zReadAuxSql = sqlite3_mprintf( 3576 "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1", 3577 zDb, zPrefix); 3578 if( pRtree->zReadAuxSql==0 ){ 3579 rc = SQLITE_NOMEM; 3580 }else{ 3581 sqlite3_str *p = sqlite3_str_new(db); 3582 int ii; 3583 char *zSql; 3584 sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix); 3585 for(ii=0; ii<pRtree->nAux; ii++){ 3586 if( ii ) sqlite3_str_append(p, ",", 1); 3587 if( ii<pRtree->nAuxNotNull ){ 3588 sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii); 3589 }else{ 3590 sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2); 3591 } 3592 } 3593 sqlite3_str_appendf(p, " WHERE rowid=?1"); 3594 zSql = sqlite3_str_finish(p); 3595 if( zSql==0 ){ 3596 rc = SQLITE_NOMEM; 3597 }else{ 3598 rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); 3599 sqlite3_free(zSql); 3600 } 3601 } 3602 } 3603 3604 return rc; 3605 } 3606 3607 /* 3608 ** The second argument to this function contains the text of an SQL statement 3609 ** that returns a single integer value. The statement is compiled and executed 3610 ** using database connection db. If successful, the integer value returned 3611 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error 3612 ** code is returned and the value of *piVal after returning is not defined. 3613 */ 3614 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){ 3615 int rc = SQLITE_NOMEM; 3616 if( zSql ){ 3617 sqlite3_stmt *pStmt = 0; 3618 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3619 if( rc==SQLITE_OK ){ 3620 if( SQLITE_ROW==sqlite3_step(pStmt) ){ 3621 *piVal = sqlite3_column_int(pStmt, 0); 3622 } 3623 rc = sqlite3_finalize(pStmt); 3624 } 3625 } 3626 return rc; 3627 } 3628 3629 /* 3630 ** This function is called from within the xConnect() or xCreate() method to 3631 ** determine the node-size used by the rtree table being created or connected 3632 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned. 3633 ** Otherwise, an SQLite error code is returned. 3634 ** 3635 ** If this function is being called as part of an xConnect(), then the rtree 3636 ** table already exists. In this case the node-size is determined by inspecting 3637 ** the root node of the tree. 3638 ** 3639 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 3640 ** This ensures that each node is stored on a single database page. If the 3641 ** database page-size is so large that more than RTREE_MAXCELLS entries 3642 ** would fit in a single node, use a smaller node-size. 3643 */ 3644 static int getNodeSize( 3645 sqlite3 *db, /* Database handle */ 3646 Rtree *pRtree, /* Rtree handle */ 3647 int isCreate, /* True for xCreate, false for xConnect */ 3648 char **pzErr /* OUT: Error message, if any */ 3649 ){ 3650 int rc; 3651 char *zSql; 3652 if( isCreate ){ 3653 int iPageSize = 0; 3654 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb); 3655 rc = getIntFromStmt(db, zSql, &iPageSize); 3656 if( rc==SQLITE_OK ){ 3657 pRtree->iNodeSize = iPageSize-64; 3658 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){ 3659 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; 3660 } 3661 }else{ 3662 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 3663 } 3664 }else{ 3665 zSql = sqlite3_mprintf( 3666 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1", 3667 pRtree->zDb, pRtree->zName 3668 ); 3669 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize); 3670 if( rc!=SQLITE_OK ){ 3671 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 3672 }else if( pRtree->iNodeSize<(512-64) ){ 3673 rc = SQLITE_CORRUPT_VTAB; 3674 RTREE_IS_CORRUPT(pRtree); 3675 *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"", 3676 pRtree->zName); 3677 } 3678 } 3679 3680 sqlite3_free(zSql); 3681 return rc; 3682 } 3683 3684 /* 3685 ** Return the length of a token 3686 */ 3687 static int rtreeTokenLength(const char *z){ 3688 int dummy = 0; 3689 return sqlite3GetToken((const unsigned char*)z,&dummy); 3690 } 3691 3692 /* 3693 ** This function is the implementation of both the xConnect and xCreate 3694 ** methods of the r-tree virtual table. 3695 ** 3696 ** argv[0] -> module name 3697 ** argv[1] -> database name 3698 ** argv[2] -> table name 3699 ** argv[...] -> column names... 3700 */ 3701 static int rtreeInit( 3702 sqlite3 *db, /* Database connection */ 3703 void *pAux, /* One of the RTREE_COORD_* constants */ 3704 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ 3705 sqlite3_vtab **ppVtab, /* OUT: New virtual table */ 3706 char **pzErr, /* OUT: Error message, if any */ 3707 int isCreate /* True for xCreate, false for xConnect */ 3708 ){ 3709 int rc = SQLITE_OK; 3710 Rtree *pRtree; 3711 int nDb; /* Length of string argv[1] */ 3712 int nName; /* Length of string argv[2] */ 3713 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32); 3714 sqlite3_str *pSql; 3715 char *zSql; 3716 int ii = 4; 3717 int iErr; 3718 3719 const char *aErrMsg[] = { 3720 0, /* 0 */ 3721 "Wrong number of columns for an rtree table", /* 1 */ 3722 "Too few columns for an rtree table", /* 2 */ 3723 "Too many columns for an rtree table", /* 3 */ 3724 "Auxiliary rtree columns must be last" /* 4 */ 3725 }; 3726 3727 assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */ 3728 if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){ 3729 *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]); 3730 return SQLITE_ERROR; 3731 } 3732 3733 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); 3734 3735 /* Allocate the sqlite3_vtab structure */ 3736 nDb = (int)strlen(argv[1]); 3737 nName = (int)strlen(argv[2]); 3738 pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); 3739 if( !pRtree ){ 3740 return SQLITE_NOMEM; 3741 } 3742 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); 3743 pRtree->nBusy = 1; 3744 pRtree->base.pModule = &rtreeModule; 3745 pRtree->zDb = (char *)&pRtree[1]; 3746 pRtree->zName = &pRtree->zDb[nDb+1]; 3747 pRtree->eCoordType = (u8)eCoordType; 3748 memcpy(pRtree->zDb, argv[1], nDb); 3749 memcpy(pRtree->zName, argv[2], nName); 3750 3751 3752 /* Create/Connect to the underlying relational database schema. If 3753 ** that is successful, call sqlite3_declare_vtab() to configure 3754 ** the r-tree table schema. 3755 */ 3756 pSql = sqlite3_str_new(db); 3757 sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT", 3758 rtreeTokenLength(argv[3]), argv[3]); 3759 for(ii=4; ii<argc; ii++){ 3760 const char *zArg = argv[ii]; 3761 if( zArg[0]=='+' ){ 3762 pRtree->nAux++; 3763 sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1); 3764 }else if( pRtree->nAux>0 ){ 3765 break; 3766 }else{ 3767 static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"}; 3768 pRtree->nDim2++; 3769 sqlite3_str_appendf(pSql, azFormat[eCoordType], 3770 rtreeTokenLength(zArg), zArg); 3771 } 3772 } 3773 sqlite3_str_appendf(pSql, ");"); 3774 zSql = sqlite3_str_finish(pSql); 3775 if( !zSql ){ 3776 rc = SQLITE_NOMEM; 3777 }else if( ii<argc ){ 3778 *pzErr = sqlite3_mprintf("%s", aErrMsg[4]); 3779 rc = SQLITE_ERROR; 3780 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){ 3781 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 3782 } 3783 sqlite3_free(zSql); 3784 if( rc ) goto rtreeInit_fail; 3785 pRtree->nDim = pRtree->nDim2/2; 3786 if( pRtree->nDim<1 ){ 3787 iErr = 2; 3788 }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){ 3789 iErr = 3; 3790 }else if( pRtree->nDim2 % 2 ){ 3791 iErr = 1; 3792 }else{ 3793 iErr = 0; 3794 } 3795 if( iErr ){ 3796 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); 3797 goto rtreeInit_fail; 3798 } 3799 pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; 3800 3801 /* Figure out the node size to use. */ 3802 rc = getNodeSize(db, pRtree, isCreate, pzErr); 3803 if( rc ) goto rtreeInit_fail; 3804 rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate); 3805 if( rc ){ 3806 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); 3807 goto rtreeInit_fail; 3808 } 3809 3810 *ppVtab = (sqlite3_vtab *)pRtree; 3811 return SQLITE_OK; 3812 3813 rtreeInit_fail: 3814 if( rc==SQLITE_OK ) rc = SQLITE_ERROR; 3815 assert( *ppVtab==0 ); 3816 assert( pRtree->nBusy==1 ); 3817 rtreeRelease(pRtree); 3818 return rc; 3819 } 3820 3821 3822 /* 3823 ** Implementation of a scalar function that decodes r-tree nodes to 3824 ** human readable strings. This can be used for debugging and analysis. 3825 ** 3826 ** The scalar function takes two arguments: (1) the number of dimensions 3827 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing 3828 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to 3829 ** deserialize all nodes, a statement like: 3830 ** 3831 ** SELECT rtreenode(2, data) FROM rt_node; 3832 ** 3833 ** The human readable string takes the form of a Tcl list with one 3834 ** entry for each cell in the r-tree node. Each entry is itself a 3835 ** list, containing the 8-byte rowid/pageno followed by the 3836 ** <num-dimension>*2 coordinates. 3837 */ 3838 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ 3839 RtreeNode node; 3840 Rtree tree; 3841 int ii; 3842 int nData; 3843 int errCode; 3844 sqlite3_str *pOut; 3845 3846 UNUSED_PARAMETER(nArg); 3847 memset(&node, 0, sizeof(RtreeNode)); 3848 memset(&tree, 0, sizeof(Rtree)); 3849 tree.nDim = (u8)sqlite3_value_int(apArg[0]); 3850 if( tree.nDim<1 || tree.nDim>5 ) return; 3851 tree.nDim2 = tree.nDim*2; 3852 tree.nBytesPerCell = 8 + 8 * tree.nDim; 3853 node.zData = (u8 *)sqlite3_value_blob(apArg[1]); 3854 nData = sqlite3_value_bytes(apArg[1]); 3855 if( nData<4 ) return; 3856 if( nData<NCELL(&node)*tree.nBytesPerCell ) return; 3857 3858 pOut = sqlite3_str_new(0); 3859 for(ii=0; ii<NCELL(&node); ii++){ 3860 RtreeCell cell; 3861 int jj; 3862 3863 nodeGetCell(&tree, &node, ii, &cell); 3864 if( ii>0 ) sqlite3_str_append(pOut, " ", 1); 3865 sqlite3_str_appendf(pOut, "{%lld", cell.iRowid); 3866 for(jj=0; jj<tree.nDim2; jj++){ 3867 #ifndef SQLITE_RTREE_INT_ONLY 3868 sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f); 3869 #else 3870 sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i); 3871 #endif 3872 } 3873 sqlite3_str_append(pOut, "}", 1); 3874 } 3875 errCode = sqlite3_str_errcode(pOut); 3876 sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free); 3877 sqlite3_result_error_code(ctx, errCode); 3878 } 3879 3880 /* This routine implements an SQL function that returns the "depth" parameter 3881 ** from the front of a blob that is an r-tree node. For example: 3882 ** 3883 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1; 3884 ** 3885 ** The depth value is 0 for all nodes other than the root node, and the root 3886 ** node always has nodeno=1, so the example above is the primary use for this 3887 ** routine. This routine is intended for testing and analysis only. 3888 */ 3889 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ 3890 UNUSED_PARAMETER(nArg); 3891 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 3892 || sqlite3_value_bytes(apArg[0])<2 3893 ){ 3894 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 3895 }else{ 3896 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]); 3897 sqlite3_result_int(ctx, readInt16(zBlob)); 3898 } 3899 } 3900 3901 /* 3902 ** Context object passed between the various routines that make up the 3903 ** implementation of integrity-check function rtreecheck(). 3904 */ 3905 typedef struct RtreeCheck RtreeCheck; 3906 struct RtreeCheck { 3907 sqlite3 *db; /* Database handle */ 3908 const char *zDb; /* Database containing rtree table */ 3909 const char *zTab; /* Name of rtree table */ 3910 int bInt; /* True for rtree_i32 table */ 3911 int nDim; /* Number of dimensions for this rtree tbl */ 3912 sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */ 3913 sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */ 3914 int nLeaf; /* Number of leaf cells in table */ 3915 int nNonLeaf; /* Number of non-leaf cells in table */ 3916 int rc; /* Return code */ 3917 char *zReport; /* Message to report */ 3918 int nErr; /* Number of lines in zReport */ 3919 }; 3920 3921 #define RTREE_CHECK_MAX_ERROR 100 3922 3923 /* 3924 ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error, 3925 ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code. 3926 */ 3927 static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){ 3928 int rc = sqlite3_reset(pStmt); 3929 if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc; 3930 } 3931 3932 /* 3933 ** The second and subsequent arguments to this function are a format string 3934 ** and printf style arguments. This function formats the string and attempts 3935 ** to compile it as an SQL statement. 3936 ** 3937 ** If successful, a pointer to the new SQL statement is returned. Otherwise, 3938 ** NULL is returned and an error code left in RtreeCheck.rc. 3939 */ 3940 static sqlite3_stmt *rtreeCheckPrepare( 3941 RtreeCheck *pCheck, /* RtreeCheck object */ 3942 const char *zFmt, ... /* Format string and trailing args */ 3943 ){ 3944 va_list ap; 3945 char *z; 3946 sqlite3_stmt *pRet = 0; 3947 3948 va_start(ap, zFmt); 3949 z = sqlite3_vmprintf(zFmt, ap); 3950 3951 if( pCheck->rc==SQLITE_OK ){ 3952 if( z==0 ){ 3953 pCheck->rc = SQLITE_NOMEM; 3954 }else{ 3955 pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0); 3956 } 3957 } 3958 3959 sqlite3_free(z); 3960 va_end(ap); 3961 return pRet; 3962 } 3963 3964 /* 3965 ** The second and subsequent arguments to this function are a printf() 3966 ** style format string and arguments. This function formats the string and 3967 ** appends it to the report being accumuated in pCheck. 3968 */ 3969 static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){ 3970 va_list ap; 3971 va_start(ap, zFmt); 3972 if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){ 3973 char *z = sqlite3_vmprintf(zFmt, ap); 3974 if( z==0 ){ 3975 pCheck->rc = SQLITE_NOMEM; 3976 }else{ 3977 pCheck->zReport = sqlite3_mprintf("%z%s%z", 3978 pCheck->zReport, (pCheck->zReport ? "\n" : ""), z 3979 ); 3980 if( pCheck->zReport==0 ){ 3981 pCheck->rc = SQLITE_NOMEM; 3982 } 3983 } 3984 pCheck->nErr++; 3985 } 3986 va_end(ap); 3987 } 3988 3989 /* 3990 ** This function is a no-op if there is already an error code stored 3991 ** in the RtreeCheck object indicated by the first argument. NULL is 3992 ** returned in this case. 3993 ** 3994 ** Otherwise, the contents of rtree table node iNode are loaded from 3995 ** the database and copied into a buffer obtained from sqlite3_malloc(). 3996 ** If no error occurs, a pointer to the buffer is returned and (*pnNode) 3997 ** is set to the size of the buffer in bytes. 3998 ** 3999 ** Or, if an error does occur, NULL is returned and an error code left 4000 ** in the RtreeCheck object. The final value of *pnNode is undefined in 4001 ** this case. 4002 */ 4003 static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){ 4004 u8 *pRet = 0; /* Return value */ 4005 4006 if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){ 4007 pCheck->pGetNode = rtreeCheckPrepare(pCheck, 4008 "SELECT data FROM %Q.'%q_node' WHERE nodeno=?", 4009 pCheck->zDb, pCheck->zTab 4010 ); 4011 } 4012 4013 if( pCheck->rc==SQLITE_OK ){ 4014 sqlite3_bind_int64(pCheck->pGetNode, 1, iNode); 4015 if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){ 4016 int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0); 4017 const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0); 4018 pRet = sqlite3_malloc64(nNode); 4019 if( pRet==0 ){ 4020 pCheck->rc = SQLITE_NOMEM; 4021 }else{ 4022 memcpy(pRet, pNode, nNode); 4023 *pnNode = nNode; 4024 } 4025 } 4026 rtreeCheckReset(pCheck, pCheck->pGetNode); 4027 if( pCheck->rc==SQLITE_OK && pRet==0 ){ 4028 rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode); 4029 } 4030 } 4031 4032 return pRet; 4033 } 4034 4035 /* 4036 ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid 4037 ** (if bLeaf==1) table contains a specified entry. The schemas of the 4038 ** two tables are: 4039 ** 4040 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) 4041 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...) 4042 ** 4043 ** In both cases, this function checks that there exists an entry with 4044 ** IPK value iKey and the second column set to iVal. 4045 ** 4046 */ 4047 static void rtreeCheckMapping( 4048 RtreeCheck *pCheck, /* RtreeCheck object */ 4049 int bLeaf, /* True for a leaf cell, false for interior */ 4050 i64 iKey, /* Key for mapping */ 4051 i64 iVal /* Expected value for mapping */ 4052 ){ 4053 int rc; 4054 sqlite3_stmt *pStmt; 4055 const char *azSql[2] = { 4056 "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1", 4057 "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1" 4058 }; 4059 4060 assert( bLeaf==0 || bLeaf==1 ); 4061 if( pCheck->aCheckMapping[bLeaf]==0 ){ 4062 pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck, 4063 azSql[bLeaf], pCheck->zDb, pCheck->zTab 4064 ); 4065 } 4066 if( pCheck->rc!=SQLITE_OK ) return; 4067 4068 pStmt = pCheck->aCheckMapping[bLeaf]; 4069 sqlite3_bind_int64(pStmt, 1, iKey); 4070 rc = sqlite3_step(pStmt); 4071 if( rc==SQLITE_DONE ){ 4072 rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table", 4073 iKey, iVal, (bLeaf ? "%_rowid" : "%_parent") 4074 ); 4075 }else if( rc==SQLITE_ROW ){ 4076 i64 ii = sqlite3_column_int64(pStmt, 0); 4077 if( ii!=iVal ){ 4078 rtreeCheckAppendMsg(pCheck, 4079 "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)", 4080 iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal 4081 ); 4082 } 4083 } 4084 rtreeCheckReset(pCheck, pStmt); 4085 } 4086 4087 /* 4088 ** Argument pCell points to an array of coordinates stored on an rtree page. 4089 ** This function checks that the coordinates are internally consistent (no 4090 ** x1>x2 conditions) and adds an error message to the RtreeCheck object 4091 ** if they are not. 4092 ** 4093 ** Additionally, if pParent is not NULL, then it is assumed to point to 4094 ** the array of coordinates on the parent page that bound the page 4095 ** containing pCell. In this case it is also verified that the two 4096 ** sets of coordinates are mutually consistent and an error message added 4097 ** to the RtreeCheck object if they are not. 4098 */ 4099 static void rtreeCheckCellCoord( 4100 RtreeCheck *pCheck, 4101 i64 iNode, /* Node id to use in error messages */ 4102 int iCell, /* Cell number to use in error messages */ 4103 u8 *pCell, /* Pointer to cell coordinates */ 4104 u8 *pParent /* Pointer to parent coordinates */ 4105 ){ 4106 RtreeCoord c1, c2; 4107 RtreeCoord p1, p2; 4108 int i; 4109 4110 for(i=0; i<pCheck->nDim; i++){ 4111 readCoord(&pCell[4*2*i], &c1); 4112 readCoord(&pCell[4*(2*i + 1)], &c2); 4113 4114 /* printf("%e, %e\n", c1.u.f, c2.u.f); */ 4115 if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){ 4116 rtreeCheckAppendMsg(pCheck, 4117 "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode 4118 ); 4119 } 4120 4121 if( pParent ){ 4122 readCoord(&pParent[4*2*i], &p1); 4123 readCoord(&pParent[4*(2*i + 1)], &p2); 4124 4125 if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f) 4126 || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f) 4127 ){ 4128 rtreeCheckAppendMsg(pCheck, 4129 "Dimension %d of cell %d on node %lld is corrupt relative to parent" 4130 , i, iCell, iNode 4131 ); 4132 } 4133 } 4134 } 4135 } 4136 4137 /* 4138 ** Run rtreecheck() checks on node iNode, which is at depth iDepth within 4139 ** the r-tree structure. Argument aParent points to the array of coordinates 4140 ** that bound node iNode on the parent node. 4141 ** 4142 ** If any problems are discovered, an error message is appended to the 4143 ** report accumulated in the RtreeCheck object. 4144 */ 4145 static void rtreeCheckNode( 4146 RtreeCheck *pCheck, 4147 int iDepth, /* Depth of iNode (0==leaf) */ 4148 u8 *aParent, /* Buffer containing parent coords */ 4149 i64 iNode /* Node to check */ 4150 ){ 4151 u8 *aNode = 0; 4152 int nNode = 0; 4153 4154 assert( iNode==1 || aParent!=0 ); 4155 assert( pCheck->nDim>0 ); 4156 4157 aNode = rtreeCheckGetNode(pCheck, iNode, &nNode); 4158 if( aNode ){ 4159 if( nNode<4 ){ 4160 rtreeCheckAppendMsg(pCheck, 4161 "Node %lld is too small (%d bytes)", iNode, nNode 4162 ); 4163 }else{ 4164 int nCell; /* Number of cells on page */ 4165 int i; /* Used to iterate through cells */ 4166 if( aParent==0 ){ 4167 iDepth = readInt16(aNode); 4168 if( iDepth>RTREE_MAX_DEPTH ){ 4169 rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth); 4170 sqlite3_free(aNode); 4171 return; 4172 } 4173 } 4174 nCell = readInt16(&aNode[2]); 4175 if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){ 4176 rtreeCheckAppendMsg(pCheck, 4177 "Node %lld is too small for cell count of %d (%d bytes)", 4178 iNode, nCell, nNode 4179 ); 4180 }else{ 4181 for(i=0; i<nCell; i++){ 4182 u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)]; 4183 i64 iVal = readInt64(pCell); 4184 rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent); 4185 4186 if( iDepth>0 ){ 4187 rtreeCheckMapping(pCheck, 0, iVal, iNode); 4188 rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal); 4189 pCheck->nNonLeaf++; 4190 }else{ 4191 rtreeCheckMapping(pCheck, 1, iVal, iNode); 4192 pCheck->nLeaf++; 4193 } 4194 } 4195 } 4196 } 4197 sqlite3_free(aNode); 4198 } 4199 } 4200 4201 /* 4202 ** The second argument to this function must be either "_rowid" or 4203 ** "_parent". This function checks that the number of entries in the 4204 ** %_rowid or %_parent table is exactly nExpect. If not, it adds 4205 ** an error message to the report in the RtreeCheck object indicated 4206 ** by the first argument. 4207 */ 4208 static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){ 4209 if( pCheck->rc==SQLITE_OK ){ 4210 sqlite3_stmt *pCount; 4211 pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'", 4212 pCheck->zDb, pCheck->zTab, zTbl 4213 ); 4214 if( pCount ){ 4215 if( sqlite3_step(pCount)==SQLITE_ROW ){ 4216 i64 nActual = sqlite3_column_int64(pCount, 0); 4217 if( nActual!=nExpect ){ 4218 rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table" 4219 " - expected %lld, actual %lld" , zTbl, nExpect, nActual 4220 ); 4221 } 4222 } 4223 pCheck->rc = sqlite3_finalize(pCount); 4224 } 4225 } 4226 } 4227 4228 /* 4229 ** This function does the bulk of the work for the rtree integrity-check. 4230 ** It is called by rtreecheck(), which is the SQL function implementation. 4231 */ 4232 static int rtreeCheckTable( 4233 sqlite3 *db, /* Database handle to access db through */ 4234 const char *zDb, /* Name of db ("main", "temp" etc.) */ 4235 const char *zTab, /* Name of rtree table to check */ 4236 char **pzReport /* OUT: sqlite3_malloc'd report text */ 4237 ){ 4238 RtreeCheck check; /* Common context for various routines */ 4239 sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */ 4240 int bEnd = 0; /* True if transaction should be closed */ 4241 int nAux = 0; /* Number of extra columns. */ 4242 4243 /* Initialize the context object */ 4244 memset(&check, 0, sizeof(check)); 4245 check.db = db; 4246 check.zDb = zDb; 4247 check.zTab = zTab; 4248 4249 /* If there is not already an open transaction, open one now. This is 4250 ** to ensure that the queries run as part of this integrity-check operate 4251 ** on a consistent snapshot. */ 4252 if( sqlite3_get_autocommit(db) ){ 4253 check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); 4254 bEnd = 1; 4255 } 4256 4257 /* Find the number of auxiliary columns */ 4258 if( check.rc==SQLITE_OK ){ 4259 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab); 4260 if( pStmt ){ 4261 nAux = sqlite3_column_count(pStmt) - 2; 4262 sqlite3_finalize(pStmt); 4263 } 4264 check.rc = SQLITE_OK; 4265 } 4266 4267 /* Find number of dimensions in the rtree table. */ 4268 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab); 4269 if( pStmt ){ 4270 int rc; 4271 check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2; 4272 if( check.nDim<1 ){ 4273 rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree"); 4274 }else if( SQLITE_ROW==sqlite3_step(pStmt) ){ 4275 check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER); 4276 } 4277 rc = sqlite3_finalize(pStmt); 4278 if( rc!=SQLITE_CORRUPT ) check.rc = rc; 4279 } 4280 4281 /* Do the actual integrity-check */ 4282 if( check.nDim>=1 ){ 4283 if( check.rc==SQLITE_OK ){ 4284 rtreeCheckNode(&check, 0, 0, 1); 4285 } 4286 rtreeCheckCount(&check, "_rowid", check.nLeaf); 4287 rtreeCheckCount(&check, "_parent", check.nNonLeaf); 4288 } 4289 4290 /* Finalize SQL statements used by the integrity-check */ 4291 sqlite3_finalize(check.pGetNode); 4292 sqlite3_finalize(check.aCheckMapping[0]); 4293 sqlite3_finalize(check.aCheckMapping[1]); 4294 4295 /* If one was opened, close the transaction */ 4296 if( bEnd ){ 4297 int rc = sqlite3_exec(db, "END", 0, 0, 0); 4298 if( check.rc==SQLITE_OK ) check.rc = rc; 4299 } 4300 *pzReport = check.zReport; 4301 return check.rc; 4302 } 4303 4304 /* 4305 ** Usage: 4306 ** 4307 ** rtreecheck(<rtree-table>); 4308 ** rtreecheck(<database>, <rtree-table>); 4309 ** 4310 ** Invoking this SQL function runs an integrity-check on the named rtree 4311 ** table. The integrity-check verifies the following: 4312 ** 4313 ** 1. For each cell in the r-tree structure (%_node table), that: 4314 ** 4315 ** a) for each dimension, (coord1 <= coord2). 4316 ** 4317 ** b) unless the cell is on the root node, that the cell is bounded 4318 ** by the parent cell on the parent node. 4319 ** 4320 ** c) for leaf nodes, that there is an entry in the %_rowid 4321 ** table corresponding to the cell's rowid value that 4322 ** points to the correct node. 4323 ** 4324 ** d) for cells on non-leaf nodes, that there is an entry in the 4325 ** %_parent table mapping from the cell's child node to the 4326 ** node that it resides on. 4327 ** 4328 ** 2. That there are the same number of entries in the %_rowid table 4329 ** as there are leaf cells in the r-tree structure, and that there 4330 ** is a leaf cell that corresponds to each entry in the %_rowid table. 4331 ** 4332 ** 3. That there are the same number of entries in the %_parent table 4333 ** as there are non-leaf cells in the r-tree structure, and that 4334 ** there is a non-leaf cell that corresponds to each entry in the 4335 ** %_parent table. 4336 */ 4337 static void rtreecheck( 4338 sqlite3_context *ctx, 4339 int nArg, 4340 sqlite3_value **apArg 4341 ){ 4342 if( nArg!=1 && nArg!=2 ){ 4343 sqlite3_result_error(ctx, 4344 "wrong number of arguments to function rtreecheck()", -1 4345 ); 4346 }else{ 4347 int rc; 4348 char *zReport = 0; 4349 const char *zDb = (const char*)sqlite3_value_text(apArg[0]); 4350 const char *zTab; 4351 if( nArg==1 ){ 4352 zTab = zDb; 4353 zDb = "main"; 4354 }else{ 4355 zTab = (const char*)sqlite3_value_text(apArg[1]); 4356 } 4357 rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport); 4358 if( rc==SQLITE_OK ){ 4359 sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT); 4360 }else{ 4361 sqlite3_result_error_code(ctx, rc); 4362 } 4363 sqlite3_free(zReport); 4364 } 4365 } 4366 4367 /* Conditionally include the geopoly code */ 4368 #ifdef SQLITE_ENABLE_GEOPOLY 4369 # include "geopoly.c" 4370 #endif 4371 4372 /* 4373 ** Register the r-tree module with database handle db. This creates the 4374 ** virtual table module "rtree" and the debugging/analysis scalar 4375 ** function "rtreenode". 4376 */ 4377 int sqlite3RtreeInit(sqlite3 *db){ 4378 const int utf8 = SQLITE_UTF8; 4379 int rc; 4380 4381 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0); 4382 if( rc==SQLITE_OK ){ 4383 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0); 4384 } 4385 if( rc==SQLITE_OK ){ 4386 rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0); 4387 } 4388 if( rc==SQLITE_OK ){ 4389 #ifdef SQLITE_RTREE_INT_ONLY 4390 void *c = (void *)RTREE_COORD_INT32; 4391 #else 4392 void *c = (void *)RTREE_COORD_REAL32; 4393 #endif 4394 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0); 4395 } 4396 if( rc==SQLITE_OK ){ 4397 void *c = (void *)RTREE_COORD_INT32; 4398 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0); 4399 } 4400 #ifdef SQLITE_ENABLE_GEOPOLY 4401 if( rc==SQLITE_OK ){ 4402 rc = sqlite3_geopoly_init(db); 4403 } 4404 #endif 4405 4406 return rc; 4407 } 4408 4409 /* 4410 ** This routine deletes the RtreeGeomCallback object that was attached 4411 ** one of the SQL functions create by sqlite3_rtree_geometry_callback() 4412 ** or sqlite3_rtree_query_callback(). In other words, this routine is the 4413 ** destructor for an RtreeGeomCallback objecct. This routine is called when 4414 ** the corresponding SQL function is deleted. 4415 */ 4416 static void rtreeFreeCallback(void *p){ 4417 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p; 4418 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext); 4419 sqlite3_free(p); 4420 } 4421 4422 /* 4423 ** This routine frees the BLOB that is returned by geomCallback(). 4424 */ 4425 static void rtreeMatchArgFree(void *pArg){ 4426 int i; 4427 RtreeMatchArg *p = (RtreeMatchArg*)pArg; 4428 for(i=0; i<p->nParam; i++){ 4429 sqlite3_value_free(p->apSqlParam[i]); 4430 } 4431 sqlite3_free(p); 4432 } 4433 4434 /* 4435 ** Each call to sqlite3_rtree_geometry_callback() or 4436 ** sqlite3_rtree_query_callback() creates an ordinary SQLite 4437 ** scalar function that is implemented by this routine. 4438 ** 4439 ** All this function does is construct an RtreeMatchArg object that 4440 ** contains the geometry-checking callback routines and a list of 4441 ** parameters to this function, then return that RtreeMatchArg object 4442 ** as a BLOB. 4443 ** 4444 ** The R-Tree MATCH operator will read the returned BLOB, deserialize 4445 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure 4446 ** out which elements of the R-Tree should be returned by the query. 4447 */ 4448 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){ 4449 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx); 4450 RtreeMatchArg *pBlob; 4451 sqlite3_int64 nBlob; 4452 int memErr = 0; 4453 4454 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) 4455 + nArg*sizeof(sqlite3_value*); 4456 pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob); 4457 if( !pBlob ){ 4458 sqlite3_result_error_nomem(ctx); 4459 }else{ 4460 int i; 4461 pBlob->iSize = nBlob; 4462 pBlob->cb = pGeomCtx[0]; 4463 pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg]; 4464 pBlob->nParam = nArg; 4465 for(i=0; i<nArg; i++){ 4466 pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]); 4467 if( pBlob->apSqlParam[i]==0 ) memErr = 1; 4468 #ifdef SQLITE_RTREE_INT_ONLY 4469 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]); 4470 #else 4471 pBlob->aParam[i] = sqlite3_value_double(aArg[i]); 4472 #endif 4473 } 4474 if( memErr ){ 4475 sqlite3_result_error_nomem(ctx); 4476 rtreeMatchArgFree(pBlob); 4477 }else{ 4478 sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree); 4479 } 4480 } 4481 } 4482 4483 /* 4484 ** Register a new geometry function for use with the r-tree MATCH operator. 4485 */ 4486 int sqlite3_rtree_geometry_callback( 4487 sqlite3 *db, /* Register SQL function on this connection */ 4488 const char *zGeom, /* Name of the new SQL function */ 4489 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */ 4490 void *pContext /* Extra data associated with the callback */ 4491 ){ 4492 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ 4493 4494 /* Allocate and populate the context object. */ 4495 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); 4496 if( !pGeomCtx ) return SQLITE_NOMEM; 4497 pGeomCtx->xGeom = xGeom; 4498 pGeomCtx->xQueryFunc = 0; 4499 pGeomCtx->xDestructor = 0; 4500 pGeomCtx->pContext = pContext; 4501 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 4502 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback 4503 ); 4504 } 4505 4506 /* 4507 ** Register a new 2nd-generation geometry function for use with the 4508 ** r-tree MATCH operator. 4509 */ 4510 int sqlite3_rtree_query_callback( 4511 sqlite3 *db, /* Register SQL function on this connection */ 4512 const char *zQueryFunc, /* Name of new SQL function */ 4513 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */ 4514 void *pContext, /* Extra data passed into the callback */ 4515 void (*xDestructor)(void*) /* Destructor for the extra data */ 4516 ){ 4517 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */ 4518 4519 /* Allocate and populate the context object. */ 4520 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback)); 4521 if( !pGeomCtx ) return SQLITE_NOMEM; 4522 pGeomCtx->xGeom = 0; 4523 pGeomCtx->xQueryFunc = xQueryFunc; 4524 pGeomCtx->xDestructor = xDestructor; 4525 pGeomCtx->pContext = pContext; 4526 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 4527 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback 4528 ); 4529 } 4530 4531 #if !SQLITE_CORE 4532 #ifdef _WIN32 4533 __declspec(dllexport) 4534 #endif 4535 int sqlite3_rtree_init( 4536 sqlite3 *db, 4537 char **pzErrMsg, 4538 const sqlite3_api_routines *pApi 4539 ){ 4540 SQLITE_EXTENSION_INIT2(pApi) 4541 return sqlite3RtreeInit(db); 4542 } 4543 #endif 4544 4545 #endif 4546