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