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