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