xref: /sqlite-3.40.0/ext/rtree/rtree.c (revision 83569e2e)
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 #include <stdlib.h>
86 
87 /*  The following macro is used to suppress compiler warnings.
88 */
89 #ifndef UNUSED_PARAMETER
90 # define UNUSED_PARAMETER(x) (void)(x)
91 #endif
92 
93 typedef struct Rtree Rtree;
94 typedef struct RtreeCursor RtreeCursor;
95 typedef struct RtreeNode RtreeNode;
96 typedef struct RtreeCell RtreeCell;
97 typedef struct RtreeConstraint RtreeConstraint;
98 typedef struct RtreeMatchArg RtreeMatchArg;
99 typedef struct RtreeGeomCallback RtreeGeomCallback;
100 typedef union RtreeCoord RtreeCoord;
101 typedef struct RtreeSearchPoint RtreeSearchPoint;
102 
103 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
104 #define RTREE_MAX_DIMENSIONS 5
105 
106 /* Maximum number of auxiliary columns */
107 #define RTREE_MAX_AUX_COLUMN 100
108 
109 /* Size of hash table Rtree.aHash. This hash table is not expected to
110 ** ever contain very many entries, so a fixed number of buckets is
111 ** used.
112 */
113 #define HASHSIZE 97
114 
115 /* The xBestIndex method of this virtual table requires an estimate of
116 ** the number of rows in the virtual table to calculate the costs of
117 ** various strategies. If possible, this estimate is loaded from the
118 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
119 ** Otherwise, if no sqlite_stat1 entry is available, use
120 ** RTREE_DEFAULT_ROWEST.
121 */
122 #define RTREE_DEFAULT_ROWEST 1048576
123 #define RTREE_MIN_ROWEST         100
124 
125 /*
126 ** An rtree virtual-table object.
127 */
128 struct Rtree {
129   sqlite3_vtab base;          /* Base class.  Must be first */
130   sqlite3 *db;                /* Host database connection */
131   int iNodeSize;              /* Size in bytes of each node in the node table */
132   u8 nDim;                    /* Number of dimensions */
133   u8 nDim2;                   /* Twice the number of dimensions */
134   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
135   u8 nBytesPerCell;           /* Bytes consumed per cell */
136   u8 inWrTrans;               /* True if inside write transaction */
137   u8 nAux;                    /* # of auxiliary columns in %_rowid */
138   u8 nAuxNotNull;             /* Number of initial not-null aux columns */
139 #ifdef SQLITE_DEBUG
140   u8 bCorrupt;                /* Shadow table corruption detected */
141 #endif
142   int iDepth;                 /* Current depth of the r-tree structure */
143   char *zDb;                  /* Name of database containing r-tree table */
144   char *zName;                /* Name of r-tree table */
145   u32 nBusy;                  /* Current number of users of this structure */
146   i64 nRowEst;                /* Estimated number of rows in this table */
147   u32 nCursor;                /* Number of open cursors */
148   u32 nNodeRef;               /* Number RtreeNodes with positive nRef */
149   char *zReadAuxSql;          /* SQL for statement to read aux data */
150 
151   /* List of nodes removed during a CondenseTree operation. List is
152   ** linked together via the pointer normally used for hash chains -
153   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
154   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
155   */
156   RtreeNode *pDeleted;
157   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
158 
159   /* Blob I/O on xxx_node */
160   sqlite3_blob *pNodeBlob;
161 
162   /* Statements to read/write/delete a record from xxx_node */
163   sqlite3_stmt *pWriteNode;
164   sqlite3_stmt *pDeleteNode;
165 
166   /* Statements to read/write/delete a record from xxx_rowid */
167   sqlite3_stmt *pReadRowid;
168   sqlite3_stmt *pWriteRowid;
169   sqlite3_stmt *pDeleteRowid;
170 
171   /* Statements to read/write/delete a record from xxx_parent */
172   sqlite3_stmt *pReadParent;
173   sqlite3_stmt *pWriteParent;
174   sqlite3_stmt *pDeleteParent;
175 
176   /* Statement for writing to the "aux:" fields, if there are any */
177   sqlite3_stmt *pWriteAux;
178 
179   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
180 };
181 
182 /* Possible values for Rtree.eCoordType: */
183 #define RTREE_COORD_REAL32 0
184 #define RTREE_COORD_INT32  1
185 
186 /*
187 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
188 ** only deal with integer coordinates.  No floating point operations
189 ** will be done.
190 */
191 #ifdef SQLITE_RTREE_INT_ONLY
192   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
193   typedef int RtreeValue;                  /* Low accuracy coordinate */
194 # define RTREE_ZERO 0
195 #else
196   typedef double RtreeDValue;              /* High accuracy coordinate */
197   typedef float RtreeValue;                /* Low accuracy coordinate */
198 # define RTREE_ZERO 0.0
199 #endif
200 
201 /*
202 ** Set the Rtree.bCorrupt flag
203 */
204 #ifdef SQLITE_DEBUG
205 # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
206 #else
207 # define RTREE_IS_CORRUPT(X)
208 #endif
209 
210 /*
211 ** When doing a search of an r-tree, instances of the following structure
212 ** record intermediate results from the tree walk.
213 **
214 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
215 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
216 ** the id is of the parent node and the cell that RtreeSearchPoint
217 ** represents is the iCell-th entry in the parent node.
218 */
219 struct RtreeSearchPoint {
220   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
221   sqlite3_int64 id;      /* Node ID */
222   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
223   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
224   u8 iCell;              /* Cell index within the node */
225 };
226 
227 /*
228 ** The minimum number of cells allowed for a node is a third of the
229 ** maximum. In Gutman's notation:
230 **
231 **     m = M/3
232 **
233 ** If an R*-tree "Reinsert" operation is required, the same number of
234 ** cells are removed from the overfull node and reinserted into the tree.
235 */
236 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
237 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
238 #define RTREE_MAXCELLS 51
239 
240 /*
241 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
242 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
243 ** Therefore all non-root nodes must contain at least 3 entries. Since
244 ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
245 ** 40 or less.
246 */
247 #define RTREE_MAX_DEPTH 40
248 
249 
250 /*
251 ** Number of entries in the cursor RtreeNode cache.  The first entry is
252 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
253 ** entries cache the RtreeNode for the first elements of the priority queue.
254 */
255 #define RTREE_CACHE_SZ  5
256 
257 /*
258 ** An rtree cursor object.
259 */
260 struct RtreeCursor {
261   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
262   u8 atEOF;                         /* True if at end of search */
263   u8 bPoint;                        /* True if sPoint is valid */
264   u8 bAuxValid;                     /* True if pReadAux is valid */
265   int iStrategy;                    /* Copy of idxNum search parameter */
266   int nConstraint;                  /* Number of entries in aConstraint */
267   RtreeConstraint *aConstraint;     /* Search constraints. */
268   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
269   int nPoint;                       /* Number of slots used in aPoint[] */
270   int mxLevel;                      /* iLevel value for root of the tree */
271   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
272   sqlite3_stmt *pReadAux;           /* Statement to read aux-data */
273   RtreeSearchPoint sPoint;          /* Cached next search point */
274   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
275   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
276 };
277 
278 /* Return the Rtree of a RtreeCursor */
279 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
280 
281 /*
282 ** A coordinate can be either a floating point number or a integer.  All
283 ** coordinates within a single R-Tree are always of the same time.
284 */
285 union RtreeCoord {
286   RtreeValue f;      /* Floating point value */
287   int i;             /* Integer value */
288   u32 u;             /* Unsigned for byte-order conversions */
289 };
290 
291 /*
292 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
293 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
294 ** variable pRtree points to the Rtree structure associated with the
295 ** RtreeCoord.
296 */
297 #ifdef SQLITE_RTREE_INT_ONLY
298 # define DCOORD(coord) ((RtreeDValue)coord.i)
299 #else
300 # define DCOORD(coord) (                           \
301     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
302       ((double)coord.f) :                           \
303       ((double)coord.i)                             \
304   )
305 #endif
306 
307 /*
308 ** A search constraint.
309 */
310 struct RtreeConstraint {
311   int iCoord;                     /* Index of constrained coordinate */
312   int op;                         /* Constraining operation */
313   union {
314     RtreeDValue rValue;             /* Constraint value. */
315     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
316     int (*xQueryFunc)(sqlite3_rtree_query_info*);
317   } u;
318   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
319 };
320 
321 /* Possible values for RtreeConstraint.op */
322 #define RTREE_EQ    0x41  /* A */
323 #define RTREE_LE    0x42  /* B */
324 #define RTREE_LT    0x43  /* C */
325 #define RTREE_GE    0x44  /* D */
326 #define RTREE_GT    0x45  /* E */
327 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
328 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
329 
330 /* Special operators available only on cursors.  Needs to be consecutive
331 ** with the normal values above, but must be less than RTREE_MATCH.  These
332 ** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
333 ** x<'xyz' (RTREE_TRUE) */
334 #define RTREE_TRUE  0x3f  /* ? */
335 #define RTREE_FALSE 0x40  /* @ */
336 
337 /*
338 ** An rtree structure node.
339 */
340 struct RtreeNode {
341   RtreeNode *pParent;         /* Parent node */
342   i64 iNode;                  /* The node number */
343   int nRef;                   /* Number of references to this node */
344   int isDirty;                /* True if the node needs to be written to disk */
345   u8 *zData;                  /* Content of the node, as should be on disk */
346   RtreeNode *pNext;           /* Next node in this hash collision chain */
347 };
348 
349 /* Return the number of cells in a node  */
350 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
351 
352 /*
353 ** A single cell from a node, deserialized
354 */
355 struct RtreeCell {
356   i64 iRowid;                                 /* Node or entry ID */
357   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
358 };
359 
360 
361 /*
362 ** This object becomes the sqlite3_user_data() for the SQL functions
363 ** that are created by sqlite3_rtree_geometry_callback() and
364 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
365 ** operators in order to constrain a search.
366 **
367 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
368 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
369 ** SQL function was created using sqlite3_rtree_geometry_callback() or
370 ** sqlite3_rtree_query_callback().
371 **
372 ** This object is deleted automatically by the destructor mechanism in
373 ** sqlite3_create_function_v2().
374 */
375 struct RtreeGeomCallback {
376   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
377   int (*xQueryFunc)(sqlite3_rtree_query_info*);
378   void (*xDestructor)(void*);
379   void *pContext;
380 };
381 
382 /*
383 ** An instance of this structure (in the form of a BLOB) is returned by
384 ** the SQL functions that sqlite3_rtree_geometry_callback() and
385 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
386 ** operand to the MATCH operator of an R-Tree.
387 */
388 struct RtreeMatchArg {
389   u32 iSize;                  /* Size of this object */
390   RtreeGeomCallback cb;       /* Info about the callback functions */
391   int nParam;                 /* Number of parameters to the SQL function */
392   sqlite3_value **apSqlParam; /* Original SQL parameter values */
393   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
394 };
395 
396 #ifndef MAX
397 # define MAX(x,y) ((x) < (y) ? (y) : (x))
398 #endif
399 #ifndef MIN
400 # define MIN(x,y) ((x) > (y) ? (y) : (x))
401 #endif
402 
403 /* What version of GCC is being used.  0 means GCC is not being used .
404 ** Note that the GCC_VERSION macro will also be set correctly when using
405 ** clang, since clang works hard to be gcc compatible.  So the gcc
406 ** optimizations will also work when compiling with clang.
407 */
408 #ifndef GCC_VERSION
409 #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
410 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
411 #else
412 # define GCC_VERSION 0
413 #endif
414 #endif
415 
416 /* The testcase() macro should already be defined in the amalgamation.  If
417 ** it is not, make it a no-op.
418 */
419 #ifndef SQLITE_AMALGAMATION
420 # define testcase(X)
421 #endif
422 
423 /*
424 ** Make sure that the compiler intrinsics we desire are enabled when
425 ** compiling with an appropriate version of MSVC unless prevented by
426 ** the SQLITE_DISABLE_INTRINSIC define.
427 */
428 #if !defined(SQLITE_DISABLE_INTRINSIC)
429 #  if defined(_MSC_VER) && _MSC_VER>=1400
430 #    if !defined(_WIN32_WCE)
431 #      include <intrin.h>
432 #      pragma intrinsic(_byteswap_ulong)
433 #      pragma intrinsic(_byteswap_uint64)
434 #    else
435 #      include <cmnintrin.h>
436 #    endif
437 #  endif
438 #endif
439 
440 /*
441 ** Macros to determine whether the machine is big or little endian,
442 ** and whether or not that determination is run-time or compile-time.
443 **
444 ** For best performance, an attempt is made to guess at the byte-order
445 ** using C-preprocessor macros.  If that is unsuccessful, or if
446 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
447 ** at run-time.
448 */
449 #ifndef SQLITE_BYTEORDER
450 #if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
451     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
452     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
453     defined(__arm__)
454 # define SQLITE_BYTEORDER    1234
455 #elif defined(sparc)    || defined(__ppc__)
456 # define SQLITE_BYTEORDER    4321
457 #else
458 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
459 #endif
460 #endif
461 
462 
463 /* What version of MSVC is being used.  0 means MSVC is not being used */
464 #ifndef MSVC_VERSION
465 #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
466 # define MSVC_VERSION _MSC_VER
467 #else
468 # define MSVC_VERSION 0
469 #endif
470 #endif
471 
472 /*
473 ** Functions to deserialize a 16 bit integer, 32 bit real number and
474 ** 64 bit integer. The deserialized value is returned.
475 */
476 static int readInt16(u8 *p){
477   return (p[0]<<8) + p[1];
478 }
479 static void readCoord(u8 *p, RtreeCoord *pCoord){
480   assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
481 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
482   pCoord->u = _byteswap_ulong(*(u32*)p);
483 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
484   pCoord->u = __builtin_bswap32(*(u32*)p);
485 #elif SQLITE_BYTEORDER==4321
486   pCoord->u = *(u32*)p;
487 #else
488   pCoord->u = (
489     (((u32)p[0]) << 24) +
490     (((u32)p[1]) << 16) +
491     (((u32)p[2]) <<  8) +
492     (((u32)p[3]) <<  0)
493   );
494 #endif
495 }
496 static i64 readInt64(u8 *p){
497 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
498   u64 x;
499   memcpy(&x, p, 8);
500   return (i64)_byteswap_uint64(x);
501 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
502   u64 x;
503   memcpy(&x, p, 8);
504   return (i64)__builtin_bswap64(x);
505 #elif SQLITE_BYTEORDER==4321
506   i64 x;
507   memcpy(&x, p, 8);
508   return x;
509 #else
510   return (i64)(
511     (((u64)p[0]) << 56) +
512     (((u64)p[1]) << 48) +
513     (((u64)p[2]) << 40) +
514     (((u64)p[3]) << 32) +
515     (((u64)p[4]) << 24) +
516     (((u64)p[5]) << 16) +
517     (((u64)p[6]) <<  8) +
518     (((u64)p[7]) <<  0)
519   );
520 #endif
521 }
522 
523 /*
524 ** Functions to serialize a 16 bit integer, 32 bit real number and
525 ** 64 bit integer. The value returned is the number of bytes written
526 ** to the argument buffer (always 2, 4 and 8 respectively).
527 */
528 static void writeInt16(u8 *p, int i){
529   p[0] = (i>> 8)&0xFF;
530   p[1] = (i>> 0)&0xFF;
531 }
532 static int writeCoord(u8 *p, RtreeCoord *pCoord){
533   u32 i;
534   assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
535   assert( sizeof(RtreeCoord)==4 );
536   assert( sizeof(u32)==4 );
537 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
538   i = __builtin_bswap32(pCoord->u);
539   memcpy(p, &i, 4);
540 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
541   i = _byteswap_ulong(pCoord->u);
542   memcpy(p, &i, 4);
543 #elif SQLITE_BYTEORDER==4321
544   i = pCoord->u;
545   memcpy(p, &i, 4);
546 #else
547   i = pCoord->u;
548   p[0] = (i>>24)&0xFF;
549   p[1] = (i>>16)&0xFF;
550   p[2] = (i>> 8)&0xFF;
551   p[3] = (i>> 0)&0xFF;
552 #endif
553   return 4;
554 }
555 static int writeInt64(u8 *p, i64 i){
556 #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
557   i = (i64)__builtin_bswap64((u64)i);
558   memcpy(p, &i, 8);
559 #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
560   i = (i64)_byteswap_uint64((u64)i);
561   memcpy(p, &i, 8);
562 #elif SQLITE_BYTEORDER==4321
563   memcpy(p, &i, 8);
564 #else
565   p[0] = (i>>56)&0xFF;
566   p[1] = (i>>48)&0xFF;
567   p[2] = (i>>40)&0xFF;
568   p[3] = (i>>32)&0xFF;
569   p[4] = (i>>24)&0xFF;
570   p[5] = (i>>16)&0xFF;
571   p[6] = (i>> 8)&0xFF;
572   p[7] = (i>> 0)&0xFF;
573 #endif
574   return 8;
575 }
576 
577 /*
578 ** Increment the reference count of node p.
579 */
580 static void nodeReference(RtreeNode *p){
581   if( p ){
582     assert( p->nRef>0 );
583     p->nRef++;
584   }
585 }
586 
587 /*
588 ** Clear the content of node p (set all bytes to 0x00).
589 */
590 static void nodeZero(Rtree *pRtree, RtreeNode *p){
591   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
592   p->isDirty = 1;
593 }
594 
595 /*
596 ** Given a node number iNode, return the corresponding key to use
597 ** in the Rtree.aHash table.
598 */
599 static unsigned int nodeHash(i64 iNode){
600   return ((unsigned)iNode) % HASHSIZE;
601 }
602 
603 /*
604 ** Search the node hash table for node iNode. If found, return a pointer
605 ** to it. Otherwise, return 0.
606 */
607 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
608   RtreeNode *p;
609   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
610   return p;
611 }
612 
613 /*
614 ** Add node pNode to the node hash table.
615 */
616 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
617   int iHash;
618   assert( pNode->pNext==0 );
619   iHash = nodeHash(pNode->iNode);
620   pNode->pNext = pRtree->aHash[iHash];
621   pRtree->aHash[iHash] = pNode;
622 }
623 
624 /*
625 ** Remove node pNode from the node hash table.
626 */
627 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
628   RtreeNode **pp;
629   if( pNode->iNode!=0 ){
630     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
631     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
632     *pp = pNode->pNext;
633     pNode->pNext = 0;
634   }
635 }
636 
637 /*
638 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
639 ** indicating that node has not yet been assigned a node number. It is
640 ** assigned a node number when nodeWrite() is called to write the
641 ** node contents out to the database.
642 */
643 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
644   RtreeNode *pNode;
645   pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
646   if( pNode ){
647     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
648     pNode->zData = (u8 *)&pNode[1];
649     pNode->nRef = 1;
650     pRtree->nNodeRef++;
651     pNode->pParent = pParent;
652     pNode->isDirty = 1;
653     nodeReference(pParent);
654   }
655   return pNode;
656 }
657 
658 /*
659 ** Clear the Rtree.pNodeBlob object
660 */
661 static void nodeBlobReset(Rtree *pRtree){
662   if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
663     sqlite3_blob *pBlob = pRtree->pNodeBlob;
664     pRtree->pNodeBlob = 0;
665     sqlite3_blob_close(pBlob);
666   }
667 }
668 
669 /*
670 ** Obtain a reference to an r-tree node.
671 */
672 static int nodeAcquire(
673   Rtree *pRtree,             /* R-tree structure */
674   i64 iNode,                 /* Node number to load */
675   RtreeNode *pParent,        /* Either the parent node or NULL */
676   RtreeNode **ppNode         /* OUT: Acquired node */
677 ){
678   int rc = SQLITE_OK;
679   RtreeNode *pNode = 0;
680 
681   /* Check if the requested node is already in the hash table. If so,
682   ** increase its reference count and return it.
683   */
684   if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
685     if( pParent && pParent!=pNode->pParent ){
686       RTREE_IS_CORRUPT(pRtree);
687       return SQLITE_CORRUPT_VTAB;
688     }
689     pNode->nRef++;
690     *ppNode = pNode;
691     return SQLITE_OK;
692   }
693 
694   if( pRtree->pNodeBlob ){
695     sqlite3_blob *pBlob = pRtree->pNodeBlob;
696     pRtree->pNodeBlob = 0;
697     rc = sqlite3_blob_reopen(pBlob, iNode);
698     pRtree->pNodeBlob = pBlob;
699     if( rc ){
700       nodeBlobReset(pRtree);
701       if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
702     }
703   }
704   if( pRtree->pNodeBlob==0 ){
705     char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
706     if( zTab==0 ) return SQLITE_NOMEM;
707     rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
708                            &pRtree->pNodeBlob);
709     sqlite3_free(zTab);
710   }
711   if( rc ){
712     nodeBlobReset(pRtree);
713     *ppNode = 0;
714     /* If unable to open an sqlite3_blob on the desired row, that can only
715     ** be because the shadow tables hold erroneous data. */
716     if( rc==SQLITE_ERROR ){
717       rc = SQLITE_CORRUPT_VTAB;
718       RTREE_IS_CORRUPT(pRtree);
719     }
720   }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
721     pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
722     if( !pNode ){
723       rc = SQLITE_NOMEM;
724     }else{
725       pNode->pParent = pParent;
726       pNode->zData = (u8 *)&pNode[1];
727       pNode->nRef = 1;
728       pRtree->nNodeRef++;
729       pNode->iNode = iNode;
730       pNode->isDirty = 0;
731       pNode->pNext = 0;
732       rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
733                              pRtree->iNodeSize, 0);
734     }
735   }
736 
737   /* If the root node was just loaded, set pRtree->iDepth to the height
738   ** of the r-tree structure. A height of zero means all data is stored on
739   ** the root node. A height of one means the children of the root node
740   ** are the leaves, and so on. If the depth as specified on the root node
741   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
742   */
743   if( pNode && rc==SQLITE_OK && iNode==1 ){
744     pRtree->iDepth = readInt16(pNode->zData);
745     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
746       rc = SQLITE_CORRUPT_VTAB;
747       RTREE_IS_CORRUPT(pRtree);
748     }
749   }
750 
751   /* If no error has occurred so far, check if the "number of entries"
752   ** field on the node is too large. If so, set the return code to
753   ** SQLITE_CORRUPT_VTAB.
754   */
755   if( pNode && rc==SQLITE_OK ){
756     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
757       rc = SQLITE_CORRUPT_VTAB;
758       RTREE_IS_CORRUPT(pRtree);
759     }
760   }
761 
762   if( rc==SQLITE_OK ){
763     if( pNode!=0 ){
764       nodeReference(pParent);
765       nodeHashInsert(pRtree, pNode);
766     }else{
767       rc = SQLITE_CORRUPT_VTAB;
768       RTREE_IS_CORRUPT(pRtree);
769     }
770     *ppNode = pNode;
771   }else{
772     if( pNode ){
773       pRtree->nNodeRef--;
774       sqlite3_free(pNode);
775     }
776     *ppNode = 0;
777   }
778 
779   return rc;
780 }
781 
782 /*
783 ** Overwrite cell iCell of node pNode with the contents of pCell.
784 */
785 static void nodeOverwriteCell(
786   Rtree *pRtree,             /* The overall R-Tree */
787   RtreeNode *pNode,          /* The node into which the cell is to be written */
788   RtreeCell *pCell,          /* The cell to write */
789   int iCell                  /* Index into pNode into which pCell is written */
790 ){
791   int ii;
792   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
793   p += writeInt64(p, pCell->iRowid);
794   for(ii=0; ii<pRtree->nDim2; ii++){
795     p += writeCoord(p, &pCell->aCoord[ii]);
796   }
797   pNode->isDirty = 1;
798 }
799 
800 /*
801 ** Remove the cell with index iCell from node pNode.
802 */
803 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
804   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
805   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
806   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
807   memmove(pDst, pSrc, nByte);
808   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
809   pNode->isDirty = 1;
810 }
811 
812 /*
813 ** Insert the contents of cell pCell into node pNode. If the insert
814 ** is successful, return SQLITE_OK.
815 **
816 ** If there is not enough free space in pNode, return SQLITE_FULL.
817 */
818 static int nodeInsertCell(
819   Rtree *pRtree,                /* The overall R-Tree */
820   RtreeNode *pNode,             /* Write new cell into this node */
821   RtreeCell *pCell              /* The cell to be inserted */
822 ){
823   int nCell;                    /* Current number of cells in pNode */
824   int nMaxCell;                 /* Maximum number of cells for pNode */
825 
826   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
827   nCell = NCELL(pNode);
828 
829   assert( nCell<=nMaxCell );
830   if( nCell<nMaxCell ){
831     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
832     writeInt16(&pNode->zData[2], nCell+1);
833     pNode->isDirty = 1;
834   }
835 
836   return (nCell==nMaxCell);
837 }
838 
839 /*
840 ** If the node is dirty, write it out to the database.
841 */
842 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
843   int rc = SQLITE_OK;
844   if( pNode->isDirty ){
845     sqlite3_stmt *p = pRtree->pWriteNode;
846     if( pNode->iNode ){
847       sqlite3_bind_int64(p, 1, pNode->iNode);
848     }else{
849       sqlite3_bind_null(p, 1);
850     }
851     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
852     sqlite3_step(p);
853     pNode->isDirty = 0;
854     rc = sqlite3_reset(p);
855     sqlite3_bind_null(p, 2);
856     if( pNode->iNode==0 && rc==SQLITE_OK ){
857       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
858       nodeHashInsert(pRtree, pNode);
859     }
860   }
861   return rc;
862 }
863 
864 /*
865 ** Release a reference to a node. If the node is dirty and the reference
866 ** count drops to zero, the node data is written to the database.
867 */
868 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
869   int rc = SQLITE_OK;
870   if( pNode ){
871     assert( pNode->nRef>0 );
872     assert( pRtree->nNodeRef>0 );
873     pNode->nRef--;
874     if( pNode->nRef==0 ){
875       pRtree->nNodeRef--;
876       if( pNode->iNode==1 ){
877         pRtree->iDepth = -1;
878       }
879       if( pNode->pParent ){
880         rc = nodeRelease(pRtree, pNode->pParent);
881       }
882       if( rc==SQLITE_OK ){
883         rc = nodeWrite(pRtree, pNode);
884       }
885       nodeHashDelete(pRtree, pNode);
886       sqlite3_free(pNode);
887     }
888   }
889   return rc;
890 }
891 
892 /*
893 ** Return the 64-bit integer value associated with cell iCell of
894 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
895 ** an internal node, then the 64-bit integer is a child page number.
896 */
897 static i64 nodeGetRowid(
898   Rtree *pRtree,       /* The overall R-Tree */
899   RtreeNode *pNode,    /* The node from which to extract the ID */
900   int iCell            /* The cell index from which to extract the ID */
901 ){
902   assert( iCell<NCELL(pNode) );
903   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
904 }
905 
906 /*
907 ** Return coordinate iCoord from cell iCell in node pNode.
908 */
909 static void nodeGetCoord(
910   Rtree *pRtree,               /* The overall R-Tree */
911   RtreeNode *pNode,            /* The node from which to extract a coordinate */
912   int iCell,                   /* The index of the cell within the node */
913   int iCoord,                  /* Which coordinate to extract */
914   RtreeCoord *pCoord           /* OUT: Space to write result to */
915 ){
916   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
917 }
918 
919 /*
920 ** Deserialize cell iCell of node pNode. Populate the structure pointed
921 ** to by pCell with the results.
922 */
923 static void nodeGetCell(
924   Rtree *pRtree,               /* The overall R-Tree */
925   RtreeNode *pNode,            /* The node containing the cell to be read */
926   int iCell,                   /* Index of the cell within the node */
927   RtreeCell *pCell             /* OUT: Write the cell contents here */
928 ){
929   u8 *pData;
930   RtreeCoord *pCoord;
931   int ii = 0;
932   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
933   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
934   pCoord = pCell->aCoord;
935   do{
936     readCoord(pData, &pCoord[ii]);
937     readCoord(pData+4, &pCoord[ii+1]);
938     pData += 8;
939     ii += 2;
940   }while( ii<pRtree->nDim2 );
941 }
942 
943 
944 /* Forward declaration for the function that does the work of
945 ** the virtual table module xCreate() and xConnect() methods.
946 */
947 static int rtreeInit(
948   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
949 );
950 
951 /*
952 ** Rtree virtual table module xCreate method.
953 */
954 static int rtreeCreate(
955   sqlite3 *db,
956   void *pAux,
957   int argc, const char *const*argv,
958   sqlite3_vtab **ppVtab,
959   char **pzErr
960 ){
961   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
962 }
963 
964 /*
965 ** Rtree virtual table module xConnect method.
966 */
967 static int rtreeConnect(
968   sqlite3 *db,
969   void *pAux,
970   int argc, const char *const*argv,
971   sqlite3_vtab **ppVtab,
972   char **pzErr
973 ){
974   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
975 }
976 
977 /*
978 ** Increment the r-tree reference count.
979 */
980 static void rtreeReference(Rtree *pRtree){
981   pRtree->nBusy++;
982 }
983 
984 /*
985 ** Decrement the r-tree reference count. When the reference count reaches
986 ** zero the structure is deleted.
987 */
988 static void rtreeRelease(Rtree *pRtree){
989   pRtree->nBusy--;
990   if( pRtree->nBusy==0 ){
991     pRtree->inWrTrans = 0;
992     assert( pRtree->nCursor==0 );
993     nodeBlobReset(pRtree);
994     assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
995     sqlite3_finalize(pRtree->pWriteNode);
996     sqlite3_finalize(pRtree->pDeleteNode);
997     sqlite3_finalize(pRtree->pReadRowid);
998     sqlite3_finalize(pRtree->pWriteRowid);
999     sqlite3_finalize(pRtree->pDeleteRowid);
1000     sqlite3_finalize(pRtree->pReadParent);
1001     sqlite3_finalize(pRtree->pWriteParent);
1002     sqlite3_finalize(pRtree->pDeleteParent);
1003     sqlite3_finalize(pRtree->pWriteAux);
1004     sqlite3_free(pRtree->zReadAuxSql);
1005     sqlite3_free(pRtree);
1006   }
1007 }
1008 
1009 /*
1010 ** Rtree virtual table module xDisconnect method.
1011 */
1012 static int rtreeDisconnect(sqlite3_vtab *pVtab){
1013   rtreeRelease((Rtree *)pVtab);
1014   return SQLITE_OK;
1015 }
1016 
1017 /*
1018 ** Rtree virtual table module xDestroy method.
1019 */
1020 static int rtreeDestroy(sqlite3_vtab *pVtab){
1021   Rtree *pRtree = (Rtree *)pVtab;
1022   int rc;
1023   char *zCreate = sqlite3_mprintf(
1024     "DROP TABLE '%q'.'%q_node';"
1025     "DROP TABLE '%q'.'%q_rowid';"
1026     "DROP TABLE '%q'.'%q_parent';",
1027     pRtree->zDb, pRtree->zName,
1028     pRtree->zDb, pRtree->zName,
1029     pRtree->zDb, pRtree->zName
1030   );
1031   if( !zCreate ){
1032     rc = SQLITE_NOMEM;
1033   }else{
1034     nodeBlobReset(pRtree);
1035     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
1036     sqlite3_free(zCreate);
1037   }
1038   if( rc==SQLITE_OK ){
1039     rtreeRelease(pRtree);
1040   }
1041 
1042   return rc;
1043 }
1044 
1045 /*
1046 ** Rtree virtual table module xOpen method.
1047 */
1048 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
1049   int rc = SQLITE_NOMEM;
1050   Rtree *pRtree = (Rtree *)pVTab;
1051   RtreeCursor *pCsr;
1052 
1053   pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
1054   if( pCsr ){
1055     memset(pCsr, 0, sizeof(RtreeCursor));
1056     pCsr->base.pVtab = pVTab;
1057     rc = SQLITE_OK;
1058     pRtree->nCursor++;
1059   }
1060   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
1061 
1062   return rc;
1063 }
1064 
1065 
1066 /*
1067 ** Reset a cursor back to its initial state.
1068 */
1069 static void resetCursor(RtreeCursor *pCsr){
1070   Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
1071   int ii;
1072   sqlite3_stmt *pStmt;
1073   if( pCsr->aConstraint ){
1074     int i;                        /* Used to iterate through constraint array */
1075     for(i=0; i<pCsr->nConstraint; i++){
1076       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
1077       if( pInfo ){
1078         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
1079         sqlite3_free(pInfo);
1080       }
1081     }
1082     sqlite3_free(pCsr->aConstraint);
1083     pCsr->aConstraint = 0;
1084   }
1085   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
1086   sqlite3_free(pCsr->aPoint);
1087   pStmt = pCsr->pReadAux;
1088   memset(pCsr, 0, sizeof(RtreeCursor));
1089   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
1090   pCsr->pReadAux = pStmt;
1091 
1092 }
1093 
1094 /*
1095 ** Rtree virtual table module xClose method.
1096 */
1097 static int rtreeClose(sqlite3_vtab_cursor *cur){
1098   Rtree *pRtree = (Rtree *)(cur->pVtab);
1099   RtreeCursor *pCsr = (RtreeCursor *)cur;
1100   assert( pRtree->nCursor>0 );
1101   resetCursor(pCsr);
1102   sqlite3_finalize(pCsr->pReadAux);
1103   sqlite3_free(pCsr);
1104   pRtree->nCursor--;
1105   nodeBlobReset(pRtree);
1106   return SQLITE_OK;
1107 }
1108 
1109 /*
1110 ** Rtree virtual table module xEof method.
1111 **
1112 ** Return non-zero if the cursor does not currently point to a valid
1113 ** record (i.e if the scan has finished), or zero otherwise.
1114 */
1115 static int rtreeEof(sqlite3_vtab_cursor *cur){
1116   RtreeCursor *pCsr = (RtreeCursor *)cur;
1117   return pCsr->atEOF;
1118 }
1119 
1120 /*
1121 ** Convert raw bits from the on-disk RTree record into a coordinate value.
1122 ** The on-disk format is big-endian and needs to be converted for little-
1123 ** endian platforms.  The on-disk record stores integer coordinates if
1124 ** eInt is true and it stores 32-bit floating point records if eInt is
1125 ** false.  a[] is the four bytes of the on-disk record to be decoded.
1126 ** Store the results in "r".
1127 **
1128 ** There are five versions of this macro.  The last one is generic.  The
1129 ** other four are various architectures-specific optimizations.
1130 */
1131 #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1132 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
1133     RtreeCoord c;    /* Coordinate decoded */                   \
1134     c.u = _byteswap_ulong(*(u32*)a);                            \
1135     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1136 }
1137 #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
1138 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
1139     RtreeCoord c;    /* Coordinate decoded */                   \
1140     c.u = __builtin_bswap32(*(u32*)a);                          \
1141     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1142 }
1143 #elif SQLITE_BYTEORDER==1234
1144 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
1145     RtreeCoord c;    /* Coordinate decoded */                   \
1146     memcpy(&c.u,a,4);                                           \
1147     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
1148           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
1149     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1150 }
1151 #elif SQLITE_BYTEORDER==4321
1152 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
1153     RtreeCoord c;    /* Coordinate decoded */                   \
1154     memcpy(&c.u,a,4);                                           \
1155     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1156 }
1157 #else
1158 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
1159     RtreeCoord c;    /* Coordinate decoded */                   \
1160     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
1161            +((u32)a[2]<<8) + a[3];                              \
1162     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1163 }
1164 #endif
1165 
1166 /*
1167 ** Check the RTree node or entry given by pCellData and p against the MATCH
1168 ** constraint pConstraint.
1169 */
1170 static int rtreeCallbackConstraint(
1171   RtreeConstraint *pConstraint,  /* The constraint to test */
1172   int eInt,                      /* True if RTree holding integer coordinates */
1173   u8 *pCellData,                 /* Raw cell content */
1174   RtreeSearchPoint *pSearch,     /* Container of this cell */
1175   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
1176   int *peWithin                  /* OUT: visibility of the cell */
1177 ){
1178   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
1179   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
1180   int rc;                                             /* Callback return code */
1181   RtreeCoord c;                                       /* Translator union */
1182   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
1183 
1184   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
1185   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
1186 
1187   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
1188     pInfo->iRowid = readInt64(pCellData);
1189   }
1190   pCellData += 8;
1191 #ifndef SQLITE_RTREE_INT_ONLY
1192   if( eInt==0 ){
1193     switch( nCoord ){
1194       case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
1195                 readCoord(pCellData+32, &c); aCoord[8] = c.f;
1196       case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
1197                 readCoord(pCellData+24, &c); aCoord[6] = c.f;
1198       case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
1199                 readCoord(pCellData+16, &c); aCoord[4] = c.f;
1200       case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
1201                 readCoord(pCellData+8,  &c); aCoord[2] = c.f;
1202       default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
1203                 readCoord(pCellData,    &c); aCoord[0] = c.f;
1204     }
1205   }else
1206 #endif
1207   {
1208     switch( nCoord ){
1209       case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
1210                 readCoord(pCellData+32, &c); aCoord[8] = c.i;
1211       case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
1212                 readCoord(pCellData+24, &c); aCoord[6] = c.i;
1213       case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
1214                 readCoord(pCellData+16, &c); aCoord[4] = c.i;
1215       case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
1216                 readCoord(pCellData+8,  &c); aCoord[2] = c.i;
1217       default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
1218                 readCoord(pCellData,    &c); aCoord[0] = c.i;
1219     }
1220   }
1221   if( pConstraint->op==RTREE_MATCH ){
1222     int eWithin = 0;
1223     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
1224                               nCoord, aCoord, &eWithin);
1225     if( eWithin==0 ) *peWithin = NOT_WITHIN;
1226     *prScore = RTREE_ZERO;
1227   }else{
1228     pInfo->aCoord = aCoord;
1229     pInfo->iLevel = pSearch->iLevel - 1;
1230     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
1231     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
1232     rc = pConstraint->u.xQueryFunc(pInfo);
1233     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
1234     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
1235       *prScore = pInfo->rScore;
1236     }
1237   }
1238   return rc;
1239 }
1240 
1241 /*
1242 ** Check the internal RTree node given by pCellData against constraint p.
1243 ** If this constraint cannot be satisfied by any child within the node,
1244 ** set *peWithin to NOT_WITHIN.
1245 */
1246 static void rtreeNonleafConstraint(
1247   RtreeConstraint *p,        /* The constraint to test */
1248   int eInt,                  /* True if RTree holds integer coordinates */
1249   u8 *pCellData,             /* Raw cell content as appears on disk */
1250   int *peWithin              /* Adjust downward, as appropriate */
1251 ){
1252   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
1253 
1254   /* p->iCoord might point to either a lower or upper bound coordinate
1255   ** in a coordinate pair.  But make pCellData point to the lower bound.
1256   */
1257   pCellData += 8 + 4*(p->iCoord&0xfe);
1258 
1259   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1260       || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1261       || p->op==RTREE_FALSE );
1262   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
1263   switch( p->op ){
1264     case RTREE_TRUE:  return;   /* Always satisfied */
1265     case RTREE_FALSE: break;    /* Never satisfied */
1266     case RTREE_LE:
1267     case RTREE_LT:
1268     case RTREE_EQ:
1269       RTREE_DECODE_COORD(eInt, pCellData, val);
1270       /* val now holds the lower bound of the coordinate pair */
1271       if( p->u.rValue>=val ) return;
1272       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
1273       /* Fall through for the RTREE_EQ case */
1274 
1275     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
1276       pCellData += 4;
1277       RTREE_DECODE_COORD(eInt, pCellData, val);
1278       /* val now holds the upper bound of the coordinate pair */
1279       if( p->u.rValue<=val ) return;
1280   }
1281   *peWithin = NOT_WITHIN;
1282 }
1283 
1284 /*
1285 ** Check the leaf RTree cell given by pCellData against constraint p.
1286 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
1287 ** If the constraint is satisfied, leave *peWithin unchanged.
1288 **
1289 ** The constraint is of the form:  xN op $val
1290 **
1291 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
1292 ** pCellData.  $val is given by p->u.rValue.
1293 */
1294 static void rtreeLeafConstraint(
1295   RtreeConstraint *p,        /* The constraint to test */
1296   int eInt,                  /* True if RTree holds integer coordinates */
1297   u8 *pCellData,             /* Raw cell content as appears on disk */
1298   int *peWithin              /* Adjust downward, as appropriate */
1299 ){
1300   RtreeDValue xN;      /* Coordinate value converted to a double */
1301 
1302   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1303       || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1304       || p->op==RTREE_FALSE );
1305   pCellData += 8 + p->iCoord*4;
1306   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
1307   RTREE_DECODE_COORD(eInt, pCellData, xN);
1308   switch( p->op ){
1309     case RTREE_TRUE:  return;   /* Always satisfied */
1310     case RTREE_FALSE: break;    /* Never satisfied */
1311     case RTREE_LE:    if( xN <= p->u.rValue ) return;  break;
1312     case RTREE_LT:    if( xN <  p->u.rValue ) return;  break;
1313     case RTREE_GE:    if( xN >= p->u.rValue ) return;  break;
1314     case RTREE_GT:    if( xN >  p->u.rValue ) return;  break;
1315     default:          if( xN == p->u.rValue ) return;  break;
1316   }
1317   *peWithin = NOT_WITHIN;
1318 }
1319 
1320 /*
1321 ** One of the cells in node pNode is guaranteed to have a 64-bit
1322 ** integer value equal to iRowid. Return the index of this cell.
1323 */
1324 static int nodeRowidIndex(
1325   Rtree *pRtree,
1326   RtreeNode *pNode,
1327   i64 iRowid,
1328   int *piIndex
1329 ){
1330   int ii;
1331   int nCell = NCELL(pNode);
1332   assert( nCell<200 );
1333   for(ii=0; ii<nCell; ii++){
1334     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1335       *piIndex = ii;
1336       return SQLITE_OK;
1337     }
1338   }
1339   RTREE_IS_CORRUPT(pRtree);
1340   return SQLITE_CORRUPT_VTAB;
1341 }
1342 
1343 /*
1344 ** Return the index of the cell containing a pointer to node pNode
1345 ** in its parent. If pNode is the root node, return -1.
1346 */
1347 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1348   RtreeNode *pParent = pNode->pParent;
1349   if( pParent ){
1350     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1351   }
1352   *piIndex = -1;
1353   return SQLITE_OK;
1354 }
1355 
1356 /*
1357 ** Compare two search points.  Return negative, zero, or positive if the first
1358 ** is less than, equal to, or greater than the second.
1359 **
1360 ** The rScore is the primary key.  Smaller rScore values come first.
1361 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
1362 ** iLevel values coming first.  In this way, if rScore is the same for all
1363 ** SearchPoints, then iLevel becomes the deciding factor and the result
1364 ** is a depth-first search, which is the desired default behavior.
1365 */
1366 static int rtreeSearchPointCompare(
1367   const RtreeSearchPoint *pA,
1368   const RtreeSearchPoint *pB
1369 ){
1370   if( pA->rScore<pB->rScore ) return -1;
1371   if( pA->rScore>pB->rScore ) return +1;
1372   if( pA->iLevel<pB->iLevel ) return -1;
1373   if( pA->iLevel>pB->iLevel ) return +1;
1374   return 0;
1375 }
1376 
1377 /*
1378 ** Interchange two search points in a cursor.
1379 */
1380 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
1381   RtreeSearchPoint t = p->aPoint[i];
1382   assert( i<j );
1383   p->aPoint[i] = p->aPoint[j];
1384   p->aPoint[j] = t;
1385   i++; j++;
1386   if( i<RTREE_CACHE_SZ ){
1387     if( j>=RTREE_CACHE_SZ ){
1388       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1389       p->aNode[i] = 0;
1390     }else{
1391       RtreeNode *pTemp = p->aNode[i];
1392       p->aNode[i] = p->aNode[j];
1393       p->aNode[j] = pTemp;
1394     }
1395   }
1396 }
1397 
1398 /*
1399 ** Return the search point with the lowest current score.
1400 */
1401 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
1402   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
1403 }
1404 
1405 /*
1406 ** Get the RtreeNode for the search point with the lowest score.
1407 */
1408 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
1409   sqlite3_int64 id;
1410   int ii = 1 - pCur->bPoint;
1411   assert( ii==0 || ii==1 );
1412   assert( pCur->bPoint || pCur->nPoint );
1413   if( pCur->aNode[ii]==0 ){
1414     assert( pRC!=0 );
1415     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
1416     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
1417   }
1418   return pCur->aNode[ii];
1419 }
1420 
1421 /*
1422 ** Push a new element onto the priority queue
1423 */
1424 static RtreeSearchPoint *rtreeEnqueue(
1425   RtreeCursor *pCur,    /* The cursor */
1426   RtreeDValue rScore,   /* Score for the new search point */
1427   u8 iLevel             /* Level for the new search point */
1428 ){
1429   int i, j;
1430   RtreeSearchPoint *pNew;
1431   if( pCur->nPoint>=pCur->nPointAlloc ){
1432     int nNew = pCur->nPointAlloc*2 + 8;
1433     pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
1434     if( pNew==0 ) return 0;
1435     pCur->aPoint = pNew;
1436     pCur->nPointAlloc = nNew;
1437   }
1438   i = pCur->nPoint++;
1439   pNew = pCur->aPoint + i;
1440   pNew->rScore = rScore;
1441   pNew->iLevel = iLevel;
1442   assert( iLevel<=RTREE_MAX_DEPTH );
1443   while( i>0 ){
1444     RtreeSearchPoint *pParent;
1445     j = (i-1)/2;
1446     pParent = pCur->aPoint + j;
1447     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
1448     rtreeSearchPointSwap(pCur, j, i);
1449     i = j;
1450     pNew = pParent;
1451   }
1452   return pNew;
1453 }
1454 
1455 /*
1456 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
1457 ** NULL if malloc fails.
1458 */
1459 static RtreeSearchPoint *rtreeSearchPointNew(
1460   RtreeCursor *pCur,    /* The cursor */
1461   RtreeDValue rScore,   /* Score for the new search point */
1462   u8 iLevel             /* Level for the new search point */
1463 ){
1464   RtreeSearchPoint *pNew, *pFirst;
1465   pFirst = rtreeSearchPointFirst(pCur);
1466   pCur->anQueue[iLevel]++;
1467   if( pFirst==0
1468    || pFirst->rScore>rScore
1469    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
1470   ){
1471     if( pCur->bPoint ){
1472       int ii;
1473       pNew = rtreeEnqueue(pCur, rScore, iLevel);
1474       if( pNew==0 ) return 0;
1475       ii = (int)(pNew - pCur->aPoint) + 1;
1476       if( ii<RTREE_CACHE_SZ ){
1477         assert( pCur->aNode[ii]==0 );
1478         pCur->aNode[ii] = pCur->aNode[0];
1479       }else{
1480         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
1481       }
1482       pCur->aNode[0] = 0;
1483       *pNew = pCur->sPoint;
1484     }
1485     pCur->sPoint.rScore = rScore;
1486     pCur->sPoint.iLevel = iLevel;
1487     pCur->bPoint = 1;
1488     return &pCur->sPoint;
1489   }else{
1490     return rtreeEnqueue(pCur, rScore, iLevel);
1491   }
1492 }
1493 
1494 #if 0
1495 /* Tracing routines for the RtreeSearchPoint queue */
1496 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
1497   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
1498   printf(" %d.%05lld.%02d %g %d",
1499     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
1500   );
1501   idx++;
1502   if( idx<RTREE_CACHE_SZ ){
1503     printf(" %p\n", pCur->aNode[idx]);
1504   }else{
1505     printf("\n");
1506   }
1507 }
1508 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
1509   int ii;
1510   printf("=== %9s ", zPrefix);
1511   if( pCur->bPoint ){
1512     tracePoint(&pCur->sPoint, -1, pCur);
1513   }
1514   for(ii=0; ii<pCur->nPoint; ii++){
1515     if( ii>0 || pCur->bPoint ) printf("              ");
1516     tracePoint(&pCur->aPoint[ii], ii, pCur);
1517   }
1518 }
1519 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
1520 #else
1521 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
1522 #endif
1523 
1524 /* Remove the search point with the lowest current score.
1525 */
1526 static void rtreeSearchPointPop(RtreeCursor *p){
1527   int i, j, k, n;
1528   i = 1 - p->bPoint;
1529   assert( i==0 || i==1 );
1530   if( p->aNode[i] ){
1531     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1532     p->aNode[i] = 0;
1533   }
1534   if( p->bPoint ){
1535     p->anQueue[p->sPoint.iLevel]--;
1536     p->bPoint = 0;
1537   }else if( p->nPoint ){
1538     p->anQueue[p->aPoint[0].iLevel]--;
1539     n = --p->nPoint;
1540     p->aPoint[0] = p->aPoint[n];
1541     if( n<RTREE_CACHE_SZ-1 ){
1542       p->aNode[1] = p->aNode[n+1];
1543       p->aNode[n+1] = 0;
1544     }
1545     i = 0;
1546     while( (j = i*2+1)<n ){
1547       k = j+1;
1548       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
1549         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
1550           rtreeSearchPointSwap(p, i, k);
1551           i = k;
1552         }else{
1553           break;
1554         }
1555       }else{
1556         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
1557           rtreeSearchPointSwap(p, i, j);
1558           i = j;
1559         }else{
1560           break;
1561         }
1562       }
1563     }
1564   }
1565 }
1566 
1567 
1568 /*
1569 ** Continue the search on cursor pCur until the front of the queue
1570 ** contains an entry suitable for returning as a result-set row,
1571 ** or until the RtreeSearchPoint queue is empty, indicating that the
1572 ** query has completed.
1573 */
1574 static int rtreeStepToLeaf(RtreeCursor *pCur){
1575   RtreeSearchPoint *p;
1576   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
1577   RtreeNode *pNode;
1578   int eWithin;
1579   int rc = SQLITE_OK;
1580   int nCell;
1581   int nConstraint = pCur->nConstraint;
1582   int ii;
1583   int eInt;
1584   RtreeSearchPoint x;
1585 
1586   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
1587   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
1588     u8 *pCellData;
1589     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
1590     if( rc ) return rc;
1591     nCell = NCELL(pNode);
1592     assert( nCell<200 );
1593     pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
1594     while( p->iCell<nCell ){
1595       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
1596       eWithin = FULLY_WITHIN;
1597       for(ii=0; ii<nConstraint; ii++){
1598         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
1599         if( pConstraint->op>=RTREE_MATCH ){
1600           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
1601                                        &rScore, &eWithin);
1602           if( rc ) return rc;
1603         }else if( p->iLevel==1 ){
1604           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
1605         }else{
1606           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
1607         }
1608         if( eWithin==NOT_WITHIN ){
1609           p->iCell++;
1610           pCellData += pRtree->nBytesPerCell;
1611           break;
1612         }
1613       }
1614       if( eWithin==NOT_WITHIN ) continue;
1615       p->iCell++;
1616       x.iLevel = p->iLevel - 1;
1617       if( x.iLevel ){
1618         x.id = readInt64(pCellData);
1619         for(ii=0; ii<pCur->nPoint; ii++){
1620           if( pCur->aPoint[ii].id==x.id ){
1621             RTREE_IS_CORRUPT(pRtree);
1622             return SQLITE_CORRUPT_VTAB;
1623           }
1624         }
1625         x.iCell = 0;
1626       }else{
1627         x.id = p->id;
1628         x.iCell = p->iCell - 1;
1629       }
1630       if( p->iCell>=nCell ){
1631         RTREE_QUEUE_TRACE(pCur, "POP-S:");
1632         rtreeSearchPointPop(pCur);
1633       }
1634       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
1635       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
1636       if( p==0 ) return SQLITE_NOMEM;
1637       p->eWithin = (u8)eWithin;
1638       p->id = x.id;
1639       p->iCell = x.iCell;
1640       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
1641       break;
1642     }
1643     if( p->iCell>=nCell ){
1644       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
1645       rtreeSearchPointPop(pCur);
1646     }
1647   }
1648   pCur->atEOF = p==0;
1649   return SQLITE_OK;
1650 }
1651 
1652 /*
1653 ** Rtree virtual table module xNext method.
1654 */
1655 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1656   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1657   int rc = SQLITE_OK;
1658 
1659   /* Move to the next entry that matches the configured constraints. */
1660   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
1661   if( pCsr->bAuxValid ){
1662     pCsr->bAuxValid = 0;
1663     sqlite3_reset(pCsr->pReadAux);
1664   }
1665   rtreeSearchPointPop(pCsr);
1666   rc = rtreeStepToLeaf(pCsr);
1667   return rc;
1668 }
1669 
1670 /*
1671 ** Rtree virtual table module xRowid method.
1672 */
1673 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1674   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1675   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1676   int rc = SQLITE_OK;
1677   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1678   if( rc==SQLITE_OK && p ){
1679     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
1680   }
1681   return rc;
1682 }
1683 
1684 /*
1685 ** Rtree virtual table module xColumn method.
1686 */
1687 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1688   Rtree *pRtree = (Rtree *)cur->pVtab;
1689   RtreeCursor *pCsr = (RtreeCursor *)cur;
1690   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1691   RtreeCoord c;
1692   int rc = SQLITE_OK;
1693   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1694 
1695   if( rc ) return rc;
1696   if( p==0 ) return SQLITE_OK;
1697   if( i==0 ){
1698     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
1699   }else if( i<=pRtree->nDim2 ){
1700     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
1701 #ifndef SQLITE_RTREE_INT_ONLY
1702     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1703       sqlite3_result_double(ctx, c.f);
1704     }else
1705 #endif
1706     {
1707       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1708       sqlite3_result_int(ctx, c.i);
1709     }
1710   }else{
1711     if( !pCsr->bAuxValid ){
1712       if( pCsr->pReadAux==0 ){
1713         rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
1714                                 &pCsr->pReadAux, 0);
1715         if( rc ) return rc;
1716       }
1717       sqlite3_bind_int64(pCsr->pReadAux, 1,
1718           nodeGetRowid(pRtree, pNode, p->iCell));
1719       rc = sqlite3_step(pCsr->pReadAux);
1720       if( rc==SQLITE_ROW ){
1721         pCsr->bAuxValid = 1;
1722       }else{
1723         sqlite3_reset(pCsr->pReadAux);
1724         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1725         return rc;
1726       }
1727     }
1728     sqlite3_result_value(ctx,
1729          sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
1730   }
1731   return SQLITE_OK;
1732 }
1733 
1734 /*
1735 ** Use nodeAcquire() to obtain the leaf node containing the record with
1736 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1737 ** return SQLITE_OK. If there is no such record in the table, set
1738 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1739 ** to zero and return an SQLite error code.
1740 */
1741 static int findLeafNode(
1742   Rtree *pRtree,              /* RTree to search */
1743   i64 iRowid,                 /* The rowid searching for */
1744   RtreeNode **ppLeaf,         /* Write the node here */
1745   sqlite3_int64 *piNode       /* Write the node-id here */
1746 ){
1747   int rc;
1748   *ppLeaf = 0;
1749   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1750   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1751     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1752     if( piNode ) *piNode = iNode;
1753     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1754     sqlite3_reset(pRtree->pReadRowid);
1755   }else{
1756     rc = sqlite3_reset(pRtree->pReadRowid);
1757   }
1758   return rc;
1759 }
1760 
1761 /*
1762 ** This function is called to configure the RtreeConstraint object passed
1763 ** as the second argument for a MATCH constraint. The value passed as the
1764 ** first argument to this function is the right-hand operand to the MATCH
1765 ** operator.
1766 */
1767 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1768   RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
1769   sqlite3_rtree_query_info *pInfo;   /* Callback information */
1770 
1771   pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
1772   if( pSrc==0 ) return SQLITE_ERROR;
1773   pInfo = (sqlite3_rtree_query_info*)
1774                 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
1775   if( !pInfo ) return SQLITE_NOMEM;
1776   memset(pInfo, 0, sizeof(*pInfo));
1777   pBlob = (RtreeMatchArg*)&pInfo[1];
1778   memcpy(pBlob, pSrc, pSrc->iSize);
1779   pInfo->pContext = pBlob->cb.pContext;
1780   pInfo->nParam = pBlob->nParam;
1781   pInfo->aParam = pBlob->aParam;
1782   pInfo->apSqlParam = pBlob->apSqlParam;
1783 
1784   if( pBlob->cb.xGeom ){
1785     pCons->u.xGeom = pBlob->cb.xGeom;
1786   }else{
1787     pCons->op = RTREE_QUERY;
1788     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
1789   }
1790   pCons->pInfo = pInfo;
1791   return SQLITE_OK;
1792 }
1793 
1794 /*
1795 ** Rtree virtual table module xFilter method.
1796 */
1797 static int rtreeFilter(
1798   sqlite3_vtab_cursor *pVtabCursor,
1799   int idxNum, const char *idxStr,
1800   int argc, sqlite3_value **argv
1801 ){
1802   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1803   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1804   RtreeNode *pRoot = 0;
1805   int ii;
1806   int rc = SQLITE_OK;
1807   int iCell = 0;
1808 
1809   rtreeReference(pRtree);
1810 
1811   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
1812   resetCursor(pCsr);
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       static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
3749       pRtree->nDim2++;
3750       sqlite3_str_appendf(pSql, azFormat[eCoordType],
3751                           rtreeTokenLength(zArg), zArg);
3752     }
3753   }
3754   sqlite3_str_appendf(pSql, ");");
3755   zSql = sqlite3_str_finish(pSql);
3756   if( !zSql ){
3757     rc = SQLITE_NOMEM;
3758   }else if( ii<argc ){
3759     *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
3760     rc = SQLITE_ERROR;
3761   }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3762     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3763   }
3764   sqlite3_free(zSql);
3765   if( rc ) goto rtreeInit_fail;
3766   pRtree->nDim = pRtree->nDim2/2;
3767   if( pRtree->nDim<1 ){
3768     iErr = 2;
3769   }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
3770     iErr = 3;
3771   }else if( pRtree->nDim2 % 2 ){
3772     iErr = 1;
3773   }else{
3774     iErr = 0;
3775   }
3776   if( iErr ){
3777     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3778     goto rtreeInit_fail;
3779   }
3780   pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
3781 
3782   /* Figure out the node size to use. */
3783   rc = getNodeSize(db, pRtree, isCreate, pzErr);
3784   if( rc ) goto rtreeInit_fail;
3785   rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
3786   if( rc ){
3787     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3788     goto rtreeInit_fail;
3789   }
3790 
3791   *ppVtab = (sqlite3_vtab *)pRtree;
3792   return SQLITE_OK;
3793 
3794 rtreeInit_fail:
3795   if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
3796   assert( *ppVtab==0 );
3797   assert( pRtree->nBusy==1 );
3798   rtreeRelease(pRtree);
3799   return rc;
3800 }
3801 
3802 
3803 /*
3804 ** Implementation of a scalar function that decodes r-tree nodes to
3805 ** human readable strings. This can be used for debugging and analysis.
3806 **
3807 ** The scalar function takes two arguments: (1) the number of dimensions
3808 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
3809 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
3810 ** deserialize all nodes, a statement like:
3811 **
3812 **   SELECT rtreenode(2, data) FROM rt_node;
3813 **
3814 ** The human readable string takes the form of a Tcl list with one
3815 ** entry for each cell in the r-tree node. Each entry is itself a
3816 ** list, containing the 8-byte rowid/pageno followed by the
3817 ** <num-dimension>*2 coordinates.
3818 */
3819 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3820   RtreeNode node;
3821   Rtree tree;
3822   int ii;
3823   int nData;
3824   int errCode;
3825   sqlite3_str *pOut;
3826 
3827   UNUSED_PARAMETER(nArg);
3828   memset(&node, 0, sizeof(RtreeNode));
3829   memset(&tree, 0, sizeof(Rtree));
3830   tree.nDim = (u8)sqlite3_value_int(apArg[0]);
3831   if( tree.nDim<1 || tree.nDim>5 ) return;
3832   tree.nDim2 = tree.nDim*2;
3833   tree.nBytesPerCell = 8 + 8 * tree.nDim;
3834   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3835   nData = sqlite3_value_bytes(apArg[1]);
3836   if( nData<4 ) return;
3837   if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
3838 
3839   pOut = sqlite3_str_new(0);
3840   for(ii=0; ii<NCELL(&node); ii++){
3841     RtreeCell cell;
3842     int jj;
3843 
3844     nodeGetCell(&tree, &node, ii, &cell);
3845     if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
3846     sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
3847     for(jj=0; jj<tree.nDim2; jj++){
3848 #ifndef SQLITE_RTREE_INT_ONLY
3849       sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
3850 #else
3851       sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
3852 #endif
3853     }
3854     sqlite3_str_append(pOut, "}", 1);
3855   }
3856   errCode = sqlite3_str_errcode(pOut);
3857   sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
3858   sqlite3_result_error_code(ctx, errCode);
3859 }
3860 
3861 /* This routine implements an SQL function that returns the "depth" parameter
3862 ** from the front of a blob that is an r-tree node.  For example:
3863 **
3864 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
3865 **
3866 ** The depth value is 0 for all nodes other than the root node, and the root
3867 ** node always has nodeno=1, so the example above is the primary use for this
3868 ** routine.  This routine is intended for testing and analysis only.
3869 */
3870 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3871   UNUSED_PARAMETER(nArg);
3872   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3873    || sqlite3_value_bytes(apArg[0])<2
3874 
3875   ){
3876     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3877   }else{
3878     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3879     if( zBlob ){
3880       sqlite3_result_int(ctx, readInt16(zBlob));
3881     }else{
3882       sqlite3_result_error_nomem(ctx);
3883     }
3884   }
3885 }
3886 
3887 /*
3888 ** Context object passed between the various routines that make up the
3889 ** implementation of integrity-check function rtreecheck().
3890 */
3891 typedef struct RtreeCheck RtreeCheck;
3892 struct RtreeCheck {
3893   sqlite3 *db;                    /* Database handle */
3894   const char *zDb;                /* Database containing rtree table */
3895   const char *zTab;               /* Name of rtree table */
3896   int bInt;                       /* True for rtree_i32 table */
3897   int nDim;                       /* Number of dimensions for this rtree tbl */
3898   sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */
3899   sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
3900   int nLeaf;                      /* Number of leaf cells in table */
3901   int nNonLeaf;                   /* Number of non-leaf cells in table */
3902   int rc;                         /* Return code */
3903   char *zReport;                  /* Message to report */
3904   int nErr;                       /* Number of lines in zReport */
3905 };
3906 
3907 #define RTREE_CHECK_MAX_ERROR 100
3908 
3909 /*
3910 ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
3911 ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
3912 */
3913 static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
3914   int rc = sqlite3_reset(pStmt);
3915   if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
3916 }
3917 
3918 /*
3919 ** The second and subsequent arguments to this function are a format string
3920 ** and printf style arguments. This function formats the string and attempts
3921 ** to compile it as an SQL statement.
3922 **
3923 ** If successful, a pointer to the new SQL statement is returned. Otherwise,
3924 ** NULL is returned and an error code left in RtreeCheck.rc.
3925 */
3926 static sqlite3_stmt *rtreeCheckPrepare(
3927   RtreeCheck *pCheck,             /* RtreeCheck object */
3928   const char *zFmt, ...           /* Format string and trailing args */
3929 ){
3930   va_list ap;
3931   char *z;
3932   sqlite3_stmt *pRet = 0;
3933 
3934   va_start(ap, zFmt);
3935   z = sqlite3_vmprintf(zFmt, ap);
3936 
3937   if( pCheck->rc==SQLITE_OK ){
3938     if( z==0 ){
3939       pCheck->rc = SQLITE_NOMEM;
3940     }else{
3941       pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
3942     }
3943   }
3944 
3945   sqlite3_free(z);
3946   va_end(ap);
3947   return pRet;
3948 }
3949 
3950 /*
3951 ** The second and subsequent arguments to this function are a printf()
3952 ** style format string and arguments. This function formats the string and
3953 ** appends it to the report being accumuated in pCheck.
3954 */
3955 static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
3956   va_list ap;
3957   va_start(ap, zFmt);
3958   if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
3959     char *z = sqlite3_vmprintf(zFmt, ap);
3960     if( z==0 ){
3961       pCheck->rc = SQLITE_NOMEM;
3962     }else{
3963       pCheck->zReport = sqlite3_mprintf("%z%s%z",
3964           pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
3965       );
3966       if( pCheck->zReport==0 ){
3967         pCheck->rc = SQLITE_NOMEM;
3968       }
3969     }
3970     pCheck->nErr++;
3971   }
3972   va_end(ap);
3973 }
3974 
3975 /*
3976 ** This function is a no-op if there is already an error code stored
3977 ** in the RtreeCheck object indicated by the first argument. NULL is
3978 ** returned in this case.
3979 **
3980 ** Otherwise, the contents of rtree table node iNode are loaded from
3981 ** the database and copied into a buffer obtained from sqlite3_malloc().
3982 ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
3983 ** is set to the size of the buffer in bytes.
3984 **
3985 ** Or, if an error does occur, NULL is returned and an error code left
3986 ** in the RtreeCheck object. The final value of *pnNode is undefined in
3987 ** this case.
3988 */
3989 static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
3990   u8 *pRet = 0;                   /* Return value */
3991 
3992   if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
3993     pCheck->pGetNode = rtreeCheckPrepare(pCheck,
3994         "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
3995         pCheck->zDb, pCheck->zTab
3996     );
3997   }
3998 
3999   if( pCheck->rc==SQLITE_OK ){
4000     sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
4001     if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
4002       int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
4003       const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
4004       pRet = sqlite3_malloc64(nNode);
4005       if( pRet==0 ){
4006         pCheck->rc = SQLITE_NOMEM;
4007       }else{
4008         memcpy(pRet, pNode, nNode);
4009         *pnNode = nNode;
4010       }
4011     }
4012     rtreeCheckReset(pCheck, pCheck->pGetNode);
4013     if( pCheck->rc==SQLITE_OK && pRet==0 ){
4014       rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
4015     }
4016   }
4017 
4018   return pRet;
4019 }
4020 
4021 /*
4022 ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
4023 ** (if bLeaf==1) table contains a specified entry. The schemas of the
4024 ** two tables are:
4025 **
4026 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
4027 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
4028 **
4029 ** In both cases, this function checks that there exists an entry with
4030 ** IPK value iKey and the second column set to iVal.
4031 **
4032 */
4033 static void rtreeCheckMapping(
4034   RtreeCheck *pCheck,             /* RtreeCheck object */
4035   int bLeaf,                      /* True for a leaf cell, false for interior */
4036   i64 iKey,                       /* Key for mapping */
4037   i64 iVal                        /* Expected value for mapping */
4038 ){
4039   int rc;
4040   sqlite3_stmt *pStmt;
4041   const char *azSql[2] = {
4042     "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
4043     "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
4044   };
4045 
4046   assert( bLeaf==0 || bLeaf==1 );
4047   if( pCheck->aCheckMapping[bLeaf]==0 ){
4048     pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
4049         azSql[bLeaf], pCheck->zDb, pCheck->zTab
4050     );
4051   }
4052   if( pCheck->rc!=SQLITE_OK ) return;
4053 
4054   pStmt = pCheck->aCheckMapping[bLeaf];
4055   sqlite3_bind_int64(pStmt, 1, iKey);
4056   rc = sqlite3_step(pStmt);
4057   if( rc==SQLITE_DONE ){
4058     rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
4059         iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
4060     );
4061   }else if( rc==SQLITE_ROW ){
4062     i64 ii = sqlite3_column_int64(pStmt, 0);
4063     if( ii!=iVal ){
4064       rtreeCheckAppendMsg(pCheck,
4065           "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
4066           iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
4067       );
4068     }
4069   }
4070   rtreeCheckReset(pCheck, pStmt);
4071 }
4072 
4073 /*
4074 ** Argument pCell points to an array of coordinates stored on an rtree page.
4075 ** This function checks that the coordinates are internally consistent (no
4076 ** x1>x2 conditions) and adds an error message to the RtreeCheck object
4077 ** if they are not.
4078 **
4079 ** Additionally, if pParent is not NULL, then it is assumed to point to
4080 ** the array of coordinates on the parent page that bound the page
4081 ** containing pCell. In this case it is also verified that the two
4082 ** sets of coordinates are mutually consistent and an error message added
4083 ** to the RtreeCheck object if they are not.
4084 */
4085 static void rtreeCheckCellCoord(
4086   RtreeCheck *pCheck,
4087   i64 iNode,                      /* Node id to use in error messages */
4088   int iCell,                      /* Cell number to use in error messages */
4089   u8 *pCell,                      /* Pointer to cell coordinates */
4090   u8 *pParent                     /* Pointer to parent coordinates */
4091 ){
4092   RtreeCoord c1, c2;
4093   RtreeCoord p1, p2;
4094   int i;
4095 
4096   for(i=0; i<pCheck->nDim; i++){
4097     readCoord(&pCell[4*2*i], &c1);
4098     readCoord(&pCell[4*(2*i + 1)], &c2);
4099 
4100     /* printf("%e, %e\n", c1.u.f, c2.u.f); */
4101     if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
4102       rtreeCheckAppendMsg(pCheck,
4103           "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
4104       );
4105     }
4106 
4107     if( pParent ){
4108       readCoord(&pParent[4*2*i], &p1);
4109       readCoord(&pParent[4*(2*i + 1)], &p2);
4110 
4111       if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
4112        || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
4113       ){
4114         rtreeCheckAppendMsg(pCheck,
4115             "Dimension %d of cell %d on node %lld is corrupt relative to parent"
4116             , i, iCell, iNode
4117         );
4118       }
4119     }
4120   }
4121 }
4122 
4123 /*
4124 ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
4125 ** the r-tree structure. Argument aParent points to the array of coordinates
4126 ** that bound node iNode on the parent node.
4127 **
4128 ** If any problems are discovered, an error message is appended to the
4129 ** report accumulated in the RtreeCheck object.
4130 */
4131 static void rtreeCheckNode(
4132   RtreeCheck *pCheck,
4133   int iDepth,                     /* Depth of iNode (0==leaf) */
4134   u8 *aParent,                    /* Buffer containing parent coords */
4135   i64 iNode                       /* Node to check */
4136 ){
4137   u8 *aNode = 0;
4138   int nNode = 0;
4139 
4140   assert( iNode==1 || aParent!=0 );
4141   assert( pCheck->nDim>0 );
4142 
4143   aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
4144   if( aNode ){
4145     if( nNode<4 ){
4146       rtreeCheckAppendMsg(pCheck,
4147           "Node %lld is too small (%d bytes)", iNode, nNode
4148       );
4149     }else{
4150       int nCell;                  /* Number of cells on page */
4151       int i;                      /* Used to iterate through cells */
4152       if( aParent==0 ){
4153         iDepth = readInt16(aNode);
4154         if( iDepth>RTREE_MAX_DEPTH ){
4155           rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
4156           sqlite3_free(aNode);
4157           return;
4158         }
4159       }
4160       nCell = readInt16(&aNode[2]);
4161       if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
4162         rtreeCheckAppendMsg(pCheck,
4163             "Node %lld is too small for cell count of %d (%d bytes)",
4164             iNode, nCell, nNode
4165         );
4166       }else{
4167         for(i=0; i<nCell; i++){
4168           u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
4169           i64 iVal = readInt64(pCell);
4170           rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
4171 
4172           if( iDepth>0 ){
4173             rtreeCheckMapping(pCheck, 0, iVal, iNode);
4174             rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
4175             pCheck->nNonLeaf++;
4176           }else{
4177             rtreeCheckMapping(pCheck, 1, iVal, iNode);
4178             pCheck->nLeaf++;
4179           }
4180         }
4181       }
4182     }
4183     sqlite3_free(aNode);
4184   }
4185 }
4186 
4187 /*
4188 ** The second argument to this function must be either "_rowid" or
4189 ** "_parent". This function checks that the number of entries in the
4190 ** %_rowid or %_parent table is exactly nExpect. If not, it adds
4191 ** an error message to the report in the RtreeCheck object indicated
4192 ** by the first argument.
4193 */
4194 static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
4195   if( pCheck->rc==SQLITE_OK ){
4196     sqlite3_stmt *pCount;
4197     pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
4198         pCheck->zDb, pCheck->zTab, zTbl
4199     );
4200     if( pCount ){
4201       if( sqlite3_step(pCount)==SQLITE_ROW ){
4202         i64 nActual = sqlite3_column_int64(pCount, 0);
4203         if( nActual!=nExpect ){
4204           rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
4205               " - expected %lld, actual %lld" , zTbl, nExpect, nActual
4206           );
4207         }
4208       }
4209       pCheck->rc = sqlite3_finalize(pCount);
4210     }
4211   }
4212 }
4213 
4214 /*
4215 ** This function does the bulk of the work for the rtree integrity-check.
4216 ** It is called by rtreecheck(), which is the SQL function implementation.
4217 */
4218 static int rtreeCheckTable(
4219   sqlite3 *db,                    /* Database handle to access db through */
4220   const char *zDb,                /* Name of db ("main", "temp" etc.) */
4221   const char *zTab,               /* Name of rtree table to check */
4222   char **pzReport                 /* OUT: sqlite3_malloc'd report text */
4223 ){
4224   RtreeCheck check;               /* Common context for various routines */
4225   sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
4226   int bEnd = 0;                   /* True if transaction should be closed */
4227   int nAux = 0;                   /* Number of extra columns. */
4228 
4229   /* Initialize the context object */
4230   memset(&check, 0, sizeof(check));
4231   check.db = db;
4232   check.zDb = zDb;
4233   check.zTab = zTab;
4234 
4235   /* If there is not already an open transaction, open one now. This is
4236   ** to ensure that the queries run as part of this integrity-check operate
4237   ** on a consistent snapshot.  */
4238   if( sqlite3_get_autocommit(db) ){
4239     check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
4240     bEnd = 1;
4241   }
4242 
4243   /* Find the number of auxiliary columns */
4244   if( check.rc==SQLITE_OK ){
4245     pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
4246     if( pStmt ){
4247       nAux = sqlite3_column_count(pStmt) - 2;
4248       sqlite3_finalize(pStmt);
4249     }else
4250     if( check.rc!=SQLITE_NOMEM ){
4251       check.rc = SQLITE_OK;
4252     }
4253   }
4254 
4255   /* Find number of dimensions in the rtree table. */
4256   pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
4257   if( pStmt ){
4258     int rc;
4259     check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
4260     if( check.nDim<1 ){
4261       rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
4262     }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
4263       check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
4264     }
4265     rc = sqlite3_finalize(pStmt);
4266     if( rc!=SQLITE_CORRUPT ) check.rc = rc;
4267   }
4268 
4269   /* Do the actual integrity-check */
4270   if( check.nDim>=1 ){
4271     if( check.rc==SQLITE_OK ){
4272       rtreeCheckNode(&check, 0, 0, 1);
4273     }
4274     rtreeCheckCount(&check, "_rowid", check.nLeaf);
4275     rtreeCheckCount(&check, "_parent", check.nNonLeaf);
4276   }
4277 
4278   /* Finalize SQL statements used by the integrity-check */
4279   sqlite3_finalize(check.pGetNode);
4280   sqlite3_finalize(check.aCheckMapping[0]);
4281   sqlite3_finalize(check.aCheckMapping[1]);
4282 
4283   /* If one was opened, close the transaction */
4284   if( bEnd ){
4285     int rc = sqlite3_exec(db, "END", 0, 0, 0);
4286     if( check.rc==SQLITE_OK ) check.rc = rc;
4287   }
4288   *pzReport = check.zReport;
4289   return check.rc;
4290 }
4291 
4292 /*
4293 ** Usage:
4294 **
4295 **   rtreecheck(<rtree-table>);
4296 **   rtreecheck(<database>, <rtree-table>);
4297 **
4298 ** Invoking this SQL function runs an integrity-check on the named rtree
4299 ** table. The integrity-check verifies the following:
4300 **
4301 **   1. For each cell in the r-tree structure (%_node table), that:
4302 **
4303 **       a) for each dimension, (coord1 <= coord2).
4304 **
4305 **       b) unless the cell is on the root node, that the cell is bounded
4306 **          by the parent cell on the parent node.
4307 **
4308 **       c) for leaf nodes, that there is an entry in the %_rowid
4309 **          table corresponding to the cell's rowid value that
4310 **          points to the correct node.
4311 **
4312 **       d) for cells on non-leaf nodes, that there is an entry in the
4313 **          %_parent table mapping from the cell's child node to the
4314 **          node that it resides on.
4315 **
4316 **   2. That there are the same number of entries in the %_rowid table
4317 **      as there are leaf cells in the r-tree structure, and that there
4318 **      is a leaf cell that corresponds to each entry in the %_rowid table.
4319 **
4320 **   3. That there are the same number of entries in the %_parent table
4321 **      as there are non-leaf cells in the r-tree structure, and that
4322 **      there is a non-leaf cell that corresponds to each entry in the
4323 **      %_parent table.
4324 */
4325 static void rtreecheck(
4326   sqlite3_context *ctx,
4327   int nArg,
4328   sqlite3_value **apArg
4329 ){
4330   if( nArg!=1 && nArg!=2 ){
4331     sqlite3_result_error(ctx,
4332         "wrong number of arguments to function rtreecheck()", -1
4333     );
4334   }else{
4335     int rc;
4336     char *zReport = 0;
4337     const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
4338     const char *zTab;
4339     if( nArg==1 ){
4340       zTab = zDb;
4341       zDb = "main";
4342     }else{
4343       zTab = (const char*)sqlite3_value_text(apArg[1]);
4344     }
4345     rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
4346     if( rc==SQLITE_OK ){
4347       sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
4348     }else{
4349       sqlite3_result_error_code(ctx, rc);
4350     }
4351     sqlite3_free(zReport);
4352   }
4353 }
4354 
4355 /* Conditionally include the geopoly code */
4356 #ifdef SQLITE_ENABLE_GEOPOLY
4357 # include "geopoly.c"
4358 #endif
4359 
4360 /*
4361 ** Register the r-tree module with database handle db. This creates the
4362 ** virtual table module "rtree" and the debugging/analysis scalar
4363 ** function "rtreenode".
4364 */
4365 int sqlite3RtreeInit(sqlite3 *db){
4366   const int utf8 = SQLITE_UTF8;
4367   int rc;
4368 
4369   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
4370   if( rc==SQLITE_OK ){
4371     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
4372   }
4373   if( rc==SQLITE_OK ){
4374     rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
4375   }
4376   if( rc==SQLITE_OK ){
4377 #ifdef SQLITE_RTREE_INT_ONLY
4378     void *c = (void *)RTREE_COORD_INT32;
4379 #else
4380     void *c = (void *)RTREE_COORD_REAL32;
4381 #endif
4382     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
4383   }
4384   if( rc==SQLITE_OK ){
4385     void *c = (void *)RTREE_COORD_INT32;
4386     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
4387   }
4388 #ifdef SQLITE_ENABLE_GEOPOLY
4389   if( rc==SQLITE_OK ){
4390     rc = sqlite3_geopoly_init(db);
4391   }
4392 #endif
4393 
4394   return rc;
4395 }
4396 
4397 /*
4398 ** This routine deletes the RtreeGeomCallback object that was attached
4399 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
4400 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
4401 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
4402 ** the corresponding SQL function is deleted.
4403 */
4404 static void rtreeFreeCallback(void *p){
4405   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
4406   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
4407   sqlite3_free(p);
4408 }
4409 
4410 /*
4411 ** This routine frees the BLOB that is returned by geomCallback().
4412 */
4413 static void rtreeMatchArgFree(void *pArg){
4414   int i;
4415   RtreeMatchArg *p = (RtreeMatchArg*)pArg;
4416   for(i=0; i<p->nParam; i++){
4417     sqlite3_value_free(p->apSqlParam[i]);
4418   }
4419   sqlite3_free(p);
4420 }
4421 
4422 /*
4423 ** Each call to sqlite3_rtree_geometry_callback() or
4424 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
4425 ** scalar function that is implemented by this routine.
4426 **
4427 ** All this function does is construct an RtreeMatchArg object that
4428 ** contains the geometry-checking callback routines and a list of
4429 ** parameters to this function, then return that RtreeMatchArg object
4430 ** as a BLOB.
4431 **
4432 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
4433 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
4434 ** out which elements of the R-Tree should be returned by the query.
4435 */
4436 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
4437   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
4438   RtreeMatchArg *pBlob;
4439   sqlite3_int64 nBlob;
4440   int memErr = 0;
4441 
4442   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
4443            + nArg*sizeof(sqlite3_value*);
4444   pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
4445   if( !pBlob ){
4446     sqlite3_result_error_nomem(ctx);
4447   }else{
4448     int i;
4449     pBlob->iSize = nBlob;
4450     pBlob->cb = pGeomCtx[0];
4451     pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
4452     pBlob->nParam = nArg;
4453     for(i=0; i<nArg; i++){
4454       pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
4455       if( pBlob->apSqlParam[i]==0 ) memErr = 1;
4456 #ifdef SQLITE_RTREE_INT_ONLY
4457       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
4458 #else
4459       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
4460 #endif
4461     }
4462     if( memErr ){
4463       sqlite3_result_error_nomem(ctx);
4464       rtreeMatchArgFree(pBlob);
4465     }else{
4466       sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
4467     }
4468   }
4469 }
4470 
4471 /*
4472 ** Register a new geometry function for use with the r-tree MATCH operator.
4473 */
4474 int sqlite3_rtree_geometry_callback(
4475   sqlite3 *db,                  /* Register SQL function on this connection */
4476   const char *zGeom,            /* Name of the new SQL function */
4477   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
4478   void *pContext                /* Extra data associated with the callback */
4479 ){
4480   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
4481 
4482   /* Allocate and populate the context object. */
4483   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4484   if( !pGeomCtx ) return SQLITE_NOMEM;
4485   pGeomCtx->xGeom = xGeom;
4486   pGeomCtx->xQueryFunc = 0;
4487   pGeomCtx->xDestructor = 0;
4488   pGeomCtx->pContext = pContext;
4489   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
4490       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4491   );
4492 }
4493 
4494 /*
4495 ** Register a new 2nd-generation geometry function for use with the
4496 ** r-tree MATCH operator.
4497 */
4498 int sqlite3_rtree_query_callback(
4499   sqlite3 *db,                 /* Register SQL function on this connection */
4500   const char *zQueryFunc,      /* Name of new SQL function */
4501   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
4502   void *pContext,              /* Extra data passed into the callback */
4503   void (*xDestructor)(void*)   /* Destructor for the extra data */
4504 ){
4505   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
4506 
4507   /* Allocate and populate the context object. */
4508   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4509   if( !pGeomCtx ) return SQLITE_NOMEM;
4510   pGeomCtx->xGeom = 0;
4511   pGeomCtx->xQueryFunc = xQueryFunc;
4512   pGeomCtx->xDestructor = xDestructor;
4513   pGeomCtx->pContext = pContext;
4514   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
4515       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4516   );
4517 }
4518 
4519 #if !SQLITE_CORE
4520 #ifdef _WIN32
4521 __declspec(dllexport)
4522 #endif
4523 int sqlite3_rtree_init(
4524   sqlite3 *db,
4525   char **pzErrMsg,
4526   const sqlite3_api_routines *pApi
4527 ){
4528   SQLITE_EXTENSION_INIT2(pApi)
4529   return sqlite3RtreeInit(db);
4530 }
4531 #endif
4532 
4533 #endif
4534