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