Merge sqlite-release(3.43.1) into prerelease-integration
[sqlcipher.git] / ext / rtree / rtree.c
blob4e85cc8aecf46c6e96563cdcca1b02d7a1705faa
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 /* Macro to check for 4-byte alignment. Only used inside of assert() */
100 #ifdef SQLITE_DEBUG
101 # define FOUR_BYTE_ALIGNED(X) ((((char*)(X) - (char*)0) & 3)==0)
102 #endif
104 #include <string.h>
105 #include <stdio.h>
106 #include <assert.h>
107 #include <stdlib.h>
109 /* The following macro is used to suppress compiler warnings.
111 #ifndef UNUSED_PARAMETER
112 # define UNUSED_PARAMETER(x) (void)(x)
113 #endif
115 typedef struct Rtree Rtree;
116 typedef struct RtreeCursor RtreeCursor;
117 typedef struct RtreeNode RtreeNode;
118 typedef struct RtreeCell RtreeCell;
119 typedef struct RtreeConstraint RtreeConstraint;
120 typedef struct RtreeMatchArg RtreeMatchArg;
121 typedef struct RtreeGeomCallback RtreeGeomCallback;
122 typedef union RtreeCoord RtreeCoord;
123 typedef struct RtreeSearchPoint RtreeSearchPoint;
125 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
126 #define RTREE_MAX_DIMENSIONS 5
128 /* Maximum number of auxiliary columns */
129 #define RTREE_MAX_AUX_COLUMN 100
131 /* Size of hash table Rtree.aHash. This hash table is not expected to
132 ** ever contain very many entries, so a fixed number of buckets is
133 ** used.
135 #define HASHSIZE 97
137 /* The xBestIndex method of this virtual table requires an estimate of
138 ** the number of rows in the virtual table to calculate the costs of
139 ** various strategies. If possible, this estimate is loaded from the
140 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
141 ** Otherwise, if no sqlite_stat1 entry is available, use
142 ** RTREE_DEFAULT_ROWEST.
144 #define RTREE_DEFAULT_ROWEST 1048576
145 #define RTREE_MIN_ROWEST 100
148 ** An rtree virtual-table object.
150 struct Rtree {
151 sqlite3_vtab base; /* Base class. Must be first */
152 sqlite3 *db; /* Host database connection */
153 int iNodeSize; /* Size in bytes of each node in the node table */
154 u8 nDim; /* Number of dimensions */
155 u8 nDim2; /* Twice the number of dimensions */
156 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
157 u8 nBytesPerCell; /* Bytes consumed per cell */
158 u8 inWrTrans; /* True if inside write transaction */
159 u8 nAux; /* # of auxiliary columns in %_rowid */
160 #ifdef SQLITE_ENABLE_GEOPOLY
161 u8 nAuxNotNull; /* Number of initial not-null aux columns */
162 #endif
163 #ifdef SQLITE_DEBUG
164 u8 bCorrupt; /* Shadow table corruption detected */
165 #endif
166 int iDepth; /* Current depth of the r-tree structure */
167 char *zDb; /* Name of database containing r-tree table */
168 char *zName; /* Name of r-tree table */
169 u32 nBusy; /* Current number of users of this structure */
170 i64 nRowEst; /* Estimated number of rows in this table */
171 u32 nCursor; /* Number of open cursors */
172 u32 nNodeRef; /* Number RtreeNodes with positive nRef */
173 char *zReadAuxSql; /* SQL for statement to read aux data */
175 /* List of nodes removed during a CondenseTree operation. List is
176 ** linked together via the pointer normally used for hash chains -
177 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
178 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
180 RtreeNode *pDeleted;
181 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
183 /* Blob I/O on xxx_node */
184 sqlite3_blob *pNodeBlob;
186 /* Statements to read/write/delete a record from xxx_node */
187 sqlite3_stmt *pWriteNode;
188 sqlite3_stmt *pDeleteNode;
190 /* Statements to read/write/delete a record from xxx_rowid */
191 sqlite3_stmt *pReadRowid;
192 sqlite3_stmt *pWriteRowid;
193 sqlite3_stmt *pDeleteRowid;
195 /* Statements to read/write/delete a record from xxx_parent */
196 sqlite3_stmt *pReadParent;
197 sqlite3_stmt *pWriteParent;
198 sqlite3_stmt *pDeleteParent;
200 /* Statement for writing to the "aux:" fields, if there are any */
201 sqlite3_stmt *pWriteAux;
203 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
206 /* Possible values for Rtree.eCoordType: */
207 #define RTREE_COORD_REAL32 0
208 #define RTREE_COORD_INT32 1
211 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
212 ** only deal with integer coordinates. No floating point operations
213 ** will be done.
215 #ifdef SQLITE_RTREE_INT_ONLY
216 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
217 typedef int RtreeValue; /* Low accuracy coordinate */
218 # define RTREE_ZERO 0
219 #else
220 typedef double RtreeDValue; /* High accuracy coordinate */
221 typedef float RtreeValue; /* Low accuracy coordinate */
222 # define RTREE_ZERO 0.0
223 #endif
226 ** Set the Rtree.bCorrupt flag
228 #ifdef SQLITE_DEBUG
229 # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
230 #else
231 # define RTREE_IS_CORRUPT(X)
232 #endif
235 ** When doing a search of an r-tree, instances of the following structure
236 ** record intermediate results from the tree walk.
238 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
239 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
240 ** the id is of the parent node and the cell that RtreeSearchPoint
241 ** represents is the iCell-th entry in the parent node.
243 struct RtreeSearchPoint {
244 RtreeDValue rScore; /* The score for this node. Smallest goes first. */
245 sqlite3_int64 id; /* Node ID */
246 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
247 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
248 u8 iCell; /* Cell index within the node */
252 ** The minimum number of cells allowed for a node is a third of the
253 ** maximum. In Gutman's notation:
255 ** m = M/3
257 ** If an R*-tree "Reinsert" operation is required, the same number of
258 ** cells are removed from the overfull node and reinserted into the tree.
260 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
261 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
262 #define RTREE_MAXCELLS 51
265 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
266 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
267 ** Therefore all non-root nodes must contain at least 3 entries. Since
268 ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
269 ** 40 or less.
271 #define RTREE_MAX_DEPTH 40
275 ** Number of entries in the cursor RtreeNode cache. The first entry is
276 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
277 ** entries cache the RtreeNode for the first elements of the priority queue.
279 #define RTREE_CACHE_SZ 5
282 ** An rtree cursor object.
284 struct RtreeCursor {
285 sqlite3_vtab_cursor base; /* Base class. Must be first */
286 u8 atEOF; /* True if at end of search */
287 u8 bPoint; /* True if sPoint is valid */
288 u8 bAuxValid; /* True if pReadAux is valid */
289 int iStrategy; /* Copy of idxNum search parameter */
290 int nConstraint; /* Number of entries in aConstraint */
291 RtreeConstraint *aConstraint; /* Search constraints. */
292 int nPointAlloc; /* Number of slots allocated for aPoint[] */
293 int nPoint; /* Number of slots used in aPoint[] */
294 int mxLevel; /* iLevel value for root of the tree */
295 RtreeSearchPoint *aPoint; /* Priority queue for search points */
296 sqlite3_stmt *pReadAux; /* Statement to read aux-data */
297 RtreeSearchPoint sPoint; /* Cached next search point */
298 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
299 u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
302 /* Return the Rtree of a RtreeCursor */
303 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
306 ** A coordinate can be either a floating point number or a integer. All
307 ** coordinates within a single R-Tree are always of the same time.
309 union RtreeCoord {
310 RtreeValue f; /* Floating point value */
311 int i; /* Integer value */
312 u32 u; /* Unsigned for byte-order conversions */
316 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
317 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
318 ** variable pRtree points to the Rtree structure associated with the
319 ** RtreeCoord.
321 #ifdef SQLITE_RTREE_INT_ONLY
322 # define DCOORD(coord) ((RtreeDValue)coord.i)
323 #else
324 # define DCOORD(coord) ( \
325 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
326 ((double)coord.f) : \
327 ((double)coord.i) \
329 #endif
332 ** A search constraint.
334 struct RtreeConstraint {
335 int iCoord; /* Index of constrained coordinate */
336 int op; /* Constraining operation */
337 union {
338 RtreeDValue rValue; /* Constraint value. */
339 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
340 int (*xQueryFunc)(sqlite3_rtree_query_info*);
341 } u;
342 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
345 /* Possible values for RtreeConstraint.op */
346 #define RTREE_EQ 0x41 /* A */
347 #define RTREE_LE 0x42 /* B */
348 #define RTREE_LT 0x43 /* C */
349 #define RTREE_GE 0x44 /* D */
350 #define RTREE_GT 0x45 /* E */
351 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
352 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
354 /* Special operators available only on cursors. Needs to be consecutive
355 ** with the normal values above, but must be less than RTREE_MATCH. These
356 ** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
357 ** x<'xyz' (RTREE_TRUE) */
358 #define RTREE_TRUE 0x3f /* ? */
359 #define RTREE_FALSE 0x40 /* @ */
362 ** An rtree structure node.
364 struct RtreeNode {
365 RtreeNode *pParent; /* Parent node */
366 i64 iNode; /* The node number */
367 int nRef; /* Number of references to this node */
368 int isDirty; /* True if the node needs to be written to disk */
369 u8 *zData; /* Content of the node, as should be on disk */
370 RtreeNode *pNext; /* Next node in this hash collision chain */
373 /* Return the number of cells in a node */
374 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
377 ** A single cell from a node, deserialized
379 struct RtreeCell {
380 i64 iRowid; /* Node or entry ID */
381 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
386 ** This object becomes the sqlite3_user_data() for the SQL functions
387 ** that are created by sqlite3_rtree_geometry_callback() and
388 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
389 ** operators in order to constrain a search.
391 ** xGeom and xQueryFunc are the callback functions. Exactly one of
392 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
393 ** SQL function was created using sqlite3_rtree_geometry_callback() or
394 ** sqlite3_rtree_query_callback().
396 ** This object is deleted automatically by the destructor mechanism in
397 ** sqlite3_create_function_v2().
399 struct RtreeGeomCallback {
400 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
401 int (*xQueryFunc)(sqlite3_rtree_query_info*);
402 void (*xDestructor)(void*);
403 void *pContext;
407 ** An instance of this structure (in the form of a BLOB) is returned by
408 ** the SQL functions that sqlite3_rtree_geometry_callback() and
409 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
410 ** operand to the MATCH operator of an R-Tree.
412 struct RtreeMatchArg {
413 u32 iSize; /* Size of this object */
414 RtreeGeomCallback cb; /* Info about the callback functions */
415 int nParam; /* Number of parameters to the SQL function */
416 sqlite3_value **apSqlParam; /* Original SQL parameter values */
417 RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
420 #ifndef MAX
421 # define MAX(x,y) ((x) < (y) ? (y) : (x))
422 #endif
423 #ifndef MIN
424 # define MIN(x,y) ((x) > (y) ? (y) : (x))
425 #endif
427 /* What version of GCC is being used. 0 means GCC is not being used .
428 ** Note that the GCC_VERSION macro will also be set correctly when using
429 ** clang, since clang works hard to be gcc compatible. So the gcc
430 ** optimizations will also work when compiling with clang.
432 #ifndef GCC_VERSION
433 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
434 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
435 #else
436 # define GCC_VERSION 0
437 #endif
438 #endif
440 /* The testcase() macro should already be defined in the amalgamation. If
441 ** it is not, make it a no-op.
443 #ifndef SQLITE_AMALGAMATION
444 # if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
445 unsigned int sqlite3RtreeTestcase = 0;
446 # define testcase(X) if( X ){ sqlite3RtreeTestcase += __LINE__; }
447 # else
448 # define testcase(X)
449 # endif
450 #endif
453 ** Make sure that the compiler intrinsics we desire are enabled when
454 ** compiling with an appropriate version of MSVC unless prevented by
455 ** the SQLITE_DISABLE_INTRINSIC define.
457 #if !defined(SQLITE_DISABLE_INTRINSIC)
458 # if defined(_MSC_VER) && _MSC_VER>=1400
459 # if !defined(_WIN32_WCE)
460 # include <intrin.h>
461 # pragma intrinsic(_byteswap_ulong)
462 # pragma intrinsic(_byteswap_uint64)
463 # else
464 # include <cmnintrin.h>
465 # endif
466 # endif
467 #endif
470 ** Macros to determine whether the machine is big or little endian,
471 ** and whether or not that determination is run-time or compile-time.
473 ** For best performance, an attempt is made to guess at the byte-order
474 ** using C-preprocessor macros. If that is unsuccessful, or if
475 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
476 ** at run-time.
478 #ifndef SQLITE_BYTEORDER
479 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
480 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
481 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
482 defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
483 # define SQLITE_BYTEORDER 1234
484 # elif defined(sparc) || defined(__ppc__) || \
485 defined(__ARMEB__) || defined(__AARCH64EB__)
486 # define SQLITE_BYTEORDER 4321
487 # else
488 # define SQLITE_BYTEORDER 0
489 # endif
490 #endif
493 /* What version of MSVC is being used. 0 means MSVC is not being used */
494 #ifndef MSVC_VERSION
495 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
496 # define MSVC_VERSION _MSC_VER
497 #else
498 # define MSVC_VERSION 0
499 #endif
500 #endif
503 ** Functions to deserialize a 16 bit integer, 32 bit real number and
504 ** 64 bit integer. The deserialized value is returned.
506 static int readInt16(u8 *p){
507 return (p[0]<<8) + p[1];
509 static void readCoord(u8 *p, RtreeCoord *pCoord){
510 assert( FOUR_BYTE_ALIGNED(p) );
511 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
512 pCoord->u = _byteswap_ulong(*(u32*)p);
513 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
514 pCoord->u = __builtin_bswap32(*(u32*)p);
515 #elif SQLITE_BYTEORDER==4321
516 pCoord->u = *(u32*)p;
517 #else
518 pCoord->u = (
519 (((u32)p[0]) << 24) +
520 (((u32)p[1]) << 16) +
521 (((u32)p[2]) << 8) +
522 (((u32)p[3]) << 0)
524 #endif
526 static i64 readInt64(u8 *p){
527 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
528 u64 x;
529 memcpy(&x, p, 8);
530 return (i64)_byteswap_uint64(x);
531 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
532 u64 x;
533 memcpy(&x, p, 8);
534 return (i64)__builtin_bswap64(x);
535 #elif SQLITE_BYTEORDER==4321
536 i64 x;
537 memcpy(&x, p, 8);
538 return x;
539 #else
540 return (i64)(
541 (((u64)p[0]) << 56) +
542 (((u64)p[1]) << 48) +
543 (((u64)p[2]) << 40) +
544 (((u64)p[3]) << 32) +
545 (((u64)p[4]) << 24) +
546 (((u64)p[5]) << 16) +
547 (((u64)p[6]) << 8) +
548 (((u64)p[7]) << 0)
550 #endif
554 ** Functions to serialize a 16 bit integer, 32 bit real number and
555 ** 64 bit integer. The value returned is the number of bytes written
556 ** to the argument buffer (always 2, 4 and 8 respectively).
558 static void writeInt16(u8 *p, int i){
559 p[0] = (i>> 8)&0xFF;
560 p[1] = (i>> 0)&0xFF;
562 static int writeCoord(u8 *p, RtreeCoord *pCoord){
563 u32 i;
564 assert( FOUR_BYTE_ALIGNED(p) );
565 assert( sizeof(RtreeCoord)==4 );
566 assert( sizeof(u32)==4 );
567 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
568 i = __builtin_bswap32(pCoord->u);
569 memcpy(p, &i, 4);
570 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
571 i = _byteswap_ulong(pCoord->u);
572 memcpy(p, &i, 4);
573 #elif SQLITE_BYTEORDER==4321
574 i = pCoord->u;
575 memcpy(p, &i, 4);
576 #else
577 i = pCoord->u;
578 p[0] = (i>>24)&0xFF;
579 p[1] = (i>>16)&0xFF;
580 p[2] = (i>> 8)&0xFF;
581 p[3] = (i>> 0)&0xFF;
582 #endif
583 return 4;
585 static int writeInt64(u8 *p, i64 i){
586 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
587 i = (i64)__builtin_bswap64((u64)i);
588 memcpy(p, &i, 8);
589 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
590 i = (i64)_byteswap_uint64((u64)i);
591 memcpy(p, &i, 8);
592 #elif SQLITE_BYTEORDER==4321
593 memcpy(p, &i, 8);
594 #else
595 p[0] = (i>>56)&0xFF;
596 p[1] = (i>>48)&0xFF;
597 p[2] = (i>>40)&0xFF;
598 p[3] = (i>>32)&0xFF;
599 p[4] = (i>>24)&0xFF;
600 p[5] = (i>>16)&0xFF;
601 p[6] = (i>> 8)&0xFF;
602 p[7] = (i>> 0)&0xFF;
603 #endif
604 return 8;
608 ** Increment the reference count of node p.
610 static void nodeReference(RtreeNode *p){
611 if( p ){
612 assert( p->nRef>0 );
613 p->nRef++;
618 ** Clear the content of node p (set all bytes to 0x00).
620 static void nodeZero(Rtree *pRtree, RtreeNode *p){
621 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
622 p->isDirty = 1;
626 ** Given a node number iNode, return the corresponding key to use
627 ** in the Rtree.aHash table.
629 static unsigned int nodeHash(i64 iNode){
630 return ((unsigned)iNode) % HASHSIZE;
634 ** Search the node hash table for node iNode. If found, return a pointer
635 ** to it. Otherwise, return 0.
637 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
638 RtreeNode *p;
639 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
640 return p;
644 ** Add node pNode to the node hash table.
646 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
647 int iHash;
648 assert( pNode->pNext==0 );
649 iHash = nodeHash(pNode->iNode);
650 pNode->pNext = pRtree->aHash[iHash];
651 pRtree->aHash[iHash] = pNode;
655 ** Remove node pNode from the node hash table.
657 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
658 RtreeNode **pp;
659 if( pNode->iNode!=0 ){
660 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
661 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
662 *pp = pNode->pNext;
663 pNode->pNext = 0;
668 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
669 ** indicating that node has not yet been assigned a node number. It is
670 ** assigned a node number when nodeWrite() is called to write the
671 ** node contents out to the database.
673 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
674 RtreeNode *pNode;
675 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
676 if( pNode ){
677 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
678 pNode->zData = (u8 *)&pNode[1];
679 pNode->nRef = 1;
680 pRtree->nNodeRef++;
681 pNode->pParent = pParent;
682 pNode->isDirty = 1;
683 nodeReference(pParent);
685 return pNode;
689 ** Clear the Rtree.pNodeBlob object
691 static void nodeBlobReset(Rtree *pRtree){
692 if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
693 sqlite3_blob *pBlob = pRtree->pNodeBlob;
694 pRtree->pNodeBlob = 0;
695 sqlite3_blob_close(pBlob);
700 ** Obtain a reference to an r-tree node.
702 static int nodeAcquire(
703 Rtree *pRtree, /* R-tree structure */
704 i64 iNode, /* Node number to load */
705 RtreeNode *pParent, /* Either the parent node or NULL */
706 RtreeNode **ppNode /* OUT: Acquired node */
708 int rc = SQLITE_OK;
709 RtreeNode *pNode = 0;
711 /* Check if the requested node is already in the hash table. If so,
712 ** increase its reference count and return it.
714 if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
715 if( pParent && pParent!=pNode->pParent ){
716 RTREE_IS_CORRUPT(pRtree);
717 return SQLITE_CORRUPT_VTAB;
719 pNode->nRef++;
720 *ppNode = pNode;
721 return SQLITE_OK;
724 if( pRtree->pNodeBlob ){
725 sqlite3_blob *pBlob = pRtree->pNodeBlob;
726 pRtree->pNodeBlob = 0;
727 rc = sqlite3_blob_reopen(pBlob, iNode);
728 pRtree->pNodeBlob = pBlob;
729 if( rc ){
730 nodeBlobReset(pRtree);
731 if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
734 if( pRtree->pNodeBlob==0 ){
735 char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
736 if( zTab==0 ) return SQLITE_NOMEM;
737 rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
738 &pRtree->pNodeBlob);
739 sqlite3_free(zTab);
741 if( rc ){
742 nodeBlobReset(pRtree);
743 *ppNode = 0;
744 /* If unable to open an sqlite3_blob on the desired row, that can only
745 ** be because the shadow tables hold erroneous data. */
746 if( rc==SQLITE_ERROR ){
747 rc = SQLITE_CORRUPT_VTAB;
748 RTREE_IS_CORRUPT(pRtree);
750 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
751 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
752 if( !pNode ){
753 rc = SQLITE_NOMEM;
754 }else{
755 pNode->pParent = pParent;
756 pNode->zData = (u8 *)&pNode[1];
757 pNode->nRef = 1;
758 pRtree->nNodeRef++;
759 pNode->iNode = iNode;
760 pNode->isDirty = 0;
761 pNode->pNext = 0;
762 rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
763 pRtree->iNodeSize, 0);
767 /* If the root node was just loaded, set pRtree->iDepth to the height
768 ** of the r-tree structure. A height of zero means all data is stored on
769 ** the root node. A height of one means the children of the root node
770 ** are the leaves, and so on. If the depth as specified on the root node
771 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
773 if( rc==SQLITE_OK && pNode && iNode==1 ){
774 pRtree->iDepth = readInt16(pNode->zData);
775 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
776 rc = SQLITE_CORRUPT_VTAB;
777 RTREE_IS_CORRUPT(pRtree);
781 /* If no error has occurred so far, check if the "number of entries"
782 ** field on the node is too large. If so, set the return code to
783 ** SQLITE_CORRUPT_VTAB.
785 if( pNode && rc==SQLITE_OK ){
786 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
787 rc = SQLITE_CORRUPT_VTAB;
788 RTREE_IS_CORRUPT(pRtree);
792 if( rc==SQLITE_OK ){
793 if( pNode!=0 ){
794 nodeReference(pParent);
795 nodeHashInsert(pRtree, pNode);
796 }else{
797 rc = SQLITE_CORRUPT_VTAB;
798 RTREE_IS_CORRUPT(pRtree);
800 *ppNode = pNode;
801 }else{
802 if( pNode ){
803 pRtree->nNodeRef--;
804 sqlite3_free(pNode);
806 *ppNode = 0;
809 return rc;
813 ** Overwrite cell iCell of node pNode with the contents of pCell.
815 static void nodeOverwriteCell(
816 Rtree *pRtree, /* The overall R-Tree */
817 RtreeNode *pNode, /* The node into which the cell is to be written */
818 RtreeCell *pCell, /* The cell to write */
819 int iCell /* Index into pNode into which pCell is written */
821 int ii;
822 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
823 p += writeInt64(p, pCell->iRowid);
824 for(ii=0; ii<pRtree->nDim2; ii++){
825 p += writeCoord(p, &pCell->aCoord[ii]);
827 pNode->isDirty = 1;
831 ** Remove the cell with index iCell from node pNode.
833 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
834 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
835 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
836 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
837 memmove(pDst, pSrc, nByte);
838 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
839 pNode->isDirty = 1;
843 ** Insert the contents of cell pCell into node pNode. If the insert
844 ** is successful, return SQLITE_OK.
846 ** If there is not enough free space in pNode, return SQLITE_FULL.
848 static int nodeInsertCell(
849 Rtree *pRtree, /* The overall R-Tree */
850 RtreeNode *pNode, /* Write new cell into this node */
851 RtreeCell *pCell /* The cell to be inserted */
853 int nCell; /* Current number of cells in pNode */
854 int nMaxCell; /* Maximum number of cells for pNode */
856 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
857 nCell = NCELL(pNode);
859 assert( nCell<=nMaxCell );
860 if( nCell<nMaxCell ){
861 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
862 writeInt16(&pNode->zData[2], nCell+1);
863 pNode->isDirty = 1;
866 return (nCell==nMaxCell);
870 ** If the node is dirty, write it out to the database.
872 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
873 int rc = SQLITE_OK;
874 if( pNode->isDirty ){
875 sqlite3_stmt *p = pRtree->pWriteNode;
876 if( pNode->iNode ){
877 sqlite3_bind_int64(p, 1, pNode->iNode);
878 }else{
879 sqlite3_bind_null(p, 1);
881 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
882 sqlite3_step(p);
883 pNode->isDirty = 0;
884 rc = sqlite3_reset(p);
885 sqlite3_bind_null(p, 2);
886 if( pNode->iNode==0 && rc==SQLITE_OK ){
887 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
888 nodeHashInsert(pRtree, pNode);
891 return rc;
895 ** Release a reference to a node. If the node is dirty and the reference
896 ** count drops to zero, the node data is written to the database.
898 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
899 int rc = SQLITE_OK;
900 if( pNode ){
901 assert( pNode->nRef>0 );
902 assert( pRtree->nNodeRef>0 );
903 pNode->nRef--;
904 if( pNode->nRef==0 ){
905 pRtree->nNodeRef--;
906 if( pNode->iNode==1 ){
907 pRtree->iDepth = -1;
909 if( pNode->pParent ){
910 rc = nodeRelease(pRtree, pNode->pParent);
912 if( rc==SQLITE_OK ){
913 rc = nodeWrite(pRtree, pNode);
915 nodeHashDelete(pRtree, pNode);
916 sqlite3_free(pNode);
919 return rc;
923 ** Return the 64-bit integer value associated with cell iCell of
924 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
925 ** an internal node, then the 64-bit integer is a child page number.
927 static i64 nodeGetRowid(
928 Rtree *pRtree, /* The overall R-Tree */
929 RtreeNode *pNode, /* The node from which to extract the ID */
930 int iCell /* The cell index from which to extract the ID */
932 assert( iCell<NCELL(pNode) );
933 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
937 ** Return coordinate iCoord from cell iCell in node pNode.
939 static void nodeGetCoord(
940 Rtree *pRtree, /* The overall R-Tree */
941 RtreeNode *pNode, /* The node from which to extract a coordinate */
942 int iCell, /* The index of the cell within the node */
943 int iCoord, /* Which coordinate to extract */
944 RtreeCoord *pCoord /* OUT: Space to write result to */
946 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
950 ** Deserialize cell iCell of node pNode. Populate the structure pointed
951 ** to by pCell with the results.
953 static void nodeGetCell(
954 Rtree *pRtree, /* The overall R-Tree */
955 RtreeNode *pNode, /* The node containing the cell to be read */
956 int iCell, /* Index of the cell within the node */
957 RtreeCell *pCell /* OUT: Write the cell contents here */
959 u8 *pData;
960 RtreeCoord *pCoord;
961 int ii = 0;
962 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
963 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
964 pCoord = pCell->aCoord;
966 readCoord(pData, &pCoord[ii]);
967 readCoord(pData+4, &pCoord[ii+1]);
968 pData += 8;
969 ii += 2;
970 }while( ii<pRtree->nDim2 );
974 /* Forward declaration for the function that does the work of
975 ** the virtual table module xCreate() and xConnect() methods.
977 static int rtreeInit(
978 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
982 ** Rtree virtual table module xCreate method.
984 static int rtreeCreate(
985 sqlite3 *db,
986 void *pAux,
987 int argc, const char *const*argv,
988 sqlite3_vtab **ppVtab,
989 char **pzErr
991 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
995 ** Rtree virtual table module xConnect method.
997 static int rtreeConnect(
998 sqlite3 *db,
999 void *pAux,
1000 int argc, const char *const*argv,
1001 sqlite3_vtab **ppVtab,
1002 char **pzErr
1004 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
1008 ** Increment the r-tree reference count.
1010 static void rtreeReference(Rtree *pRtree){
1011 pRtree->nBusy++;
1015 ** Decrement the r-tree reference count. When the reference count reaches
1016 ** zero the structure is deleted.
1018 static void rtreeRelease(Rtree *pRtree){
1019 pRtree->nBusy--;
1020 if( pRtree->nBusy==0 ){
1021 pRtree->inWrTrans = 0;
1022 assert( pRtree->nCursor==0 );
1023 nodeBlobReset(pRtree);
1024 assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
1025 sqlite3_finalize(pRtree->pWriteNode);
1026 sqlite3_finalize(pRtree->pDeleteNode);
1027 sqlite3_finalize(pRtree->pReadRowid);
1028 sqlite3_finalize(pRtree->pWriteRowid);
1029 sqlite3_finalize(pRtree->pDeleteRowid);
1030 sqlite3_finalize(pRtree->pReadParent);
1031 sqlite3_finalize(pRtree->pWriteParent);
1032 sqlite3_finalize(pRtree->pDeleteParent);
1033 sqlite3_finalize(pRtree->pWriteAux);
1034 sqlite3_free(pRtree->zReadAuxSql);
1035 sqlite3_free(pRtree);
1040 ** Rtree virtual table module xDisconnect method.
1042 static int rtreeDisconnect(sqlite3_vtab *pVtab){
1043 rtreeRelease((Rtree *)pVtab);
1044 return SQLITE_OK;
1048 ** Rtree virtual table module xDestroy method.
1050 static int rtreeDestroy(sqlite3_vtab *pVtab){
1051 Rtree *pRtree = (Rtree *)pVtab;
1052 int rc;
1053 char *zCreate = sqlite3_mprintf(
1054 "DROP TABLE '%q'.'%q_node';"
1055 "DROP TABLE '%q'.'%q_rowid';"
1056 "DROP TABLE '%q'.'%q_parent';",
1057 pRtree->zDb, pRtree->zName,
1058 pRtree->zDb, pRtree->zName,
1059 pRtree->zDb, pRtree->zName
1061 if( !zCreate ){
1062 rc = SQLITE_NOMEM;
1063 }else{
1064 nodeBlobReset(pRtree);
1065 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
1066 sqlite3_free(zCreate);
1068 if( rc==SQLITE_OK ){
1069 rtreeRelease(pRtree);
1072 return rc;
1076 ** Rtree virtual table module xOpen method.
1078 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
1079 int rc = SQLITE_NOMEM;
1080 Rtree *pRtree = (Rtree *)pVTab;
1081 RtreeCursor *pCsr;
1083 pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
1084 if( pCsr ){
1085 memset(pCsr, 0, sizeof(RtreeCursor));
1086 pCsr->base.pVtab = pVTab;
1087 rc = SQLITE_OK;
1088 pRtree->nCursor++;
1090 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
1092 return rc;
1097 ** Reset a cursor back to its initial state.
1099 static void resetCursor(RtreeCursor *pCsr){
1100 Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
1101 int ii;
1102 sqlite3_stmt *pStmt;
1103 if( pCsr->aConstraint ){
1104 int i; /* Used to iterate through constraint array */
1105 for(i=0; i<pCsr->nConstraint; i++){
1106 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
1107 if( pInfo ){
1108 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
1109 sqlite3_free(pInfo);
1112 sqlite3_free(pCsr->aConstraint);
1113 pCsr->aConstraint = 0;
1115 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
1116 sqlite3_free(pCsr->aPoint);
1117 pStmt = pCsr->pReadAux;
1118 memset(pCsr, 0, sizeof(RtreeCursor));
1119 pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
1120 pCsr->pReadAux = pStmt;
1125 ** Rtree virtual table module xClose method.
1127 static int rtreeClose(sqlite3_vtab_cursor *cur){
1128 Rtree *pRtree = (Rtree *)(cur->pVtab);
1129 RtreeCursor *pCsr = (RtreeCursor *)cur;
1130 assert( pRtree->nCursor>0 );
1131 resetCursor(pCsr);
1132 sqlite3_finalize(pCsr->pReadAux);
1133 sqlite3_free(pCsr);
1134 pRtree->nCursor--;
1135 nodeBlobReset(pRtree);
1136 return SQLITE_OK;
1140 ** Rtree virtual table module xEof method.
1142 ** Return non-zero if the cursor does not currently point to a valid
1143 ** record (i.e if the scan has finished), or zero otherwise.
1145 static int rtreeEof(sqlite3_vtab_cursor *cur){
1146 RtreeCursor *pCsr = (RtreeCursor *)cur;
1147 return pCsr->atEOF;
1151 ** Convert raw bits from the on-disk RTree record into a coordinate value.
1152 ** The on-disk format is big-endian and needs to be converted for little-
1153 ** endian platforms. The on-disk record stores integer coordinates if
1154 ** eInt is true and it stores 32-bit floating point records if eInt is
1155 ** false. a[] is the four bytes of the on-disk record to be decoded.
1156 ** Store the results in "r".
1158 ** There are five versions of this macro. The last one is generic. The
1159 ** other four are various architectures-specific optimizations.
1161 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1162 #define RTREE_DECODE_COORD(eInt, a, r) { \
1163 RtreeCoord c; /* Coordinate decoded */ \
1164 c.u = _byteswap_ulong(*(u32*)a); \
1165 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1167 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
1168 #define RTREE_DECODE_COORD(eInt, a, r) { \
1169 RtreeCoord c; /* Coordinate decoded */ \
1170 c.u = __builtin_bswap32(*(u32*)a); \
1171 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1173 #elif SQLITE_BYTEORDER==1234
1174 #define RTREE_DECODE_COORD(eInt, a, r) { \
1175 RtreeCoord c; /* Coordinate decoded */ \
1176 memcpy(&c.u,a,4); \
1177 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
1178 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
1179 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1181 #elif SQLITE_BYTEORDER==4321
1182 #define RTREE_DECODE_COORD(eInt, a, r) { \
1183 RtreeCoord c; /* Coordinate decoded */ \
1184 memcpy(&c.u,a,4); \
1185 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1187 #else
1188 #define RTREE_DECODE_COORD(eInt, a, r) { \
1189 RtreeCoord c; /* Coordinate decoded */ \
1190 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
1191 +((u32)a[2]<<8) + a[3]; \
1192 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1194 #endif
1197 ** Check the RTree node or entry given by pCellData and p against the MATCH
1198 ** constraint pConstraint.
1200 static int rtreeCallbackConstraint(
1201 RtreeConstraint *pConstraint, /* The constraint to test */
1202 int eInt, /* True if RTree holding integer coordinates */
1203 u8 *pCellData, /* Raw cell content */
1204 RtreeSearchPoint *pSearch, /* Container of this cell */
1205 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
1206 int *peWithin /* OUT: visibility of the cell */
1208 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
1209 int nCoord = pInfo->nCoord; /* No. of coordinates */
1210 int rc; /* Callback return code */
1211 RtreeCoord c; /* Translator union */
1212 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
1214 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
1215 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
1217 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
1218 pInfo->iRowid = readInt64(pCellData);
1220 pCellData += 8;
1221 #ifndef SQLITE_RTREE_INT_ONLY
1222 if( eInt==0 ){
1223 switch( nCoord ){
1224 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
1225 readCoord(pCellData+32, &c); aCoord[8] = c.f;
1226 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
1227 readCoord(pCellData+24, &c); aCoord[6] = c.f;
1228 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
1229 readCoord(pCellData+16, &c); aCoord[4] = c.f;
1230 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
1231 readCoord(pCellData+8, &c); aCoord[2] = c.f;
1232 default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
1233 readCoord(pCellData, &c); aCoord[0] = c.f;
1235 }else
1236 #endif
1238 switch( nCoord ){
1239 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
1240 readCoord(pCellData+32, &c); aCoord[8] = c.i;
1241 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
1242 readCoord(pCellData+24, &c); aCoord[6] = c.i;
1243 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
1244 readCoord(pCellData+16, &c); aCoord[4] = c.i;
1245 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
1246 readCoord(pCellData+8, &c); aCoord[2] = c.i;
1247 default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
1248 readCoord(pCellData, &c); aCoord[0] = c.i;
1251 if( pConstraint->op==RTREE_MATCH ){
1252 int eWithin = 0;
1253 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
1254 nCoord, aCoord, &eWithin);
1255 if( eWithin==0 ) *peWithin = NOT_WITHIN;
1256 *prScore = RTREE_ZERO;
1257 }else{
1258 pInfo->aCoord = aCoord;
1259 pInfo->iLevel = pSearch->iLevel - 1;
1260 pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
1261 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
1262 rc = pConstraint->u.xQueryFunc(pInfo);
1263 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
1264 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
1265 *prScore = pInfo->rScore;
1268 return rc;
1272 ** Check the internal RTree node given by pCellData against constraint p.
1273 ** If this constraint cannot be satisfied by any child within the node,
1274 ** set *peWithin to NOT_WITHIN.
1276 static void rtreeNonleafConstraint(
1277 RtreeConstraint *p, /* The constraint to test */
1278 int eInt, /* True if RTree holds integer coordinates */
1279 u8 *pCellData, /* Raw cell content as appears on disk */
1280 int *peWithin /* Adjust downward, as appropriate */
1282 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
1284 /* p->iCoord might point to either a lower or upper bound coordinate
1285 ** in a coordinate pair. But make pCellData point to the lower bound.
1287 pCellData += 8 + 4*(p->iCoord&0xfe);
1289 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1290 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1291 || p->op==RTREE_FALSE );
1292 assert( FOUR_BYTE_ALIGNED(pCellData) );
1293 switch( p->op ){
1294 case RTREE_TRUE: return; /* Always satisfied */
1295 case RTREE_FALSE: break; /* Never satisfied */
1296 case RTREE_EQ:
1297 RTREE_DECODE_COORD(eInt, pCellData, val);
1298 /* val now holds the lower bound of the coordinate pair */
1299 if( p->u.rValue>=val ){
1300 pCellData += 4;
1301 RTREE_DECODE_COORD(eInt, pCellData, val);
1302 /* val now holds the upper bound of the coordinate pair */
1303 if( p->u.rValue<=val ) return;
1305 break;
1306 case RTREE_LE:
1307 case RTREE_LT:
1308 RTREE_DECODE_COORD(eInt, pCellData, val);
1309 /* val now holds the lower bound of the coordinate pair */
1310 if( p->u.rValue>=val ) return;
1311 break;
1313 default:
1314 pCellData += 4;
1315 RTREE_DECODE_COORD(eInt, pCellData, val);
1316 /* val now holds the upper bound of the coordinate pair */
1317 if( p->u.rValue<=val ) return;
1318 break;
1320 *peWithin = NOT_WITHIN;
1324 ** Check the leaf RTree cell given by pCellData against constraint p.
1325 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
1326 ** If the constraint is satisfied, leave *peWithin unchanged.
1328 ** The constraint is of the form: xN op $val
1330 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
1331 ** pCellData. $val is given by p->u.rValue.
1333 static void rtreeLeafConstraint(
1334 RtreeConstraint *p, /* The constraint to test */
1335 int eInt, /* True if RTree holds integer coordinates */
1336 u8 *pCellData, /* Raw cell content as appears on disk */
1337 int *peWithin /* Adjust downward, as appropriate */
1339 RtreeDValue xN; /* Coordinate value converted to a double */
1341 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1342 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1343 || p->op==RTREE_FALSE );
1344 pCellData += 8 + p->iCoord*4;
1345 assert( FOUR_BYTE_ALIGNED(pCellData) );
1346 RTREE_DECODE_COORD(eInt, pCellData, xN);
1347 switch( p->op ){
1348 case RTREE_TRUE: return; /* Always satisfied */
1349 case RTREE_FALSE: break; /* Never satisfied */
1350 case RTREE_LE: if( xN <= p->u.rValue ) return; break;
1351 case RTREE_LT: if( xN < p->u.rValue ) return; break;
1352 case RTREE_GE: if( xN >= p->u.rValue ) return; break;
1353 case RTREE_GT: if( xN > p->u.rValue ) return; break;
1354 default: if( xN == p->u.rValue ) return; break;
1356 *peWithin = NOT_WITHIN;
1360 ** One of the cells in node pNode is guaranteed to have a 64-bit
1361 ** integer value equal to iRowid. Return the index of this cell.
1363 static int nodeRowidIndex(
1364 Rtree *pRtree,
1365 RtreeNode *pNode,
1366 i64 iRowid,
1367 int *piIndex
1369 int ii;
1370 int nCell = NCELL(pNode);
1371 assert( nCell<200 );
1372 for(ii=0; ii<nCell; ii++){
1373 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1374 *piIndex = ii;
1375 return SQLITE_OK;
1378 RTREE_IS_CORRUPT(pRtree);
1379 return SQLITE_CORRUPT_VTAB;
1383 ** Return the index of the cell containing a pointer to node pNode
1384 ** in its parent. If pNode is the root node, return -1.
1386 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1387 RtreeNode *pParent = pNode->pParent;
1388 if( ALWAYS(pParent) ){
1389 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1390 }else{
1391 *piIndex = -1;
1392 return SQLITE_OK;
1397 ** Compare two search points. Return negative, zero, or positive if the first
1398 ** is less than, equal to, or greater than the second.
1400 ** The rScore is the primary key. Smaller rScore values come first.
1401 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
1402 ** iLevel values coming first. In this way, if rScore is the same for all
1403 ** SearchPoints, then iLevel becomes the deciding factor and the result
1404 ** is a depth-first search, which is the desired default behavior.
1406 static int rtreeSearchPointCompare(
1407 const RtreeSearchPoint *pA,
1408 const RtreeSearchPoint *pB
1410 if( pA->rScore<pB->rScore ) return -1;
1411 if( pA->rScore>pB->rScore ) return +1;
1412 if( pA->iLevel<pB->iLevel ) return -1;
1413 if( pA->iLevel>pB->iLevel ) return +1;
1414 return 0;
1418 ** Interchange two search points in a cursor.
1420 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
1421 RtreeSearchPoint t = p->aPoint[i];
1422 assert( i<j );
1423 p->aPoint[i] = p->aPoint[j];
1424 p->aPoint[j] = t;
1425 i++; j++;
1426 if( i<RTREE_CACHE_SZ ){
1427 if( j>=RTREE_CACHE_SZ ){
1428 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1429 p->aNode[i] = 0;
1430 }else{
1431 RtreeNode *pTemp = p->aNode[i];
1432 p->aNode[i] = p->aNode[j];
1433 p->aNode[j] = pTemp;
1439 ** Return the search point with the lowest current score.
1441 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
1442 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
1446 ** Get the RtreeNode for the search point with the lowest score.
1448 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
1449 sqlite3_int64 id;
1450 int ii = 1 - pCur->bPoint;
1451 assert( ii==0 || ii==1 );
1452 assert( pCur->bPoint || pCur->nPoint );
1453 if( pCur->aNode[ii]==0 ){
1454 assert( pRC!=0 );
1455 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
1456 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
1458 return pCur->aNode[ii];
1462 ** Push a new element onto the priority queue
1464 static RtreeSearchPoint *rtreeEnqueue(
1465 RtreeCursor *pCur, /* The cursor */
1466 RtreeDValue rScore, /* Score for the new search point */
1467 u8 iLevel /* Level for the new search point */
1469 int i, j;
1470 RtreeSearchPoint *pNew;
1471 if( pCur->nPoint>=pCur->nPointAlloc ){
1472 int nNew = pCur->nPointAlloc*2 + 8;
1473 pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
1474 if( pNew==0 ) return 0;
1475 pCur->aPoint = pNew;
1476 pCur->nPointAlloc = nNew;
1478 i = pCur->nPoint++;
1479 pNew = pCur->aPoint + i;
1480 pNew->rScore = rScore;
1481 pNew->iLevel = iLevel;
1482 assert( iLevel<=RTREE_MAX_DEPTH );
1483 while( i>0 ){
1484 RtreeSearchPoint *pParent;
1485 j = (i-1)/2;
1486 pParent = pCur->aPoint + j;
1487 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
1488 rtreeSearchPointSwap(pCur, j, i);
1489 i = j;
1490 pNew = pParent;
1492 return pNew;
1496 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
1497 ** NULL if malloc fails.
1499 static RtreeSearchPoint *rtreeSearchPointNew(
1500 RtreeCursor *pCur, /* The cursor */
1501 RtreeDValue rScore, /* Score for the new search point */
1502 u8 iLevel /* Level for the new search point */
1504 RtreeSearchPoint *pNew, *pFirst;
1505 pFirst = rtreeSearchPointFirst(pCur);
1506 pCur->anQueue[iLevel]++;
1507 if( pFirst==0
1508 || pFirst->rScore>rScore
1509 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
1511 if( pCur->bPoint ){
1512 int ii;
1513 pNew = rtreeEnqueue(pCur, rScore, iLevel);
1514 if( pNew==0 ) return 0;
1515 ii = (int)(pNew - pCur->aPoint) + 1;
1516 assert( ii==1 );
1517 if( ALWAYS(ii<RTREE_CACHE_SZ) ){
1518 assert( pCur->aNode[ii]==0 );
1519 pCur->aNode[ii] = pCur->aNode[0];
1520 }else{
1521 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
1523 pCur->aNode[0] = 0;
1524 *pNew = pCur->sPoint;
1526 pCur->sPoint.rScore = rScore;
1527 pCur->sPoint.iLevel = iLevel;
1528 pCur->bPoint = 1;
1529 return &pCur->sPoint;
1530 }else{
1531 return rtreeEnqueue(pCur, rScore, iLevel);
1535 #if 0
1536 /* Tracing routines for the RtreeSearchPoint queue */
1537 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
1538 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
1539 printf(" %d.%05lld.%02d %g %d",
1540 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
1542 idx++;
1543 if( idx<RTREE_CACHE_SZ ){
1544 printf(" %p\n", pCur->aNode[idx]);
1545 }else{
1546 printf("\n");
1549 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
1550 int ii;
1551 printf("=== %9s ", zPrefix);
1552 if( pCur->bPoint ){
1553 tracePoint(&pCur->sPoint, -1, pCur);
1555 for(ii=0; ii<pCur->nPoint; ii++){
1556 if( ii>0 || pCur->bPoint ) printf(" ");
1557 tracePoint(&pCur->aPoint[ii], ii, pCur);
1560 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
1561 #else
1562 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
1563 #endif
1565 /* Remove the search point with the lowest current score.
1567 static void rtreeSearchPointPop(RtreeCursor *p){
1568 int i, j, k, n;
1569 i = 1 - p->bPoint;
1570 assert( i==0 || i==1 );
1571 if( p->aNode[i] ){
1572 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1573 p->aNode[i] = 0;
1575 if( p->bPoint ){
1576 p->anQueue[p->sPoint.iLevel]--;
1577 p->bPoint = 0;
1578 }else if( ALWAYS(p->nPoint) ){
1579 p->anQueue[p->aPoint[0].iLevel]--;
1580 n = --p->nPoint;
1581 p->aPoint[0] = p->aPoint[n];
1582 if( n<RTREE_CACHE_SZ-1 ){
1583 p->aNode[1] = p->aNode[n+1];
1584 p->aNode[n+1] = 0;
1586 i = 0;
1587 while( (j = i*2+1)<n ){
1588 k = j+1;
1589 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
1590 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
1591 rtreeSearchPointSwap(p, i, k);
1592 i = k;
1593 }else{
1594 break;
1596 }else{
1597 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
1598 rtreeSearchPointSwap(p, i, j);
1599 i = j;
1600 }else{
1601 break;
1610 ** Continue the search on cursor pCur until the front of the queue
1611 ** contains an entry suitable for returning as a result-set row,
1612 ** or until the RtreeSearchPoint queue is empty, indicating that the
1613 ** query has completed.
1615 static int rtreeStepToLeaf(RtreeCursor *pCur){
1616 RtreeSearchPoint *p;
1617 Rtree *pRtree = RTREE_OF_CURSOR(pCur);
1618 RtreeNode *pNode;
1619 int eWithin;
1620 int rc = SQLITE_OK;
1621 int nCell;
1622 int nConstraint = pCur->nConstraint;
1623 int ii;
1624 int eInt;
1625 RtreeSearchPoint x;
1627 eInt = pRtree->eCoordType==RTREE_COORD_INT32;
1628 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
1629 u8 *pCellData;
1630 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
1631 if( rc ) return rc;
1632 nCell = NCELL(pNode);
1633 assert( nCell<200 );
1634 pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
1635 while( p->iCell<nCell ){
1636 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
1637 eWithin = FULLY_WITHIN;
1638 for(ii=0; ii<nConstraint; ii++){
1639 RtreeConstraint *pConstraint = pCur->aConstraint + ii;
1640 if( pConstraint->op>=RTREE_MATCH ){
1641 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
1642 &rScore, &eWithin);
1643 if( rc ) return rc;
1644 }else if( p->iLevel==1 ){
1645 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
1646 }else{
1647 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
1649 if( eWithin==NOT_WITHIN ){
1650 p->iCell++;
1651 pCellData += pRtree->nBytesPerCell;
1652 break;
1655 if( eWithin==NOT_WITHIN ) continue;
1656 p->iCell++;
1657 x.iLevel = p->iLevel - 1;
1658 if( x.iLevel ){
1659 x.id = readInt64(pCellData);
1660 for(ii=0; ii<pCur->nPoint; ii++){
1661 if( pCur->aPoint[ii].id==x.id ){
1662 RTREE_IS_CORRUPT(pRtree);
1663 return SQLITE_CORRUPT_VTAB;
1666 x.iCell = 0;
1667 }else{
1668 x.id = p->id;
1669 x.iCell = p->iCell - 1;
1671 if( p->iCell>=nCell ){
1672 RTREE_QUEUE_TRACE(pCur, "POP-S:");
1673 rtreeSearchPointPop(pCur);
1675 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
1676 p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
1677 if( p==0 ) return SQLITE_NOMEM;
1678 p->eWithin = (u8)eWithin;
1679 p->id = x.id;
1680 p->iCell = x.iCell;
1681 RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
1682 break;
1684 if( p->iCell>=nCell ){
1685 RTREE_QUEUE_TRACE(pCur, "POP-Se:");
1686 rtreeSearchPointPop(pCur);
1689 pCur->atEOF = p==0;
1690 return SQLITE_OK;
1694 ** Rtree virtual table module xNext method.
1696 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1697 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1698 int rc = SQLITE_OK;
1700 /* Move to the next entry that matches the configured constraints. */
1701 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
1702 if( pCsr->bAuxValid ){
1703 pCsr->bAuxValid = 0;
1704 sqlite3_reset(pCsr->pReadAux);
1706 rtreeSearchPointPop(pCsr);
1707 rc = rtreeStepToLeaf(pCsr);
1708 return rc;
1712 ** Rtree virtual table module xRowid method.
1714 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1715 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1716 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1717 int rc = SQLITE_OK;
1718 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1719 if( rc==SQLITE_OK && ALWAYS(p) ){
1720 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
1722 return rc;
1726 ** Rtree virtual table module xColumn method.
1728 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1729 Rtree *pRtree = (Rtree *)cur->pVtab;
1730 RtreeCursor *pCsr = (RtreeCursor *)cur;
1731 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1732 RtreeCoord c;
1733 int rc = SQLITE_OK;
1734 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1736 if( rc ) return rc;
1737 if( NEVER(p==0) ) return SQLITE_OK;
1738 if( i==0 ){
1739 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
1740 }else if( i<=pRtree->nDim2 ){
1741 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
1742 #ifndef SQLITE_RTREE_INT_ONLY
1743 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1744 sqlite3_result_double(ctx, c.f);
1745 }else
1746 #endif
1748 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1749 sqlite3_result_int(ctx, c.i);
1751 }else{
1752 if( !pCsr->bAuxValid ){
1753 if( pCsr->pReadAux==0 ){
1754 rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
1755 &pCsr->pReadAux, 0);
1756 if( rc ) return rc;
1758 sqlite3_bind_int64(pCsr->pReadAux, 1,
1759 nodeGetRowid(pRtree, pNode, p->iCell));
1760 rc = sqlite3_step(pCsr->pReadAux);
1761 if( rc==SQLITE_ROW ){
1762 pCsr->bAuxValid = 1;
1763 }else{
1764 sqlite3_reset(pCsr->pReadAux);
1765 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1766 return rc;
1769 sqlite3_result_value(ctx,
1770 sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
1772 return SQLITE_OK;
1776 ** Use nodeAcquire() to obtain the leaf node containing the record with
1777 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1778 ** return SQLITE_OK. If there is no such record in the table, set
1779 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1780 ** to zero and return an SQLite error code.
1782 static int findLeafNode(
1783 Rtree *pRtree, /* RTree to search */
1784 i64 iRowid, /* The rowid searching for */
1785 RtreeNode **ppLeaf, /* Write the node here */
1786 sqlite3_int64 *piNode /* Write the node-id here */
1788 int rc;
1789 *ppLeaf = 0;
1790 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1791 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1792 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1793 if( piNode ) *piNode = iNode;
1794 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1795 sqlite3_reset(pRtree->pReadRowid);
1796 }else{
1797 rc = sqlite3_reset(pRtree->pReadRowid);
1799 return rc;
1803 ** This function is called to configure the RtreeConstraint object passed
1804 ** as the second argument for a MATCH constraint. The value passed as the
1805 ** first argument to this function is the right-hand operand to the MATCH
1806 ** operator.
1808 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1809 RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
1810 sqlite3_rtree_query_info *pInfo; /* Callback information */
1812 pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
1813 if( pSrc==0 ) return SQLITE_ERROR;
1814 pInfo = (sqlite3_rtree_query_info*)
1815 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
1816 if( !pInfo ) return SQLITE_NOMEM;
1817 memset(pInfo, 0, sizeof(*pInfo));
1818 pBlob = (RtreeMatchArg*)&pInfo[1];
1819 memcpy(pBlob, pSrc, pSrc->iSize);
1820 pInfo->pContext = pBlob->cb.pContext;
1821 pInfo->nParam = pBlob->nParam;
1822 pInfo->aParam = pBlob->aParam;
1823 pInfo->apSqlParam = pBlob->apSqlParam;
1825 if( pBlob->cb.xGeom ){
1826 pCons->u.xGeom = pBlob->cb.xGeom;
1827 }else{
1828 pCons->op = RTREE_QUERY;
1829 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
1831 pCons->pInfo = pInfo;
1832 return SQLITE_OK;
1836 ** Rtree virtual table module xFilter method.
1838 static int rtreeFilter(
1839 sqlite3_vtab_cursor *pVtabCursor,
1840 int idxNum, const char *idxStr,
1841 int argc, sqlite3_value **argv
1843 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1844 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1845 RtreeNode *pRoot = 0;
1846 int ii;
1847 int rc = SQLITE_OK;
1848 int iCell = 0;
1850 rtreeReference(pRtree);
1852 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
1853 resetCursor(pCsr);
1855 pCsr->iStrategy = idxNum;
1856 if( idxNum==1 ){
1857 /* Special case - lookup by rowid. */
1858 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
1859 RtreeSearchPoint *p; /* Search point for the leaf */
1860 i64 iRowid = sqlite3_value_int64(argv[0]);
1861 i64 iNode = 0;
1862 int eType = sqlite3_value_numeric_type(argv[0]);
1863 if( eType==SQLITE_INTEGER
1864 || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)
1866 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
1867 }else{
1868 rc = SQLITE_OK;
1869 pLeaf = 0;
1871 if( rc==SQLITE_OK && pLeaf!=0 ){
1872 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
1873 assert( p!=0 ); /* Always returns pCsr->sPoint */
1874 pCsr->aNode[0] = pLeaf;
1875 p->id = iNode;
1876 p->eWithin = PARTLY_WITHIN;
1877 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
1878 p->iCell = (u8)iCell;
1879 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
1880 }else{
1881 pCsr->atEOF = 1;
1883 }else{
1884 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1885 ** with the configured constraints.
1887 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1888 if( rc==SQLITE_OK && argc>0 ){
1889 pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
1890 pCsr->nConstraint = argc;
1891 if( !pCsr->aConstraint ){
1892 rc = SQLITE_NOMEM;
1893 }else{
1894 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1895 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
1896 assert( (idxStr==0 && argc==0)
1897 || (idxStr && (int)strlen(idxStr)==argc*2) );
1898 for(ii=0; ii<argc; ii++){
1899 RtreeConstraint *p = &pCsr->aConstraint[ii];
1900 int eType = sqlite3_value_numeric_type(argv[ii]);
1901 p->op = idxStr[ii*2];
1902 p->iCoord = idxStr[ii*2+1]-'0';
1903 if( p->op>=RTREE_MATCH ){
1904 /* A MATCH operator. The right-hand-side must be a blob that
1905 ** can be cast into an RtreeMatchArg object. One created using
1906 ** an sqlite3_rtree_geometry_callback() SQL user function.
1908 rc = deserializeGeometry(argv[ii], p);
1909 if( rc!=SQLITE_OK ){
1910 break;
1912 p->pInfo->nCoord = pRtree->nDim2;
1913 p->pInfo->anQueue = pCsr->anQueue;
1914 p->pInfo->mxLevel = pRtree->iDepth + 1;
1915 }else if( eType==SQLITE_INTEGER ){
1916 sqlite3_int64 iVal = sqlite3_value_int64(argv[ii]);
1917 #ifdef SQLITE_RTREE_INT_ONLY
1918 p->u.rValue = iVal;
1919 #else
1920 p->u.rValue = (double)iVal;
1921 if( iVal>=((sqlite3_int64)1)<<48
1922 || iVal<=-(((sqlite3_int64)1)<<48)
1924 if( p->op==RTREE_LT ) p->op = RTREE_LE;
1925 if( p->op==RTREE_GT ) p->op = RTREE_GE;
1927 #endif
1928 }else if( eType==SQLITE_FLOAT ){
1929 #ifdef SQLITE_RTREE_INT_ONLY
1930 p->u.rValue = sqlite3_value_int64(argv[ii]);
1931 #else
1932 p->u.rValue = sqlite3_value_double(argv[ii]);
1933 #endif
1934 }else{
1935 p->u.rValue = RTREE_ZERO;
1936 if( eType==SQLITE_NULL ){
1937 p->op = RTREE_FALSE;
1938 }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
1939 p->op = RTREE_TRUE;
1940 }else{
1941 p->op = RTREE_FALSE;
1947 if( rc==SQLITE_OK ){
1948 RtreeSearchPoint *pNew;
1949 assert( pCsr->bPoint==0 ); /* Due to the resetCursor() call above */
1950 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
1951 if( NEVER(pNew==0) ){ /* Because pCsr->bPoint was FALSE */
1952 return SQLITE_NOMEM;
1954 pNew->id = 1;
1955 pNew->iCell = 0;
1956 pNew->eWithin = PARTLY_WITHIN;
1957 assert( pCsr->bPoint==1 );
1958 pCsr->aNode[0] = pRoot;
1959 pRoot = 0;
1960 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
1961 rc = rtreeStepToLeaf(pCsr);
1965 nodeRelease(pRtree, pRoot);
1966 rtreeRelease(pRtree);
1967 return rc;
1971 ** Rtree virtual table module xBestIndex method. There are three
1972 ** table scan strategies to choose from (in order from most to
1973 ** least desirable):
1975 ** idxNum idxStr Strategy
1976 ** ------------------------------------------------
1977 ** 1 Unused Direct lookup by rowid.
1978 ** 2 See below R-tree query or full-table scan.
1979 ** ------------------------------------------------
1981 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1982 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1983 ** constraint used. The first two bytes of idxStr correspond to
1984 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1985 ** (argvIndex==1) etc.
1987 ** The first of each pair of bytes in idxStr identifies the constraint
1988 ** operator as follows:
1990 ** Operator Byte Value
1991 ** ----------------------
1992 ** = 0x41 ('A')
1993 ** <= 0x42 ('B')
1994 ** < 0x43 ('C')
1995 ** >= 0x44 ('D')
1996 ** > 0x45 ('E')
1997 ** MATCH 0x46 ('F')
1998 ** ----------------------
2000 ** The second of each pair of bytes identifies the coordinate column
2001 ** to which the constraint applies. The leftmost coordinate column
2002 ** is 'a', the second from the left 'b' etc.
2004 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2005 Rtree *pRtree = (Rtree*)tab;
2006 int rc = SQLITE_OK;
2007 int ii;
2008 int bMatch = 0; /* True if there exists a MATCH constraint */
2009 i64 nRow; /* Estimated rows returned by this scan */
2011 int iIdx = 0;
2012 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
2013 memset(zIdxStr, 0, sizeof(zIdxStr));
2015 /* Check if there exists a MATCH constraint - even an unusable one. If there
2016 ** is, do not consider the lookup-by-rowid plan as using such a plan would
2017 ** require the VDBE to evaluate the MATCH constraint, which is not currently
2018 ** possible. */
2019 for(ii=0; ii<pIdxInfo->nConstraint; ii++){
2020 if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
2021 bMatch = 1;
2025 assert( pIdxInfo->idxStr==0 );
2026 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
2027 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
2029 if( bMatch==0 && p->usable
2030 && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
2032 /* We have an equality constraint on the rowid. Use strategy 1. */
2033 int jj;
2034 for(jj=0; jj<ii; jj++){
2035 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
2036 pIdxInfo->aConstraintUsage[jj].omit = 0;
2038 pIdxInfo->idxNum = 1;
2039 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
2040 pIdxInfo->aConstraintUsage[jj].omit = 1;
2042 /* This strategy involves a two rowid lookups on an B-Tree structures
2043 ** and then a linear search of an R-Tree node. This should be
2044 ** considered almost as quick as a direct rowid lookup (for which
2045 ** sqlite uses an internal cost of 0.0). It is expected to return
2046 ** a single row.
2048 pIdxInfo->estimatedCost = 30.0;
2049 pIdxInfo->estimatedRows = 1;
2050 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
2051 return SQLITE_OK;
2054 if( p->usable
2055 && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
2056 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
2058 u8 op;
2059 u8 doOmit = 1;
2060 switch( p->op ){
2061 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; doOmit = 0; break;
2062 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; doOmit = 0; break;
2063 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
2064 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; doOmit = 0; break;
2065 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
2066 case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
2067 default: op = 0; break;
2069 if( op ){
2070 zIdxStr[iIdx++] = op;
2071 zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
2072 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
2073 pIdxInfo->aConstraintUsage[ii].omit = doOmit;
2078 pIdxInfo->idxNum = 2;
2079 pIdxInfo->needToFreeIdxStr = 1;
2080 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
2081 return SQLITE_NOMEM;
2084 nRow = pRtree->nRowEst >> (iIdx/2);
2085 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
2086 pIdxInfo->estimatedRows = nRow;
2088 return rc;
2092 ** Return the N-dimensional volumn of the cell stored in *p.
2094 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
2095 RtreeDValue area = (RtreeDValue)1;
2096 assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
2097 #ifndef SQLITE_RTREE_INT_ONLY
2098 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2099 switch( pRtree->nDim ){
2100 case 5: area = p->aCoord[9].f - p->aCoord[8].f;
2101 case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
2102 case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
2103 case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
2104 default: area *= p->aCoord[1].f - p->aCoord[0].f;
2106 }else
2107 #endif
2109 switch( pRtree->nDim ){
2110 case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
2111 case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
2112 case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
2113 case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
2114 default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
2117 return area;
2121 ** Return the margin length of cell p. The margin length is the sum
2122 ** of the objects size in each dimension.
2124 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
2125 RtreeDValue margin = 0;
2126 int ii = pRtree->nDim2 - 2;
2128 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
2129 ii -= 2;
2130 }while( ii>=0 );
2131 return margin;
2135 ** Store the union of cells p1 and p2 in p1.
2137 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2138 int ii = 0;
2139 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2141 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
2142 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
2143 ii += 2;
2144 }while( ii<pRtree->nDim2 );
2145 }else{
2147 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
2148 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
2149 ii += 2;
2150 }while( ii<pRtree->nDim2 );
2155 ** Return true if the area covered by p2 is a subset of the area covered
2156 ** by p1. False otherwise.
2158 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2159 int ii;
2160 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
2161 for(ii=0; ii<pRtree->nDim2; ii+=2){
2162 RtreeCoord *a1 = &p1->aCoord[ii];
2163 RtreeCoord *a2 = &p2->aCoord[ii];
2164 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
2165 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
2167 return 0;
2170 return 1;
2174 ** Return the amount cell p would grow by if it were unioned with pCell.
2176 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
2177 RtreeDValue area;
2178 RtreeCell cell;
2179 memcpy(&cell, p, sizeof(RtreeCell));
2180 area = cellArea(pRtree, &cell);
2181 cellUnion(pRtree, &cell, pCell);
2182 return (cellArea(pRtree, &cell)-area);
2185 static RtreeDValue cellOverlap(
2186 Rtree *pRtree,
2187 RtreeCell *p,
2188 RtreeCell *aCell,
2189 int nCell
2191 int ii;
2192 RtreeDValue overlap = RTREE_ZERO;
2193 for(ii=0; ii<nCell; ii++){
2194 int jj;
2195 RtreeDValue o = (RtreeDValue)1;
2196 for(jj=0; jj<pRtree->nDim2; jj+=2){
2197 RtreeDValue x1, x2;
2198 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
2199 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
2200 if( x2<x1 ){
2201 o = (RtreeDValue)0;
2202 break;
2203 }else{
2204 o = o * (x2-x1);
2207 overlap += o;
2209 return overlap;
2214 ** This function implements the ChooseLeaf algorithm from Gutman[84].
2215 ** ChooseSubTree in r*tree terminology.
2217 static int ChooseLeaf(
2218 Rtree *pRtree, /* Rtree table */
2219 RtreeCell *pCell, /* Cell to insert into rtree */
2220 int iHeight, /* Height of sub-tree rooted at pCell */
2221 RtreeNode **ppLeaf /* OUT: Selected leaf page */
2223 int rc;
2224 int ii;
2225 RtreeNode *pNode = 0;
2226 rc = nodeAcquire(pRtree, 1, 0, &pNode);
2228 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
2229 int iCell;
2230 sqlite3_int64 iBest = 0;
2232 RtreeDValue fMinGrowth = RTREE_ZERO;
2233 RtreeDValue fMinArea = RTREE_ZERO;
2235 int nCell = NCELL(pNode);
2236 RtreeCell cell;
2237 RtreeNode *pChild = 0;
2239 RtreeCell *aCell = 0;
2241 /* Select the child node which will be enlarged the least if pCell
2242 ** is inserted into it. Resolve ties by choosing the entry with
2243 ** the smallest area.
2245 for(iCell=0; iCell<nCell; iCell++){
2246 int bBest = 0;
2247 RtreeDValue growth;
2248 RtreeDValue area;
2249 nodeGetCell(pRtree, pNode, iCell, &cell);
2250 growth = cellGrowth(pRtree, &cell, pCell);
2251 area = cellArea(pRtree, &cell);
2252 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
2253 bBest = 1;
2255 if( bBest ){
2256 fMinGrowth = growth;
2257 fMinArea = area;
2258 iBest = cell.iRowid;
2262 sqlite3_free(aCell);
2263 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
2264 nodeRelease(pRtree, pNode);
2265 pNode = pChild;
2268 *ppLeaf = pNode;
2269 return rc;
2273 ** A cell with the same content as pCell has just been inserted into
2274 ** the node pNode. This function updates the bounding box cells in
2275 ** all ancestor elements.
2277 static int AdjustTree(
2278 Rtree *pRtree, /* Rtree table */
2279 RtreeNode *pNode, /* Adjust ancestry of this node. */
2280 RtreeCell *pCell /* This cell was just inserted */
2282 RtreeNode *p = pNode;
2283 int cnt = 0;
2284 int rc;
2285 while( p->pParent ){
2286 RtreeNode *pParent = p->pParent;
2287 RtreeCell cell;
2288 int iCell;
2290 cnt++;
2291 if( NEVER(cnt>100) ){
2292 RTREE_IS_CORRUPT(pRtree);
2293 return SQLITE_CORRUPT_VTAB;
2295 rc = nodeParentIndex(pRtree, p, &iCell);
2296 if( NEVER(rc!=SQLITE_OK) ){
2297 RTREE_IS_CORRUPT(pRtree);
2298 return SQLITE_CORRUPT_VTAB;
2301 nodeGetCell(pRtree, pParent, iCell, &cell);
2302 if( !cellContains(pRtree, &cell, pCell) ){
2303 cellUnion(pRtree, &cell, pCell);
2304 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
2307 p = pParent;
2309 return SQLITE_OK;
2313 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
2315 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
2316 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
2317 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
2318 sqlite3_step(pRtree->pWriteRowid);
2319 return sqlite3_reset(pRtree->pWriteRowid);
2323 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
2325 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
2326 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
2327 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
2328 sqlite3_step(pRtree->pWriteParent);
2329 return sqlite3_reset(pRtree->pWriteParent);
2332 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
2336 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
2337 ** nIdx. The aIdx array contains the set of integers from 0 to
2338 ** (nIdx-1) in no particular order. This function sorts the values
2339 ** in aIdx according to the indexed values in aDistance. For
2340 ** example, assuming the inputs:
2342 ** aIdx = { 0, 1, 2, 3 }
2343 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
2345 ** this function sets the aIdx array to contain:
2347 ** aIdx = { 0, 1, 2, 3 }
2349 ** The aSpare array is used as temporary working space by the
2350 ** sorting algorithm.
2352 static void SortByDistance(
2353 int *aIdx,
2354 int nIdx,
2355 RtreeDValue *aDistance,
2356 int *aSpare
2358 if( nIdx>1 ){
2359 int iLeft = 0;
2360 int iRight = 0;
2362 int nLeft = nIdx/2;
2363 int nRight = nIdx-nLeft;
2364 int *aLeft = aIdx;
2365 int *aRight = &aIdx[nLeft];
2367 SortByDistance(aLeft, nLeft, aDistance, aSpare);
2368 SortByDistance(aRight, nRight, aDistance, aSpare);
2370 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2371 aLeft = aSpare;
2373 while( iLeft<nLeft || iRight<nRight ){
2374 if( iLeft==nLeft ){
2375 aIdx[iLeft+iRight] = aRight[iRight];
2376 iRight++;
2377 }else if( iRight==nRight ){
2378 aIdx[iLeft+iRight] = aLeft[iLeft];
2379 iLeft++;
2380 }else{
2381 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
2382 RtreeDValue fRight = aDistance[aRight[iRight]];
2383 if( fLeft<fRight ){
2384 aIdx[iLeft+iRight] = aLeft[iLeft];
2385 iLeft++;
2386 }else{
2387 aIdx[iLeft+iRight] = aRight[iRight];
2388 iRight++;
2393 #if 0
2394 /* Check that the sort worked */
2396 int jj;
2397 for(jj=1; jj<nIdx; jj++){
2398 RtreeDValue left = aDistance[aIdx[jj-1]];
2399 RtreeDValue right = aDistance[aIdx[jj]];
2400 assert( left<=right );
2403 #endif
2408 ** Arguments aIdx, aCell and aSpare all point to arrays of size
2409 ** nIdx. The aIdx array contains the set of integers from 0 to
2410 ** (nIdx-1) in no particular order. This function sorts the values
2411 ** in aIdx according to dimension iDim of the cells in aCell. The
2412 ** minimum value of dimension iDim is considered first, the
2413 ** maximum used to break ties.
2415 ** The aSpare array is used as temporary working space by the
2416 ** sorting algorithm.
2418 static void SortByDimension(
2419 Rtree *pRtree,
2420 int *aIdx,
2421 int nIdx,
2422 int iDim,
2423 RtreeCell *aCell,
2424 int *aSpare
2426 if( nIdx>1 ){
2428 int iLeft = 0;
2429 int iRight = 0;
2431 int nLeft = nIdx/2;
2432 int nRight = nIdx-nLeft;
2433 int *aLeft = aIdx;
2434 int *aRight = &aIdx[nLeft];
2436 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
2437 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
2439 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2440 aLeft = aSpare;
2441 while( iLeft<nLeft || iRight<nRight ){
2442 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
2443 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
2444 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
2445 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
2446 if( (iLeft!=nLeft) && ((iRight==nRight)
2447 || (xleft1<xright1)
2448 || (xleft1==xright1 && xleft2<xright2)
2450 aIdx[iLeft+iRight] = aLeft[iLeft];
2451 iLeft++;
2452 }else{
2453 aIdx[iLeft+iRight] = aRight[iRight];
2454 iRight++;
2458 #if 0
2459 /* Check that the sort worked */
2461 int jj;
2462 for(jj=1; jj<nIdx; jj++){
2463 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2464 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2465 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2466 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2467 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2470 #endif
2475 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2477 static int splitNodeStartree(
2478 Rtree *pRtree,
2479 RtreeCell *aCell,
2480 int nCell,
2481 RtreeNode *pLeft,
2482 RtreeNode *pRight,
2483 RtreeCell *pBboxLeft,
2484 RtreeCell *pBboxRight
2486 int **aaSorted;
2487 int *aSpare;
2488 int ii;
2490 int iBestDim = 0;
2491 int iBestSplit = 0;
2492 RtreeDValue fBestMargin = RTREE_ZERO;
2494 sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2496 aaSorted = (int **)sqlite3_malloc64(nByte);
2497 if( !aaSorted ){
2498 return SQLITE_NOMEM;
2501 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2502 memset(aaSorted, 0, nByte);
2503 for(ii=0; ii<pRtree->nDim; ii++){
2504 int jj;
2505 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2506 for(jj=0; jj<nCell; jj++){
2507 aaSorted[ii][jj] = jj;
2509 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2512 for(ii=0; ii<pRtree->nDim; ii++){
2513 RtreeDValue margin = RTREE_ZERO;
2514 RtreeDValue fBestOverlap = RTREE_ZERO;
2515 RtreeDValue fBestArea = RTREE_ZERO;
2516 int iBestLeft = 0;
2517 int nLeft;
2519 for(
2520 nLeft=RTREE_MINCELLS(pRtree);
2521 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2522 nLeft++
2524 RtreeCell left;
2525 RtreeCell right;
2526 int kk;
2527 RtreeDValue overlap;
2528 RtreeDValue area;
2530 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2531 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2532 for(kk=1; kk<(nCell-1); kk++){
2533 if( kk<nLeft ){
2534 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2535 }else{
2536 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2539 margin += cellMargin(pRtree, &left);
2540 margin += cellMargin(pRtree, &right);
2541 overlap = cellOverlap(pRtree, &left, &right, 1);
2542 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2543 if( (nLeft==RTREE_MINCELLS(pRtree))
2544 || (overlap<fBestOverlap)
2545 || (overlap==fBestOverlap && area<fBestArea)
2547 iBestLeft = nLeft;
2548 fBestOverlap = overlap;
2549 fBestArea = area;
2553 if( ii==0 || margin<fBestMargin ){
2554 iBestDim = ii;
2555 fBestMargin = margin;
2556 iBestSplit = iBestLeft;
2560 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2561 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2562 for(ii=0; ii<nCell; ii++){
2563 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2564 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2565 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2566 nodeInsertCell(pRtree, pTarget, pCell);
2567 cellUnion(pRtree, pBbox, pCell);
2570 sqlite3_free(aaSorted);
2571 return SQLITE_OK;
2575 static int updateMapping(
2576 Rtree *pRtree,
2577 i64 iRowid,
2578 RtreeNode *pNode,
2579 int iHeight
2581 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2582 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2583 if( iHeight>0 ){
2584 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2585 RtreeNode *p;
2586 for(p=pNode; p; p=p->pParent){
2587 if( p==pChild ) return SQLITE_CORRUPT_VTAB;
2589 if( pChild ){
2590 nodeRelease(pRtree, pChild->pParent);
2591 nodeReference(pNode);
2592 pChild->pParent = pNode;
2595 if( NEVER(pNode==0) ) return SQLITE_ERROR;
2596 return xSetMapping(pRtree, iRowid, pNode->iNode);
2599 static int SplitNode(
2600 Rtree *pRtree,
2601 RtreeNode *pNode,
2602 RtreeCell *pCell,
2603 int iHeight
2605 int i;
2606 int newCellIsRight = 0;
2608 int rc = SQLITE_OK;
2609 int nCell = NCELL(pNode);
2610 RtreeCell *aCell;
2611 int *aiUsed;
2613 RtreeNode *pLeft = 0;
2614 RtreeNode *pRight = 0;
2616 RtreeCell leftbbox;
2617 RtreeCell rightbbox;
2619 /* Allocate an array and populate it with a copy of pCell and
2620 ** all cells from node pLeft. Then zero the original node.
2622 aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2623 if( !aCell ){
2624 rc = SQLITE_NOMEM;
2625 goto splitnode_out;
2627 aiUsed = (int *)&aCell[nCell+1];
2628 memset(aiUsed, 0, sizeof(int)*(nCell+1));
2629 for(i=0; i<nCell; i++){
2630 nodeGetCell(pRtree, pNode, i, &aCell[i]);
2632 nodeZero(pRtree, pNode);
2633 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2634 nCell++;
2636 if( pNode->iNode==1 ){
2637 pRight = nodeNew(pRtree, pNode);
2638 pLeft = nodeNew(pRtree, pNode);
2639 pRtree->iDepth++;
2640 pNode->isDirty = 1;
2641 writeInt16(pNode->zData, pRtree->iDepth);
2642 }else{
2643 pLeft = pNode;
2644 pRight = nodeNew(pRtree, pLeft->pParent);
2645 pLeft->nRef++;
2648 if( !pLeft || !pRight ){
2649 rc = SQLITE_NOMEM;
2650 goto splitnode_out;
2653 memset(pLeft->zData, 0, pRtree->iNodeSize);
2654 memset(pRight->zData, 0, pRtree->iNodeSize);
2656 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
2657 &leftbbox, &rightbbox);
2658 if( rc!=SQLITE_OK ){
2659 goto splitnode_out;
2662 /* Ensure both child nodes have node numbers assigned to them by calling
2663 ** nodeWrite(). Node pRight always needs a node number, as it was created
2664 ** by nodeNew() above. But node pLeft sometimes already has a node number.
2665 ** In this case avoid the all to nodeWrite().
2667 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2668 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2670 goto splitnode_out;
2673 rightbbox.iRowid = pRight->iNode;
2674 leftbbox.iRowid = pLeft->iNode;
2676 if( pNode->iNode==1 ){
2677 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2678 if( rc!=SQLITE_OK ){
2679 goto splitnode_out;
2681 }else{
2682 RtreeNode *pParent = pLeft->pParent;
2683 int iCell;
2684 rc = nodeParentIndex(pRtree, pLeft, &iCell);
2685 if( ALWAYS(rc==SQLITE_OK) ){
2686 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2687 rc = AdjustTree(pRtree, pParent, &leftbbox);
2688 assert( rc==SQLITE_OK );
2690 if( NEVER(rc!=SQLITE_OK) ){
2691 goto splitnode_out;
2694 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2695 goto splitnode_out;
2698 for(i=0; i<NCELL(pRight); i++){
2699 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2700 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2701 if( iRowid==pCell->iRowid ){
2702 newCellIsRight = 1;
2704 if( rc!=SQLITE_OK ){
2705 goto splitnode_out;
2708 if( pNode->iNode==1 ){
2709 for(i=0; i<NCELL(pLeft); i++){
2710 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2711 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2712 if( rc!=SQLITE_OK ){
2713 goto splitnode_out;
2716 }else if( newCellIsRight==0 ){
2717 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2720 if( rc==SQLITE_OK ){
2721 rc = nodeRelease(pRtree, pRight);
2722 pRight = 0;
2724 if( rc==SQLITE_OK ){
2725 rc = nodeRelease(pRtree, pLeft);
2726 pLeft = 0;
2729 splitnode_out:
2730 nodeRelease(pRtree, pRight);
2731 nodeRelease(pRtree, pLeft);
2732 sqlite3_free(aCell);
2733 return rc;
2737 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2738 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2739 ** the pLeaf->pParent chain all the way up to the root node.
2741 ** This operation is required when a row is deleted (or updated - an update
2742 ** is implemented as a delete followed by an insert). SQLite provides the
2743 ** rowid of the row to delete, which can be used to find the leaf on which
2744 ** the entry resides (argument pLeaf). Once the leaf is located, this
2745 ** function is called to determine its ancestry.
2747 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2748 int rc = SQLITE_OK;
2749 RtreeNode *pChild = pLeaf;
2750 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2751 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
2752 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2753 rc = sqlite3_step(pRtree->pReadParent);
2754 if( rc==SQLITE_ROW ){
2755 RtreeNode *pTest; /* Used to test for reference loops */
2756 i64 iNode; /* Node number of parent node */
2758 /* Before setting pChild->pParent, test that we are not creating a
2759 ** loop of references (as we would if, say, pChild==pParent). We don't
2760 ** want to do this as it leads to a memory leak when trying to delete
2761 ** the referenced counted node structures.
2763 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2764 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2765 if( pTest==0 ){
2766 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2769 rc = sqlite3_reset(pRtree->pReadParent);
2770 if( rc==SQLITE_OK ) rc = rc2;
2771 if( rc==SQLITE_OK && !pChild->pParent ){
2772 RTREE_IS_CORRUPT(pRtree);
2773 rc = SQLITE_CORRUPT_VTAB;
2775 pChild = pChild->pParent;
2777 return rc;
2780 static int deleteCell(Rtree *, RtreeNode *, int, int);
2782 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2783 int rc;
2784 int rc2;
2785 RtreeNode *pParent = 0;
2786 int iCell;
2788 assert( pNode->nRef==1 );
2790 /* Remove the entry in the parent cell. */
2791 rc = nodeParentIndex(pRtree, pNode, &iCell);
2792 if( rc==SQLITE_OK ){
2793 pParent = pNode->pParent;
2794 pNode->pParent = 0;
2795 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2796 testcase( rc!=SQLITE_OK );
2798 rc2 = nodeRelease(pRtree, pParent);
2799 if( rc==SQLITE_OK ){
2800 rc = rc2;
2802 if( rc!=SQLITE_OK ){
2803 return rc;
2806 /* Remove the xxx_node entry. */
2807 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2808 sqlite3_step(pRtree->pDeleteNode);
2809 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2810 return rc;
2813 /* Remove the xxx_parent entry. */
2814 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2815 sqlite3_step(pRtree->pDeleteParent);
2816 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2817 return rc;
2820 /* Remove the node from the in-memory hash table and link it into
2821 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2823 nodeHashDelete(pRtree, pNode);
2824 pNode->iNode = iHeight;
2825 pNode->pNext = pRtree->pDeleted;
2826 pNode->nRef++;
2827 pRtree->pDeleted = pNode;
2829 return SQLITE_OK;
2832 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2833 RtreeNode *pParent = pNode->pParent;
2834 int rc = SQLITE_OK;
2835 if( pParent ){
2836 int ii;
2837 int nCell = NCELL(pNode);
2838 RtreeCell box; /* Bounding box for pNode */
2839 nodeGetCell(pRtree, pNode, 0, &box);
2840 for(ii=1; ii<nCell; ii++){
2841 RtreeCell cell;
2842 nodeGetCell(pRtree, pNode, ii, &cell);
2843 cellUnion(pRtree, &box, &cell);
2845 box.iRowid = pNode->iNode;
2846 rc = nodeParentIndex(pRtree, pNode, &ii);
2847 if( rc==SQLITE_OK ){
2848 nodeOverwriteCell(pRtree, pParent, &box, ii);
2849 rc = fixBoundingBox(pRtree, pParent);
2852 return rc;
2856 ** Delete the cell at index iCell of node pNode. After removing the
2857 ** cell, adjust the r-tree data structure if required.
2859 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2860 RtreeNode *pParent;
2861 int rc;
2863 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2864 return rc;
2867 /* Remove the cell from the node. This call just moves bytes around
2868 ** the in-memory node image, so it cannot fail.
2870 nodeDeleteCell(pRtree, pNode, iCell);
2872 /* If the node is not the tree root and now has less than the minimum
2873 ** number of cells, remove it from the tree. Otherwise, update the
2874 ** cell in the parent node so that it tightly contains the updated
2875 ** node.
2877 pParent = pNode->pParent;
2878 assert( pParent || pNode->iNode==1 );
2879 if( pParent ){
2880 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2881 rc = removeNode(pRtree, pNode, iHeight);
2882 }else{
2883 rc = fixBoundingBox(pRtree, pNode);
2887 return rc;
2890 static int Reinsert(
2891 Rtree *pRtree,
2892 RtreeNode *pNode,
2893 RtreeCell *pCell,
2894 int iHeight
2896 int *aOrder;
2897 int *aSpare;
2898 RtreeCell *aCell;
2899 RtreeDValue *aDistance;
2900 int nCell;
2901 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
2902 int iDim;
2903 int ii;
2904 int rc = SQLITE_OK;
2905 int n;
2907 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
2909 nCell = NCELL(pNode)+1;
2910 n = (nCell+1)&(~1);
2912 /* Allocate the buffers used by this operation. The allocation is
2913 ** relinquished before this function returns.
2915 aCell = (RtreeCell *)sqlite3_malloc64(n * (
2916 sizeof(RtreeCell) + /* aCell array */
2917 sizeof(int) + /* aOrder array */
2918 sizeof(int) + /* aSpare array */
2919 sizeof(RtreeDValue) /* aDistance array */
2921 if( !aCell ){
2922 return SQLITE_NOMEM;
2924 aOrder = (int *)&aCell[n];
2925 aSpare = (int *)&aOrder[n];
2926 aDistance = (RtreeDValue *)&aSpare[n];
2928 for(ii=0; ii<nCell; ii++){
2929 if( ii==(nCell-1) ){
2930 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2931 }else{
2932 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2934 aOrder[ii] = ii;
2935 for(iDim=0; iDim<pRtree->nDim; iDim++){
2936 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2937 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2940 for(iDim=0; iDim<pRtree->nDim; iDim++){
2941 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
2944 for(ii=0; ii<nCell; ii++){
2945 aDistance[ii] = RTREE_ZERO;
2946 for(iDim=0; iDim<pRtree->nDim; iDim++){
2947 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
2948 DCOORD(aCell[ii].aCoord[iDim*2]));
2949 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2953 SortByDistance(aOrder, nCell, aDistance, aSpare);
2954 nodeZero(pRtree, pNode);
2956 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2957 RtreeCell *p = &aCell[aOrder[ii]];
2958 nodeInsertCell(pRtree, pNode, p);
2959 if( p->iRowid==pCell->iRowid ){
2960 if( iHeight==0 ){
2961 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2962 }else{
2963 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2967 if( rc==SQLITE_OK ){
2968 rc = fixBoundingBox(pRtree, pNode);
2970 for(; rc==SQLITE_OK && ii<nCell; ii++){
2971 /* Find a node to store this cell in. pNode->iNode currently contains
2972 ** the height of the sub-tree headed by the cell.
2974 RtreeNode *pInsert;
2975 RtreeCell *p = &aCell[aOrder[ii]];
2976 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2977 if( rc==SQLITE_OK ){
2978 int rc2;
2979 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2980 rc2 = nodeRelease(pRtree, pInsert);
2981 if( rc==SQLITE_OK ){
2982 rc = rc2;
2987 sqlite3_free(aCell);
2988 return rc;
2992 ** Insert cell pCell into node pNode. Node pNode is the head of a
2993 ** subtree iHeight high (leaf nodes have iHeight==0).
2995 static int rtreeInsertCell(
2996 Rtree *pRtree,
2997 RtreeNode *pNode,
2998 RtreeCell *pCell,
2999 int iHeight
3001 int rc = SQLITE_OK;
3002 if( iHeight>0 ){
3003 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
3004 if( pChild ){
3005 nodeRelease(pRtree, pChild->pParent);
3006 nodeReference(pNode);
3007 pChild->pParent = pNode;
3010 if( nodeInsertCell(pRtree, pNode, pCell) ){
3011 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
3012 rc = SplitNode(pRtree, pNode, pCell, iHeight);
3013 }else{
3014 pRtree->iReinsertHeight = iHeight;
3015 rc = Reinsert(pRtree, pNode, pCell, iHeight);
3017 }else{
3018 rc = AdjustTree(pRtree, pNode, pCell);
3019 if( ALWAYS(rc==SQLITE_OK) ){
3020 if( iHeight==0 ){
3021 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
3022 }else{
3023 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
3027 return rc;
3030 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
3031 int ii;
3032 int rc = SQLITE_OK;
3033 int nCell = NCELL(pNode);
3035 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
3036 RtreeNode *pInsert;
3037 RtreeCell cell;
3038 nodeGetCell(pRtree, pNode, ii, &cell);
3040 /* Find a node to store this cell in. pNode->iNode currently contains
3041 ** the height of the sub-tree headed by the cell.
3043 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
3044 if( rc==SQLITE_OK ){
3045 int rc2;
3046 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
3047 rc2 = nodeRelease(pRtree, pInsert);
3048 if( rc==SQLITE_OK ){
3049 rc = rc2;
3053 return rc;
3057 ** Select a currently unused rowid for a new r-tree record.
3059 static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
3060 int rc;
3061 sqlite3_bind_null(pRtree->pWriteRowid, 1);
3062 sqlite3_bind_null(pRtree->pWriteRowid, 2);
3063 sqlite3_step(pRtree->pWriteRowid);
3064 rc = sqlite3_reset(pRtree->pWriteRowid);
3065 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
3066 return rc;
3070 ** Remove the entry with rowid=iDelete from the r-tree structure.
3072 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
3073 int rc; /* Return code */
3074 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
3075 int iCell; /* Index of iDelete cell in pLeaf */
3076 RtreeNode *pRoot = 0; /* Root node of rtree structure */
3079 /* Obtain a reference to the root node to initialize Rtree.iDepth */
3080 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
3082 /* Obtain a reference to the leaf node that contains the entry
3083 ** about to be deleted.
3085 if( rc==SQLITE_OK ){
3086 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
3089 #ifdef CORRUPT_DB
3090 assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
3091 #endif
3093 /* Delete the cell in question from the leaf node. */
3094 if( rc==SQLITE_OK && pLeaf ){
3095 int rc2;
3096 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
3097 if( rc==SQLITE_OK ){
3098 rc = deleteCell(pRtree, pLeaf, iCell, 0);
3100 rc2 = nodeRelease(pRtree, pLeaf);
3101 if( rc==SQLITE_OK ){
3102 rc = rc2;
3106 /* Delete the corresponding entry in the <rtree>_rowid table. */
3107 if( rc==SQLITE_OK ){
3108 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
3109 sqlite3_step(pRtree->pDeleteRowid);
3110 rc = sqlite3_reset(pRtree->pDeleteRowid);
3113 /* Check if the root node now has exactly one child. If so, remove
3114 ** it, schedule the contents of the child for reinsertion and
3115 ** reduce the tree height by one.
3117 ** This is equivalent to copying the contents of the child into
3118 ** the root node (the operation that Gutman's paper says to perform
3119 ** in this scenario).
3121 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
3122 int rc2;
3123 RtreeNode *pChild = 0;
3124 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
3125 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); /* tag-20210916a */
3126 if( rc==SQLITE_OK ){
3127 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
3129 rc2 = nodeRelease(pRtree, pChild);
3130 if( rc==SQLITE_OK ) rc = rc2;
3131 if( rc==SQLITE_OK ){
3132 pRtree->iDepth--;
3133 writeInt16(pRoot->zData, pRtree->iDepth);
3134 pRoot->isDirty = 1;
3138 /* Re-insert the contents of any underfull nodes removed from the tree. */
3139 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
3140 if( rc==SQLITE_OK ){
3141 rc = reinsertNodeContent(pRtree, pLeaf);
3143 pRtree->pDeleted = pLeaf->pNext;
3144 pRtree->nNodeRef--;
3145 sqlite3_free(pLeaf);
3148 /* Release the reference to the root node. */
3149 if( rc==SQLITE_OK ){
3150 rc = nodeRelease(pRtree, pRoot);
3151 }else{
3152 nodeRelease(pRtree, pRoot);
3155 return rc;
3159 ** Rounding constants for float->double conversion.
3161 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
3162 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
3164 #if !defined(SQLITE_RTREE_INT_ONLY)
3166 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
3167 ** while taking care to round toward negative or positive, respectively.
3169 static RtreeValue rtreeValueDown(sqlite3_value *v){
3170 double d = sqlite3_value_double(v);
3171 float f = (float)d;
3172 if( f>d ){
3173 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
3175 return f;
3177 static RtreeValue rtreeValueUp(sqlite3_value *v){
3178 double d = sqlite3_value_double(v);
3179 float f = (float)d;
3180 if( f<d ){
3181 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
3183 return f;
3185 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
3188 ** A constraint has failed while inserting a row into an rtree table.
3189 ** Assuming no OOM error occurs, this function sets the error message
3190 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
3191 ** SQLITE_CONSTRAINT.
3193 ** Parameter iCol is the index of the leftmost column involved in the
3194 ** constraint failure. If it is 0, then the constraint that failed is
3195 ** the unique constraint on the id column. Otherwise, it is the rtree
3196 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
3198 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
3200 static int rtreeConstraintError(Rtree *pRtree, int iCol){
3201 sqlite3_stmt *pStmt = 0;
3202 char *zSql;
3203 int rc;
3205 assert( iCol==0 || iCol%2 );
3206 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
3207 if( zSql ){
3208 rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
3209 }else{
3210 rc = SQLITE_NOMEM;
3212 sqlite3_free(zSql);
3214 if( rc==SQLITE_OK ){
3215 if( iCol==0 ){
3216 const char *zCol = sqlite3_column_name(pStmt, 0);
3217 pRtree->base.zErrMsg = sqlite3_mprintf(
3218 "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
3220 }else{
3221 const char *zCol1 = sqlite3_column_name(pStmt, iCol);
3222 const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
3223 pRtree->base.zErrMsg = sqlite3_mprintf(
3224 "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
3229 sqlite3_finalize(pStmt);
3230 return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
3236 ** The xUpdate method for rtree module virtual tables.
3238 static int rtreeUpdate(
3239 sqlite3_vtab *pVtab,
3240 int nData,
3241 sqlite3_value **aData,
3242 sqlite_int64 *pRowid
3244 Rtree *pRtree = (Rtree *)pVtab;
3245 int rc = SQLITE_OK;
3246 RtreeCell cell; /* New cell to insert if nData>1 */
3247 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
3249 if( pRtree->nNodeRef ){
3250 /* Unable to write to the btree while another cursor is reading from it,
3251 ** since the write might do a rebalance which would disrupt the read
3252 ** cursor. */
3253 return SQLITE_LOCKED_VTAB;
3255 rtreeReference(pRtree);
3256 assert(nData>=1);
3258 memset(&cell, 0, sizeof(cell));
3260 /* Constraint handling. A write operation on an r-tree table may return
3261 ** SQLITE_CONSTRAINT for two reasons:
3263 ** 1. A duplicate rowid value, or
3264 ** 2. The supplied data violates the "x2>=x1" constraint.
3266 ** In the first case, if the conflict-handling mode is REPLACE, then
3267 ** the conflicting row can be removed before proceeding. In the second
3268 ** case, SQLITE_CONSTRAINT must be returned regardless of the
3269 ** conflict-handling mode specified by the user.
3271 if( nData>1 ){
3272 int ii;
3273 int nn = nData - 4;
3275 if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
3276 /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
3278 ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
3279 ** with "column" that are interpreted as table constraints.
3280 ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
3281 ** This problem was discovered after years of use, so we silently ignore
3282 ** these kinds of misdeclared tables to avoid breaking any legacy.
3285 #ifndef SQLITE_RTREE_INT_ONLY
3286 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
3287 for(ii=0; ii<nn; ii+=2){
3288 cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
3289 cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
3290 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
3291 rc = rtreeConstraintError(pRtree, ii+1);
3292 goto constraint;
3295 }else
3296 #endif
3298 for(ii=0; ii<nn; ii+=2){
3299 cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
3300 cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
3301 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
3302 rc = rtreeConstraintError(pRtree, ii+1);
3303 goto constraint;
3308 /* If a rowid value was supplied, check if it is already present in
3309 ** the table. If so, the constraint has failed. */
3310 if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
3311 cell.iRowid = sqlite3_value_int64(aData[2]);
3312 if( sqlite3_value_type(aData[0])==SQLITE_NULL
3313 || sqlite3_value_int64(aData[0])!=cell.iRowid
3315 int steprc;
3316 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
3317 steprc = sqlite3_step(pRtree->pReadRowid);
3318 rc = sqlite3_reset(pRtree->pReadRowid);
3319 if( SQLITE_ROW==steprc ){
3320 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
3321 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
3322 }else{
3323 rc = rtreeConstraintError(pRtree, 0);
3324 goto constraint;
3328 bHaveRowid = 1;
3332 /* If aData[0] is not an SQL NULL value, it is the rowid of a
3333 ** record to delete from the r-tree table. The following block does
3334 ** just that.
3336 if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
3337 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
3340 /* If the aData[] array contains more than one element, elements
3341 ** (aData[2]..aData[argc-1]) contain a new record to insert into
3342 ** the r-tree structure.
3344 if( rc==SQLITE_OK && nData>1 ){
3345 /* Insert the new record into the r-tree */
3346 RtreeNode *pLeaf = 0;
3348 /* Figure out the rowid of the new row. */
3349 if( bHaveRowid==0 ){
3350 rc = rtreeNewRowid(pRtree, &cell.iRowid);
3352 *pRowid = cell.iRowid;
3354 if( rc==SQLITE_OK ){
3355 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
3357 if( rc==SQLITE_OK ){
3358 int rc2;
3359 pRtree->iReinsertHeight = -1;
3360 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
3361 rc2 = nodeRelease(pRtree, pLeaf);
3362 if( rc==SQLITE_OK ){
3363 rc = rc2;
3366 if( rc==SQLITE_OK && pRtree->nAux ){
3367 sqlite3_stmt *pUp = pRtree->pWriteAux;
3368 int jj;
3369 sqlite3_bind_int64(pUp, 1, *pRowid);
3370 for(jj=0; jj<pRtree->nAux; jj++){
3371 sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
3373 sqlite3_step(pUp);
3374 rc = sqlite3_reset(pUp);
3378 constraint:
3379 rtreeRelease(pRtree);
3380 return rc;
3384 ** Called when a transaction starts.
3386 static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
3387 Rtree *pRtree = (Rtree *)pVtab;
3388 assert( pRtree->inWrTrans==0 );
3389 pRtree->inWrTrans++;
3390 return SQLITE_OK;
3394 ** Called when a transaction completes (either by COMMIT or ROLLBACK).
3395 ** The sqlite3_blob object should be released at this point.
3397 static int rtreeEndTransaction(sqlite3_vtab *pVtab){
3398 Rtree *pRtree = (Rtree *)pVtab;
3399 pRtree->inWrTrans = 0;
3400 nodeBlobReset(pRtree);
3401 return SQLITE_OK;
3405 ** The xRename method for rtree module virtual tables.
3407 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
3408 Rtree *pRtree = (Rtree *)pVtab;
3409 int rc = SQLITE_NOMEM;
3410 char *zSql = sqlite3_mprintf(
3411 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
3412 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
3413 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
3414 , pRtree->zDb, pRtree->zName, zNewName
3415 , pRtree->zDb, pRtree->zName, zNewName
3416 , pRtree->zDb, pRtree->zName, zNewName
3418 if( zSql ){
3419 nodeBlobReset(pRtree);
3420 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
3421 sqlite3_free(zSql);
3423 return rc;
3427 ** The xSavepoint method.
3429 ** This module does not need to do anything to support savepoints. However,
3430 ** it uses this hook to close any open blob handle. This is done because a
3431 ** DROP TABLE command - which fortunately always opens a savepoint - cannot
3432 ** succeed if there are any open blob handles. i.e. if the blob handle were
3433 ** not closed here, the following would fail:
3435 ** BEGIN;
3436 ** INSERT INTO rtree...
3437 ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
3438 ** COMMIT;
3440 static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
3441 Rtree *pRtree = (Rtree *)pVtab;
3442 u8 iwt = pRtree->inWrTrans;
3443 UNUSED_PARAMETER(iSavepoint);
3444 pRtree->inWrTrans = 0;
3445 nodeBlobReset(pRtree);
3446 pRtree->inWrTrans = iwt;
3447 return SQLITE_OK;
3451 ** This function populates the pRtree->nRowEst variable with an estimate
3452 ** of the number of rows in the virtual table. If possible, this is based
3453 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
3455 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
3456 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
3457 char *zSql;
3458 sqlite3_stmt *p;
3459 int rc;
3460 i64 nRow = RTREE_MIN_ROWEST;
3462 rc = sqlite3_table_column_metadata(
3463 db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
3465 if( rc!=SQLITE_OK ){
3466 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
3467 return rc==SQLITE_ERROR ? SQLITE_OK : rc;
3469 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
3470 if( zSql==0 ){
3471 rc = SQLITE_NOMEM;
3472 }else{
3473 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
3474 if( rc==SQLITE_OK ){
3475 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
3476 rc = sqlite3_finalize(p);
3478 sqlite3_free(zSql);
3480 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
3481 return rc;
3486 ** Return true if zName is the extension on one of the shadow tables used
3487 ** by this module.
3489 static int rtreeShadowName(const char *zName){
3490 static const char *azName[] = {
3491 "node", "parent", "rowid"
3493 unsigned int i;
3494 for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
3495 if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
3497 return 0;
3500 static sqlite3_module rtreeModule = {
3501 3, /* iVersion */
3502 rtreeCreate, /* xCreate - create a table */
3503 rtreeConnect, /* xConnect - connect to an existing table */
3504 rtreeBestIndex, /* xBestIndex - Determine search strategy */
3505 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
3506 rtreeDestroy, /* xDestroy - Drop a table */
3507 rtreeOpen, /* xOpen - open a cursor */
3508 rtreeClose, /* xClose - close a cursor */
3509 rtreeFilter, /* xFilter - configure scan constraints */
3510 rtreeNext, /* xNext - advance a cursor */
3511 rtreeEof, /* xEof */
3512 rtreeColumn, /* xColumn - read data */
3513 rtreeRowid, /* xRowid - read data */
3514 rtreeUpdate, /* xUpdate - write data */
3515 rtreeBeginTransaction, /* xBegin - begin transaction */
3516 rtreeEndTransaction, /* xSync - sync transaction */
3517 rtreeEndTransaction, /* xCommit - commit transaction */
3518 rtreeEndTransaction, /* xRollback - rollback transaction */
3519 0, /* xFindFunction - function overloading */
3520 rtreeRename, /* xRename - rename the table */
3521 rtreeSavepoint, /* xSavepoint */
3522 0, /* xRelease */
3523 0, /* xRollbackTo */
3524 rtreeShadowName /* xShadowName */
3527 static int rtreeSqlInit(
3528 Rtree *pRtree,
3529 sqlite3 *db,
3530 const char *zDb,
3531 const char *zPrefix,
3532 int isCreate
3534 int rc = SQLITE_OK;
3536 #define N_STATEMENT 8
3537 static const char *azSql[N_STATEMENT] = {
3538 /* Write the xxx_node table */
3539 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
3540 "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
3542 /* Read and write the xxx_rowid table */
3543 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3544 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
3545 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3547 /* Read and write the xxx_parent table */
3548 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
3549 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
3550 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
3552 sqlite3_stmt **appStmt[N_STATEMENT];
3553 int i;
3554 const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
3556 pRtree->db = db;
3558 if( isCreate ){
3559 char *zCreate;
3560 sqlite3_str *p = sqlite3_str_new(db);
3561 int ii;
3562 sqlite3_str_appendf(p,
3563 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
3564 zDb, zPrefix);
3565 for(ii=0; ii<pRtree->nAux; ii++){
3566 sqlite3_str_appendf(p,",a%d",ii);
3568 sqlite3_str_appendf(p,
3569 ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
3570 zDb, zPrefix);
3571 sqlite3_str_appendf(p,
3572 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
3573 zDb, zPrefix);
3574 sqlite3_str_appendf(p,
3575 "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
3576 zDb, zPrefix, pRtree->iNodeSize);
3577 zCreate = sqlite3_str_finish(p);
3578 if( !zCreate ){
3579 return SQLITE_NOMEM;
3581 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
3582 sqlite3_free(zCreate);
3583 if( rc!=SQLITE_OK ){
3584 return rc;
3588 appStmt[0] = &pRtree->pWriteNode;
3589 appStmt[1] = &pRtree->pDeleteNode;
3590 appStmt[2] = &pRtree->pReadRowid;
3591 appStmt[3] = &pRtree->pWriteRowid;
3592 appStmt[4] = &pRtree->pDeleteRowid;
3593 appStmt[5] = &pRtree->pReadParent;
3594 appStmt[6] = &pRtree->pWriteParent;
3595 appStmt[7] = &pRtree->pDeleteParent;
3597 rc = rtreeQueryStat1(db, pRtree);
3598 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
3599 char *zSql;
3600 const char *zFormat;
3601 if( i!=3 || pRtree->nAux==0 ){
3602 zFormat = azSql[i];
3603 }else {
3604 /* An UPSERT is very slightly slower than REPLACE, but it is needed
3605 ** if there are auxiliary columns */
3606 zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
3607 "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
3609 zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
3610 if( zSql ){
3611 rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
3612 }else{
3613 rc = SQLITE_NOMEM;
3615 sqlite3_free(zSql);
3617 if( pRtree->nAux ){
3618 pRtree->zReadAuxSql = sqlite3_mprintf(
3619 "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
3620 zDb, zPrefix);
3621 if( pRtree->zReadAuxSql==0 ){
3622 rc = SQLITE_NOMEM;
3623 }else{
3624 sqlite3_str *p = sqlite3_str_new(db);
3625 int ii;
3626 char *zSql;
3627 sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
3628 for(ii=0; ii<pRtree->nAux; ii++){
3629 if( ii ) sqlite3_str_append(p, ",", 1);
3630 #ifdef SQLITE_ENABLE_GEOPOLY
3631 if( ii<pRtree->nAuxNotNull ){
3632 sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
3633 }else
3634 #endif
3636 sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
3639 sqlite3_str_appendf(p, " WHERE rowid=?1");
3640 zSql = sqlite3_str_finish(p);
3641 if( zSql==0 ){
3642 rc = SQLITE_NOMEM;
3643 }else{
3644 rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
3645 sqlite3_free(zSql);
3650 return rc;
3654 ** The second argument to this function contains the text of an SQL statement
3655 ** that returns a single integer value. The statement is compiled and executed
3656 ** using database connection db. If successful, the integer value returned
3657 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
3658 ** code is returned and the value of *piVal after returning is not defined.
3660 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
3661 int rc = SQLITE_NOMEM;
3662 if( zSql ){
3663 sqlite3_stmt *pStmt = 0;
3664 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3665 if( rc==SQLITE_OK ){
3666 if( SQLITE_ROW==sqlite3_step(pStmt) ){
3667 *piVal = sqlite3_column_int(pStmt, 0);
3669 rc = sqlite3_finalize(pStmt);
3672 return rc;
3676 ** This function is called from within the xConnect() or xCreate() method to
3677 ** determine the node-size used by the rtree table being created or connected
3678 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
3679 ** Otherwise, an SQLite error code is returned.
3681 ** If this function is being called as part of an xConnect(), then the rtree
3682 ** table already exists. In this case the node-size is determined by inspecting
3683 ** the root node of the tree.
3685 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
3686 ** This ensures that each node is stored on a single database page. If the
3687 ** database page-size is so large that more than RTREE_MAXCELLS entries
3688 ** would fit in a single node, use a smaller node-size.
3690 static int getNodeSize(
3691 sqlite3 *db, /* Database handle */
3692 Rtree *pRtree, /* Rtree handle */
3693 int isCreate, /* True for xCreate, false for xConnect */
3694 char **pzErr /* OUT: Error message, if any */
3696 int rc;
3697 char *zSql;
3698 if( isCreate ){
3699 int iPageSize = 0;
3700 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
3701 rc = getIntFromStmt(db, zSql, &iPageSize);
3702 if( rc==SQLITE_OK ){
3703 pRtree->iNodeSize = iPageSize-64;
3704 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
3705 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
3707 }else{
3708 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3710 }else{
3711 zSql = sqlite3_mprintf(
3712 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
3713 pRtree->zDb, pRtree->zName
3715 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
3716 if( rc!=SQLITE_OK ){
3717 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3718 }else if( pRtree->iNodeSize<(512-64) ){
3719 rc = SQLITE_CORRUPT_VTAB;
3720 RTREE_IS_CORRUPT(pRtree);
3721 *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
3722 pRtree->zName);
3726 sqlite3_free(zSql);
3727 return rc;
3731 ** Return the length of a token
3733 static int rtreeTokenLength(const char *z){
3734 int dummy = 0;
3735 return sqlite3GetToken((const unsigned char*)z,&dummy);
3739 ** This function is the implementation of both the xConnect and xCreate
3740 ** methods of the r-tree virtual table.
3742 ** argv[0] -> module name
3743 ** argv[1] -> database name
3744 ** argv[2] -> table name
3745 ** argv[...] -> column names...
3747 static int rtreeInit(
3748 sqlite3 *db, /* Database connection */
3749 void *pAux, /* One of the RTREE_COORD_* constants */
3750 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
3751 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
3752 char **pzErr, /* OUT: Error message, if any */
3753 int isCreate /* True for xCreate, false for xConnect */
3755 int rc = SQLITE_OK;
3756 Rtree *pRtree;
3757 int nDb; /* Length of string argv[1] */
3758 int nName; /* Length of string argv[2] */
3759 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
3760 sqlite3_str *pSql;
3761 char *zSql;
3762 int ii = 4;
3763 int iErr;
3765 const char *aErrMsg[] = {
3766 0, /* 0 */
3767 "Wrong number of columns for an rtree table", /* 1 */
3768 "Too few columns for an rtree table", /* 2 */
3769 "Too many columns for an rtree table", /* 3 */
3770 "Auxiliary rtree columns must be last" /* 4 */
3773 assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
3774 if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
3775 *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
3776 return SQLITE_ERROR;
3779 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
3781 /* Allocate the sqlite3_vtab structure */
3782 nDb = (int)strlen(argv[1]);
3783 nName = (int)strlen(argv[2]);
3784 pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
3785 if( !pRtree ){
3786 return SQLITE_NOMEM;
3788 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
3789 pRtree->nBusy = 1;
3790 pRtree->base.pModule = &rtreeModule;
3791 pRtree->zDb = (char *)&pRtree[1];
3792 pRtree->zName = &pRtree->zDb[nDb+1];
3793 pRtree->eCoordType = (u8)eCoordType;
3794 memcpy(pRtree->zDb, argv[1], nDb);
3795 memcpy(pRtree->zName, argv[2], nName);
3798 /* Create/Connect to the underlying relational database schema. If
3799 ** that is successful, call sqlite3_declare_vtab() to configure
3800 ** the r-tree table schema.
3802 pSql = sqlite3_str_new(db);
3803 sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
3804 rtreeTokenLength(argv[3]), argv[3]);
3805 for(ii=4; ii<argc; ii++){
3806 const char *zArg = argv[ii];
3807 if( zArg[0]=='+' ){
3808 pRtree->nAux++;
3809 sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
3810 }else if( pRtree->nAux>0 ){
3811 break;
3812 }else{
3813 static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
3814 pRtree->nDim2++;
3815 sqlite3_str_appendf(pSql, azFormat[eCoordType],
3816 rtreeTokenLength(zArg), zArg);
3819 sqlite3_str_appendf(pSql, ");");
3820 zSql = sqlite3_str_finish(pSql);
3821 if( !zSql ){
3822 rc = SQLITE_NOMEM;
3823 }else if( ii<argc ){
3824 *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
3825 rc = SQLITE_ERROR;
3826 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3827 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3829 sqlite3_free(zSql);
3830 if( rc ) goto rtreeInit_fail;
3831 pRtree->nDim = pRtree->nDim2/2;
3832 if( pRtree->nDim<1 ){
3833 iErr = 2;
3834 }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
3835 iErr = 3;
3836 }else if( pRtree->nDim2 % 2 ){
3837 iErr = 1;
3838 }else{
3839 iErr = 0;
3841 if( iErr ){
3842 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3843 goto rtreeInit_fail;
3845 pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
3847 /* Figure out the node size to use. */
3848 rc = getNodeSize(db, pRtree, isCreate, pzErr);
3849 if( rc ) goto rtreeInit_fail;
3850 rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
3851 if( rc ){
3852 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3853 goto rtreeInit_fail;
3856 *ppVtab = (sqlite3_vtab *)pRtree;
3857 return SQLITE_OK;
3859 rtreeInit_fail:
3860 if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
3861 assert( *ppVtab==0 );
3862 assert( pRtree->nBusy==1 );
3863 rtreeRelease(pRtree);
3864 return rc;
3869 ** Implementation of a scalar function that decodes r-tree nodes to
3870 ** human readable strings. This can be used for debugging and analysis.
3872 ** The scalar function takes two arguments: (1) the number of dimensions
3873 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
3874 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
3875 ** deserialize all nodes, a statement like:
3877 ** SELECT rtreenode(2, data) FROM rt_node;
3879 ** The human readable string takes the form of a Tcl list with one
3880 ** entry for each cell in the r-tree node. Each entry is itself a
3881 ** list, containing the 8-byte rowid/pageno followed by the
3882 ** <num-dimension>*2 coordinates.
3884 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3885 RtreeNode node;
3886 Rtree tree;
3887 int ii;
3888 int nData;
3889 int errCode;
3890 sqlite3_str *pOut;
3892 UNUSED_PARAMETER(nArg);
3893 memset(&node, 0, sizeof(RtreeNode));
3894 memset(&tree, 0, sizeof(Rtree));
3895 tree.nDim = (u8)sqlite3_value_int(apArg[0]);
3896 if( tree.nDim<1 || tree.nDim>5 ) return;
3897 tree.nDim2 = tree.nDim*2;
3898 tree.nBytesPerCell = 8 + 8 * tree.nDim;
3899 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3900 if( node.zData==0 ) return;
3901 nData = sqlite3_value_bytes(apArg[1]);
3902 if( nData<4 ) return;
3903 if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
3905 pOut = sqlite3_str_new(0);
3906 for(ii=0; ii<NCELL(&node); ii++){
3907 RtreeCell cell;
3908 int jj;
3910 nodeGetCell(&tree, &node, ii, &cell);
3911 if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
3912 sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
3913 for(jj=0; jj<tree.nDim2; jj++){
3914 #ifndef SQLITE_RTREE_INT_ONLY
3915 sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
3916 #else
3917 sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
3918 #endif
3920 sqlite3_str_append(pOut, "}", 1);
3922 errCode = sqlite3_str_errcode(pOut);
3923 sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
3924 sqlite3_result_error_code(ctx, errCode);
3927 /* This routine implements an SQL function that returns the "depth" parameter
3928 ** from the front of a blob that is an r-tree node. For example:
3930 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
3932 ** The depth value is 0 for all nodes other than the root node, and the root
3933 ** node always has nodeno=1, so the example above is the primary use for this
3934 ** routine. This routine is intended for testing and analysis only.
3936 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3937 UNUSED_PARAMETER(nArg);
3938 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3939 || sqlite3_value_bytes(apArg[0])<2
3942 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3943 }else{
3944 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3945 if( zBlob ){
3946 sqlite3_result_int(ctx, readInt16(zBlob));
3947 }else{
3948 sqlite3_result_error_nomem(ctx);
3954 ** Context object passed between the various routines that make up the
3955 ** implementation of integrity-check function rtreecheck().
3957 typedef struct RtreeCheck RtreeCheck;
3958 struct RtreeCheck {
3959 sqlite3 *db; /* Database handle */
3960 const char *zDb; /* Database containing rtree table */
3961 const char *zTab; /* Name of rtree table */
3962 int bInt; /* True for rtree_i32 table */
3963 int nDim; /* Number of dimensions for this rtree tbl */
3964 sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
3965 sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
3966 int nLeaf; /* Number of leaf cells in table */
3967 int nNonLeaf; /* Number of non-leaf cells in table */
3968 int rc; /* Return code */
3969 char *zReport; /* Message to report */
3970 int nErr; /* Number of lines in zReport */
3973 #define RTREE_CHECK_MAX_ERROR 100
3976 ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
3977 ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
3979 static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
3980 int rc = sqlite3_reset(pStmt);
3981 if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
3985 ** The second and subsequent arguments to this function are a format string
3986 ** and printf style arguments. This function formats the string and attempts
3987 ** to compile it as an SQL statement.
3989 ** If successful, a pointer to the new SQL statement is returned. Otherwise,
3990 ** NULL is returned and an error code left in RtreeCheck.rc.
3992 static sqlite3_stmt *rtreeCheckPrepare(
3993 RtreeCheck *pCheck, /* RtreeCheck object */
3994 const char *zFmt, ... /* Format string and trailing args */
3996 va_list ap;
3997 char *z;
3998 sqlite3_stmt *pRet = 0;
4000 va_start(ap, zFmt);
4001 z = sqlite3_vmprintf(zFmt, ap);
4003 if( pCheck->rc==SQLITE_OK ){
4004 if( z==0 ){
4005 pCheck->rc = SQLITE_NOMEM;
4006 }else{
4007 pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
4011 sqlite3_free(z);
4012 va_end(ap);
4013 return pRet;
4017 ** The second and subsequent arguments to this function are a printf()
4018 ** style format string and arguments. This function formats the string and
4019 ** appends it to the report being accumuated in pCheck.
4021 static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
4022 va_list ap;
4023 va_start(ap, zFmt);
4024 if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
4025 char *z = sqlite3_vmprintf(zFmt, ap);
4026 if( z==0 ){
4027 pCheck->rc = SQLITE_NOMEM;
4028 }else{
4029 pCheck->zReport = sqlite3_mprintf("%z%s%z",
4030 pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
4032 if( pCheck->zReport==0 ){
4033 pCheck->rc = SQLITE_NOMEM;
4036 pCheck->nErr++;
4038 va_end(ap);
4042 ** This function is a no-op if there is already an error code stored
4043 ** in the RtreeCheck object indicated by the first argument. NULL is
4044 ** returned in this case.
4046 ** Otherwise, the contents of rtree table node iNode are loaded from
4047 ** the database and copied into a buffer obtained from sqlite3_malloc().
4048 ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
4049 ** is set to the size of the buffer in bytes.
4051 ** Or, if an error does occur, NULL is returned and an error code left
4052 ** in the RtreeCheck object. The final value of *pnNode is undefined in
4053 ** this case.
4055 static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
4056 u8 *pRet = 0; /* Return value */
4058 if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
4059 pCheck->pGetNode = rtreeCheckPrepare(pCheck,
4060 "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
4061 pCheck->zDb, pCheck->zTab
4065 if( pCheck->rc==SQLITE_OK ){
4066 sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
4067 if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
4068 int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
4069 const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
4070 pRet = sqlite3_malloc64(nNode);
4071 if( pRet==0 ){
4072 pCheck->rc = SQLITE_NOMEM;
4073 }else{
4074 memcpy(pRet, pNode, nNode);
4075 *pnNode = nNode;
4078 rtreeCheckReset(pCheck, pCheck->pGetNode);
4079 if( pCheck->rc==SQLITE_OK && pRet==0 ){
4080 rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
4084 return pRet;
4088 ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
4089 ** (if bLeaf==1) table contains a specified entry. The schemas of the
4090 ** two tables are:
4092 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
4093 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
4095 ** In both cases, this function checks that there exists an entry with
4096 ** IPK value iKey and the second column set to iVal.
4099 static void rtreeCheckMapping(
4100 RtreeCheck *pCheck, /* RtreeCheck object */
4101 int bLeaf, /* True for a leaf cell, false for interior */
4102 i64 iKey, /* Key for mapping */
4103 i64 iVal /* Expected value for mapping */
4105 int rc;
4106 sqlite3_stmt *pStmt;
4107 const char *azSql[2] = {
4108 "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
4109 "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
4112 assert( bLeaf==0 || bLeaf==1 );
4113 if( pCheck->aCheckMapping[bLeaf]==0 ){
4114 pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
4115 azSql[bLeaf], pCheck->zDb, pCheck->zTab
4118 if( pCheck->rc!=SQLITE_OK ) return;
4120 pStmt = pCheck->aCheckMapping[bLeaf];
4121 sqlite3_bind_int64(pStmt, 1, iKey);
4122 rc = sqlite3_step(pStmt);
4123 if( rc==SQLITE_DONE ){
4124 rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
4125 iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
4127 }else if( rc==SQLITE_ROW ){
4128 i64 ii = sqlite3_column_int64(pStmt, 0);
4129 if( ii!=iVal ){
4130 rtreeCheckAppendMsg(pCheck,
4131 "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
4132 iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
4136 rtreeCheckReset(pCheck, pStmt);
4140 ** Argument pCell points to an array of coordinates stored on an rtree page.
4141 ** This function checks that the coordinates are internally consistent (no
4142 ** x1>x2 conditions) and adds an error message to the RtreeCheck object
4143 ** if they are not.
4145 ** Additionally, if pParent is not NULL, then it is assumed to point to
4146 ** the array of coordinates on the parent page that bound the page
4147 ** containing pCell. In this case it is also verified that the two
4148 ** sets of coordinates are mutually consistent and an error message added
4149 ** to the RtreeCheck object if they are not.
4151 static void rtreeCheckCellCoord(
4152 RtreeCheck *pCheck,
4153 i64 iNode, /* Node id to use in error messages */
4154 int iCell, /* Cell number to use in error messages */
4155 u8 *pCell, /* Pointer to cell coordinates */
4156 u8 *pParent /* Pointer to parent coordinates */
4158 RtreeCoord c1, c2;
4159 RtreeCoord p1, p2;
4160 int i;
4162 for(i=0; i<pCheck->nDim; i++){
4163 readCoord(&pCell[4*2*i], &c1);
4164 readCoord(&pCell[4*(2*i + 1)], &c2);
4166 /* printf("%e, %e\n", c1.u.f, c2.u.f); */
4167 if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
4168 rtreeCheckAppendMsg(pCheck,
4169 "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
4173 if( pParent ){
4174 readCoord(&pParent[4*2*i], &p1);
4175 readCoord(&pParent[4*(2*i + 1)], &p2);
4177 if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
4178 || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
4180 rtreeCheckAppendMsg(pCheck,
4181 "Dimension %d of cell %d on node %lld is corrupt relative to parent"
4182 , i, iCell, iNode
4190 ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
4191 ** the r-tree structure. Argument aParent points to the array of coordinates
4192 ** that bound node iNode on the parent node.
4194 ** If any problems are discovered, an error message is appended to the
4195 ** report accumulated in the RtreeCheck object.
4197 static void rtreeCheckNode(
4198 RtreeCheck *pCheck,
4199 int iDepth, /* Depth of iNode (0==leaf) */
4200 u8 *aParent, /* Buffer containing parent coords */
4201 i64 iNode /* Node to check */
4203 u8 *aNode = 0;
4204 int nNode = 0;
4206 assert( iNode==1 || aParent!=0 );
4207 assert( pCheck->nDim>0 );
4209 aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
4210 if( aNode ){
4211 if( nNode<4 ){
4212 rtreeCheckAppendMsg(pCheck,
4213 "Node %lld is too small (%d bytes)", iNode, nNode
4215 }else{
4216 int nCell; /* Number of cells on page */
4217 int i; /* Used to iterate through cells */
4218 if( aParent==0 ){
4219 iDepth = readInt16(aNode);
4220 if( iDepth>RTREE_MAX_DEPTH ){
4221 rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
4222 sqlite3_free(aNode);
4223 return;
4226 nCell = readInt16(&aNode[2]);
4227 if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
4228 rtreeCheckAppendMsg(pCheck,
4229 "Node %lld is too small for cell count of %d (%d bytes)",
4230 iNode, nCell, nNode
4232 }else{
4233 for(i=0; i<nCell; i++){
4234 u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
4235 i64 iVal = readInt64(pCell);
4236 rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
4238 if( iDepth>0 ){
4239 rtreeCheckMapping(pCheck, 0, iVal, iNode);
4240 rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
4241 pCheck->nNonLeaf++;
4242 }else{
4243 rtreeCheckMapping(pCheck, 1, iVal, iNode);
4244 pCheck->nLeaf++;
4249 sqlite3_free(aNode);
4254 ** The second argument to this function must be either "_rowid" or
4255 ** "_parent". This function checks that the number of entries in the
4256 ** %_rowid or %_parent table is exactly nExpect. If not, it adds
4257 ** an error message to the report in the RtreeCheck object indicated
4258 ** by the first argument.
4260 static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
4261 if( pCheck->rc==SQLITE_OK ){
4262 sqlite3_stmt *pCount;
4263 pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
4264 pCheck->zDb, pCheck->zTab, zTbl
4266 if( pCount ){
4267 if( sqlite3_step(pCount)==SQLITE_ROW ){
4268 i64 nActual = sqlite3_column_int64(pCount, 0);
4269 if( nActual!=nExpect ){
4270 rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
4271 " - expected %lld, actual %lld" , zTbl, nExpect, nActual
4275 pCheck->rc = sqlite3_finalize(pCount);
4281 ** This function does the bulk of the work for the rtree integrity-check.
4282 ** It is called by rtreecheck(), which is the SQL function implementation.
4284 static int rtreeCheckTable(
4285 sqlite3 *db, /* Database handle to access db through */
4286 const char *zDb, /* Name of db ("main", "temp" etc.) */
4287 const char *zTab, /* Name of rtree table to check */
4288 char **pzReport /* OUT: sqlite3_malloc'd report text */
4290 RtreeCheck check; /* Common context for various routines */
4291 sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
4292 int bEnd = 0; /* True if transaction should be closed */
4293 int nAux = 0; /* Number of extra columns. */
4295 /* Initialize the context object */
4296 memset(&check, 0, sizeof(check));
4297 check.db = db;
4298 check.zDb = zDb;
4299 check.zTab = zTab;
4301 /* If there is not already an open transaction, open one now. This is
4302 ** to ensure that the queries run as part of this integrity-check operate
4303 ** on a consistent snapshot. */
4304 if( sqlite3_get_autocommit(db) ){
4305 check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
4306 bEnd = 1;
4309 /* Find the number of auxiliary columns */
4310 if( check.rc==SQLITE_OK ){
4311 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
4312 if( pStmt ){
4313 nAux = sqlite3_column_count(pStmt) - 2;
4314 sqlite3_finalize(pStmt);
4315 }else
4316 if( check.rc!=SQLITE_NOMEM ){
4317 check.rc = SQLITE_OK;
4321 /* Find number of dimensions in the rtree table. */
4322 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
4323 if( pStmt ){
4324 int rc;
4325 check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
4326 if( check.nDim<1 ){
4327 rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
4328 }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
4329 check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
4331 rc = sqlite3_finalize(pStmt);
4332 if( rc!=SQLITE_CORRUPT ) check.rc = rc;
4335 /* Do the actual integrity-check */
4336 if( check.nDim>=1 ){
4337 if( check.rc==SQLITE_OK ){
4338 rtreeCheckNode(&check, 0, 0, 1);
4340 rtreeCheckCount(&check, "_rowid", check.nLeaf);
4341 rtreeCheckCount(&check, "_parent", check.nNonLeaf);
4344 /* Finalize SQL statements used by the integrity-check */
4345 sqlite3_finalize(check.pGetNode);
4346 sqlite3_finalize(check.aCheckMapping[0]);
4347 sqlite3_finalize(check.aCheckMapping[1]);
4349 /* If one was opened, close the transaction */
4350 if( bEnd ){
4351 int rc = sqlite3_exec(db, "END", 0, 0, 0);
4352 if( check.rc==SQLITE_OK ) check.rc = rc;
4354 *pzReport = check.zReport;
4355 return check.rc;
4359 ** Usage:
4361 ** rtreecheck(<rtree-table>);
4362 ** rtreecheck(<database>, <rtree-table>);
4364 ** Invoking this SQL function runs an integrity-check on the named rtree
4365 ** table. The integrity-check verifies the following:
4367 ** 1. For each cell in the r-tree structure (%_node table), that:
4369 ** a) for each dimension, (coord1 <= coord2).
4371 ** b) unless the cell is on the root node, that the cell is bounded
4372 ** by the parent cell on the parent node.
4374 ** c) for leaf nodes, that there is an entry in the %_rowid
4375 ** table corresponding to the cell's rowid value that
4376 ** points to the correct node.
4378 ** d) for cells on non-leaf nodes, that there is an entry in the
4379 ** %_parent table mapping from the cell's child node to the
4380 ** node that it resides on.
4382 ** 2. That there are the same number of entries in the %_rowid table
4383 ** as there are leaf cells in the r-tree structure, and that there
4384 ** is a leaf cell that corresponds to each entry in the %_rowid table.
4386 ** 3. That there are the same number of entries in the %_parent table
4387 ** as there are non-leaf cells in the r-tree structure, and that
4388 ** there is a non-leaf cell that corresponds to each entry in the
4389 ** %_parent table.
4391 static void rtreecheck(
4392 sqlite3_context *ctx,
4393 int nArg,
4394 sqlite3_value **apArg
4396 if( nArg!=1 && nArg!=2 ){
4397 sqlite3_result_error(ctx,
4398 "wrong number of arguments to function rtreecheck()", -1
4400 }else{
4401 int rc;
4402 char *zReport = 0;
4403 const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
4404 const char *zTab;
4405 if( nArg==1 ){
4406 zTab = zDb;
4407 zDb = "main";
4408 }else{
4409 zTab = (const char*)sqlite3_value_text(apArg[1]);
4411 rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
4412 if( rc==SQLITE_OK ){
4413 sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
4414 }else{
4415 sqlite3_result_error_code(ctx, rc);
4417 sqlite3_free(zReport);
4421 /* Conditionally include the geopoly code */
4422 #ifdef SQLITE_ENABLE_GEOPOLY
4423 # include "geopoly.c"
4424 #endif
4427 ** Register the r-tree module with database handle db. This creates the
4428 ** virtual table module "rtree" and the debugging/analysis scalar
4429 ** function "rtreenode".
4431 int sqlite3RtreeInit(sqlite3 *db){
4432 const int utf8 = SQLITE_UTF8;
4433 int rc;
4435 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
4436 if( rc==SQLITE_OK ){
4437 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
4439 if( rc==SQLITE_OK ){
4440 rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
4442 if( rc==SQLITE_OK ){
4443 #ifdef SQLITE_RTREE_INT_ONLY
4444 void *c = (void *)RTREE_COORD_INT32;
4445 #else
4446 void *c = (void *)RTREE_COORD_REAL32;
4447 #endif
4448 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
4450 if( rc==SQLITE_OK ){
4451 void *c = (void *)RTREE_COORD_INT32;
4452 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
4454 #ifdef SQLITE_ENABLE_GEOPOLY
4455 if( rc==SQLITE_OK ){
4456 rc = sqlite3_geopoly_init(db);
4458 #endif
4460 return rc;
4464 ** This routine deletes the RtreeGeomCallback object that was attached
4465 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
4466 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
4467 ** destructor for an RtreeGeomCallback objecct. This routine is called when
4468 ** the corresponding SQL function is deleted.
4470 static void rtreeFreeCallback(void *p){
4471 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
4472 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
4473 sqlite3_free(p);
4477 ** This routine frees the BLOB that is returned by geomCallback().
4479 static void rtreeMatchArgFree(void *pArg){
4480 int i;
4481 RtreeMatchArg *p = (RtreeMatchArg*)pArg;
4482 for(i=0; i<p->nParam; i++){
4483 sqlite3_value_free(p->apSqlParam[i]);
4485 sqlite3_free(p);
4489 ** Each call to sqlite3_rtree_geometry_callback() or
4490 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
4491 ** scalar function that is implemented by this routine.
4493 ** All this function does is construct an RtreeMatchArg object that
4494 ** contains the geometry-checking callback routines and a list of
4495 ** parameters to this function, then return that RtreeMatchArg object
4496 ** as a BLOB.
4498 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
4499 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
4500 ** out which elements of the R-Tree should be returned by the query.
4502 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
4503 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
4504 RtreeMatchArg *pBlob;
4505 sqlite3_int64 nBlob;
4506 int memErr = 0;
4508 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
4509 + nArg*sizeof(sqlite3_value*);
4510 pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
4511 if( !pBlob ){
4512 sqlite3_result_error_nomem(ctx);
4513 }else{
4514 int i;
4515 pBlob->iSize = nBlob;
4516 pBlob->cb = pGeomCtx[0];
4517 pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
4518 pBlob->nParam = nArg;
4519 for(i=0; i<nArg; i++){
4520 pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
4521 if( pBlob->apSqlParam[i]==0 ) memErr = 1;
4522 #ifdef SQLITE_RTREE_INT_ONLY
4523 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
4524 #else
4525 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
4526 #endif
4528 if( memErr ){
4529 sqlite3_result_error_nomem(ctx);
4530 rtreeMatchArgFree(pBlob);
4531 }else{
4532 sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
4538 ** Register a new geometry function for use with the r-tree MATCH operator.
4540 int sqlite3_rtree_geometry_callback(
4541 sqlite3 *db, /* Register SQL function on this connection */
4542 const char *zGeom, /* Name of the new SQL function */
4543 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
4544 void *pContext /* Extra data associated with the callback */
4546 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
4548 /* Allocate and populate the context object. */
4549 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4550 if( !pGeomCtx ) return SQLITE_NOMEM;
4551 pGeomCtx->xGeom = xGeom;
4552 pGeomCtx->xQueryFunc = 0;
4553 pGeomCtx->xDestructor = 0;
4554 pGeomCtx->pContext = pContext;
4555 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
4556 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4561 ** Register a new 2nd-generation geometry function for use with the
4562 ** r-tree MATCH operator.
4564 int sqlite3_rtree_query_callback(
4565 sqlite3 *db, /* Register SQL function on this connection */
4566 const char *zQueryFunc, /* Name of new SQL function */
4567 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
4568 void *pContext, /* Extra data passed into the callback */
4569 void (*xDestructor)(void*) /* Destructor for the extra data */
4571 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
4573 /* Allocate and populate the context object. */
4574 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4575 if( !pGeomCtx ){
4576 if( xDestructor ) xDestructor(pContext);
4577 return SQLITE_NOMEM;
4579 pGeomCtx->xGeom = 0;
4580 pGeomCtx->xQueryFunc = xQueryFunc;
4581 pGeomCtx->xDestructor = xDestructor;
4582 pGeomCtx->pContext = pContext;
4583 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
4584 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4588 #if !SQLITE_CORE
4589 #ifdef _WIN32
4590 __declspec(dllexport)
4591 #endif
4592 int sqlite3_rtree_init(
4593 sqlite3 *db,
4594 char **pzErrMsg,
4595 const sqlite3_api_routines *pApi
4597 SQLITE_EXTENSION_INIT2(pApi)
4598 return sqlite3RtreeInit(db);
4600 #endif
4602 #endif