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