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