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