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