xref: /sqlite-3.40.0/ext/rtree/rtree.c (revision 86b262ec)
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       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
1912       if( pNew==0 ) return SQLITE_NOMEM;
1913       pNew->id = 1;
1914       pNew->iCell = 0;
1915       pNew->eWithin = PARTLY_WITHIN;
1916       assert( pCsr->bPoint==1 );
1917       pCsr->aNode[0] = pRoot;
1918       pRoot = 0;
1919       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
1920       rc = rtreeStepToLeaf(pCsr);
1921     }
1922   }
1923 
1924   nodeRelease(pRtree, pRoot);
1925   rtreeRelease(pRtree);
1926   return rc;
1927 }
1928 
1929 /*
1930 ** Rtree virtual table module xBestIndex method. There are three
1931 ** table scan strategies to choose from (in order from most to
1932 ** least desirable):
1933 **
1934 **   idxNum     idxStr        Strategy
1935 **   ------------------------------------------------
1936 **     1        Unused        Direct lookup by rowid.
1937 **     2        See below     R-tree query or full-table scan.
1938 **   ------------------------------------------------
1939 **
1940 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1941 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1942 ** constraint used. The first two bytes of idxStr correspond to
1943 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1944 ** (argvIndex==1) etc.
1945 **
1946 ** The first of each pair of bytes in idxStr identifies the constraint
1947 ** operator as follows:
1948 **
1949 **   Operator    Byte Value
1950 **   ----------------------
1951 **      =        0x41 ('A')
1952 **     <=        0x42 ('B')
1953 **      <        0x43 ('C')
1954 **     >=        0x44 ('D')
1955 **      >        0x45 ('E')
1956 **   MATCH       0x46 ('F')
1957 **   ----------------------
1958 **
1959 ** The second of each pair of bytes identifies the coordinate column
1960 ** to which the constraint applies. The leftmost coordinate column
1961 ** is 'a', the second from the left 'b' etc.
1962 */
1963 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1964   Rtree *pRtree = (Rtree*)tab;
1965   int rc = SQLITE_OK;
1966   int ii;
1967   int bMatch = 0;                 /* True if there exists a MATCH constraint */
1968   i64 nRow;                       /* Estimated rows returned by this scan */
1969 
1970   int iIdx = 0;
1971   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
1972   memset(zIdxStr, 0, sizeof(zIdxStr));
1973 
1974   /* Check if there exists a MATCH constraint - even an unusable one. If there
1975   ** is, do not consider the lookup-by-rowid plan as using such a plan would
1976   ** require the VDBE to evaluate the MATCH constraint, which is not currently
1977   ** possible. */
1978   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
1979     if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
1980       bMatch = 1;
1981     }
1982   }
1983 
1984   assert( pIdxInfo->idxStr==0 );
1985   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
1986     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
1987 
1988     if( bMatch==0 && p->usable
1989      && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
1990     ){
1991       /* We have an equality constraint on the rowid. Use strategy 1. */
1992       int jj;
1993       for(jj=0; jj<ii; jj++){
1994         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
1995         pIdxInfo->aConstraintUsage[jj].omit = 0;
1996       }
1997       pIdxInfo->idxNum = 1;
1998       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
1999       pIdxInfo->aConstraintUsage[jj].omit = 1;
2000 
2001       /* This strategy involves a two rowid lookups on an B-Tree structures
2002       ** and then a linear search of an R-Tree node. This should be
2003       ** considered almost as quick as a direct rowid lookup (for which
2004       ** sqlite uses an internal cost of 0.0). It is expected to return
2005       ** a single row.
2006       */
2007       pIdxInfo->estimatedCost = 30.0;
2008       pIdxInfo->estimatedRows = 1;
2009       pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
2010       return SQLITE_OK;
2011     }
2012 
2013     if( p->usable
2014     && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
2015         || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
2016     ){
2017       u8 op;
2018       switch( p->op ){
2019         case SQLITE_INDEX_CONSTRAINT_EQ:    op = RTREE_EQ;    break;
2020         case SQLITE_INDEX_CONSTRAINT_GT:    op = RTREE_GT;    break;
2021         case SQLITE_INDEX_CONSTRAINT_LE:    op = RTREE_LE;    break;
2022         case SQLITE_INDEX_CONSTRAINT_LT:    op = RTREE_LT;    break;
2023         case SQLITE_INDEX_CONSTRAINT_GE:    op = RTREE_GE;    break;
2024         case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
2025         default:                            op = 0;           break;
2026       }
2027       if( op ){
2028         zIdxStr[iIdx++] = op;
2029         zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
2030         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
2031         pIdxInfo->aConstraintUsage[ii].omit = 1;
2032       }
2033     }
2034   }
2035 
2036   pIdxInfo->idxNum = 2;
2037   pIdxInfo->needToFreeIdxStr = 1;
2038   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
2039     return SQLITE_NOMEM;
2040   }
2041 
2042   nRow = pRtree->nRowEst >> (iIdx/2);
2043   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
2044   pIdxInfo->estimatedRows = nRow;
2045 
2046   return rc;
2047 }
2048 
2049 /*
2050 ** Return the N-dimensional volumn of the cell stored in *p.
2051 */
2052 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
2053   RtreeDValue area = (RtreeDValue)1;
2054   assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
2055 #ifndef SQLITE_RTREE_INT_ONLY
2056   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2057     switch( pRtree->nDim ){
2058       case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
2059       case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
2060       case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
2061       case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
2062       default: area *= p->aCoord[1].f - p->aCoord[0].f;
2063     }
2064   }else
2065 #endif
2066   {
2067     switch( pRtree->nDim ){
2068       case 5:  area  = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
2069       case 4:  area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
2070       case 3:  area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
2071       case 2:  area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
2072       default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
2073     }
2074   }
2075   return area;
2076 }
2077 
2078 /*
2079 ** Return the margin length of cell p. The margin length is the sum
2080 ** of the objects size in each dimension.
2081 */
2082 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
2083   RtreeDValue margin = 0;
2084   int ii = pRtree->nDim2 - 2;
2085   do{
2086     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
2087     ii -= 2;
2088   }while( ii>=0 );
2089   return margin;
2090 }
2091 
2092 /*
2093 ** Store the union of cells p1 and p2 in p1.
2094 */
2095 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2096   int ii = 0;
2097   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2098     do{
2099       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
2100       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
2101       ii += 2;
2102     }while( ii<pRtree->nDim2 );
2103   }else{
2104     do{
2105       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
2106       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
2107       ii += 2;
2108     }while( ii<pRtree->nDim2 );
2109   }
2110 }
2111 
2112 /*
2113 ** Return true if the area covered by p2 is a subset of the area covered
2114 ** by p1. False otherwise.
2115 */
2116 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2117   int ii;
2118   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
2119   for(ii=0; ii<pRtree->nDim2; ii+=2){
2120     RtreeCoord *a1 = &p1->aCoord[ii];
2121     RtreeCoord *a2 = &p2->aCoord[ii];
2122     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
2123      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
2124     ){
2125       return 0;
2126     }
2127   }
2128   return 1;
2129 }
2130 
2131 /*
2132 ** Return the amount cell p would grow by if it were unioned with pCell.
2133 */
2134 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
2135   RtreeDValue area;
2136   RtreeCell cell;
2137   memcpy(&cell, p, sizeof(RtreeCell));
2138   area = cellArea(pRtree, &cell);
2139   cellUnion(pRtree, &cell, pCell);
2140   return (cellArea(pRtree, &cell)-area);
2141 }
2142 
2143 static RtreeDValue cellOverlap(
2144   Rtree *pRtree,
2145   RtreeCell *p,
2146   RtreeCell *aCell,
2147   int nCell
2148 ){
2149   int ii;
2150   RtreeDValue overlap = RTREE_ZERO;
2151   for(ii=0; ii<nCell; ii++){
2152     int jj;
2153     RtreeDValue o = (RtreeDValue)1;
2154     for(jj=0; jj<pRtree->nDim2; jj+=2){
2155       RtreeDValue x1, x2;
2156       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
2157       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
2158       if( x2<x1 ){
2159         o = (RtreeDValue)0;
2160         break;
2161       }else{
2162         o = o * (x2-x1);
2163       }
2164     }
2165     overlap += o;
2166   }
2167   return overlap;
2168 }
2169 
2170 
2171 /*
2172 ** This function implements the ChooseLeaf algorithm from Gutman[84].
2173 ** ChooseSubTree in r*tree terminology.
2174 */
2175 static int ChooseLeaf(
2176   Rtree *pRtree,               /* Rtree table */
2177   RtreeCell *pCell,            /* Cell to insert into rtree */
2178   int iHeight,                 /* Height of sub-tree rooted at pCell */
2179   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
2180 ){
2181   int rc;
2182   int ii;
2183   RtreeNode *pNode = 0;
2184   rc = nodeAcquire(pRtree, 1, 0, &pNode);
2185 
2186   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
2187     int iCell;
2188     sqlite3_int64 iBest = 0;
2189 
2190     RtreeDValue fMinGrowth = RTREE_ZERO;
2191     RtreeDValue fMinArea = RTREE_ZERO;
2192 
2193     int nCell = NCELL(pNode);
2194     RtreeCell cell;
2195     RtreeNode *pChild;
2196 
2197     RtreeCell *aCell = 0;
2198 
2199     /* Select the child node which will be enlarged the least if pCell
2200     ** is inserted into it. Resolve ties by choosing the entry with
2201     ** the smallest area.
2202     */
2203     for(iCell=0; iCell<nCell; iCell++){
2204       int bBest = 0;
2205       RtreeDValue growth;
2206       RtreeDValue area;
2207       nodeGetCell(pRtree, pNode, iCell, &cell);
2208       growth = cellGrowth(pRtree, &cell, pCell);
2209       area = cellArea(pRtree, &cell);
2210       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
2211         bBest = 1;
2212       }
2213       if( bBest ){
2214         fMinGrowth = growth;
2215         fMinArea = area;
2216         iBest = cell.iRowid;
2217       }
2218     }
2219 
2220     sqlite3_free(aCell);
2221     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
2222     nodeRelease(pRtree, pNode);
2223     pNode = pChild;
2224   }
2225 
2226   *ppLeaf = pNode;
2227   return rc;
2228 }
2229 
2230 /*
2231 ** A cell with the same content as pCell has just been inserted into
2232 ** the node pNode. This function updates the bounding box cells in
2233 ** all ancestor elements.
2234 */
2235 static int AdjustTree(
2236   Rtree *pRtree,                    /* Rtree table */
2237   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
2238   RtreeCell *pCell                  /* This cell was just inserted */
2239 ){
2240   RtreeNode *p = pNode;
2241   int cnt = 0;
2242   int rc;
2243   while( p->pParent ){
2244     RtreeNode *pParent = p->pParent;
2245     RtreeCell cell;
2246     int iCell;
2247 
2248     cnt++;
2249     if( NEVER(cnt>100) ){
2250       RTREE_IS_CORRUPT(pRtree);
2251       return SQLITE_CORRUPT_VTAB;
2252     }
2253     rc = nodeParentIndex(pRtree, p, &iCell);
2254     if( NEVER(rc!=SQLITE_OK) ){
2255       RTREE_IS_CORRUPT(pRtree);
2256       return SQLITE_CORRUPT_VTAB;
2257     }
2258 
2259     nodeGetCell(pRtree, pParent, iCell, &cell);
2260     if( !cellContains(pRtree, &cell, pCell) ){
2261       cellUnion(pRtree, &cell, pCell);
2262       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
2263     }
2264 
2265     p = pParent;
2266   }
2267   return SQLITE_OK;
2268 }
2269 
2270 /*
2271 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
2272 */
2273 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
2274   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
2275   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
2276   sqlite3_step(pRtree->pWriteRowid);
2277   return sqlite3_reset(pRtree->pWriteRowid);
2278 }
2279 
2280 /*
2281 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
2282 */
2283 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
2284   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
2285   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
2286   sqlite3_step(pRtree->pWriteParent);
2287   return sqlite3_reset(pRtree->pWriteParent);
2288 }
2289 
2290 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
2291 
2292 
2293 /*
2294 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
2295 ** nIdx. The aIdx array contains the set of integers from 0 to
2296 ** (nIdx-1) in no particular order. This function sorts the values
2297 ** in aIdx according to the indexed values in aDistance. For
2298 ** example, assuming the inputs:
2299 **
2300 **   aIdx      = { 0,   1,   2,   3 }
2301 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
2302 **
2303 ** this function sets the aIdx array to contain:
2304 **
2305 **   aIdx      = { 0,   1,   2,   3 }
2306 **
2307 ** The aSpare array is used as temporary working space by the
2308 ** sorting algorithm.
2309 */
2310 static void SortByDistance(
2311   int *aIdx,
2312   int nIdx,
2313   RtreeDValue *aDistance,
2314   int *aSpare
2315 ){
2316   if( nIdx>1 ){
2317     int iLeft = 0;
2318     int iRight = 0;
2319 
2320     int nLeft = nIdx/2;
2321     int nRight = nIdx-nLeft;
2322     int *aLeft = aIdx;
2323     int *aRight = &aIdx[nLeft];
2324 
2325     SortByDistance(aLeft, nLeft, aDistance, aSpare);
2326     SortByDistance(aRight, nRight, aDistance, aSpare);
2327 
2328     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2329     aLeft = aSpare;
2330 
2331     while( iLeft<nLeft || iRight<nRight ){
2332       if( iLeft==nLeft ){
2333         aIdx[iLeft+iRight] = aRight[iRight];
2334         iRight++;
2335       }else if( iRight==nRight ){
2336         aIdx[iLeft+iRight] = aLeft[iLeft];
2337         iLeft++;
2338       }else{
2339         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
2340         RtreeDValue fRight = aDistance[aRight[iRight]];
2341         if( fLeft<fRight ){
2342           aIdx[iLeft+iRight] = aLeft[iLeft];
2343           iLeft++;
2344         }else{
2345           aIdx[iLeft+iRight] = aRight[iRight];
2346           iRight++;
2347         }
2348       }
2349     }
2350 
2351 #if 0
2352     /* Check that the sort worked */
2353     {
2354       int jj;
2355       for(jj=1; jj<nIdx; jj++){
2356         RtreeDValue left = aDistance[aIdx[jj-1]];
2357         RtreeDValue right = aDistance[aIdx[jj]];
2358         assert( left<=right );
2359       }
2360     }
2361 #endif
2362   }
2363 }
2364 
2365 /*
2366 ** Arguments aIdx, aCell and aSpare all point to arrays of size
2367 ** nIdx. The aIdx array contains the set of integers from 0 to
2368 ** (nIdx-1) in no particular order. This function sorts the values
2369 ** in aIdx according to dimension iDim of the cells in aCell. The
2370 ** minimum value of dimension iDim is considered first, the
2371 ** maximum used to break ties.
2372 **
2373 ** The aSpare array is used as temporary working space by the
2374 ** sorting algorithm.
2375 */
2376 static void SortByDimension(
2377   Rtree *pRtree,
2378   int *aIdx,
2379   int nIdx,
2380   int iDim,
2381   RtreeCell *aCell,
2382   int *aSpare
2383 ){
2384   if( nIdx>1 ){
2385 
2386     int iLeft = 0;
2387     int iRight = 0;
2388 
2389     int nLeft = nIdx/2;
2390     int nRight = nIdx-nLeft;
2391     int *aLeft = aIdx;
2392     int *aRight = &aIdx[nLeft];
2393 
2394     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
2395     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
2396 
2397     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2398     aLeft = aSpare;
2399     while( iLeft<nLeft || iRight<nRight ){
2400       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
2401       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
2402       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
2403       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
2404       if( (iLeft!=nLeft) && ((iRight==nRight)
2405        || (xleft1<xright1)
2406        || (xleft1==xright1 && xleft2<xright2)
2407       )){
2408         aIdx[iLeft+iRight] = aLeft[iLeft];
2409         iLeft++;
2410       }else{
2411         aIdx[iLeft+iRight] = aRight[iRight];
2412         iRight++;
2413       }
2414     }
2415 
2416 #if 0
2417     /* Check that the sort worked */
2418     {
2419       int jj;
2420       for(jj=1; jj<nIdx; jj++){
2421         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2422         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2423         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2424         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2425         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2426       }
2427     }
2428 #endif
2429   }
2430 }
2431 
2432 /*
2433 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2434 */
2435 static int splitNodeStartree(
2436   Rtree *pRtree,
2437   RtreeCell *aCell,
2438   int nCell,
2439   RtreeNode *pLeft,
2440   RtreeNode *pRight,
2441   RtreeCell *pBboxLeft,
2442   RtreeCell *pBboxRight
2443 ){
2444   int **aaSorted;
2445   int *aSpare;
2446   int ii;
2447 
2448   int iBestDim = 0;
2449   int iBestSplit = 0;
2450   RtreeDValue fBestMargin = RTREE_ZERO;
2451 
2452   sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2453 
2454   aaSorted = (int **)sqlite3_malloc64(nByte);
2455   if( !aaSorted ){
2456     return SQLITE_NOMEM;
2457   }
2458 
2459   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2460   memset(aaSorted, 0, nByte);
2461   for(ii=0; ii<pRtree->nDim; ii++){
2462     int jj;
2463     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2464     for(jj=0; jj<nCell; jj++){
2465       aaSorted[ii][jj] = jj;
2466     }
2467     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2468   }
2469 
2470   for(ii=0; ii<pRtree->nDim; ii++){
2471     RtreeDValue margin = RTREE_ZERO;
2472     RtreeDValue fBestOverlap = RTREE_ZERO;
2473     RtreeDValue fBestArea = RTREE_ZERO;
2474     int iBestLeft = 0;
2475     int nLeft;
2476 
2477     for(
2478       nLeft=RTREE_MINCELLS(pRtree);
2479       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2480       nLeft++
2481     ){
2482       RtreeCell left;
2483       RtreeCell right;
2484       int kk;
2485       RtreeDValue overlap;
2486       RtreeDValue area;
2487 
2488       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2489       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2490       for(kk=1; kk<(nCell-1); kk++){
2491         if( kk<nLeft ){
2492           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2493         }else{
2494           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2495         }
2496       }
2497       margin += cellMargin(pRtree, &left);
2498       margin += cellMargin(pRtree, &right);
2499       overlap = cellOverlap(pRtree, &left, &right, 1);
2500       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2501       if( (nLeft==RTREE_MINCELLS(pRtree))
2502        || (overlap<fBestOverlap)
2503        || (overlap==fBestOverlap && area<fBestArea)
2504       ){
2505         iBestLeft = nLeft;
2506         fBestOverlap = overlap;
2507         fBestArea = area;
2508       }
2509     }
2510 
2511     if( ii==0 || margin<fBestMargin ){
2512       iBestDim = ii;
2513       fBestMargin = margin;
2514       iBestSplit = iBestLeft;
2515     }
2516   }
2517 
2518   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2519   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2520   for(ii=0; ii<nCell; ii++){
2521     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2522     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2523     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2524     nodeInsertCell(pRtree, pTarget, pCell);
2525     cellUnion(pRtree, pBbox, pCell);
2526   }
2527 
2528   sqlite3_free(aaSorted);
2529   return SQLITE_OK;
2530 }
2531 
2532 
2533 static int updateMapping(
2534   Rtree *pRtree,
2535   i64 iRowid,
2536   RtreeNode *pNode,
2537   int iHeight
2538 ){
2539   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2540   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2541   if( iHeight>0 ){
2542     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2543     if( pChild ){
2544       nodeRelease(pRtree, pChild->pParent);
2545       nodeReference(pNode);
2546       pChild->pParent = pNode;
2547     }
2548   }
2549   return xSetMapping(pRtree, iRowid, pNode->iNode);
2550 }
2551 
2552 static int SplitNode(
2553   Rtree *pRtree,
2554   RtreeNode *pNode,
2555   RtreeCell *pCell,
2556   int iHeight
2557 ){
2558   int i;
2559   int newCellIsRight = 0;
2560 
2561   int rc = SQLITE_OK;
2562   int nCell = NCELL(pNode);
2563   RtreeCell *aCell;
2564   int *aiUsed;
2565 
2566   RtreeNode *pLeft = 0;
2567   RtreeNode *pRight = 0;
2568 
2569   RtreeCell leftbbox;
2570   RtreeCell rightbbox;
2571 
2572   /* Allocate an array and populate it with a copy of pCell and
2573   ** all cells from node pLeft. Then zero the original node.
2574   */
2575   aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2576   if( !aCell ){
2577     rc = SQLITE_NOMEM;
2578     goto splitnode_out;
2579   }
2580   aiUsed = (int *)&aCell[nCell+1];
2581   memset(aiUsed, 0, sizeof(int)*(nCell+1));
2582   for(i=0; i<nCell; i++){
2583     nodeGetCell(pRtree, pNode, i, &aCell[i]);
2584   }
2585   nodeZero(pRtree, pNode);
2586   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2587   nCell++;
2588 
2589   if( pNode->iNode==1 ){
2590     pRight = nodeNew(pRtree, pNode);
2591     pLeft = nodeNew(pRtree, pNode);
2592     pRtree->iDepth++;
2593     pNode->isDirty = 1;
2594     writeInt16(pNode->zData, pRtree->iDepth);
2595   }else{
2596     pLeft = pNode;
2597     pRight = nodeNew(pRtree, pLeft->pParent);
2598     pLeft->nRef++;
2599   }
2600 
2601   if( !pLeft || !pRight ){
2602     rc = SQLITE_NOMEM;
2603     goto splitnode_out;
2604   }
2605 
2606   memset(pLeft->zData, 0, pRtree->iNodeSize);
2607   memset(pRight->zData, 0, pRtree->iNodeSize);
2608 
2609   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
2610                          &leftbbox, &rightbbox);
2611   if( rc!=SQLITE_OK ){
2612     goto splitnode_out;
2613   }
2614 
2615   /* Ensure both child nodes have node numbers assigned to them by calling
2616   ** nodeWrite(). Node pRight always needs a node number, as it was created
2617   ** by nodeNew() above. But node pLeft sometimes already has a node number.
2618   ** In this case avoid the all to nodeWrite().
2619   */
2620   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2621    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2622   ){
2623     goto splitnode_out;
2624   }
2625 
2626   rightbbox.iRowid = pRight->iNode;
2627   leftbbox.iRowid = pLeft->iNode;
2628 
2629   if( pNode->iNode==1 ){
2630     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2631     if( rc!=SQLITE_OK ){
2632       goto splitnode_out;
2633     }
2634   }else{
2635     RtreeNode *pParent = pLeft->pParent;
2636     int iCell;
2637     rc = nodeParentIndex(pRtree, pLeft, &iCell);
2638     if( ALWAYS(rc==SQLITE_OK) ){
2639       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2640       rc = AdjustTree(pRtree, pParent, &leftbbox);
2641       assert( rc==SQLITE_OK );
2642     }
2643     if( NEVER(rc!=SQLITE_OK) ){
2644       goto splitnode_out;
2645     }
2646   }
2647   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2648     goto splitnode_out;
2649   }
2650 
2651   for(i=0; i<NCELL(pRight); i++){
2652     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2653     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2654     if( iRowid==pCell->iRowid ){
2655       newCellIsRight = 1;
2656     }
2657     if( rc!=SQLITE_OK ){
2658       goto splitnode_out;
2659     }
2660   }
2661   if( pNode->iNode==1 ){
2662     for(i=0; i<NCELL(pLeft); i++){
2663       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2664       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2665       if( rc!=SQLITE_OK ){
2666         goto splitnode_out;
2667       }
2668     }
2669   }else if( newCellIsRight==0 ){
2670     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2671   }
2672 
2673   if( rc==SQLITE_OK ){
2674     rc = nodeRelease(pRtree, pRight);
2675     pRight = 0;
2676   }
2677   if( rc==SQLITE_OK ){
2678     rc = nodeRelease(pRtree, pLeft);
2679     pLeft = 0;
2680   }
2681 
2682 splitnode_out:
2683   nodeRelease(pRtree, pRight);
2684   nodeRelease(pRtree, pLeft);
2685   sqlite3_free(aCell);
2686   return rc;
2687 }
2688 
2689 /*
2690 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2691 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2692 ** the pLeaf->pParent chain all the way up to the root node.
2693 **
2694 ** This operation is required when a row is deleted (or updated - an update
2695 ** is implemented as a delete followed by an insert). SQLite provides the
2696 ** rowid of the row to delete, which can be used to find the leaf on which
2697 ** the entry resides (argument pLeaf). Once the leaf is located, this
2698 ** function is called to determine its ancestry.
2699 */
2700 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2701   int rc = SQLITE_OK;
2702   RtreeNode *pChild = pLeaf;
2703   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2704     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
2705     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2706     rc = sqlite3_step(pRtree->pReadParent);
2707     if( rc==SQLITE_ROW ){
2708       RtreeNode *pTest;           /* Used to test for reference loops */
2709       i64 iNode;                  /* Node number of parent node */
2710 
2711       /* Before setting pChild->pParent, test that we are not creating a
2712       ** loop of references (as we would if, say, pChild==pParent). We don't
2713       ** want to do this as it leads to a memory leak when trying to delete
2714       ** the referenced counted node structures.
2715       */
2716       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2717       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2718       if( pTest==0 ){
2719         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2720       }
2721     }
2722     rc = sqlite3_reset(pRtree->pReadParent);
2723     if( rc==SQLITE_OK ) rc = rc2;
2724     if( rc==SQLITE_OK && !pChild->pParent ){
2725       RTREE_IS_CORRUPT(pRtree);
2726       rc = SQLITE_CORRUPT_VTAB;
2727     }
2728     pChild = pChild->pParent;
2729   }
2730   return rc;
2731 }
2732 
2733 static int deleteCell(Rtree *, RtreeNode *, int, int);
2734 
2735 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2736   int rc;
2737   int rc2;
2738   RtreeNode *pParent = 0;
2739   int iCell;
2740 
2741   assert( pNode->nRef==1 );
2742 
2743   /* Remove the entry in the parent cell. */
2744   rc = nodeParentIndex(pRtree, pNode, &iCell);
2745   if( rc==SQLITE_OK ){
2746     pParent = pNode->pParent;
2747     pNode->pParent = 0;
2748     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2749     assert( rc==SQLITE_OK );
2750   }
2751   rc2 = nodeRelease(pRtree, pParent);
2752   if( rc==SQLITE_OK ){
2753     rc = rc2;
2754   }
2755   if( rc!=SQLITE_OK ){
2756     return rc;
2757   }
2758 
2759   /* Remove the xxx_node entry. */
2760   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2761   sqlite3_step(pRtree->pDeleteNode);
2762   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2763     return rc;
2764   }
2765 
2766   /* Remove the xxx_parent entry. */
2767   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2768   sqlite3_step(pRtree->pDeleteParent);
2769   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2770     return rc;
2771   }
2772 
2773   /* Remove the node from the in-memory hash table and link it into
2774   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2775   */
2776   nodeHashDelete(pRtree, pNode);
2777   pNode->iNode = iHeight;
2778   pNode->pNext = pRtree->pDeleted;
2779   pNode->nRef++;
2780   pRtree->pDeleted = pNode;
2781 
2782   return SQLITE_OK;
2783 }
2784 
2785 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2786   RtreeNode *pParent = pNode->pParent;
2787   int rc = SQLITE_OK;
2788   if( pParent ){
2789     int ii;
2790     int nCell = NCELL(pNode);
2791     RtreeCell box;                            /* Bounding box for pNode */
2792     nodeGetCell(pRtree, pNode, 0, &box);
2793     for(ii=1; ii<nCell; ii++){
2794       RtreeCell cell;
2795       nodeGetCell(pRtree, pNode, ii, &cell);
2796       cellUnion(pRtree, &box, &cell);
2797     }
2798     box.iRowid = pNode->iNode;
2799     rc = nodeParentIndex(pRtree, pNode, &ii);
2800     if( rc==SQLITE_OK ){
2801       nodeOverwriteCell(pRtree, pParent, &box, ii);
2802       rc = fixBoundingBox(pRtree, pParent);
2803     }
2804   }
2805   return rc;
2806 }
2807 
2808 /*
2809 ** Delete the cell at index iCell of node pNode. After removing the
2810 ** cell, adjust the r-tree data structure if required.
2811 */
2812 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2813   RtreeNode *pParent;
2814   int rc;
2815 
2816   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2817     return rc;
2818   }
2819 
2820   /* Remove the cell from the node. This call just moves bytes around
2821   ** the in-memory node image, so it cannot fail.
2822   */
2823   nodeDeleteCell(pRtree, pNode, iCell);
2824 
2825   /* If the node is not the tree root and now has less than the minimum
2826   ** number of cells, remove it from the tree. Otherwise, update the
2827   ** cell in the parent node so that it tightly contains the updated
2828   ** node.
2829   */
2830   pParent = pNode->pParent;
2831   assert( pParent || pNode->iNode==1 );
2832   if( pParent ){
2833     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2834       rc = removeNode(pRtree, pNode, iHeight);
2835     }else{
2836       rc = fixBoundingBox(pRtree, pNode);
2837     }
2838   }
2839 
2840   return rc;
2841 }
2842 
2843 static int Reinsert(
2844   Rtree *pRtree,
2845   RtreeNode *pNode,
2846   RtreeCell *pCell,
2847   int iHeight
2848 ){
2849   int *aOrder;
2850   int *aSpare;
2851   RtreeCell *aCell;
2852   RtreeDValue *aDistance;
2853   int nCell;
2854   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
2855   int iDim;
2856   int ii;
2857   int rc = SQLITE_OK;
2858   int n;
2859 
2860   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
2861 
2862   nCell = NCELL(pNode)+1;
2863   n = (nCell+1)&(~1);
2864 
2865   /* Allocate the buffers used by this operation. The allocation is
2866   ** relinquished before this function returns.
2867   */
2868   aCell = (RtreeCell *)sqlite3_malloc64(n * (
2869     sizeof(RtreeCell)     +         /* aCell array */
2870     sizeof(int)           +         /* aOrder array */
2871     sizeof(int)           +         /* aSpare array */
2872     sizeof(RtreeDValue)             /* aDistance array */
2873   ));
2874   if( !aCell ){
2875     return SQLITE_NOMEM;
2876   }
2877   aOrder    = (int *)&aCell[n];
2878   aSpare    = (int *)&aOrder[n];
2879   aDistance = (RtreeDValue *)&aSpare[n];
2880 
2881   for(ii=0; ii<nCell; ii++){
2882     if( ii==(nCell-1) ){
2883       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2884     }else{
2885       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2886     }
2887     aOrder[ii] = ii;
2888     for(iDim=0; iDim<pRtree->nDim; iDim++){
2889       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2890       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2891     }
2892   }
2893   for(iDim=0; iDim<pRtree->nDim; iDim++){
2894     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
2895   }
2896 
2897   for(ii=0; ii<nCell; ii++){
2898     aDistance[ii] = RTREE_ZERO;
2899     for(iDim=0; iDim<pRtree->nDim; iDim++){
2900       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
2901                                DCOORD(aCell[ii].aCoord[iDim*2]));
2902       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2903     }
2904   }
2905 
2906   SortByDistance(aOrder, nCell, aDistance, aSpare);
2907   nodeZero(pRtree, pNode);
2908 
2909   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2910     RtreeCell *p = &aCell[aOrder[ii]];
2911     nodeInsertCell(pRtree, pNode, p);
2912     if( p->iRowid==pCell->iRowid ){
2913       if( iHeight==0 ){
2914         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2915       }else{
2916         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2917       }
2918     }
2919   }
2920   if( rc==SQLITE_OK ){
2921     rc = fixBoundingBox(pRtree, pNode);
2922   }
2923   for(; rc==SQLITE_OK && ii<nCell; ii++){
2924     /* Find a node to store this cell in. pNode->iNode currently contains
2925     ** the height of the sub-tree headed by the cell.
2926     */
2927     RtreeNode *pInsert;
2928     RtreeCell *p = &aCell[aOrder[ii]];
2929     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2930     if( rc==SQLITE_OK ){
2931       int rc2;
2932       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2933       rc2 = nodeRelease(pRtree, pInsert);
2934       if( rc==SQLITE_OK ){
2935         rc = rc2;
2936       }
2937     }
2938   }
2939 
2940   sqlite3_free(aCell);
2941   return rc;
2942 }
2943 
2944 /*
2945 ** Insert cell pCell into node pNode. Node pNode is the head of a
2946 ** subtree iHeight high (leaf nodes have iHeight==0).
2947 */
2948 static int rtreeInsertCell(
2949   Rtree *pRtree,
2950   RtreeNode *pNode,
2951   RtreeCell *pCell,
2952   int iHeight
2953 ){
2954   int rc = SQLITE_OK;
2955   if( iHeight>0 ){
2956     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2957     if( pChild ){
2958       nodeRelease(pRtree, pChild->pParent);
2959       nodeReference(pNode);
2960       pChild->pParent = pNode;
2961     }
2962   }
2963   if( nodeInsertCell(pRtree, pNode, pCell) ){
2964     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
2965       rc = SplitNode(pRtree, pNode, pCell, iHeight);
2966     }else{
2967       pRtree->iReinsertHeight = iHeight;
2968       rc = Reinsert(pRtree, pNode, pCell, iHeight);
2969     }
2970   }else{
2971     rc = AdjustTree(pRtree, pNode, pCell);
2972     if( ALWAYS(rc==SQLITE_OK) ){
2973       if( iHeight==0 ){
2974         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
2975       }else{
2976         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
2977       }
2978     }
2979   }
2980   return rc;
2981 }
2982 
2983 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
2984   int ii;
2985   int rc = SQLITE_OK;
2986   int nCell = NCELL(pNode);
2987 
2988   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
2989     RtreeNode *pInsert;
2990     RtreeCell cell;
2991     nodeGetCell(pRtree, pNode, ii, &cell);
2992 
2993     /* Find a node to store this cell in. pNode->iNode currently contains
2994     ** the height of the sub-tree headed by the cell.
2995     */
2996     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
2997     if( rc==SQLITE_OK ){
2998       int rc2;
2999       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
3000       rc2 = nodeRelease(pRtree, pInsert);
3001       if( rc==SQLITE_OK ){
3002         rc = rc2;
3003       }
3004     }
3005   }
3006   return rc;
3007 }
3008 
3009 /*
3010 ** Select a currently unused rowid for a new r-tree record.
3011 */
3012 static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
3013   int rc;
3014   sqlite3_bind_null(pRtree->pWriteRowid, 1);
3015   sqlite3_bind_null(pRtree->pWriteRowid, 2);
3016   sqlite3_step(pRtree->pWriteRowid);
3017   rc = sqlite3_reset(pRtree->pWriteRowid);
3018   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
3019   return rc;
3020 }
3021 
3022 /*
3023 ** Remove the entry with rowid=iDelete from the r-tree structure.
3024 */
3025 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
3026   int rc;                         /* Return code */
3027   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
3028   int iCell;                      /* Index of iDelete cell in pLeaf */
3029   RtreeNode *pRoot = 0;           /* Root node of rtree structure */
3030 
3031 
3032   /* Obtain a reference to the root node to initialize Rtree.iDepth */
3033   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
3034 
3035   /* Obtain a reference to the leaf node that contains the entry
3036   ** about to be deleted.
3037   */
3038   if( rc==SQLITE_OK ){
3039     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
3040   }
3041 
3042 #ifdef CORRUPT_DB
3043   assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
3044 #endif
3045 
3046   /* Delete the cell in question from the leaf node. */
3047   if( rc==SQLITE_OK && pLeaf ){
3048     int rc2;
3049     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
3050     if( rc==SQLITE_OK ){
3051       rc = deleteCell(pRtree, pLeaf, iCell, 0);
3052     }
3053     rc2 = nodeRelease(pRtree, pLeaf);
3054     if( rc==SQLITE_OK ){
3055       rc = rc2;
3056     }
3057   }
3058 
3059   /* Delete the corresponding entry in the <rtree>_rowid table. */
3060   if( rc==SQLITE_OK ){
3061     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
3062     sqlite3_step(pRtree->pDeleteRowid);
3063     rc = sqlite3_reset(pRtree->pDeleteRowid);
3064   }
3065 
3066   /* Check if the root node now has exactly one child. If so, remove
3067   ** it, schedule the contents of the child for reinsertion and
3068   ** reduce the tree height by one.
3069   **
3070   ** This is equivalent to copying the contents of the child into
3071   ** the root node (the operation that Gutman's paper says to perform
3072   ** in this scenario).
3073   */
3074   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
3075     int rc2;
3076     RtreeNode *pChild = 0;
3077     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
3078     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
3079     if( rc==SQLITE_OK ){
3080       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
3081     }
3082     rc2 = nodeRelease(pRtree, pChild);
3083     if( rc==SQLITE_OK ) rc = rc2;
3084     if( rc==SQLITE_OK ){
3085       pRtree->iDepth--;
3086       writeInt16(pRoot->zData, pRtree->iDepth);
3087       pRoot->isDirty = 1;
3088     }
3089   }
3090 
3091   /* Re-insert the contents of any underfull nodes removed from the tree. */
3092   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
3093     if( rc==SQLITE_OK ){
3094       rc = reinsertNodeContent(pRtree, pLeaf);
3095     }
3096     pRtree->pDeleted = pLeaf->pNext;
3097     pRtree->nNodeRef--;
3098     sqlite3_free(pLeaf);
3099   }
3100 
3101   /* Release the reference to the root node. */
3102   if( rc==SQLITE_OK ){
3103     rc = nodeRelease(pRtree, pRoot);
3104   }else{
3105     nodeRelease(pRtree, pRoot);
3106   }
3107 
3108   return rc;
3109 }
3110 
3111 /*
3112 ** Rounding constants for float->double conversion.
3113 */
3114 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
3115 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
3116 
3117 #if !defined(SQLITE_RTREE_INT_ONLY)
3118 /*
3119 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
3120 ** while taking care to round toward negative or positive, respectively.
3121 */
3122 static RtreeValue rtreeValueDown(sqlite3_value *v){
3123   double d = sqlite3_value_double(v);
3124   float f = (float)d;
3125   if( f>d ){
3126     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
3127   }
3128   return f;
3129 }
3130 static RtreeValue rtreeValueUp(sqlite3_value *v){
3131   double d = sqlite3_value_double(v);
3132   float f = (float)d;
3133   if( f<d ){
3134     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
3135   }
3136   return f;
3137 }
3138 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
3139 
3140 /*
3141 ** A constraint has failed while inserting a row into an rtree table.
3142 ** Assuming no OOM error occurs, this function sets the error message
3143 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
3144 ** SQLITE_CONSTRAINT.
3145 **
3146 ** Parameter iCol is the index of the leftmost column involved in the
3147 ** constraint failure. If it is 0, then the constraint that failed is
3148 ** the unique constraint on the id column. Otherwise, it is the rtree
3149 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
3150 **
3151 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
3152 */
3153 static int rtreeConstraintError(Rtree *pRtree, int iCol){
3154   sqlite3_stmt *pStmt = 0;
3155   char *zSql;
3156   int rc;
3157 
3158   assert( iCol==0 || iCol%2 );
3159   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
3160   if( zSql ){
3161     rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
3162   }else{
3163     rc = SQLITE_NOMEM;
3164   }
3165   sqlite3_free(zSql);
3166 
3167   if( rc==SQLITE_OK ){
3168     if( iCol==0 ){
3169       const char *zCol = sqlite3_column_name(pStmt, 0);
3170       pRtree->base.zErrMsg = sqlite3_mprintf(
3171           "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
3172       );
3173     }else{
3174       const char *zCol1 = sqlite3_column_name(pStmt, iCol);
3175       const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
3176       pRtree->base.zErrMsg = sqlite3_mprintf(
3177           "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
3178       );
3179     }
3180   }
3181 
3182   sqlite3_finalize(pStmt);
3183   return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
3184 }
3185 
3186 
3187 
3188 /*
3189 ** The xUpdate method for rtree module virtual tables.
3190 */
3191 static int rtreeUpdate(
3192   sqlite3_vtab *pVtab,
3193   int nData,
3194   sqlite3_value **aData,
3195   sqlite_int64 *pRowid
3196 ){
3197   Rtree *pRtree = (Rtree *)pVtab;
3198   int rc = SQLITE_OK;
3199   RtreeCell cell;                 /* New cell to insert if nData>1 */
3200   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
3201 
3202   if( pRtree->nNodeRef ){
3203     /* Unable to write to the btree while another cursor is reading from it,
3204     ** since the write might do a rebalance which would disrupt the read
3205     ** cursor. */
3206     return SQLITE_LOCKED_VTAB;
3207   }
3208   rtreeReference(pRtree);
3209   assert(nData>=1);
3210 
3211   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
3212 
3213   /* Constraint handling. A write operation on an r-tree table may return
3214   ** SQLITE_CONSTRAINT for two reasons:
3215   **
3216   **   1. A duplicate rowid value, or
3217   **   2. The supplied data violates the "x2>=x1" constraint.
3218   **
3219   ** In the first case, if the conflict-handling mode is REPLACE, then
3220   ** the conflicting row can be removed before proceeding. In the second
3221   ** case, SQLITE_CONSTRAINT must be returned regardless of the
3222   ** conflict-handling mode specified by the user.
3223   */
3224   if( nData>1 ){
3225     int ii;
3226     int nn = nData - 4;
3227 
3228     if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
3229     /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
3230     **
3231     ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
3232     ** with "column" that are interpreted as table constraints.
3233     ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
3234     ** This problem was discovered after years of use, so we silently ignore
3235     ** these kinds of misdeclared tables to avoid breaking any legacy.
3236     */
3237 
3238 #ifndef SQLITE_RTREE_INT_ONLY
3239     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
3240       for(ii=0; ii<nn; ii+=2){
3241         cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
3242         cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
3243         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
3244           rc = rtreeConstraintError(pRtree, ii+1);
3245           goto constraint;
3246         }
3247       }
3248     }else
3249 #endif
3250     {
3251       for(ii=0; ii<nn; ii+=2){
3252         cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
3253         cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
3254         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
3255           rc = rtreeConstraintError(pRtree, ii+1);
3256           goto constraint;
3257         }
3258       }
3259     }
3260 
3261     /* If a rowid value was supplied, check if it is already present in
3262     ** the table. If so, the constraint has failed. */
3263     if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
3264       cell.iRowid = sqlite3_value_int64(aData[2]);
3265       if( sqlite3_value_type(aData[0])==SQLITE_NULL
3266        || sqlite3_value_int64(aData[0])!=cell.iRowid
3267       ){
3268         int steprc;
3269         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
3270         steprc = sqlite3_step(pRtree->pReadRowid);
3271         rc = sqlite3_reset(pRtree->pReadRowid);
3272         if( SQLITE_ROW==steprc ){
3273           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
3274             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
3275           }else{
3276             rc = rtreeConstraintError(pRtree, 0);
3277             goto constraint;
3278           }
3279         }
3280       }
3281       bHaveRowid = 1;
3282     }
3283   }
3284 
3285   /* If aData[0] is not an SQL NULL value, it is the rowid of a
3286   ** record to delete from the r-tree table. The following block does
3287   ** just that.
3288   */
3289   if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
3290     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
3291   }
3292 
3293   /* If the aData[] array contains more than one element, elements
3294   ** (aData[2]..aData[argc-1]) contain a new record to insert into
3295   ** the r-tree structure.
3296   */
3297   if( rc==SQLITE_OK && nData>1 ){
3298     /* Insert the new record into the r-tree */
3299     RtreeNode *pLeaf = 0;
3300 
3301     /* Figure out the rowid of the new row. */
3302     if( bHaveRowid==0 ){
3303       rc = rtreeNewRowid(pRtree, &cell.iRowid);
3304     }
3305     *pRowid = cell.iRowid;
3306 
3307     if( rc==SQLITE_OK ){
3308       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
3309     }
3310     if( rc==SQLITE_OK ){
3311       int rc2;
3312       pRtree->iReinsertHeight = -1;
3313       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
3314       rc2 = nodeRelease(pRtree, pLeaf);
3315       if( rc==SQLITE_OK ){
3316         rc = rc2;
3317       }
3318     }
3319     if( rc==SQLITE_OK && pRtree->nAux ){
3320       sqlite3_stmt *pUp = pRtree->pWriteAux;
3321       int jj;
3322       sqlite3_bind_int64(pUp, 1, *pRowid);
3323       for(jj=0; jj<pRtree->nAux; jj++){
3324         sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
3325       }
3326       sqlite3_step(pUp);
3327       rc = sqlite3_reset(pUp);
3328     }
3329   }
3330 
3331 constraint:
3332   rtreeRelease(pRtree);
3333   return rc;
3334 }
3335 
3336 /*
3337 ** Called when a transaction starts.
3338 */
3339 static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
3340   Rtree *pRtree = (Rtree *)pVtab;
3341   assert( pRtree->inWrTrans==0 );
3342   pRtree->inWrTrans++;
3343   return SQLITE_OK;
3344 }
3345 
3346 /*
3347 ** Called when a transaction completes (either by COMMIT or ROLLBACK).
3348 ** The sqlite3_blob object should be released at this point.
3349 */
3350 static int rtreeEndTransaction(sqlite3_vtab *pVtab){
3351   Rtree *pRtree = (Rtree *)pVtab;
3352   pRtree->inWrTrans = 0;
3353   nodeBlobReset(pRtree);
3354   return SQLITE_OK;
3355 }
3356 
3357 /*
3358 ** The xRename method for rtree module virtual tables.
3359 */
3360 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
3361   Rtree *pRtree = (Rtree *)pVtab;
3362   int rc = SQLITE_NOMEM;
3363   char *zSql = sqlite3_mprintf(
3364     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
3365     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
3366     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
3367     , pRtree->zDb, pRtree->zName, zNewName
3368     , pRtree->zDb, pRtree->zName, zNewName
3369     , pRtree->zDb, pRtree->zName, zNewName
3370   );
3371   if( zSql ){
3372     nodeBlobReset(pRtree);
3373     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
3374     sqlite3_free(zSql);
3375   }
3376   return rc;
3377 }
3378 
3379 /*
3380 ** The xSavepoint method.
3381 **
3382 ** This module does not need to do anything to support savepoints. However,
3383 ** it uses this hook to close any open blob handle. This is done because a
3384 ** DROP TABLE command - which fortunately always opens a savepoint - cannot
3385 ** succeed if there are any open blob handles. i.e. if the blob handle were
3386 ** not closed here, the following would fail:
3387 **
3388 **   BEGIN;
3389 **     INSERT INTO rtree...
3390 **     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
3391 **   COMMIT;
3392 */
3393 static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
3394   Rtree *pRtree = (Rtree *)pVtab;
3395   u8 iwt = pRtree->inWrTrans;
3396   UNUSED_PARAMETER(iSavepoint);
3397   pRtree->inWrTrans = 0;
3398   nodeBlobReset(pRtree);
3399   pRtree->inWrTrans = iwt;
3400   return SQLITE_OK;
3401 }
3402 
3403 /*
3404 ** This function populates the pRtree->nRowEst variable with an estimate
3405 ** of the number of rows in the virtual table. If possible, this is based
3406 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
3407 */
3408 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
3409   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
3410   char *zSql;
3411   sqlite3_stmt *p;
3412   int rc;
3413   i64 nRow = RTREE_MIN_ROWEST;
3414 
3415   rc = sqlite3_table_column_metadata(
3416       db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
3417   );
3418   if( rc!=SQLITE_OK ){
3419     pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
3420     return rc==SQLITE_ERROR ? SQLITE_OK : rc;
3421   }
3422   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
3423   if( zSql==0 ){
3424     rc = SQLITE_NOMEM;
3425   }else{
3426     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
3427     if( rc==SQLITE_OK ){
3428       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
3429       rc = sqlite3_finalize(p);
3430     }
3431     sqlite3_free(zSql);
3432   }
3433   pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
3434   return rc;
3435 }
3436 
3437 
3438 /*
3439 ** Return true if zName is the extension on one of the shadow tables used
3440 ** by this module.
3441 */
3442 static int rtreeShadowName(const char *zName){
3443   static const char *azName[] = {
3444     "node", "parent", "rowid"
3445   };
3446   unsigned int i;
3447   for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
3448     if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
3449   }
3450   return 0;
3451 }
3452 
3453 static sqlite3_module rtreeModule = {
3454   3,                          /* iVersion */
3455   rtreeCreate,                /* xCreate - create a table */
3456   rtreeConnect,               /* xConnect - connect to an existing table */
3457   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
3458   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
3459   rtreeDestroy,               /* xDestroy - Drop a table */
3460   rtreeOpen,                  /* xOpen - open a cursor */
3461   rtreeClose,                 /* xClose - close a cursor */
3462   rtreeFilter,                /* xFilter - configure scan constraints */
3463   rtreeNext,                  /* xNext - advance a cursor */
3464   rtreeEof,                   /* xEof */
3465   rtreeColumn,                /* xColumn - read data */
3466   rtreeRowid,                 /* xRowid - read data */
3467   rtreeUpdate,                /* xUpdate - write data */
3468   rtreeBeginTransaction,      /* xBegin - begin transaction */
3469   rtreeEndTransaction,        /* xSync - sync transaction */
3470   rtreeEndTransaction,        /* xCommit - commit transaction */
3471   rtreeEndTransaction,        /* xRollback - rollback transaction */
3472   0,                          /* xFindFunction - function overloading */
3473   rtreeRename,                /* xRename - rename the table */
3474   rtreeSavepoint,             /* xSavepoint */
3475   0,                          /* xRelease */
3476   0,                          /* xRollbackTo */
3477   rtreeShadowName             /* xShadowName */
3478 };
3479 
3480 static int rtreeSqlInit(
3481   Rtree *pRtree,
3482   sqlite3 *db,
3483   const char *zDb,
3484   const char *zPrefix,
3485   int isCreate
3486 ){
3487   int rc = SQLITE_OK;
3488 
3489   #define N_STATEMENT 8
3490   static const char *azSql[N_STATEMENT] = {
3491     /* Write the xxx_node table */
3492     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
3493     "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
3494 
3495     /* Read and write the xxx_rowid table */
3496     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3497     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
3498     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3499 
3500     /* Read and write the xxx_parent table */
3501     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
3502     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
3503     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
3504   };
3505   sqlite3_stmt **appStmt[N_STATEMENT];
3506   int i;
3507   const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
3508 
3509   pRtree->db = db;
3510 
3511   if( isCreate ){
3512     char *zCreate;
3513     sqlite3_str *p = sqlite3_str_new(db);
3514     int ii;
3515     sqlite3_str_appendf(p,
3516        "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
3517        zDb, zPrefix);
3518     for(ii=0; ii<pRtree->nAux; ii++){
3519       sqlite3_str_appendf(p,",a%d",ii);
3520     }
3521     sqlite3_str_appendf(p,
3522       ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
3523       zDb, zPrefix);
3524     sqlite3_str_appendf(p,
3525     "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
3526       zDb, zPrefix);
3527     sqlite3_str_appendf(p,
3528        "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
3529        zDb, zPrefix, pRtree->iNodeSize);
3530     zCreate = sqlite3_str_finish(p);
3531     if( !zCreate ){
3532       return SQLITE_NOMEM;
3533     }
3534     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
3535     sqlite3_free(zCreate);
3536     if( rc!=SQLITE_OK ){
3537       return rc;
3538     }
3539   }
3540 
3541   appStmt[0] = &pRtree->pWriteNode;
3542   appStmt[1] = &pRtree->pDeleteNode;
3543   appStmt[2] = &pRtree->pReadRowid;
3544   appStmt[3] = &pRtree->pWriteRowid;
3545   appStmt[4] = &pRtree->pDeleteRowid;
3546   appStmt[5] = &pRtree->pReadParent;
3547   appStmt[6] = &pRtree->pWriteParent;
3548   appStmt[7] = &pRtree->pDeleteParent;
3549 
3550   rc = rtreeQueryStat1(db, pRtree);
3551   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
3552     char *zSql;
3553     const char *zFormat;
3554     if( i!=3 || pRtree->nAux==0 ){
3555        zFormat = azSql[i];
3556     }else {
3557        /* An UPSERT is very slightly slower than REPLACE, but it is needed
3558        ** if there are auxiliary columns */
3559        zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
3560                   "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
3561     }
3562     zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
3563     if( zSql ){
3564       rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
3565     }else{
3566       rc = SQLITE_NOMEM;
3567     }
3568     sqlite3_free(zSql);
3569   }
3570   if( pRtree->nAux ){
3571     pRtree->zReadAuxSql = sqlite3_mprintf(
3572        "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
3573        zDb, zPrefix);
3574     if( pRtree->zReadAuxSql==0 ){
3575       rc = SQLITE_NOMEM;
3576     }else{
3577       sqlite3_str *p = sqlite3_str_new(db);
3578       int ii;
3579       char *zSql;
3580       sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
3581       for(ii=0; ii<pRtree->nAux; ii++){
3582         if( ii ) sqlite3_str_append(p, ",", 1);
3583         if( ii<pRtree->nAuxNotNull ){
3584           sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
3585         }else{
3586           sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
3587         }
3588       }
3589       sqlite3_str_appendf(p, " WHERE rowid=?1");
3590       zSql = sqlite3_str_finish(p);
3591       if( zSql==0 ){
3592         rc = SQLITE_NOMEM;
3593       }else{
3594         rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
3595         sqlite3_free(zSql);
3596       }
3597     }
3598   }
3599 
3600   return rc;
3601 }
3602 
3603 /*
3604 ** The second argument to this function contains the text of an SQL statement
3605 ** that returns a single integer value. The statement is compiled and executed
3606 ** using database connection db. If successful, the integer value returned
3607 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
3608 ** code is returned and the value of *piVal after returning is not defined.
3609 */
3610 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
3611   int rc = SQLITE_NOMEM;
3612   if( zSql ){
3613     sqlite3_stmt *pStmt = 0;
3614     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3615     if( rc==SQLITE_OK ){
3616       if( SQLITE_ROW==sqlite3_step(pStmt) ){
3617         *piVal = sqlite3_column_int(pStmt, 0);
3618       }
3619       rc = sqlite3_finalize(pStmt);
3620     }
3621   }
3622   return rc;
3623 }
3624 
3625 /*
3626 ** This function is called from within the xConnect() or xCreate() method to
3627 ** determine the node-size used by the rtree table being created or connected
3628 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
3629 ** Otherwise, an SQLite error code is returned.
3630 **
3631 ** If this function is being called as part of an xConnect(), then the rtree
3632 ** table already exists. In this case the node-size is determined by inspecting
3633 ** the root node of the tree.
3634 **
3635 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
3636 ** This ensures that each node is stored on a single database page. If the
3637 ** database page-size is so large that more than RTREE_MAXCELLS entries
3638 ** would fit in a single node, use a smaller node-size.
3639 */
3640 static int getNodeSize(
3641   sqlite3 *db,                    /* Database handle */
3642   Rtree *pRtree,                  /* Rtree handle */
3643   int isCreate,                   /* True for xCreate, false for xConnect */
3644   char **pzErr                    /* OUT: Error message, if any */
3645 ){
3646   int rc;
3647   char *zSql;
3648   if( isCreate ){
3649     int iPageSize = 0;
3650     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
3651     rc = getIntFromStmt(db, zSql, &iPageSize);
3652     if( rc==SQLITE_OK ){
3653       pRtree->iNodeSize = iPageSize-64;
3654       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
3655         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
3656       }
3657     }else{
3658       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3659     }
3660   }else{
3661     zSql = sqlite3_mprintf(
3662         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
3663         pRtree->zDb, pRtree->zName
3664     );
3665     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
3666     if( rc!=SQLITE_OK ){
3667       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3668     }else if( pRtree->iNodeSize<(512-64) ){
3669       rc = SQLITE_CORRUPT_VTAB;
3670       RTREE_IS_CORRUPT(pRtree);
3671       *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
3672                                pRtree->zName);
3673     }
3674   }
3675 
3676   sqlite3_free(zSql);
3677   return rc;
3678 }
3679 
3680 /*
3681 ** Return the length of a token
3682 */
3683 static int rtreeTokenLength(const char *z){
3684   int dummy = 0;
3685   return sqlite3GetToken((const unsigned char*)z,&dummy);
3686 }
3687 
3688 /*
3689 ** This function is the implementation of both the xConnect and xCreate
3690 ** methods of the r-tree virtual table.
3691 **
3692 **   argv[0]   -> module name
3693 **   argv[1]   -> database name
3694 **   argv[2]   -> table name
3695 **   argv[...] -> column names...
3696 */
3697 static int rtreeInit(
3698   sqlite3 *db,                        /* Database connection */
3699   void *pAux,                         /* One of the RTREE_COORD_* constants */
3700   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
3701   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
3702   char **pzErr,                       /* OUT: Error message, if any */
3703   int isCreate                        /* True for xCreate, false for xConnect */
3704 ){
3705   int rc = SQLITE_OK;
3706   Rtree *pRtree;
3707   int nDb;              /* Length of string argv[1] */
3708   int nName;            /* Length of string argv[2] */
3709   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
3710   sqlite3_str *pSql;
3711   char *zSql;
3712   int ii = 4;
3713   int iErr;
3714 
3715   const char *aErrMsg[] = {
3716     0,                                                    /* 0 */
3717     "Wrong number of columns for an rtree table",         /* 1 */
3718     "Too few columns for an rtree table",                 /* 2 */
3719     "Too many columns for an rtree table",                /* 3 */
3720     "Auxiliary rtree columns must be last"                /* 4 */
3721   };
3722 
3723   assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
3724   if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
3725     *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
3726     return SQLITE_ERROR;
3727   }
3728 
3729   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
3730 
3731   /* Allocate the sqlite3_vtab structure */
3732   nDb = (int)strlen(argv[1]);
3733   nName = (int)strlen(argv[2]);
3734   pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
3735   if( !pRtree ){
3736     return SQLITE_NOMEM;
3737   }
3738   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
3739   pRtree->nBusy = 1;
3740   pRtree->base.pModule = &rtreeModule;
3741   pRtree->zDb = (char *)&pRtree[1];
3742   pRtree->zName = &pRtree->zDb[nDb+1];
3743   pRtree->eCoordType = (u8)eCoordType;
3744   memcpy(pRtree->zDb, argv[1], nDb);
3745   memcpy(pRtree->zName, argv[2], nName);
3746 
3747 
3748   /* Create/Connect to the underlying relational database schema. If
3749   ** that is successful, call sqlite3_declare_vtab() to configure
3750   ** the r-tree table schema.
3751   */
3752   pSql = sqlite3_str_new(db);
3753   sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
3754                       rtreeTokenLength(argv[3]), argv[3]);
3755   for(ii=4; ii<argc; ii++){
3756     const char *zArg = argv[ii];
3757     if( zArg[0]=='+' ){
3758       pRtree->nAux++;
3759       sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
3760     }else if( pRtree->nAux>0 ){
3761       break;
3762     }else{
3763       static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
3764       pRtree->nDim2++;
3765       sqlite3_str_appendf(pSql, azFormat[eCoordType],
3766                           rtreeTokenLength(zArg), zArg);
3767     }
3768   }
3769   sqlite3_str_appendf(pSql, ");");
3770   zSql = sqlite3_str_finish(pSql);
3771   if( !zSql ){
3772     rc = SQLITE_NOMEM;
3773   }else if( ii<argc ){
3774     *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
3775     rc = SQLITE_ERROR;
3776   }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3777     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3778   }
3779   sqlite3_free(zSql);
3780   if( rc ) goto rtreeInit_fail;
3781   pRtree->nDim = pRtree->nDim2/2;
3782   if( pRtree->nDim<1 ){
3783     iErr = 2;
3784   }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
3785     iErr = 3;
3786   }else if( pRtree->nDim2 % 2 ){
3787     iErr = 1;
3788   }else{
3789     iErr = 0;
3790   }
3791   if( iErr ){
3792     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3793     goto rtreeInit_fail;
3794   }
3795   pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
3796 
3797   /* Figure out the node size to use. */
3798   rc = getNodeSize(db, pRtree, isCreate, pzErr);
3799   if( rc ) goto rtreeInit_fail;
3800   rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
3801   if( rc ){
3802     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3803     goto rtreeInit_fail;
3804   }
3805 
3806   *ppVtab = (sqlite3_vtab *)pRtree;
3807   return SQLITE_OK;
3808 
3809 rtreeInit_fail:
3810   if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
3811   assert( *ppVtab==0 );
3812   assert( pRtree->nBusy==1 );
3813   rtreeRelease(pRtree);
3814   return rc;
3815 }
3816 
3817 
3818 /*
3819 ** Implementation of a scalar function that decodes r-tree nodes to
3820 ** human readable strings. This can be used for debugging and analysis.
3821 **
3822 ** The scalar function takes two arguments: (1) the number of dimensions
3823 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
3824 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
3825 ** deserialize all nodes, a statement like:
3826 **
3827 **   SELECT rtreenode(2, data) FROM rt_node;
3828 **
3829 ** The human readable string takes the form of a Tcl list with one
3830 ** entry for each cell in the r-tree node. Each entry is itself a
3831 ** list, containing the 8-byte rowid/pageno followed by the
3832 ** <num-dimension>*2 coordinates.
3833 */
3834 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3835   RtreeNode node;
3836   Rtree tree;
3837   int ii;
3838   int nData;
3839   int errCode;
3840   sqlite3_str *pOut;
3841 
3842   UNUSED_PARAMETER(nArg);
3843   memset(&node, 0, sizeof(RtreeNode));
3844   memset(&tree, 0, sizeof(Rtree));
3845   tree.nDim = (u8)sqlite3_value_int(apArg[0]);
3846   if( tree.nDim<1 || tree.nDim>5 ) return;
3847   tree.nDim2 = tree.nDim*2;
3848   tree.nBytesPerCell = 8 + 8 * tree.nDim;
3849   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3850   nData = sqlite3_value_bytes(apArg[1]);
3851   if( nData<4 ) return;
3852   if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
3853 
3854   pOut = sqlite3_str_new(0);
3855   for(ii=0; ii<NCELL(&node); ii++){
3856     RtreeCell cell;
3857     int jj;
3858 
3859     nodeGetCell(&tree, &node, ii, &cell);
3860     if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
3861     sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
3862     for(jj=0; jj<tree.nDim2; jj++){
3863 #ifndef SQLITE_RTREE_INT_ONLY
3864       sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
3865 #else
3866       sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
3867 #endif
3868     }
3869     sqlite3_str_append(pOut, "}", 1);
3870   }
3871   errCode = sqlite3_str_errcode(pOut);
3872   sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
3873   sqlite3_result_error_code(ctx, errCode);
3874 }
3875 
3876 /* This routine implements an SQL function that returns the "depth" parameter
3877 ** from the front of a blob that is an r-tree node.  For example:
3878 **
3879 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
3880 **
3881 ** The depth value is 0 for all nodes other than the root node, and the root
3882 ** node always has nodeno=1, so the example above is the primary use for this
3883 ** routine.  This routine is intended for testing and analysis only.
3884 */
3885 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3886   UNUSED_PARAMETER(nArg);
3887   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3888    || sqlite3_value_bytes(apArg[0])<2
3889 
3890   ){
3891     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3892   }else{
3893     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3894     if( zBlob ){
3895       sqlite3_result_int(ctx, readInt16(zBlob));
3896     }else{
3897       sqlite3_result_error_nomem(ctx);
3898     }
3899   }
3900 }
3901 
3902 /*
3903 ** Context object passed between the various routines that make up the
3904 ** implementation of integrity-check function rtreecheck().
3905 */
3906 typedef struct RtreeCheck RtreeCheck;
3907 struct RtreeCheck {
3908   sqlite3 *db;                    /* Database handle */
3909   const char *zDb;                /* Database containing rtree table */
3910   const char *zTab;               /* Name of rtree table */
3911   int bInt;                       /* True for rtree_i32 table */
3912   int nDim;                       /* Number of dimensions for this rtree tbl */
3913   sqlite3_stmt *pGetNode;         /* Statement used to retrieve nodes */
3914   sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
3915   int nLeaf;                      /* Number of leaf cells in table */
3916   int nNonLeaf;                   /* Number of non-leaf cells in table */
3917   int rc;                         /* Return code */
3918   char *zReport;                  /* Message to report */
3919   int nErr;                       /* Number of lines in zReport */
3920 };
3921 
3922 #define RTREE_CHECK_MAX_ERROR 100
3923 
3924 /*
3925 ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
3926 ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
3927 */
3928 static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
3929   int rc = sqlite3_reset(pStmt);
3930   if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
3931 }
3932 
3933 /*
3934 ** The second and subsequent arguments to this function are a format string
3935 ** and printf style arguments. This function formats the string and attempts
3936 ** to compile it as an SQL statement.
3937 **
3938 ** If successful, a pointer to the new SQL statement is returned. Otherwise,
3939 ** NULL is returned and an error code left in RtreeCheck.rc.
3940 */
3941 static sqlite3_stmt *rtreeCheckPrepare(
3942   RtreeCheck *pCheck,             /* RtreeCheck object */
3943   const char *zFmt, ...           /* Format string and trailing args */
3944 ){
3945   va_list ap;
3946   char *z;
3947   sqlite3_stmt *pRet = 0;
3948 
3949   va_start(ap, zFmt);
3950   z = sqlite3_vmprintf(zFmt, ap);
3951 
3952   if( pCheck->rc==SQLITE_OK ){
3953     if( z==0 ){
3954       pCheck->rc = SQLITE_NOMEM;
3955     }else{
3956       pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
3957     }
3958   }
3959 
3960   sqlite3_free(z);
3961   va_end(ap);
3962   return pRet;
3963 }
3964 
3965 /*
3966 ** The second and subsequent arguments to this function are a printf()
3967 ** style format string and arguments. This function formats the string and
3968 ** appends it to the report being accumuated in pCheck.
3969 */
3970 static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
3971   va_list ap;
3972   va_start(ap, zFmt);
3973   if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
3974     char *z = sqlite3_vmprintf(zFmt, ap);
3975     if( z==0 ){
3976       pCheck->rc = SQLITE_NOMEM;
3977     }else{
3978       pCheck->zReport = sqlite3_mprintf("%z%s%z",
3979           pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
3980       );
3981       if( pCheck->zReport==0 ){
3982         pCheck->rc = SQLITE_NOMEM;
3983       }
3984     }
3985     pCheck->nErr++;
3986   }
3987   va_end(ap);
3988 }
3989 
3990 /*
3991 ** This function is a no-op if there is already an error code stored
3992 ** in the RtreeCheck object indicated by the first argument. NULL is
3993 ** returned in this case.
3994 **
3995 ** Otherwise, the contents of rtree table node iNode are loaded from
3996 ** the database and copied into a buffer obtained from sqlite3_malloc().
3997 ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
3998 ** is set to the size of the buffer in bytes.
3999 **
4000 ** Or, if an error does occur, NULL is returned and an error code left
4001 ** in the RtreeCheck object. The final value of *pnNode is undefined in
4002 ** this case.
4003 */
4004 static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
4005   u8 *pRet = 0;                   /* Return value */
4006 
4007   if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
4008     pCheck->pGetNode = rtreeCheckPrepare(pCheck,
4009         "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
4010         pCheck->zDb, pCheck->zTab
4011     );
4012   }
4013 
4014   if( pCheck->rc==SQLITE_OK ){
4015     sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
4016     if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
4017       int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
4018       const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
4019       pRet = sqlite3_malloc64(nNode);
4020       if( pRet==0 ){
4021         pCheck->rc = SQLITE_NOMEM;
4022       }else{
4023         memcpy(pRet, pNode, nNode);
4024         *pnNode = nNode;
4025       }
4026     }
4027     rtreeCheckReset(pCheck, pCheck->pGetNode);
4028     if( pCheck->rc==SQLITE_OK && pRet==0 ){
4029       rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
4030     }
4031   }
4032 
4033   return pRet;
4034 }
4035 
4036 /*
4037 ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
4038 ** (if bLeaf==1) table contains a specified entry. The schemas of the
4039 ** two tables are:
4040 **
4041 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
4042 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
4043 **
4044 ** In both cases, this function checks that there exists an entry with
4045 ** IPK value iKey and the second column set to iVal.
4046 **
4047 */
4048 static void rtreeCheckMapping(
4049   RtreeCheck *pCheck,             /* RtreeCheck object */
4050   int bLeaf,                      /* True for a leaf cell, false for interior */
4051   i64 iKey,                       /* Key for mapping */
4052   i64 iVal                        /* Expected value for mapping */
4053 ){
4054   int rc;
4055   sqlite3_stmt *pStmt;
4056   const char *azSql[2] = {
4057     "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
4058     "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
4059   };
4060 
4061   assert( bLeaf==0 || bLeaf==1 );
4062   if( pCheck->aCheckMapping[bLeaf]==0 ){
4063     pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
4064         azSql[bLeaf], pCheck->zDb, pCheck->zTab
4065     );
4066   }
4067   if( pCheck->rc!=SQLITE_OK ) return;
4068 
4069   pStmt = pCheck->aCheckMapping[bLeaf];
4070   sqlite3_bind_int64(pStmt, 1, iKey);
4071   rc = sqlite3_step(pStmt);
4072   if( rc==SQLITE_DONE ){
4073     rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
4074         iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
4075     );
4076   }else if( rc==SQLITE_ROW ){
4077     i64 ii = sqlite3_column_int64(pStmt, 0);
4078     if( ii!=iVal ){
4079       rtreeCheckAppendMsg(pCheck,
4080           "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
4081           iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
4082       );
4083     }
4084   }
4085   rtreeCheckReset(pCheck, pStmt);
4086 }
4087 
4088 /*
4089 ** Argument pCell points to an array of coordinates stored on an rtree page.
4090 ** This function checks that the coordinates are internally consistent (no
4091 ** x1>x2 conditions) and adds an error message to the RtreeCheck object
4092 ** if they are not.
4093 **
4094 ** Additionally, if pParent is not NULL, then it is assumed to point to
4095 ** the array of coordinates on the parent page that bound the page
4096 ** containing pCell. In this case it is also verified that the two
4097 ** sets of coordinates are mutually consistent and an error message added
4098 ** to the RtreeCheck object if they are not.
4099 */
4100 static void rtreeCheckCellCoord(
4101   RtreeCheck *pCheck,
4102   i64 iNode,                      /* Node id to use in error messages */
4103   int iCell,                      /* Cell number to use in error messages */
4104   u8 *pCell,                      /* Pointer to cell coordinates */
4105   u8 *pParent                     /* Pointer to parent coordinates */
4106 ){
4107   RtreeCoord c1, c2;
4108   RtreeCoord p1, p2;
4109   int i;
4110 
4111   for(i=0; i<pCheck->nDim; i++){
4112     readCoord(&pCell[4*2*i], &c1);
4113     readCoord(&pCell[4*(2*i + 1)], &c2);
4114 
4115     /* printf("%e, %e\n", c1.u.f, c2.u.f); */
4116     if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
4117       rtreeCheckAppendMsg(pCheck,
4118           "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
4119       );
4120     }
4121 
4122     if( pParent ){
4123       readCoord(&pParent[4*2*i], &p1);
4124       readCoord(&pParent[4*(2*i + 1)], &p2);
4125 
4126       if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
4127        || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
4128       ){
4129         rtreeCheckAppendMsg(pCheck,
4130             "Dimension %d of cell %d on node %lld is corrupt relative to parent"
4131             , i, iCell, iNode
4132         );
4133       }
4134     }
4135   }
4136 }
4137 
4138 /*
4139 ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
4140 ** the r-tree structure. Argument aParent points to the array of coordinates
4141 ** that bound node iNode on the parent node.
4142 **
4143 ** If any problems are discovered, an error message is appended to the
4144 ** report accumulated in the RtreeCheck object.
4145 */
4146 static void rtreeCheckNode(
4147   RtreeCheck *pCheck,
4148   int iDepth,                     /* Depth of iNode (0==leaf) */
4149   u8 *aParent,                    /* Buffer containing parent coords */
4150   i64 iNode                       /* Node to check */
4151 ){
4152   u8 *aNode = 0;
4153   int nNode = 0;
4154 
4155   assert( iNode==1 || aParent!=0 );
4156   assert( pCheck->nDim>0 );
4157 
4158   aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
4159   if( aNode ){
4160     if( nNode<4 ){
4161       rtreeCheckAppendMsg(pCheck,
4162           "Node %lld is too small (%d bytes)", iNode, nNode
4163       );
4164     }else{
4165       int nCell;                  /* Number of cells on page */
4166       int i;                      /* Used to iterate through cells */
4167       if( aParent==0 ){
4168         iDepth = readInt16(aNode);
4169         if( iDepth>RTREE_MAX_DEPTH ){
4170           rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
4171           sqlite3_free(aNode);
4172           return;
4173         }
4174       }
4175       nCell = readInt16(&aNode[2]);
4176       if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
4177         rtreeCheckAppendMsg(pCheck,
4178             "Node %lld is too small for cell count of %d (%d bytes)",
4179             iNode, nCell, nNode
4180         );
4181       }else{
4182         for(i=0; i<nCell; i++){
4183           u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
4184           i64 iVal = readInt64(pCell);
4185           rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
4186 
4187           if( iDepth>0 ){
4188             rtreeCheckMapping(pCheck, 0, iVal, iNode);
4189             rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
4190             pCheck->nNonLeaf++;
4191           }else{
4192             rtreeCheckMapping(pCheck, 1, iVal, iNode);
4193             pCheck->nLeaf++;
4194           }
4195         }
4196       }
4197     }
4198     sqlite3_free(aNode);
4199   }
4200 }
4201 
4202 /*
4203 ** The second argument to this function must be either "_rowid" or
4204 ** "_parent". This function checks that the number of entries in the
4205 ** %_rowid or %_parent table is exactly nExpect. If not, it adds
4206 ** an error message to the report in the RtreeCheck object indicated
4207 ** by the first argument.
4208 */
4209 static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
4210   if( pCheck->rc==SQLITE_OK ){
4211     sqlite3_stmt *pCount;
4212     pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
4213         pCheck->zDb, pCheck->zTab, zTbl
4214     );
4215     if( pCount ){
4216       if( sqlite3_step(pCount)==SQLITE_ROW ){
4217         i64 nActual = sqlite3_column_int64(pCount, 0);
4218         if( nActual!=nExpect ){
4219           rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
4220               " - expected %lld, actual %lld" , zTbl, nExpect, nActual
4221           );
4222         }
4223       }
4224       pCheck->rc = sqlite3_finalize(pCount);
4225     }
4226   }
4227 }
4228 
4229 /*
4230 ** This function does the bulk of the work for the rtree integrity-check.
4231 ** It is called by rtreecheck(), which is the SQL function implementation.
4232 */
4233 static int rtreeCheckTable(
4234   sqlite3 *db,                    /* Database handle to access db through */
4235   const char *zDb,                /* Name of db ("main", "temp" etc.) */
4236   const char *zTab,               /* Name of rtree table to check */
4237   char **pzReport                 /* OUT: sqlite3_malloc'd report text */
4238 ){
4239   RtreeCheck check;               /* Common context for various routines */
4240   sqlite3_stmt *pStmt = 0;        /* Used to find column count of rtree table */
4241   int bEnd = 0;                   /* True if transaction should be closed */
4242   int nAux = 0;                   /* Number of extra columns. */
4243 
4244   /* Initialize the context object */
4245   memset(&check, 0, sizeof(check));
4246   check.db = db;
4247   check.zDb = zDb;
4248   check.zTab = zTab;
4249 
4250   /* If there is not already an open transaction, open one now. This is
4251   ** to ensure that the queries run as part of this integrity-check operate
4252   ** on a consistent snapshot.  */
4253   if( sqlite3_get_autocommit(db) ){
4254     check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
4255     bEnd = 1;
4256   }
4257 
4258   /* Find the number of auxiliary columns */
4259   if( check.rc==SQLITE_OK ){
4260     pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
4261     if( pStmt ){
4262       nAux = sqlite3_column_count(pStmt) - 2;
4263       sqlite3_finalize(pStmt);
4264     }else
4265     if( check.rc!=SQLITE_NOMEM ){
4266       check.rc = SQLITE_OK;
4267     }
4268   }
4269 
4270   /* Find number of dimensions in the rtree table. */
4271   pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
4272   if( pStmt ){
4273     int rc;
4274     check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
4275     if( check.nDim<1 ){
4276       rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
4277     }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
4278       check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
4279     }
4280     rc = sqlite3_finalize(pStmt);
4281     if( rc!=SQLITE_CORRUPT ) check.rc = rc;
4282   }
4283 
4284   /* Do the actual integrity-check */
4285   if( check.nDim>=1 ){
4286     if( check.rc==SQLITE_OK ){
4287       rtreeCheckNode(&check, 0, 0, 1);
4288     }
4289     rtreeCheckCount(&check, "_rowid", check.nLeaf);
4290     rtreeCheckCount(&check, "_parent", check.nNonLeaf);
4291   }
4292 
4293   /* Finalize SQL statements used by the integrity-check */
4294   sqlite3_finalize(check.pGetNode);
4295   sqlite3_finalize(check.aCheckMapping[0]);
4296   sqlite3_finalize(check.aCheckMapping[1]);
4297 
4298   /* If one was opened, close the transaction */
4299   if( bEnd ){
4300     int rc = sqlite3_exec(db, "END", 0, 0, 0);
4301     if( check.rc==SQLITE_OK ) check.rc = rc;
4302   }
4303   *pzReport = check.zReport;
4304   return check.rc;
4305 }
4306 
4307 /*
4308 ** Usage:
4309 **
4310 **   rtreecheck(<rtree-table>);
4311 **   rtreecheck(<database>, <rtree-table>);
4312 **
4313 ** Invoking this SQL function runs an integrity-check on the named rtree
4314 ** table. The integrity-check verifies the following:
4315 **
4316 **   1. For each cell in the r-tree structure (%_node table), that:
4317 **
4318 **       a) for each dimension, (coord1 <= coord2).
4319 **
4320 **       b) unless the cell is on the root node, that the cell is bounded
4321 **          by the parent cell on the parent node.
4322 **
4323 **       c) for leaf nodes, that there is an entry in the %_rowid
4324 **          table corresponding to the cell's rowid value that
4325 **          points to the correct node.
4326 **
4327 **       d) for cells on non-leaf nodes, that there is an entry in the
4328 **          %_parent table mapping from the cell's child node to the
4329 **          node that it resides on.
4330 **
4331 **   2. That there are the same number of entries in the %_rowid table
4332 **      as there are leaf cells in the r-tree structure, and that there
4333 **      is a leaf cell that corresponds to each entry in the %_rowid table.
4334 **
4335 **   3. That there are the same number of entries in the %_parent table
4336 **      as there are non-leaf cells in the r-tree structure, and that
4337 **      there is a non-leaf cell that corresponds to each entry in the
4338 **      %_parent table.
4339 */
4340 static void rtreecheck(
4341   sqlite3_context *ctx,
4342   int nArg,
4343   sqlite3_value **apArg
4344 ){
4345   if( nArg!=1 && nArg!=2 ){
4346     sqlite3_result_error(ctx,
4347         "wrong number of arguments to function rtreecheck()", -1
4348     );
4349   }else{
4350     int rc;
4351     char *zReport = 0;
4352     const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
4353     const char *zTab;
4354     if( nArg==1 ){
4355       zTab = zDb;
4356       zDb = "main";
4357     }else{
4358       zTab = (const char*)sqlite3_value_text(apArg[1]);
4359     }
4360     rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
4361     if( rc==SQLITE_OK ){
4362       sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
4363     }else{
4364       sqlite3_result_error_code(ctx, rc);
4365     }
4366     sqlite3_free(zReport);
4367   }
4368 }
4369 
4370 /* Conditionally include the geopoly code */
4371 #ifdef SQLITE_ENABLE_GEOPOLY
4372 # include "geopoly.c"
4373 #endif
4374 
4375 /*
4376 ** Register the r-tree module with database handle db. This creates the
4377 ** virtual table module "rtree" and the debugging/analysis scalar
4378 ** function "rtreenode".
4379 */
4380 int sqlite3RtreeInit(sqlite3 *db){
4381   const int utf8 = SQLITE_UTF8;
4382   int rc;
4383 
4384   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
4385   if( rc==SQLITE_OK ){
4386     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
4387   }
4388   if( rc==SQLITE_OK ){
4389     rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
4390   }
4391   if( rc==SQLITE_OK ){
4392 #ifdef SQLITE_RTREE_INT_ONLY
4393     void *c = (void *)RTREE_COORD_INT32;
4394 #else
4395     void *c = (void *)RTREE_COORD_REAL32;
4396 #endif
4397     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
4398   }
4399   if( rc==SQLITE_OK ){
4400     void *c = (void *)RTREE_COORD_INT32;
4401     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
4402   }
4403 #ifdef SQLITE_ENABLE_GEOPOLY
4404   if( rc==SQLITE_OK ){
4405     rc = sqlite3_geopoly_init(db);
4406   }
4407 #endif
4408 
4409   return rc;
4410 }
4411 
4412 /*
4413 ** This routine deletes the RtreeGeomCallback object that was attached
4414 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
4415 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
4416 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
4417 ** the corresponding SQL function is deleted.
4418 */
4419 static void rtreeFreeCallback(void *p){
4420   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
4421   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
4422   sqlite3_free(p);
4423 }
4424 
4425 /*
4426 ** This routine frees the BLOB that is returned by geomCallback().
4427 */
4428 static void rtreeMatchArgFree(void *pArg){
4429   int i;
4430   RtreeMatchArg *p = (RtreeMatchArg*)pArg;
4431   for(i=0; i<p->nParam; i++){
4432     sqlite3_value_free(p->apSqlParam[i]);
4433   }
4434   sqlite3_free(p);
4435 }
4436 
4437 /*
4438 ** Each call to sqlite3_rtree_geometry_callback() or
4439 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
4440 ** scalar function that is implemented by this routine.
4441 **
4442 ** All this function does is construct an RtreeMatchArg object that
4443 ** contains the geometry-checking callback routines and a list of
4444 ** parameters to this function, then return that RtreeMatchArg object
4445 ** as a BLOB.
4446 **
4447 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
4448 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
4449 ** out which elements of the R-Tree should be returned by the query.
4450 */
4451 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
4452   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
4453   RtreeMatchArg *pBlob;
4454   sqlite3_int64 nBlob;
4455   int memErr = 0;
4456 
4457   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
4458            + nArg*sizeof(sqlite3_value*);
4459   pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
4460   if( !pBlob ){
4461     sqlite3_result_error_nomem(ctx);
4462   }else{
4463     int i;
4464     pBlob->iSize = nBlob;
4465     pBlob->cb = pGeomCtx[0];
4466     pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
4467     pBlob->nParam = nArg;
4468     for(i=0; i<nArg; i++){
4469       pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
4470       if( pBlob->apSqlParam[i]==0 ) memErr = 1;
4471 #ifdef SQLITE_RTREE_INT_ONLY
4472       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
4473 #else
4474       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
4475 #endif
4476     }
4477     if( memErr ){
4478       sqlite3_result_error_nomem(ctx);
4479       rtreeMatchArgFree(pBlob);
4480     }else{
4481       sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
4482     }
4483   }
4484 }
4485 
4486 /*
4487 ** Register a new geometry function for use with the r-tree MATCH operator.
4488 */
4489 int sqlite3_rtree_geometry_callback(
4490   sqlite3 *db,                  /* Register SQL function on this connection */
4491   const char *zGeom,            /* Name of the new SQL function */
4492   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
4493   void *pContext                /* Extra data associated with the callback */
4494 ){
4495   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
4496 
4497   /* Allocate and populate the context object. */
4498   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4499   if( !pGeomCtx ) return SQLITE_NOMEM;
4500   pGeomCtx->xGeom = xGeom;
4501   pGeomCtx->xQueryFunc = 0;
4502   pGeomCtx->xDestructor = 0;
4503   pGeomCtx->pContext = pContext;
4504   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
4505       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4506   );
4507 }
4508 
4509 /*
4510 ** Register a new 2nd-generation geometry function for use with the
4511 ** r-tree MATCH operator.
4512 */
4513 int sqlite3_rtree_query_callback(
4514   sqlite3 *db,                 /* Register SQL function on this connection */
4515   const char *zQueryFunc,      /* Name of new SQL function */
4516   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
4517   void *pContext,              /* Extra data passed into the callback */
4518   void (*xDestructor)(void*)   /* Destructor for the extra data */
4519 ){
4520   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
4521 
4522   /* Allocate and populate the context object. */
4523   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4524   if( !pGeomCtx ) return SQLITE_NOMEM;
4525   pGeomCtx->xGeom = 0;
4526   pGeomCtx->xQueryFunc = xQueryFunc;
4527   pGeomCtx->xDestructor = xDestructor;
4528   pGeomCtx->pContext = pContext;
4529   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
4530       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4531   );
4532 }
4533 
4534 #if !SQLITE_CORE
4535 #ifdef _WIN32
4536 __declspec(dllexport)
4537 #endif
4538 int sqlite3_rtree_init(
4539   sqlite3 *db,
4540   char **pzErrMsg,
4541   const sqlite3_api_routines *pApi
4542 ){
4543   SQLITE_EXTENSION_INIT2(pApi)
4544   return sqlite3RtreeInit(db);
4545 }
4546 #endif
4547 
4548 #endif
4549