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