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