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