xref: /sqlite-3.40.0/ext/rtree/rtree.c (revision b43be55e)
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   pCoord->u = (
373     (((u32)p[0]) << 24) +
374     (((u32)p[1]) << 16) +
375     (((u32)p[2]) <<  8) +
376     (((u32)p[3]) <<  0)
377   );
378 }
379 static i64 readInt64(u8 *p){
380   return (
381     (((i64)p[0]) << 56) +
382     (((i64)p[1]) << 48) +
383     (((i64)p[2]) << 40) +
384     (((i64)p[3]) << 32) +
385     (((i64)p[4]) << 24) +
386     (((i64)p[5]) << 16) +
387     (((i64)p[6]) <<  8) +
388     (((i64)p[7]) <<  0)
389   );
390 }
391 
392 /*
393 ** Functions to serialize a 16 bit integer, 32 bit real number and
394 ** 64 bit integer. The value returned is the number of bytes written
395 ** to the argument buffer (always 2, 4 and 8 respectively).
396 */
397 static int writeInt16(u8 *p, int i){
398   p[0] = (i>> 8)&0xFF;
399   p[1] = (i>> 0)&0xFF;
400   return 2;
401 }
402 static int writeCoord(u8 *p, RtreeCoord *pCoord){
403   u32 i;
404   assert( sizeof(RtreeCoord)==4 );
405   assert( sizeof(u32)==4 );
406   i = pCoord->u;
407   p[0] = (i>>24)&0xFF;
408   p[1] = (i>>16)&0xFF;
409   p[2] = (i>> 8)&0xFF;
410   p[3] = (i>> 0)&0xFF;
411   return 4;
412 }
413 static int writeInt64(u8 *p, i64 i){
414   p[0] = (i>>56)&0xFF;
415   p[1] = (i>>48)&0xFF;
416   p[2] = (i>>40)&0xFF;
417   p[3] = (i>>32)&0xFF;
418   p[4] = (i>>24)&0xFF;
419   p[5] = (i>>16)&0xFF;
420   p[6] = (i>> 8)&0xFF;
421   p[7] = (i>> 0)&0xFF;
422   return 8;
423 }
424 
425 /*
426 ** Increment the reference count of node p.
427 */
428 static void nodeReference(RtreeNode *p){
429   if( p ){
430     p->nRef++;
431   }
432 }
433 
434 /*
435 ** Clear the content of node p (set all bytes to 0x00).
436 */
437 static void nodeZero(Rtree *pRtree, RtreeNode *p){
438   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
439   p->isDirty = 1;
440 }
441 
442 /*
443 ** Given a node number iNode, return the corresponding key to use
444 ** in the Rtree.aHash table.
445 */
446 static int nodeHash(i64 iNode){
447   return iNode % HASHSIZE;
448 }
449 
450 /*
451 ** Search the node hash table for node iNode. If found, return a pointer
452 ** to it. Otherwise, return 0.
453 */
454 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
455   RtreeNode *p;
456   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
457   return p;
458 }
459 
460 /*
461 ** Add node pNode to the node hash table.
462 */
463 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
464   int iHash;
465   assert( pNode->pNext==0 );
466   iHash = nodeHash(pNode->iNode);
467   pNode->pNext = pRtree->aHash[iHash];
468   pRtree->aHash[iHash] = pNode;
469 }
470 
471 /*
472 ** Remove node pNode from the node hash table.
473 */
474 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
475   RtreeNode **pp;
476   if( pNode->iNode!=0 ){
477     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
478     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
479     *pp = pNode->pNext;
480     pNode->pNext = 0;
481   }
482 }
483 
484 /*
485 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
486 ** indicating that node has not yet been assigned a node number. It is
487 ** assigned a node number when nodeWrite() is called to write the
488 ** node contents out to the database.
489 */
490 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
491   RtreeNode *pNode;
492   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
493   if( pNode ){
494     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
495     pNode->zData = (u8 *)&pNode[1];
496     pNode->nRef = 1;
497     pNode->pParent = pParent;
498     pNode->isDirty = 1;
499     nodeReference(pParent);
500   }
501   return pNode;
502 }
503 
504 /*
505 ** Obtain a reference to an r-tree node.
506 */
507 static int nodeAcquire(
508   Rtree *pRtree,             /* R-tree structure */
509   i64 iNode,                 /* Node number to load */
510   RtreeNode *pParent,        /* Either the parent node or NULL */
511   RtreeNode **ppNode         /* OUT: Acquired node */
512 ){
513   int rc;
514   int rc2 = SQLITE_OK;
515   RtreeNode *pNode;
516 
517   /* Check if the requested node is already in the hash table. If so,
518   ** increase its reference count and return it.
519   */
520   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
521     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
522     if( pParent && !pNode->pParent ){
523       nodeReference(pParent);
524       pNode->pParent = pParent;
525     }
526     pNode->nRef++;
527     *ppNode = pNode;
528     return SQLITE_OK;
529   }
530 
531   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
532   rc = sqlite3_step(pRtree->pReadNode);
533   if( rc==SQLITE_ROW ){
534     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
535     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
536       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
537       if( !pNode ){
538         rc2 = SQLITE_NOMEM;
539       }else{
540         pNode->pParent = pParent;
541         pNode->zData = (u8 *)&pNode[1];
542         pNode->nRef = 1;
543         pNode->iNode = iNode;
544         pNode->isDirty = 0;
545         pNode->pNext = 0;
546         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
547         nodeReference(pParent);
548       }
549     }
550   }
551   rc = sqlite3_reset(pRtree->pReadNode);
552   if( rc==SQLITE_OK ) rc = rc2;
553 
554   /* If the root node was just loaded, set pRtree->iDepth to the height
555   ** of the r-tree structure. A height of zero means all data is stored on
556   ** the root node. A height of one means the children of the root node
557   ** are the leaves, and so on. If the depth as specified on the root node
558   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
559   */
560   if( pNode && iNode==1 ){
561     pRtree->iDepth = readInt16(pNode->zData);
562     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
563       rc = SQLITE_CORRUPT_VTAB;
564     }
565   }
566 
567   /* If no error has occurred so far, check if the "number of entries"
568   ** field on the node is too large. If so, set the return code to
569   ** SQLITE_CORRUPT_VTAB.
570   */
571   if( pNode && rc==SQLITE_OK ){
572     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
573       rc = SQLITE_CORRUPT_VTAB;
574     }
575   }
576 
577   if( rc==SQLITE_OK ){
578     if( pNode!=0 ){
579       nodeHashInsert(pRtree, pNode);
580     }else{
581       rc = SQLITE_CORRUPT_VTAB;
582     }
583     *ppNode = pNode;
584   }else{
585     sqlite3_free(pNode);
586     *ppNode = 0;
587   }
588 
589   return rc;
590 }
591 
592 /*
593 ** Overwrite cell iCell of node pNode with the contents of pCell.
594 */
595 static void nodeOverwriteCell(
596   Rtree *pRtree,             /* The overall R-Tree */
597   RtreeNode *pNode,          /* The node into which the cell is to be written */
598   RtreeCell *pCell,          /* The cell to write */
599   int iCell                  /* Index into pNode into which pCell is written */
600 ){
601   int ii;
602   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
603   p += writeInt64(p, pCell->iRowid);
604   for(ii=0; ii<(pRtree->nDim*2); ii++){
605     p += writeCoord(p, &pCell->aCoord[ii]);
606   }
607   pNode->isDirty = 1;
608 }
609 
610 /*
611 ** Remove the cell with index iCell from node pNode.
612 */
613 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
614   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
615   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
616   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
617   memmove(pDst, pSrc, nByte);
618   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
619   pNode->isDirty = 1;
620 }
621 
622 /*
623 ** Insert the contents of cell pCell into node pNode. If the insert
624 ** is successful, return SQLITE_OK.
625 **
626 ** If there is not enough free space in pNode, return SQLITE_FULL.
627 */
628 static int nodeInsertCell(
629   Rtree *pRtree,                /* The overall R-Tree */
630   RtreeNode *pNode,             /* Write new cell into this node */
631   RtreeCell *pCell              /* The cell to be inserted */
632 ){
633   int nCell;                    /* Current number of cells in pNode */
634   int nMaxCell;                 /* Maximum number of cells for pNode */
635 
636   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
637   nCell = NCELL(pNode);
638 
639   assert( nCell<=nMaxCell );
640   if( nCell<nMaxCell ){
641     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
642     writeInt16(&pNode->zData[2], nCell+1);
643     pNode->isDirty = 1;
644   }
645 
646   return (nCell==nMaxCell);
647 }
648 
649 /*
650 ** If the node is dirty, write it out to the database.
651 */
652 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
653   int rc = SQLITE_OK;
654   if( pNode->isDirty ){
655     sqlite3_stmt *p = pRtree->pWriteNode;
656     if( pNode->iNode ){
657       sqlite3_bind_int64(p, 1, pNode->iNode);
658     }else{
659       sqlite3_bind_null(p, 1);
660     }
661     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
662     sqlite3_step(p);
663     pNode->isDirty = 0;
664     rc = sqlite3_reset(p);
665     if( pNode->iNode==0 && rc==SQLITE_OK ){
666       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
667       nodeHashInsert(pRtree, pNode);
668     }
669   }
670   return rc;
671 }
672 
673 /*
674 ** Release a reference to a node. If the node is dirty and the reference
675 ** count drops to zero, the node data is written to the database.
676 */
677 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
678   int rc = SQLITE_OK;
679   if( pNode ){
680     assert( pNode->nRef>0 );
681     pNode->nRef--;
682     if( pNode->nRef==0 ){
683       if( pNode->iNode==1 ){
684         pRtree->iDepth = -1;
685       }
686       if( pNode->pParent ){
687         rc = nodeRelease(pRtree, pNode->pParent);
688       }
689       if( rc==SQLITE_OK ){
690         rc = nodeWrite(pRtree, pNode);
691       }
692       nodeHashDelete(pRtree, pNode);
693       sqlite3_free(pNode);
694     }
695   }
696   return rc;
697 }
698 
699 /*
700 ** Return the 64-bit integer value associated with cell iCell of
701 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
702 ** an internal node, then the 64-bit integer is a child page number.
703 */
704 static i64 nodeGetRowid(
705   Rtree *pRtree,       /* The overall R-Tree */
706   RtreeNode *pNode,    /* The node from which to extract the ID */
707   int iCell            /* The cell index from which to extract the ID */
708 ){
709   assert( iCell<NCELL(pNode) );
710   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
711 }
712 
713 /*
714 ** Return coordinate iCoord from cell iCell in node pNode.
715 */
716 static void nodeGetCoord(
717   Rtree *pRtree,               /* The overall R-Tree */
718   RtreeNode *pNode,            /* The node from which to extract a coordinate */
719   int iCell,                   /* The index of the cell within the node */
720   int iCoord,                  /* Which coordinate to extract */
721   RtreeCoord *pCoord           /* OUT: Space to write result to */
722 ){
723   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
724 }
725 
726 /*
727 ** Deserialize cell iCell of node pNode. Populate the structure pointed
728 ** to by pCell with the results.
729 */
730 static void nodeGetCell(
731   Rtree *pRtree,               /* The overall R-Tree */
732   RtreeNode *pNode,            /* The node containing the cell to be read */
733   int iCell,                   /* Index of the cell within the node */
734   RtreeCell *pCell             /* OUT: Write the cell contents here */
735 ){
736   u8 *pData;
737   RtreeCoord *pCoord;
738   int ii;
739   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
740   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
741   pCoord = pCell->aCoord;
742   for(ii=0; ii<pRtree->nDim*2; ii++){
743     readCoord(&pData[ii*4], &pCoord[ii]);
744   }
745 }
746 
747 
748 /* Forward declaration for the function that does the work of
749 ** the virtual table module xCreate() and xConnect() methods.
750 */
751 static int rtreeInit(
752   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
753 );
754 
755 /*
756 ** Rtree virtual table module xCreate method.
757 */
758 static int rtreeCreate(
759   sqlite3 *db,
760   void *pAux,
761   int argc, const char *const*argv,
762   sqlite3_vtab **ppVtab,
763   char **pzErr
764 ){
765   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
766 }
767 
768 /*
769 ** Rtree virtual table module xConnect method.
770 */
771 static int rtreeConnect(
772   sqlite3 *db,
773   void *pAux,
774   int argc, const char *const*argv,
775   sqlite3_vtab **ppVtab,
776   char **pzErr
777 ){
778   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
779 }
780 
781 /*
782 ** Increment the r-tree reference count.
783 */
784 static void rtreeReference(Rtree *pRtree){
785   pRtree->nBusy++;
786 }
787 
788 /*
789 ** Decrement the r-tree reference count. When the reference count reaches
790 ** zero the structure is deleted.
791 */
792 static void rtreeRelease(Rtree *pRtree){
793   pRtree->nBusy--;
794   if( pRtree->nBusy==0 ){
795     sqlite3_finalize(pRtree->pReadNode);
796     sqlite3_finalize(pRtree->pWriteNode);
797     sqlite3_finalize(pRtree->pDeleteNode);
798     sqlite3_finalize(pRtree->pReadRowid);
799     sqlite3_finalize(pRtree->pWriteRowid);
800     sqlite3_finalize(pRtree->pDeleteRowid);
801     sqlite3_finalize(pRtree->pReadParent);
802     sqlite3_finalize(pRtree->pWriteParent);
803     sqlite3_finalize(pRtree->pDeleteParent);
804     sqlite3_free(pRtree);
805   }
806 }
807 
808 /*
809 ** Rtree virtual table module xDisconnect method.
810 */
811 static int rtreeDisconnect(sqlite3_vtab *pVtab){
812   rtreeRelease((Rtree *)pVtab);
813   return SQLITE_OK;
814 }
815 
816 /*
817 ** Rtree virtual table module xDestroy method.
818 */
819 static int rtreeDestroy(sqlite3_vtab *pVtab){
820   Rtree *pRtree = (Rtree *)pVtab;
821   int rc;
822   char *zCreate = sqlite3_mprintf(
823     "DROP TABLE '%q'.'%q_node';"
824     "DROP TABLE '%q'.'%q_rowid';"
825     "DROP TABLE '%q'.'%q_parent';",
826     pRtree->zDb, pRtree->zName,
827     pRtree->zDb, pRtree->zName,
828     pRtree->zDb, pRtree->zName
829   );
830   if( !zCreate ){
831     rc = SQLITE_NOMEM;
832   }else{
833     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
834     sqlite3_free(zCreate);
835   }
836   if( rc==SQLITE_OK ){
837     rtreeRelease(pRtree);
838   }
839 
840   return rc;
841 }
842 
843 /*
844 ** Rtree virtual table module xOpen method.
845 */
846 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
847   int rc = SQLITE_NOMEM;
848   RtreeCursor *pCsr;
849 
850   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
851   if( pCsr ){
852     memset(pCsr, 0, sizeof(RtreeCursor));
853     pCsr->base.pVtab = pVTab;
854     rc = SQLITE_OK;
855   }
856   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
857 
858   return rc;
859 }
860 
861 
862 /*
863 ** Free the RtreeCursor.aConstraint[] array and its contents.
864 */
865 static void freeCursorConstraints(RtreeCursor *pCsr){
866   if( pCsr->aConstraint ){
867     int i;                        /* Used to iterate through constraint array */
868     for(i=0; i<pCsr->nConstraint; i++){
869       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
870       if( pInfo ){
871         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
872         sqlite3_free(pInfo);
873       }
874     }
875     sqlite3_free(pCsr->aConstraint);
876     pCsr->aConstraint = 0;
877   }
878 }
879 
880 /*
881 ** Rtree virtual table module xClose method.
882 */
883 static int rtreeClose(sqlite3_vtab_cursor *cur){
884   Rtree *pRtree = (Rtree *)(cur->pVtab);
885   int ii;
886   RtreeCursor *pCsr = (RtreeCursor *)cur;
887   freeCursorConstraints(pCsr);
888   sqlite3_free(pCsr->aPoint);
889   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
890   sqlite3_free(pCsr);
891   return SQLITE_OK;
892 }
893 
894 /*
895 ** Rtree virtual table module xEof method.
896 **
897 ** Return non-zero if the cursor does not currently point to a valid
898 ** record (i.e if the scan has finished), or zero otherwise.
899 */
900 static int rtreeEof(sqlite3_vtab_cursor *cur){
901   RtreeCursor *pCsr = (RtreeCursor *)cur;
902   return pCsr->atEOF;
903 }
904 
905 /*
906 ** Convert raw bits from the on-disk RTree record into a coordinate value.
907 ** The on-disk format is big-endian and needs to be converted for little-
908 ** endian platforms.  The on-disk record stores integer coordinates if
909 ** eInt is true and it stores 32-bit floating point records if eInt is
910 ** false.  a[] is the four bytes of the on-disk record to be decoded.
911 ** Store the results in "r".
912 **
913 ** There are three versions of this macro, one each for little-endian and
914 ** big-endian processors and a third generic implementation.  The endian-
915 ** specific implementations are much faster and are preferred if the
916 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
917 ** macro is part of sqliteInt.h and hence the endian-specific
918 ** implementation will only be used if this module is compiled as part
919 ** of the amalgamation.
920 */
921 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
922 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
923     RtreeCoord c;    /* Coordinate decoded */                   \
924     memcpy(&c.u,a,4);                                           \
925     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
926           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
927     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
928 }
929 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
930 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
931     RtreeCoord c;    /* Coordinate decoded */                   \
932     memcpy(&c.u,a,4);                                           \
933     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
934 }
935 #else
936 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
937     RtreeCoord c;    /* Coordinate decoded */                   \
938     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
939            +((u32)a[2]<<8) + a[3];                              \
940     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
941 }
942 #endif
943 
944 /*
945 ** Check the RTree node or entry given by pCellData and p against the MATCH
946 ** constraint pConstraint.
947 */
948 static int rtreeCallbackConstraint(
949   RtreeConstraint *pConstraint,  /* The constraint to test */
950   int eInt,                      /* True if RTree holding integer coordinates */
951   u8 *pCellData,                 /* Raw cell content */
952   RtreeSearchPoint *pSearch,     /* Container of this cell */
953   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
954   int *peWithin                  /* OUT: visibility of the cell */
955 ){
956   int i;                                                /* Loop counter */
957   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
958   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
959   int rc;                                             /* Callback return code */
960   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
961 
962   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
963   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
964 
965   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
966     pInfo->iRowid = readInt64(pCellData);
967   }
968   pCellData += 8;
969   for(i=0; i<nCoord; i++, pCellData += 4){
970     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
971   }
972   if( pConstraint->op==RTREE_MATCH ){
973     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
974                               nCoord, aCoord, &i);
975     if( i==0 ) *peWithin = NOT_WITHIN;
976     *prScore = RTREE_ZERO;
977   }else{
978     pInfo->aCoord = aCoord;
979     pInfo->iLevel = pSearch->iLevel - 1;
980     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
981     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
982     rc = pConstraint->u.xQueryFunc(pInfo);
983     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
984     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
985       *prScore = pInfo->rScore;
986     }
987   }
988   return rc;
989 }
990 
991 /*
992 ** Check the internal RTree node given by pCellData against constraint p.
993 ** If this constraint cannot be satisfied by any child within the node,
994 ** set *peWithin to NOT_WITHIN.
995 */
996 static void rtreeNonleafConstraint(
997   RtreeConstraint *p,        /* The constraint to test */
998   int eInt,                  /* True if RTree holds integer coordinates */
999   u8 *pCellData,             /* Raw cell content as appears on disk */
1000   int *peWithin              /* Adjust downward, as appropriate */
1001 ){
1002   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
1003 
1004   /* p->iCoord might point to either a lower or upper bound coordinate
1005   ** in a coordinate pair.  But make pCellData point to the lower bound.
1006   */
1007   pCellData += 8 + 4*(p->iCoord&0xfe);
1008 
1009   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1010       || p->op==RTREE_GT || p->op==RTREE_EQ );
1011   switch( p->op ){
1012     case RTREE_LE:
1013     case RTREE_LT:
1014     case RTREE_EQ:
1015       RTREE_DECODE_COORD(eInt, pCellData, val);
1016       /* val now holds the lower bound of the coordinate pair */
1017       if( p->u.rValue>=val ) return;
1018       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
1019       /* Fall through for the RTREE_EQ case */
1020 
1021     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
1022       pCellData += 4;
1023       RTREE_DECODE_COORD(eInt, pCellData, val);
1024       /* val now holds the upper bound of the coordinate pair */
1025       if( p->u.rValue<=val ) return;
1026   }
1027   *peWithin = NOT_WITHIN;
1028 }
1029 
1030 /*
1031 ** Check the leaf RTree cell given by pCellData against constraint p.
1032 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
1033 ** If the constraint is satisfied, leave *peWithin unchanged.
1034 **
1035 ** The constraint is of the form:  xN op $val
1036 **
1037 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
1038 ** pCellData.  $val is given by p->u.rValue.
1039 */
1040 static void rtreeLeafConstraint(
1041   RtreeConstraint *p,        /* The constraint to test */
1042   int eInt,                  /* True if RTree holds integer coordinates */
1043   u8 *pCellData,             /* Raw cell content as appears on disk */
1044   int *peWithin              /* Adjust downward, as appropriate */
1045 ){
1046   RtreeDValue xN;      /* Coordinate value converted to a double */
1047 
1048   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1049       || p->op==RTREE_GT || p->op==RTREE_EQ );
1050   pCellData += 8 + p->iCoord*4;
1051   RTREE_DECODE_COORD(eInt, pCellData, xN);
1052   switch( p->op ){
1053     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
1054     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
1055     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
1056     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
1057     default:       if( xN == p->u.rValue ) return;  break;
1058   }
1059   *peWithin = NOT_WITHIN;
1060 }
1061 
1062 /*
1063 ** One of the cells in node pNode is guaranteed to have a 64-bit
1064 ** integer value equal to iRowid. Return the index of this cell.
1065 */
1066 static int nodeRowidIndex(
1067   Rtree *pRtree,
1068   RtreeNode *pNode,
1069   i64 iRowid,
1070   int *piIndex
1071 ){
1072   int ii;
1073   int nCell = NCELL(pNode);
1074   assert( nCell<200 );
1075   for(ii=0; ii<nCell; ii++){
1076     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1077       *piIndex = ii;
1078       return SQLITE_OK;
1079     }
1080   }
1081   return SQLITE_CORRUPT_VTAB;
1082 }
1083 
1084 /*
1085 ** Return the index of the cell containing a pointer to node pNode
1086 ** in its parent. If pNode is the root node, return -1.
1087 */
1088 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1089   RtreeNode *pParent = pNode->pParent;
1090   if( pParent ){
1091     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1092   }
1093   *piIndex = -1;
1094   return SQLITE_OK;
1095 }
1096 
1097 /*
1098 ** Compare two search points.  Return negative, zero, or positive if the first
1099 ** is less than, equal to, or greater than the second.
1100 **
1101 ** The rScore is the primary key.  Smaller rScore values come first.
1102 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
1103 ** iLevel values coming first.  In this way, if rScore is the same for all
1104 ** SearchPoints, then iLevel becomes the deciding factor and the result
1105 ** is a depth-first search, which is the desired default behavior.
1106 */
1107 static int rtreeSearchPointCompare(
1108   const RtreeSearchPoint *pA,
1109   const RtreeSearchPoint *pB
1110 ){
1111   if( pA->rScore<pB->rScore ) return -1;
1112   if( pA->rScore>pB->rScore ) return +1;
1113   if( pA->iLevel<pB->iLevel ) return -1;
1114   if( pA->iLevel>pB->iLevel ) return +1;
1115   return 0;
1116 }
1117 
1118 /*
1119 ** Interchange to search points in a cursor.
1120 */
1121 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
1122   RtreeSearchPoint t = p->aPoint[i];
1123   assert( i<j );
1124   p->aPoint[i] = p->aPoint[j];
1125   p->aPoint[j] = t;
1126   i++; j++;
1127   if( i<RTREE_CACHE_SZ ){
1128     if( j>=RTREE_CACHE_SZ ){
1129       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1130       p->aNode[i] = 0;
1131     }else{
1132       RtreeNode *pTemp = p->aNode[i];
1133       p->aNode[i] = p->aNode[j];
1134       p->aNode[j] = pTemp;
1135     }
1136   }
1137 }
1138 
1139 /*
1140 ** Return the search point with the lowest current score.
1141 */
1142 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
1143   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
1144 }
1145 
1146 /*
1147 ** Get the RtreeNode for the search point with the lowest score.
1148 */
1149 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
1150   sqlite3_int64 id;
1151   int ii = 1 - pCur->bPoint;
1152   assert( ii==0 || ii==1 );
1153   assert( pCur->bPoint || pCur->nPoint );
1154   if( pCur->aNode[ii]==0 ){
1155     assert( pRC!=0 );
1156     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
1157     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
1158   }
1159   return pCur->aNode[ii];
1160 }
1161 
1162 /*
1163 ** Push a new element onto the priority queue
1164 */
1165 static RtreeSearchPoint *rtreeEnqueue(
1166   RtreeCursor *pCur,    /* The cursor */
1167   RtreeDValue rScore,   /* Score for the new search point */
1168   u8 iLevel             /* Level for the new search point */
1169 ){
1170   int i, j;
1171   RtreeSearchPoint *pNew;
1172   if( pCur->nPoint>=pCur->nPointAlloc ){
1173     int nNew = pCur->nPointAlloc*2 + 8;
1174     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
1175     if( pNew==0 ) return 0;
1176     pCur->aPoint = pNew;
1177     pCur->nPointAlloc = nNew;
1178   }
1179   i = pCur->nPoint++;
1180   pNew = pCur->aPoint + i;
1181   pNew->rScore = rScore;
1182   pNew->iLevel = iLevel;
1183   assert( iLevel<=RTREE_MAX_DEPTH );
1184   while( i>0 ){
1185     RtreeSearchPoint *pParent;
1186     j = (i-1)/2;
1187     pParent = pCur->aPoint + j;
1188     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
1189     rtreeSearchPointSwap(pCur, j, i);
1190     i = j;
1191     pNew = pParent;
1192   }
1193   return pNew;
1194 }
1195 
1196 /*
1197 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
1198 ** NULL if malloc fails.
1199 */
1200 static RtreeSearchPoint *rtreeSearchPointNew(
1201   RtreeCursor *pCur,    /* The cursor */
1202   RtreeDValue rScore,   /* Score for the new search point */
1203   u8 iLevel             /* Level for the new search point */
1204 ){
1205   RtreeSearchPoint *pNew, *pFirst;
1206   pFirst = rtreeSearchPointFirst(pCur);
1207   pCur->anQueue[iLevel]++;
1208   if( pFirst==0
1209    || pFirst->rScore>rScore
1210    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
1211   ){
1212     if( pCur->bPoint ){
1213       int ii;
1214       pNew = rtreeEnqueue(pCur, rScore, iLevel);
1215       if( pNew==0 ) return 0;
1216       ii = (int)(pNew - pCur->aPoint) + 1;
1217       if( ii<RTREE_CACHE_SZ ){
1218         assert( pCur->aNode[ii]==0 );
1219         pCur->aNode[ii] = pCur->aNode[0];
1220        }else{
1221         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
1222       }
1223       pCur->aNode[0] = 0;
1224       *pNew = pCur->sPoint;
1225     }
1226     pCur->sPoint.rScore = rScore;
1227     pCur->sPoint.iLevel = iLevel;
1228     pCur->bPoint = 1;
1229     return &pCur->sPoint;
1230   }else{
1231     return rtreeEnqueue(pCur, rScore, iLevel);
1232   }
1233 }
1234 
1235 #if 0
1236 /* Tracing routines for the RtreeSearchPoint queue */
1237 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
1238   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
1239   printf(" %d.%05lld.%02d %g %d",
1240     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
1241   );
1242   idx++;
1243   if( idx<RTREE_CACHE_SZ ){
1244     printf(" %p\n", pCur->aNode[idx]);
1245   }else{
1246     printf("\n");
1247   }
1248 }
1249 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
1250   int ii;
1251   printf("=== %9s ", zPrefix);
1252   if( pCur->bPoint ){
1253     tracePoint(&pCur->sPoint, -1, pCur);
1254   }
1255   for(ii=0; ii<pCur->nPoint; ii++){
1256     if( ii>0 || pCur->bPoint ) printf("              ");
1257     tracePoint(&pCur->aPoint[ii], ii, pCur);
1258   }
1259 }
1260 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
1261 #else
1262 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
1263 #endif
1264 
1265 /* Remove the search point with the lowest current score.
1266 */
1267 static void rtreeSearchPointPop(RtreeCursor *p){
1268   int i, j, k, n;
1269   i = 1 - p->bPoint;
1270   assert( i==0 || i==1 );
1271   if( p->aNode[i] ){
1272     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1273     p->aNode[i] = 0;
1274   }
1275   if( p->bPoint ){
1276     p->anQueue[p->sPoint.iLevel]--;
1277     p->bPoint = 0;
1278   }else if( p->nPoint ){
1279     p->anQueue[p->aPoint[0].iLevel]--;
1280     n = --p->nPoint;
1281     p->aPoint[0] = p->aPoint[n];
1282     if( n<RTREE_CACHE_SZ-1 ){
1283       p->aNode[1] = p->aNode[n+1];
1284       p->aNode[n+1] = 0;
1285     }
1286     i = 0;
1287     while( (j = i*2+1)<n ){
1288       k = j+1;
1289       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
1290         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
1291           rtreeSearchPointSwap(p, i, k);
1292           i = k;
1293         }else{
1294           break;
1295         }
1296       }else{
1297         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
1298           rtreeSearchPointSwap(p, i, j);
1299           i = j;
1300         }else{
1301           break;
1302         }
1303       }
1304     }
1305   }
1306 }
1307 
1308 
1309 /*
1310 ** Continue the search on cursor pCur until the front of the queue
1311 ** contains an entry suitable for returning as a result-set row,
1312 ** or until the RtreeSearchPoint queue is empty, indicating that the
1313 ** query has completed.
1314 */
1315 static int rtreeStepToLeaf(RtreeCursor *pCur){
1316   RtreeSearchPoint *p;
1317   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
1318   RtreeNode *pNode;
1319   int eWithin;
1320   int rc = SQLITE_OK;
1321   int nCell;
1322   int nConstraint = pCur->nConstraint;
1323   int ii;
1324   int eInt;
1325   RtreeSearchPoint x;
1326 
1327   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
1328   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
1329     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
1330     if( rc ) return rc;
1331     nCell = NCELL(pNode);
1332     assert( nCell<200 );
1333     while( p->iCell<nCell ){
1334       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
1335       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
1336       eWithin = FULLY_WITHIN;
1337       for(ii=0; ii<nConstraint; ii++){
1338         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
1339         if( pConstraint->op>=RTREE_MATCH ){
1340           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
1341                                        &rScore, &eWithin);
1342           if( rc ) return rc;
1343         }else if( p->iLevel==1 ){
1344           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
1345         }else{
1346           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
1347         }
1348         if( eWithin==NOT_WITHIN ) break;
1349       }
1350       p->iCell++;
1351       if( eWithin==NOT_WITHIN ) continue;
1352       x.iLevel = p->iLevel - 1;
1353       if( x.iLevel ){
1354         x.id = readInt64(pCellData);
1355         x.iCell = 0;
1356       }else{
1357         x.id = p->id;
1358         x.iCell = p->iCell - 1;
1359       }
1360       if( p->iCell>=nCell ){
1361         RTREE_QUEUE_TRACE(pCur, "POP-S:");
1362         rtreeSearchPointPop(pCur);
1363       }
1364       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
1365       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
1366       if( p==0 ) return SQLITE_NOMEM;
1367       p->eWithin = eWithin;
1368       p->id = x.id;
1369       p->iCell = x.iCell;
1370       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
1371       break;
1372     }
1373     if( p->iCell>=nCell ){
1374       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
1375       rtreeSearchPointPop(pCur);
1376     }
1377   }
1378   pCur->atEOF = p==0;
1379   return SQLITE_OK;
1380 }
1381 
1382 /*
1383 ** Rtree virtual table module xNext method.
1384 */
1385 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1386   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1387   int rc = SQLITE_OK;
1388 
1389   /* Move to the next entry that matches the configured constraints. */
1390   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
1391   rtreeSearchPointPop(pCsr);
1392   rc = rtreeStepToLeaf(pCsr);
1393   return rc;
1394 }
1395 
1396 /*
1397 ** Rtree virtual table module xRowid method.
1398 */
1399 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1400   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1401   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1402   int rc = SQLITE_OK;
1403   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1404   if( rc==SQLITE_OK && p ){
1405     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
1406   }
1407   return rc;
1408 }
1409 
1410 /*
1411 ** Rtree virtual table module xColumn method.
1412 */
1413 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1414   Rtree *pRtree = (Rtree *)cur->pVtab;
1415   RtreeCursor *pCsr = (RtreeCursor *)cur;
1416   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1417   RtreeCoord c;
1418   int rc = SQLITE_OK;
1419   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1420 
1421   if( rc ) return rc;
1422   if( p==0 ) return SQLITE_OK;
1423   if( i==0 ){
1424     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
1425   }else{
1426     if( rc ) return rc;
1427     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
1428 #ifndef SQLITE_RTREE_INT_ONLY
1429     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1430       sqlite3_result_double(ctx, c.f);
1431     }else
1432 #endif
1433     {
1434       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1435       sqlite3_result_int(ctx, c.i);
1436     }
1437   }
1438   return SQLITE_OK;
1439 }
1440 
1441 /*
1442 ** Use nodeAcquire() to obtain the leaf node containing the record with
1443 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1444 ** return SQLITE_OK. If there is no such record in the table, set
1445 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1446 ** to zero and return an SQLite error code.
1447 */
1448 static int findLeafNode(
1449   Rtree *pRtree,              /* RTree to search */
1450   i64 iRowid,                 /* The rowid searching for */
1451   RtreeNode **ppLeaf,         /* Write the node here */
1452   sqlite3_int64 *piNode       /* Write the node-id here */
1453 ){
1454   int rc;
1455   *ppLeaf = 0;
1456   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1457   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1458     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1459     if( piNode ) *piNode = iNode;
1460     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1461     sqlite3_reset(pRtree->pReadRowid);
1462   }else{
1463     rc = sqlite3_reset(pRtree->pReadRowid);
1464   }
1465   return rc;
1466 }
1467 
1468 /*
1469 ** This function is called to configure the RtreeConstraint object passed
1470 ** as the second argument for a MATCH constraint. The value passed as the
1471 ** first argument to this function is the right-hand operand to the MATCH
1472 ** operator.
1473 */
1474 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1475   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
1476   sqlite3_rtree_query_info *pInfo;   /* Callback information */
1477   int nBlob;                         /* Size of the geometry function blob */
1478   int nExpected;                     /* Expected size of the BLOB */
1479 
1480   /* Check that value is actually a blob. */
1481   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
1482 
1483   /* Check that the blob is roughly the right size. */
1484   nBlob = sqlite3_value_bytes(pValue);
1485   if( nBlob<(int)sizeof(RtreeMatchArg)
1486    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
1487   ){
1488     return SQLITE_ERROR;
1489   }
1490 
1491   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
1492   if( !pInfo ) return SQLITE_NOMEM;
1493   memset(pInfo, 0, sizeof(*pInfo));
1494   pBlob = (RtreeMatchArg*)&pInfo[1];
1495 
1496   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
1497   nExpected = (int)(sizeof(RtreeMatchArg) +
1498                     (pBlob->nParam-1)*sizeof(RtreeDValue));
1499   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
1500     sqlite3_free(pInfo);
1501     return SQLITE_ERROR;
1502   }
1503   pInfo->pContext = pBlob->cb.pContext;
1504   pInfo->nParam = pBlob->nParam;
1505   pInfo->aParam = pBlob->aParam;
1506 
1507   if( pBlob->cb.xGeom ){
1508     pCons->u.xGeom = pBlob->cb.xGeom;
1509   }else{
1510     pCons->op = RTREE_QUERY;
1511     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
1512   }
1513   pCons->pInfo = pInfo;
1514   return SQLITE_OK;
1515 }
1516 
1517 /*
1518 ** Rtree virtual table module xFilter method.
1519 */
1520 static int rtreeFilter(
1521   sqlite3_vtab_cursor *pVtabCursor,
1522   int idxNum, const char *idxStr,
1523   int argc, sqlite3_value **argv
1524 ){
1525   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1526   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1527   RtreeNode *pRoot = 0;
1528   int ii;
1529   int rc = SQLITE_OK;
1530   int iCell = 0;
1531 
1532   rtreeReference(pRtree);
1533 
1534   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
1535   freeCursorConstraints(pCsr);
1536   sqlite3_free(pCsr->aPoint);
1537   memset(pCsr, 0, sizeof(RtreeCursor));
1538   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
1539 
1540   pCsr->iStrategy = idxNum;
1541   if( idxNum==1 ){
1542     /* Special case - lookup by rowid. */
1543     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
1544     RtreeSearchPoint *p;     /* Search point for the the leaf */
1545     i64 iRowid = sqlite3_value_int64(argv[0]);
1546     i64 iNode = 0;
1547     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
1548     if( rc==SQLITE_OK && pLeaf!=0 ){
1549       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
1550       assert( p!=0 );  /* Always returns pCsr->sPoint */
1551       pCsr->aNode[0] = pLeaf;
1552       p->id = iNode;
1553       p->eWithin = PARTLY_WITHIN;
1554       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
1555       p->iCell = iCell;
1556       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
1557     }else{
1558       pCsr->atEOF = 1;
1559     }
1560   }else{
1561     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1562     ** with the configured constraints.
1563     */
1564     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1565     if( rc==SQLITE_OK && argc>0 ){
1566       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
1567       pCsr->nConstraint = argc;
1568       if( !pCsr->aConstraint ){
1569         rc = SQLITE_NOMEM;
1570       }else{
1571         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1572         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
1573         assert( (idxStr==0 && argc==0)
1574                 || (idxStr && (int)strlen(idxStr)==argc*2) );
1575         for(ii=0; ii<argc; ii++){
1576           RtreeConstraint *p = &pCsr->aConstraint[ii];
1577           p->op = idxStr[ii*2];
1578           p->iCoord = idxStr[ii*2+1]-'0';
1579           if( p->op>=RTREE_MATCH ){
1580             /* A MATCH operator. The right-hand-side must be a blob that
1581             ** can be cast into an RtreeMatchArg object. One created using
1582             ** an sqlite3_rtree_geometry_callback() SQL user function.
1583             */
1584             rc = deserializeGeometry(argv[ii], p);
1585             if( rc!=SQLITE_OK ){
1586               break;
1587             }
1588             p->pInfo->nCoord = pRtree->nDim*2;
1589             p->pInfo->anQueue = pCsr->anQueue;
1590             p->pInfo->mxLevel = pRtree->iDepth + 1;
1591           }else{
1592 #ifdef SQLITE_RTREE_INT_ONLY
1593             p->u.rValue = sqlite3_value_int64(argv[ii]);
1594 #else
1595             p->u.rValue = sqlite3_value_double(argv[ii]);
1596 #endif
1597           }
1598         }
1599       }
1600     }
1601     if( rc==SQLITE_OK ){
1602       RtreeSearchPoint *pNew;
1603       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
1604       if( pNew==0 ) return SQLITE_NOMEM;
1605       pNew->id = 1;
1606       pNew->iCell = 0;
1607       pNew->eWithin = PARTLY_WITHIN;
1608       assert( pCsr->bPoint==1 );
1609       pCsr->aNode[0] = pRoot;
1610       pRoot = 0;
1611       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
1612       rc = rtreeStepToLeaf(pCsr);
1613     }
1614   }
1615 
1616   nodeRelease(pRtree, pRoot);
1617   rtreeRelease(pRtree);
1618   return rc;
1619 }
1620 
1621 /*
1622 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
1623 ** extension is currently being used by a version of SQLite too old to
1624 ** support estimatedRows. In that case this function is a no-op.
1625 */
1626 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
1627 #if SQLITE_VERSION_NUMBER>=3008002
1628   if( sqlite3_libversion_number()>=3008002 ){
1629     pIdxInfo->estimatedRows = nRow;
1630   }
1631 #endif
1632 }
1633 
1634 /*
1635 ** Rtree virtual table module xBestIndex method. There are three
1636 ** table scan strategies to choose from (in order from most to
1637 ** least desirable):
1638 **
1639 **   idxNum     idxStr        Strategy
1640 **   ------------------------------------------------
1641 **     1        Unused        Direct lookup by rowid.
1642 **     2        See below     R-tree query or full-table scan.
1643 **   ------------------------------------------------
1644 **
1645 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1646 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1647 ** constraint used. The first two bytes of idxStr correspond to
1648 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1649 ** (argvIndex==1) etc.
1650 **
1651 ** The first of each pair of bytes in idxStr identifies the constraint
1652 ** operator as follows:
1653 **
1654 **   Operator    Byte Value
1655 **   ----------------------
1656 **      =        0x41 ('A')
1657 **     <=        0x42 ('B')
1658 **      <        0x43 ('C')
1659 **     >=        0x44 ('D')
1660 **      >        0x45 ('E')
1661 **   MATCH       0x46 ('F')
1662 **   ----------------------
1663 **
1664 ** The second of each pair of bytes identifies the coordinate column
1665 ** to which the constraint applies. The leftmost coordinate column
1666 ** is 'a', the second from the left 'b' etc.
1667 */
1668 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1669   Rtree *pRtree = (Rtree*)tab;
1670   int rc = SQLITE_OK;
1671   int ii;
1672   i64 nRow;                       /* Estimated rows returned by this scan */
1673 
1674   int iIdx = 0;
1675   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
1676   memset(zIdxStr, 0, sizeof(zIdxStr));
1677 
1678   assert( pIdxInfo->idxStr==0 );
1679   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
1680     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
1681 
1682     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
1683       /* We have an equality constraint on the rowid. Use strategy 1. */
1684       int jj;
1685       for(jj=0; jj<ii; jj++){
1686         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
1687         pIdxInfo->aConstraintUsage[jj].omit = 0;
1688       }
1689       pIdxInfo->idxNum = 1;
1690       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
1691       pIdxInfo->aConstraintUsage[jj].omit = 1;
1692 
1693       /* This strategy involves a two rowid lookups on an B-Tree structures
1694       ** and then a linear search of an R-Tree node. This should be
1695       ** considered almost as quick as a direct rowid lookup (for which
1696       ** sqlite uses an internal cost of 0.0). It is expected to return
1697       ** a single row.
1698       */
1699       pIdxInfo->estimatedCost = 30.0;
1700       setEstimatedRows(pIdxInfo, 1);
1701       return SQLITE_OK;
1702     }
1703 
1704     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
1705       u8 op;
1706       switch( p->op ){
1707         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
1708         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
1709         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
1710         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
1711         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
1712         default:
1713           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
1714           op = RTREE_MATCH;
1715           break;
1716       }
1717       zIdxStr[iIdx++] = op;
1718       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
1719       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
1720       pIdxInfo->aConstraintUsage[ii].omit = 1;
1721     }
1722   }
1723 
1724   pIdxInfo->idxNum = 2;
1725   pIdxInfo->needToFreeIdxStr = 1;
1726   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
1727     return SQLITE_NOMEM;
1728   }
1729 
1730   nRow = pRtree->nRowEst / (iIdx + 1);
1731   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
1732   setEstimatedRows(pIdxInfo, nRow);
1733 
1734   return rc;
1735 }
1736 
1737 /*
1738 ** Return the N-dimensional volumn of the cell stored in *p.
1739 */
1740 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
1741   RtreeDValue area = (RtreeDValue)1;
1742   int ii;
1743   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1744     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
1745   }
1746   return area;
1747 }
1748 
1749 /*
1750 ** Return the margin length of cell p. The margin length is the sum
1751 ** of the objects size in each dimension.
1752 */
1753 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
1754   RtreeDValue margin = (RtreeDValue)0;
1755   int ii;
1756   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1757     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
1758   }
1759   return margin;
1760 }
1761 
1762 /*
1763 ** Store the union of cells p1 and p2 in p1.
1764 */
1765 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1766   int ii;
1767   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1768     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1769       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
1770       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
1771     }
1772   }else{
1773     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1774       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
1775       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
1776     }
1777   }
1778 }
1779 
1780 /*
1781 ** Return true if the area covered by p2 is a subset of the area covered
1782 ** by p1. False otherwise.
1783 */
1784 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1785   int ii;
1786   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
1787   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1788     RtreeCoord *a1 = &p1->aCoord[ii];
1789     RtreeCoord *a2 = &p2->aCoord[ii];
1790     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
1791      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
1792     ){
1793       return 0;
1794     }
1795   }
1796   return 1;
1797 }
1798 
1799 /*
1800 ** Return the amount cell p would grow by if it were unioned with pCell.
1801 */
1802 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
1803   RtreeDValue area;
1804   RtreeCell cell;
1805   memcpy(&cell, p, sizeof(RtreeCell));
1806   area = cellArea(pRtree, &cell);
1807   cellUnion(pRtree, &cell, pCell);
1808   return (cellArea(pRtree, &cell)-area);
1809 }
1810 
1811 static RtreeDValue cellOverlap(
1812   Rtree *pRtree,
1813   RtreeCell *p,
1814   RtreeCell *aCell,
1815   int nCell
1816 ){
1817   int ii;
1818   RtreeDValue overlap = RTREE_ZERO;
1819   for(ii=0; ii<nCell; ii++){
1820     int jj;
1821     RtreeDValue o = (RtreeDValue)1;
1822     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
1823       RtreeDValue x1, x2;
1824       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
1825       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
1826       if( x2<x1 ){
1827         o = (RtreeDValue)0;
1828         break;
1829       }else{
1830         o = o * (x2-x1);
1831       }
1832     }
1833     overlap += o;
1834   }
1835   return overlap;
1836 }
1837 
1838 
1839 /*
1840 ** This function implements the ChooseLeaf algorithm from Gutman[84].
1841 ** ChooseSubTree in r*tree terminology.
1842 */
1843 static int ChooseLeaf(
1844   Rtree *pRtree,               /* Rtree table */
1845   RtreeCell *pCell,            /* Cell to insert into rtree */
1846   int iHeight,                 /* Height of sub-tree rooted at pCell */
1847   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
1848 ){
1849   int rc;
1850   int ii;
1851   RtreeNode *pNode;
1852   rc = nodeAcquire(pRtree, 1, 0, &pNode);
1853 
1854   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
1855     int iCell;
1856     sqlite3_int64 iBest = 0;
1857 
1858     RtreeDValue fMinGrowth = RTREE_ZERO;
1859     RtreeDValue fMinArea = RTREE_ZERO;
1860 
1861     int nCell = NCELL(pNode);
1862     RtreeCell cell;
1863     RtreeNode *pChild;
1864 
1865     RtreeCell *aCell = 0;
1866 
1867     /* Select the child node which will be enlarged the least if pCell
1868     ** is inserted into it. Resolve ties by choosing the entry with
1869     ** the smallest area.
1870     */
1871     for(iCell=0; iCell<nCell; iCell++){
1872       int bBest = 0;
1873       RtreeDValue growth;
1874       RtreeDValue area;
1875       nodeGetCell(pRtree, pNode, iCell, &cell);
1876       growth = cellGrowth(pRtree, &cell, pCell);
1877       area = cellArea(pRtree, &cell);
1878       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
1879         bBest = 1;
1880       }
1881       if( bBest ){
1882         fMinGrowth = growth;
1883         fMinArea = area;
1884         iBest = cell.iRowid;
1885       }
1886     }
1887 
1888     sqlite3_free(aCell);
1889     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
1890     nodeRelease(pRtree, pNode);
1891     pNode = pChild;
1892   }
1893 
1894   *ppLeaf = pNode;
1895   return rc;
1896 }
1897 
1898 /*
1899 ** A cell with the same content as pCell has just been inserted into
1900 ** the node pNode. This function updates the bounding box cells in
1901 ** all ancestor elements.
1902 */
1903 static int AdjustTree(
1904   Rtree *pRtree,                    /* Rtree table */
1905   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
1906   RtreeCell *pCell                  /* This cell was just inserted */
1907 ){
1908   RtreeNode *p = pNode;
1909   while( p->pParent ){
1910     RtreeNode *pParent = p->pParent;
1911     RtreeCell cell;
1912     int iCell;
1913 
1914     if( nodeParentIndex(pRtree, p, &iCell) ){
1915       return SQLITE_CORRUPT_VTAB;
1916     }
1917 
1918     nodeGetCell(pRtree, pParent, iCell, &cell);
1919     if( !cellContains(pRtree, &cell, pCell) ){
1920       cellUnion(pRtree, &cell, pCell);
1921       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
1922     }
1923 
1924     p = pParent;
1925   }
1926   return SQLITE_OK;
1927 }
1928 
1929 /*
1930 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
1931 */
1932 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
1933   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
1934   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
1935   sqlite3_step(pRtree->pWriteRowid);
1936   return sqlite3_reset(pRtree->pWriteRowid);
1937 }
1938 
1939 /*
1940 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
1941 */
1942 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
1943   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
1944   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
1945   sqlite3_step(pRtree->pWriteParent);
1946   return sqlite3_reset(pRtree->pWriteParent);
1947 }
1948 
1949 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
1950 
1951 
1952 /*
1953 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
1954 ** nIdx. The aIdx array contains the set of integers from 0 to
1955 ** (nIdx-1) in no particular order. This function sorts the values
1956 ** in aIdx according to the indexed values in aDistance. For
1957 ** example, assuming the inputs:
1958 **
1959 **   aIdx      = { 0,   1,   2,   3 }
1960 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
1961 **
1962 ** this function sets the aIdx array to contain:
1963 **
1964 **   aIdx      = { 0,   1,   2,   3 }
1965 **
1966 ** The aSpare array is used as temporary working space by the
1967 ** sorting algorithm.
1968 */
1969 static void SortByDistance(
1970   int *aIdx,
1971   int nIdx,
1972   RtreeDValue *aDistance,
1973   int *aSpare
1974 ){
1975   if( nIdx>1 ){
1976     int iLeft = 0;
1977     int iRight = 0;
1978 
1979     int nLeft = nIdx/2;
1980     int nRight = nIdx-nLeft;
1981     int *aLeft = aIdx;
1982     int *aRight = &aIdx[nLeft];
1983 
1984     SortByDistance(aLeft, nLeft, aDistance, aSpare);
1985     SortByDistance(aRight, nRight, aDistance, aSpare);
1986 
1987     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1988     aLeft = aSpare;
1989 
1990     while( iLeft<nLeft || iRight<nRight ){
1991       if( iLeft==nLeft ){
1992         aIdx[iLeft+iRight] = aRight[iRight];
1993         iRight++;
1994       }else if( iRight==nRight ){
1995         aIdx[iLeft+iRight] = aLeft[iLeft];
1996         iLeft++;
1997       }else{
1998         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
1999         RtreeDValue fRight = aDistance[aRight[iRight]];
2000         if( fLeft<fRight ){
2001           aIdx[iLeft+iRight] = aLeft[iLeft];
2002           iLeft++;
2003         }else{
2004           aIdx[iLeft+iRight] = aRight[iRight];
2005           iRight++;
2006         }
2007       }
2008     }
2009 
2010 #if 0
2011     /* Check that the sort worked */
2012     {
2013       int jj;
2014       for(jj=1; jj<nIdx; jj++){
2015         RtreeDValue left = aDistance[aIdx[jj-1]];
2016         RtreeDValue right = aDistance[aIdx[jj]];
2017         assert( left<=right );
2018       }
2019     }
2020 #endif
2021   }
2022 }
2023 
2024 /*
2025 ** Arguments aIdx, aCell and aSpare all point to arrays of size
2026 ** nIdx. The aIdx array contains the set of integers from 0 to
2027 ** (nIdx-1) in no particular order. This function sorts the values
2028 ** in aIdx according to dimension iDim of the cells in aCell. The
2029 ** minimum value of dimension iDim is considered first, the
2030 ** maximum used to break ties.
2031 **
2032 ** The aSpare array is used as temporary working space by the
2033 ** sorting algorithm.
2034 */
2035 static void SortByDimension(
2036   Rtree *pRtree,
2037   int *aIdx,
2038   int nIdx,
2039   int iDim,
2040   RtreeCell *aCell,
2041   int *aSpare
2042 ){
2043   if( nIdx>1 ){
2044 
2045     int iLeft = 0;
2046     int iRight = 0;
2047 
2048     int nLeft = nIdx/2;
2049     int nRight = nIdx-nLeft;
2050     int *aLeft = aIdx;
2051     int *aRight = &aIdx[nLeft];
2052 
2053     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
2054     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
2055 
2056     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2057     aLeft = aSpare;
2058     while( iLeft<nLeft || iRight<nRight ){
2059       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
2060       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
2061       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
2062       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
2063       if( (iLeft!=nLeft) && ((iRight==nRight)
2064        || (xleft1<xright1)
2065        || (xleft1==xright1 && xleft2<xright2)
2066       )){
2067         aIdx[iLeft+iRight] = aLeft[iLeft];
2068         iLeft++;
2069       }else{
2070         aIdx[iLeft+iRight] = aRight[iRight];
2071         iRight++;
2072       }
2073     }
2074 
2075 #if 0
2076     /* Check that the sort worked */
2077     {
2078       int jj;
2079       for(jj=1; jj<nIdx; jj++){
2080         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2081         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2082         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2083         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2084         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2085       }
2086     }
2087 #endif
2088   }
2089 }
2090 
2091 /*
2092 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2093 */
2094 static int splitNodeStartree(
2095   Rtree *pRtree,
2096   RtreeCell *aCell,
2097   int nCell,
2098   RtreeNode *pLeft,
2099   RtreeNode *pRight,
2100   RtreeCell *pBboxLeft,
2101   RtreeCell *pBboxRight
2102 ){
2103   int **aaSorted;
2104   int *aSpare;
2105   int ii;
2106 
2107   int iBestDim = 0;
2108   int iBestSplit = 0;
2109   RtreeDValue fBestMargin = RTREE_ZERO;
2110 
2111   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2112 
2113   aaSorted = (int **)sqlite3_malloc(nByte);
2114   if( !aaSorted ){
2115     return SQLITE_NOMEM;
2116   }
2117 
2118   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2119   memset(aaSorted, 0, nByte);
2120   for(ii=0; ii<pRtree->nDim; ii++){
2121     int jj;
2122     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2123     for(jj=0; jj<nCell; jj++){
2124       aaSorted[ii][jj] = jj;
2125     }
2126     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2127   }
2128 
2129   for(ii=0; ii<pRtree->nDim; ii++){
2130     RtreeDValue margin = RTREE_ZERO;
2131     RtreeDValue fBestOverlap = RTREE_ZERO;
2132     RtreeDValue fBestArea = RTREE_ZERO;
2133     int iBestLeft = 0;
2134     int nLeft;
2135 
2136     for(
2137       nLeft=RTREE_MINCELLS(pRtree);
2138       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2139       nLeft++
2140     ){
2141       RtreeCell left;
2142       RtreeCell right;
2143       int kk;
2144       RtreeDValue overlap;
2145       RtreeDValue area;
2146 
2147       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2148       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2149       for(kk=1; kk<(nCell-1); kk++){
2150         if( kk<nLeft ){
2151           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2152         }else{
2153           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2154         }
2155       }
2156       margin += cellMargin(pRtree, &left);
2157       margin += cellMargin(pRtree, &right);
2158       overlap = cellOverlap(pRtree, &left, &right, 1);
2159       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2160       if( (nLeft==RTREE_MINCELLS(pRtree))
2161        || (overlap<fBestOverlap)
2162        || (overlap==fBestOverlap && area<fBestArea)
2163       ){
2164         iBestLeft = nLeft;
2165         fBestOverlap = overlap;
2166         fBestArea = area;
2167       }
2168     }
2169 
2170     if( ii==0 || margin<fBestMargin ){
2171       iBestDim = ii;
2172       fBestMargin = margin;
2173       iBestSplit = iBestLeft;
2174     }
2175   }
2176 
2177   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2178   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2179   for(ii=0; ii<nCell; ii++){
2180     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2181     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2182     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2183     nodeInsertCell(pRtree, pTarget, pCell);
2184     cellUnion(pRtree, pBbox, pCell);
2185   }
2186 
2187   sqlite3_free(aaSorted);
2188   return SQLITE_OK;
2189 }
2190 
2191 
2192 static int updateMapping(
2193   Rtree *pRtree,
2194   i64 iRowid,
2195   RtreeNode *pNode,
2196   int iHeight
2197 ){
2198   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2199   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2200   if( iHeight>0 ){
2201     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2202     if( pChild ){
2203       nodeRelease(pRtree, pChild->pParent);
2204       nodeReference(pNode);
2205       pChild->pParent = pNode;
2206     }
2207   }
2208   return xSetMapping(pRtree, iRowid, pNode->iNode);
2209 }
2210 
2211 static int SplitNode(
2212   Rtree *pRtree,
2213   RtreeNode *pNode,
2214   RtreeCell *pCell,
2215   int iHeight
2216 ){
2217   int i;
2218   int newCellIsRight = 0;
2219 
2220   int rc = SQLITE_OK;
2221   int nCell = NCELL(pNode);
2222   RtreeCell *aCell;
2223   int *aiUsed;
2224 
2225   RtreeNode *pLeft = 0;
2226   RtreeNode *pRight = 0;
2227 
2228   RtreeCell leftbbox;
2229   RtreeCell rightbbox;
2230 
2231   /* Allocate an array and populate it with a copy of pCell and
2232   ** all cells from node pLeft. Then zero the original node.
2233   */
2234   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2235   if( !aCell ){
2236     rc = SQLITE_NOMEM;
2237     goto splitnode_out;
2238   }
2239   aiUsed = (int *)&aCell[nCell+1];
2240   memset(aiUsed, 0, sizeof(int)*(nCell+1));
2241   for(i=0; i<nCell; i++){
2242     nodeGetCell(pRtree, pNode, i, &aCell[i]);
2243   }
2244   nodeZero(pRtree, pNode);
2245   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2246   nCell++;
2247 
2248   if( pNode->iNode==1 ){
2249     pRight = nodeNew(pRtree, pNode);
2250     pLeft = nodeNew(pRtree, pNode);
2251     pRtree->iDepth++;
2252     pNode->isDirty = 1;
2253     writeInt16(pNode->zData, pRtree->iDepth);
2254   }else{
2255     pLeft = pNode;
2256     pRight = nodeNew(pRtree, pLeft->pParent);
2257     nodeReference(pLeft);
2258   }
2259 
2260   if( !pLeft || !pRight ){
2261     rc = SQLITE_NOMEM;
2262     goto splitnode_out;
2263   }
2264 
2265   memset(pLeft->zData, 0, pRtree->iNodeSize);
2266   memset(pRight->zData, 0, pRtree->iNodeSize);
2267 
2268   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
2269                          &leftbbox, &rightbbox);
2270   if( rc!=SQLITE_OK ){
2271     goto splitnode_out;
2272   }
2273 
2274   /* Ensure both child nodes have node numbers assigned to them by calling
2275   ** nodeWrite(). Node pRight always needs a node number, as it was created
2276   ** by nodeNew() above. But node pLeft sometimes already has a node number.
2277   ** In this case avoid the all to nodeWrite().
2278   */
2279   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2280    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2281   ){
2282     goto splitnode_out;
2283   }
2284 
2285   rightbbox.iRowid = pRight->iNode;
2286   leftbbox.iRowid = pLeft->iNode;
2287 
2288   if( pNode->iNode==1 ){
2289     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2290     if( rc!=SQLITE_OK ){
2291       goto splitnode_out;
2292     }
2293   }else{
2294     RtreeNode *pParent = pLeft->pParent;
2295     int iCell;
2296     rc = nodeParentIndex(pRtree, pLeft, &iCell);
2297     if( rc==SQLITE_OK ){
2298       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2299       rc = AdjustTree(pRtree, pParent, &leftbbox);
2300     }
2301     if( rc!=SQLITE_OK ){
2302       goto splitnode_out;
2303     }
2304   }
2305   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2306     goto splitnode_out;
2307   }
2308 
2309   for(i=0; i<NCELL(pRight); i++){
2310     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2311     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2312     if( iRowid==pCell->iRowid ){
2313       newCellIsRight = 1;
2314     }
2315     if( rc!=SQLITE_OK ){
2316       goto splitnode_out;
2317     }
2318   }
2319   if( pNode->iNode==1 ){
2320     for(i=0; i<NCELL(pLeft); i++){
2321       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2322       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2323       if( rc!=SQLITE_OK ){
2324         goto splitnode_out;
2325       }
2326     }
2327   }else if( newCellIsRight==0 ){
2328     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2329   }
2330 
2331   if( rc==SQLITE_OK ){
2332     rc = nodeRelease(pRtree, pRight);
2333     pRight = 0;
2334   }
2335   if( rc==SQLITE_OK ){
2336     rc = nodeRelease(pRtree, pLeft);
2337     pLeft = 0;
2338   }
2339 
2340 splitnode_out:
2341   nodeRelease(pRtree, pRight);
2342   nodeRelease(pRtree, pLeft);
2343   sqlite3_free(aCell);
2344   return rc;
2345 }
2346 
2347 /*
2348 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2349 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2350 ** the pLeaf->pParent chain all the way up to the root node.
2351 **
2352 ** This operation is required when a row is deleted (or updated - an update
2353 ** is implemented as a delete followed by an insert). SQLite provides the
2354 ** rowid of the row to delete, which can be used to find the leaf on which
2355 ** the entry resides (argument pLeaf). Once the leaf is located, this
2356 ** function is called to determine its ancestry.
2357 */
2358 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2359   int rc = SQLITE_OK;
2360   RtreeNode *pChild = pLeaf;
2361   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2362     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
2363     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2364     rc = sqlite3_step(pRtree->pReadParent);
2365     if( rc==SQLITE_ROW ){
2366       RtreeNode *pTest;           /* Used to test for reference loops */
2367       i64 iNode;                  /* Node number of parent node */
2368 
2369       /* Before setting pChild->pParent, test that we are not creating a
2370       ** loop of references (as we would if, say, pChild==pParent). We don't
2371       ** want to do this as it leads to a memory leak when trying to delete
2372       ** the referenced counted node structures.
2373       */
2374       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2375       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2376       if( !pTest ){
2377         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2378       }
2379     }
2380     rc = sqlite3_reset(pRtree->pReadParent);
2381     if( rc==SQLITE_OK ) rc = rc2;
2382     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
2383     pChild = pChild->pParent;
2384   }
2385   return rc;
2386 }
2387 
2388 static int deleteCell(Rtree *, RtreeNode *, int, int);
2389 
2390 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2391   int rc;
2392   int rc2;
2393   RtreeNode *pParent = 0;
2394   int iCell;
2395 
2396   assert( pNode->nRef==1 );
2397 
2398   /* Remove the entry in the parent cell. */
2399   rc = nodeParentIndex(pRtree, pNode, &iCell);
2400   if( rc==SQLITE_OK ){
2401     pParent = pNode->pParent;
2402     pNode->pParent = 0;
2403     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2404   }
2405   rc2 = nodeRelease(pRtree, pParent);
2406   if( rc==SQLITE_OK ){
2407     rc = rc2;
2408   }
2409   if( rc!=SQLITE_OK ){
2410     return rc;
2411   }
2412 
2413   /* Remove the xxx_node entry. */
2414   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2415   sqlite3_step(pRtree->pDeleteNode);
2416   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2417     return rc;
2418   }
2419 
2420   /* Remove the xxx_parent entry. */
2421   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2422   sqlite3_step(pRtree->pDeleteParent);
2423   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2424     return rc;
2425   }
2426 
2427   /* Remove the node from the in-memory hash table and link it into
2428   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2429   */
2430   nodeHashDelete(pRtree, pNode);
2431   pNode->iNode = iHeight;
2432   pNode->pNext = pRtree->pDeleted;
2433   pNode->nRef++;
2434   pRtree->pDeleted = pNode;
2435 
2436   return SQLITE_OK;
2437 }
2438 
2439 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2440   RtreeNode *pParent = pNode->pParent;
2441   int rc = SQLITE_OK;
2442   if( pParent ){
2443     int ii;
2444     int nCell = NCELL(pNode);
2445     RtreeCell box;                            /* Bounding box for pNode */
2446     nodeGetCell(pRtree, pNode, 0, &box);
2447     for(ii=1; ii<nCell; ii++){
2448       RtreeCell cell;
2449       nodeGetCell(pRtree, pNode, ii, &cell);
2450       cellUnion(pRtree, &box, &cell);
2451     }
2452     box.iRowid = pNode->iNode;
2453     rc = nodeParentIndex(pRtree, pNode, &ii);
2454     if( rc==SQLITE_OK ){
2455       nodeOverwriteCell(pRtree, pParent, &box, ii);
2456       rc = fixBoundingBox(pRtree, pParent);
2457     }
2458   }
2459   return rc;
2460 }
2461 
2462 /*
2463 ** Delete the cell at index iCell of node pNode. After removing the
2464 ** cell, adjust the r-tree data structure if required.
2465 */
2466 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2467   RtreeNode *pParent;
2468   int rc;
2469 
2470   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2471     return rc;
2472   }
2473 
2474   /* Remove the cell from the node. This call just moves bytes around
2475   ** the in-memory node image, so it cannot fail.
2476   */
2477   nodeDeleteCell(pRtree, pNode, iCell);
2478 
2479   /* If the node is not the tree root and now has less than the minimum
2480   ** number of cells, remove it from the tree. Otherwise, update the
2481   ** cell in the parent node so that it tightly contains the updated
2482   ** node.
2483   */
2484   pParent = pNode->pParent;
2485   assert( pParent || pNode->iNode==1 );
2486   if( pParent ){
2487     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2488       rc = removeNode(pRtree, pNode, iHeight);
2489     }else{
2490       rc = fixBoundingBox(pRtree, pNode);
2491     }
2492   }
2493 
2494   return rc;
2495 }
2496 
2497 static int Reinsert(
2498   Rtree *pRtree,
2499   RtreeNode *pNode,
2500   RtreeCell *pCell,
2501   int iHeight
2502 ){
2503   int *aOrder;
2504   int *aSpare;
2505   RtreeCell *aCell;
2506   RtreeDValue *aDistance;
2507   int nCell;
2508   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
2509   int iDim;
2510   int ii;
2511   int rc = SQLITE_OK;
2512   int n;
2513 
2514   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
2515 
2516   nCell = NCELL(pNode)+1;
2517   n = (nCell+1)&(~1);
2518 
2519   /* Allocate the buffers used by this operation. The allocation is
2520   ** relinquished before this function returns.
2521   */
2522   aCell = (RtreeCell *)sqlite3_malloc(n * (
2523     sizeof(RtreeCell)     +         /* aCell array */
2524     sizeof(int)           +         /* aOrder array */
2525     sizeof(int)           +         /* aSpare array */
2526     sizeof(RtreeDValue)             /* aDistance array */
2527   ));
2528   if( !aCell ){
2529     return SQLITE_NOMEM;
2530   }
2531   aOrder    = (int *)&aCell[n];
2532   aSpare    = (int *)&aOrder[n];
2533   aDistance = (RtreeDValue *)&aSpare[n];
2534 
2535   for(ii=0; ii<nCell; ii++){
2536     if( ii==(nCell-1) ){
2537       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2538     }else{
2539       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2540     }
2541     aOrder[ii] = ii;
2542     for(iDim=0; iDim<pRtree->nDim; iDim++){
2543       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2544       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2545     }
2546   }
2547   for(iDim=0; iDim<pRtree->nDim; iDim++){
2548     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
2549   }
2550 
2551   for(ii=0; ii<nCell; ii++){
2552     aDistance[ii] = RTREE_ZERO;
2553     for(iDim=0; iDim<pRtree->nDim; iDim++){
2554       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
2555                                DCOORD(aCell[ii].aCoord[iDim*2]));
2556       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2557     }
2558   }
2559 
2560   SortByDistance(aOrder, nCell, aDistance, aSpare);
2561   nodeZero(pRtree, pNode);
2562 
2563   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2564     RtreeCell *p = &aCell[aOrder[ii]];
2565     nodeInsertCell(pRtree, pNode, p);
2566     if( p->iRowid==pCell->iRowid ){
2567       if( iHeight==0 ){
2568         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2569       }else{
2570         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2571       }
2572     }
2573   }
2574   if( rc==SQLITE_OK ){
2575     rc = fixBoundingBox(pRtree, pNode);
2576   }
2577   for(; rc==SQLITE_OK && ii<nCell; ii++){
2578     /* Find a node to store this cell in. pNode->iNode currently contains
2579     ** the height of the sub-tree headed by the cell.
2580     */
2581     RtreeNode *pInsert;
2582     RtreeCell *p = &aCell[aOrder[ii]];
2583     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2584     if( rc==SQLITE_OK ){
2585       int rc2;
2586       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2587       rc2 = nodeRelease(pRtree, pInsert);
2588       if( rc==SQLITE_OK ){
2589         rc = rc2;
2590       }
2591     }
2592   }
2593 
2594   sqlite3_free(aCell);
2595   return rc;
2596 }
2597 
2598 /*
2599 ** Insert cell pCell into node pNode. Node pNode is the head of a
2600 ** subtree iHeight high (leaf nodes have iHeight==0).
2601 */
2602 static int rtreeInsertCell(
2603   Rtree *pRtree,
2604   RtreeNode *pNode,
2605   RtreeCell *pCell,
2606   int iHeight
2607 ){
2608   int rc = SQLITE_OK;
2609   if( iHeight>0 ){
2610     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2611     if( pChild ){
2612       nodeRelease(pRtree, pChild->pParent);
2613       nodeReference(pNode);
2614       pChild->pParent = pNode;
2615     }
2616   }
2617   if( nodeInsertCell(pRtree, pNode, pCell) ){
2618     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
2619       rc = SplitNode(pRtree, pNode, pCell, iHeight);
2620     }else{
2621       pRtree->iReinsertHeight = iHeight;
2622       rc = Reinsert(pRtree, pNode, pCell, iHeight);
2623     }
2624   }else{
2625     rc = AdjustTree(pRtree, pNode, pCell);
2626     if( rc==SQLITE_OK ){
2627       if( iHeight==0 ){
2628         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
2629       }else{
2630         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
2631       }
2632     }
2633   }
2634   return rc;
2635 }
2636 
2637 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
2638   int ii;
2639   int rc = SQLITE_OK;
2640   int nCell = NCELL(pNode);
2641 
2642   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
2643     RtreeNode *pInsert;
2644     RtreeCell cell;
2645     nodeGetCell(pRtree, pNode, ii, &cell);
2646 
2647     /* Find a node to store this cell in. pNode->iNode currently contains
2648     ** the height of the sub-tree headed by the cell.
2649     */
2650     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
2651     if( rc==SQLITE_OK ){
2652       int rc2;
2653       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
2654       rc2 = nodeRelease(pRtree, pInsert);
2655       if( rc==SQLITE_OK ){
2656         rc = rc2;
2657       }
2658     }
2659   }
2660   return rc;
2661 }
2662 
2663 /*
2664 ** Select a currently unused rowid for a new r-tree record.
2665 */
2666 static int newRowid(Rtree *pRtree, i64 *piRowid){
2667   int rc;
2668   sqlite3_bind_null(pRtree->pWriteRowid, 1);
2669   sqlite3_bind_null(pRtree->pWriteRowid, 2);
2670   sqlite3_step(pRtree->pWriteRowid);
2671   rc = sqlite3_reset(pRtree->pWriteRowid);
2672   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
2673   return rc;
2674 }
2675 
2676 /*
2677 ** Remove the entry with rowid=iDelete from the r-tree structure.
2678 */
2679 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
2680   int rc;                         /* Return code */
2681   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
2682   int iCell;                      /* Index of iDelete cell in pLeaf */
2683   RtreeNode *pRoot;               /* Root node of rtree structure */
2684 
2685 
2686   /* Obtain a reference to the root node to initialize Rtree.iDepth */
2687   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
2688 
2689   /* Obtain a reference to the leaf node that contains the entry
2690   ** about to be deleted.
2691   */
2692   if( rc==SQLITE_OK ){
2693     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
2694   }
2695 
2696   /* Delete the cell in question from the leaf node. */
2697   if( rc==SQLITE_OK ){
2698     int rc2;
2699     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
2700     if( rc==SQLITE_OK ){
2701       rc = deleteCell(pRtree, pLeaf, iCell, 0);
2702     }
2703     rc2 = nodeRelease(pRtree, pLeaf);
2704     if( rc==SQLITE_OK ){
2705       rc = rc2;
2706     }
2707   }
2708 
2709   /* Delete the corresponding entry in the <rtree>_rowid table. */
2710   if( rc==SQLITE_OK ){
2711     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
2712     sqlite3_step(pRtree->pDeleteRowid);
2713     rc = sqlite3_reset(pRtree->pDeleteRowid);
2714   }
2715 
2716   /* Check if the root node now has exactly one child. If so, remove
2717   ** it, schedule the contents of the child for reinsertion and
2718   ** reduce the tree height by one.
2719   **
2720   ** This is equivalent to copying the contents of the child into
2721   ** the root node (the operation that Gutman's paper says to perform
2722   ** in this scenario).
2723   */
2724   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
2725     int rc2;
2726     RtreeNode *pChild;
2727     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
2728     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
2729     if( rc==SQLITE_OK ){
2730       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
2731     }
2732     rc2 = nodeRelease(pRtree, pChild);
2733     if( rc==SQLITE_OK ) rc = rc2;
2734     if( rc==SQLITE_OK ){
2735       pRtree->iDepth--;
2736       writeInt16(pRoot->zData, pRtree->iDepth);
2737       pRoot->isDirty = 1;
2738     }
2739   }
2740 
2741   /* Re-insert the contents of any underfull nodes removed from the tree. */
2742   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
2743     if( rc==SQLITE_OK ){
2744       rc = reinsertNodeContent(pRtree, pLeaf);
2745     }
2746     pRtree->pDeleted = pLeaf->pNext;
2747     sqlite3_free(pLeaf);
2748   }
2749 
2750   /* Release the reference to the root node. */
2751   if( rc==SQLITE_OK ){
2752     rc = nodeRelease(pRtree, pRoot);
2753   }else{
2754     nodeRelease(pRtree, pRoot);
2755   }
2756 
2757   return rc;
2758 }
2759 
2760 /*
2761 ** Rounding constants for float->double conversion.
2762 */
2763 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
2764 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
2765 
2766 #if !defined(SQLITE_RTREE_INT_ONLY)
2767 /*
2768 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
2769 ** while taking care to round toward negative or positive, respectively.
2770 */
2771 static RtreeValue rtreeValueDown(sqlite3_value *v){
2772   double d = sqlite3_value_double(v);
2773   float f = (float)d;
2774   if( f>d ){
2775     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
2776   }
2777   return f;
2778 }
2779 static RtreeValue rtreeValueUp(sqlite3_value *v){
2780   double d = sqlite3_value_double(v);
2781   float f = (float)d;
2782   if( f<d ){
2783     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
2784   }
2785   return f;
2786 }
2787 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
2788 
2789 
2790 /*
2791 ** The xUpdate method for rtree module virtual tables.
2792 */
2793 static int rtreeUpdate(
2794   sqlite3_vtab *pVtab,
2795   int nData,
2796   sqlite3_value **azData,
2797   sqlite_int64 *pRowid
2798 ){
2799   Rtree *pRtree = (Rtree *)pVtab;
2800   int rc = SQLITE_OK;
2801   RtreeCell cell;                 /* New cell to insert if nData>1 */
2802   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
2803 
2804   rtreeReference(pRtree);
2805   assert(nData>=1);
2806 
2807   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
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