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