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