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