track 3.7.13
[sqlcipher.git] / ext / rtree / rtree.c
blob66da481e0f58eed1a32de929917d1f369e0cefab
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.
11 *************************************************************************
12 ** This file contains code for implementations of the r-tree and r*-tree
13 ** algorithms packaged as an SQLite virtual table module.
17 ** Database Format of R-Tree Tables
18 ** --------------------------------
20 ** The data structure for a single virtual r-tree table is stored in three
21 ** native SQLite tables declared as follows. In each case, the '%' character
22 ** in the table name is replaced with the user-supplied name of the r-tree
23 ** table.
25 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
26 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
27 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
29 ** The data for each node of the r-tree structure is stored in the %_node
30 ** table. For each node that is not the root node of the r-tree, there is
31 ** an entry in the %_parent table associating the node with its parent.
32 ** And for each row of data in the table, there is an entry in the %_rowid
33 ** table that maps from the entries rowid to the id of the node that it
34 ** is stored on.
36 ** The root node of an r-tree always exists, even if the r-tree table is
37 ** empty. The nodeno of the root node is always 1. All other nodes in the
38 ** table must be the same size as the root node. The content of each node
39 ** is formatted as follows:
41 ** 1. If the node is the root node (node 1), then the first 2 bytes
42 ** of the node contain the tree depth as a big-endian integer.
43 ** For non-root nodes, the first 2 bytes are left unused.
45 ** 2. The next 2 bytes contain the number of entries currently
46 ** stored in the node.
48 ** 3. The remainder of the node contains the node entries. Each entry
49 ** consists of a single 8-byte integer followed by an even number
50 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
51 ** of a record. For internal nodes it is the node number of a
52 ** child page.
55 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
58 ** This file contains an implementation of a couple of different variants
59 ** of the r-tree algorithm. See the README file for further details. The
60 ** same data-structure is used for all, but the algorithms for insert and
61 ** delete operations vary. The variants used are selected at compile time
62 ** by defining the following symbols:
65 /* Either, both or none of the following may be set to activate
66 ** r*tree variant algorithms.
68 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
69 #define VARIANT_RSTARTREE_REINSERT 1
71 /*
72 ** Exactly one of the following must be set to 1.
74 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
75 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
76 #define VARIANT_RSTARTREE_SPLIT 1
78 #define VARIANT_GUTTMAN_SPLIT \
79 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
81 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
82 #define PickNext QuadraticPickNext
83 #define PickSeeds QuadraticPickSeeds
84 #define AssignCells splitNodeGuttman
85 #endif
86 #if VARIANT_GUTTMAN_LINEAR_SPLIT
87 #define PickNext LinearPickNext
88 #define PickSeeds LinearPickSeeds
89 #define AssignCells splitNodeGuttman
90 #endif
91 #if VARIANT_RSTARTREE_SPLIT
92 #define AssignCells splitNodeStartree
93 #endif
95 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
96 # define NDEBUG 1
97 #endif
99 #ifndef SQLITE_CORE
100 #include "sqlite3ext.h"
101 SQLITE_EXTENSION_INIT1
102 #else
103 #include "sqlite3.h"
104 #endif
106 #include <string.h>
107 #include <assert.h>
109 #ifndef SQLITE_AMALGAMATION
110 #include "sqlite3rtree.h"
111 typedef sqlite3_int64 i64;
112 typedef unsigned char u8;
113 typedef unsigned int u32;
114 #endif
116 /* The following macro is used to suppress compiler warnings.
118 #ifndef UNUSED_PARAMETER
119 # define UNUSED_PARAMETER(x) (void)(x)
120 #endif
122 typedef struct Rtree Rtree;
123 typedef struct RtreeCursor RtreeCursor;
124 typedef struct RtreeNode RtreeNode;
125 typedef struct RtreeCell RtreeCell;
126 typedef struct RtreeConstraint RtreeConstraint;
127 typedef struct RtreeMatchArg RtreeMatchArg;
128 typedef struct RtreeGeomCallback RtreeGeomCallback;
129 typedef union RtreeCoord RtreeCoord;
131 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
132 #define RTREE_MAX_DIMENSIONS 5
134 /* Size of hash table Rtree.aHash. This hash table is not expected to
135 ** ever contain very many entries, so a fixed number of buckets is
136 ** used.
138 #define HASHSIZE 128
141 ** An rtree virtual-table object.
143 struct Rtree {
144 sqlite3_vtab base;
145 sqlite3 *db; /* Host database connection */
146 int iNodeSize; /* Size in bytes of each node in the node table */
147 int nDim; /* Number of dimensions */
148 int nBytesPerCell; /* Bytes consumed per cell */
149 int iDepth; /* Current depth of the r-tree structure */
150 char *zDb; /* Name of database containing r-tree table */
151 char *zName; /* Name of r-tree table */
152 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
153 int nBusy; /* Current number of users of this structure */
155 /* List of nodes removed during a CondenseTree operation. List is
156 ** linked together via the pointer normally used for hash chains -
157 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
158 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
160 RtreeNode *pDeleted;
161 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
163 /* Statements to read/write/delete a record from xxx_node */
164 sqlite3_stmt *pReadNode;
165 sqlite3_stmt *pWriteNode;
166 sqlite3_stmt *pDeleteNode;
168 /* Statements to read/write/delete a record from xxx_rowid */
169 sqlite3_stmt *pReadRowid;
170 sqlite3_stmt *pWriteRowid;
171 sqlite3_stmt *pDeleteRowid;
173 /* Statements to read/write/delete a record from xxx_parent */
174 sqlite3_stmt *pReadParent;
175 sqlite3_stmt *pWriteParent;
176 sqlite3_stmt *pDeleteParent;
178 int eCoordType;
181 /* Possible values for eCoordType: */
182 #define RTREE_COORD_REAL32 0
183 #define RTREE_COORD_INT32 1
186 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
187 ** only deal with integer coordinates. No floating point operations
188 ** will be done.
190 #ifdef SQLITE_RTREE_INT_ONLY
191 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
192 typedef int RtreeValue; /* Low accuracy coordinate */
193 #else
194 typedef double RtreeDValue; /* High accuracy coordinate */
195 typedef float RtreeValue; /* Low accuracy coordinate */
196 #endif
199 ** The minimum number of cells allowed for a node is a third of the
200 ** maximum. In Gutman's notation:
202 ** m = M/3
204 ** If an R*-tree "Reinsert" operation is required, the same number of
205 ** cells are removed from the overfull node and reinserted into the tree.
207 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
208 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
209 #define RTREE_MAXCELLS 51
212 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
213 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
214 ** Therefore all non-root nodes must contain at least 3 entries. Since
215 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
216 ** 40 or less.
218 #define RTREE_MAX_DEPTH 40
221 ** An rtree cursor object.
223 struct RtreeCursor {
224 sqlite3_vtab_cursor base;
225 RtreeNode *pNode; /* Node cursor is currently pointing at */
226 int iCell; /* Index of current cell in pNode */
227 int iStrategy; /* Copy of idxNum search parameter */
228 int nConstraint; /* Number of entries in aConstraint */
229 RtreeConstraint *aConstraint; /* Search constraints. */
232 union RtreeCoord {
233 RtreeValue f;
234 int i;
238 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
239 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
240 ** variable pRtree points to the Rtree structure associated with the
241 ** RtreeCoord.
243 #ifdef SQLITE_RTREE_INT_ONLY
244 # define DCOORD(coord) ((RtreeDValue)coord.i)
245 #else
246 # define DCOORD(coord) ( \
247 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
248 ((double)coord.f) : \
249 ((double)coord.i) \
251 #endif
254 ** A search constraint.
256 struct RtreeConstraint {
257 int iCoord; /* Index of constrained coordinate */
258 int op; /* Constraining operation */
259 RtreeDValue rValue; /* Constraint value. */
260 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
261 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
264 /* Possible values for RtreeConstraint.op */
265 #define RTREE_EQ 0x41
266 #define RTREE_LE 0x42
267 #define RTREE_LT 0x43
268 #define RTREE_GE 0x44
269 #define RTREE_GT 0x45
270 #define RTREE_MATCH 0x46
273 ** An rtree structure node.
275 struct RtreeNode {
276 RtreeNode *pParent; /* Parent node */
277 i64 iNode;
278 int nRef;
279 int isDirty;
280 u8 *zData;
281 RtreeNode *pNext; /* Next node in this hash chain */
283 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
286 ** Structure to store a deserialized rtree record.
288 struct RtreeCell {
289 i64 iRowid;
290 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
295 ** Value for the first field of every RtreeMatchArg object. The MATCH
296 ** operator tests that the first field of a blob operand matches this
297 ** value to avoid operating on invalid blobs (which could cause a segfault).
299 #define RTREE_GEOMETRY_MAGIC 0x891245AB
302 ** An instance of this structure must be supplied as a blob argument to
303 ** the right-hand-side of an SQL MATCH operator used to constrain an
304 ** r-tree query.
306 struct RtreeMatchArg {
307 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
308 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
309 void *pContext;
310 int nParam;
311 RtreeDValue aParam[1];
315 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
316 ** a single instance of the following structure is allocated. It is used
317 ** as the context for the user-function created by by s_r_g_c(). The object
318 ** is eventually deleted by the destructor mechanism provided by
319 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
320 ** the geometry callback function).
322 struct RtreeGeomCallback {
323 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
324 void *pContext;
327 #ifndef MAX
328 # define MAX(x,y) ((x) < (y) ? (y) : (x))
329 #endif
330 #ifndef MIN
331 # define MIN(x,y) ((x) > (y) ? (y) : (x))
332 #endif
335 ** Functions to deserialize a 16 bit integer, 32 bit real number and
336 ** 64 bit integer. The deserialized value is returned.
338 static int readInt16(u8 *p){
339 return (p[0]<<8) + p[1];
341 static void readCoord(u8 *p, RtreeCoord *pCoord){
342 u32 i = (
343 (((u32)p[0]) << 24) +
344 (((u32)p[1]) << 16) +
345 (((u32)p[2]) << 8) +
346 (((u32)p[3]) << 0)
348 *(u32 *)pCoord = i;
350 static i64 readInt64(u8 *p){
351 return (
352 (((i64)p[0]) << 56) +
353 (((i64)p[1]) << 48) +
354 (((i64)p[2]) << 40) +
355 (((i64)p[3]) << 32) +
356 (((i64)p[4]) << 24) +
357 (((i64)p[5]) << 16) +
358 (((i64)p[6]) << 8) +
359 (((i64)p[7]) << 0)
364 ** Functions to serialize a 16 bit integer, 32 bit real number and
365 ** 64 bit integer. The value returned is the number of bytes written
366 ** to the argument buffer (always 2, 4 and 8 respectively).
368 static int writeInt16(u8 *p, int i){
369 p[0] = (i>> 8)&0xFF;
370 p[1] = (i>> 0)&0xFF;
371 return 2;
373 static int writeCoord(u8 *p, RtreeCoord *pCoord){
374 u32 i;
375 assert( sizeof(RtreeCoord)==4 );
376 assert( sizeof(u32)==4 );
377 i = *(u32 *)pCoord;
378 p[0] = (i>>24)&0xFF;
379 p[1] = (i>>16)&0xFF;
380 p[2] = (i>> 8)&0xFF;
381 p[3] = (i>> 0)&0xFF;
382 return 4;
384 static int writeInt64(u8 *p, i64 i){
385 p[0] = (i>>56)&0xFF;
386 p[1] = (i>>48)&0xFF;
387 p[2] = (i>>40)&0xFF;
388 p[3] = (i>>32)&0xFF;
389 p[4] = (i>>24)&0xFF;
390 p[5] = (i>>16)&0xFF;
391 p[6] = (i>> 8)&0xFF;
392 p[7] = (i>> 0)&0xFF;
393 return 8;
397 ** Increment the reference count of node p.
399 static void nodeReference(RtreeNode *p){
400 if( p ){
401 p->nRef++;
406 ** Clear the content of node p (set all bytes to 0x00).
408 static void nodeZero(Rtree *pRtree, RtreeNode *p){
409 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
410 p->isDirty = 1;
414 ** Given a node number iNode, return the corresponding key to use
415 ** in the Rtree.aHash table.
417 static int nodeHash(i64 iNode){
418 return (
419 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
420 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
421 ) % HASHSIZE;
425 ** Search the node hash table for node iNode. If found, return a pointer
426 ** to it. Otherwise, return 0.
428 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
429 RtreeNode *p;
430 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
431 return p;
435 ** Add node pNode to the node hash table.
437 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
438 int iHash;
439 assert( pNode->pNext==0 );
440 iHash = nodeHash(pNode->iNode);
441 pNode->pNext = pRtree->aHash[iHash];
442 pRtree->aHash[iHash] = pNode;
446 ** Remove node pNode from the node hash table.
448 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
449 RtreeNode **pp;
450 if( pNode->iNode!=0 ){
451 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
452 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
453 *pp = pNode->pNext;
454 pNode->pNext = 0;
459 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
460 ** indicating that node has not yet been assigned a node number. It is
461 ** assigned a node number when nodeWrite() is called to write the
462 ** node contents out to the database.
464 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
465 RtreeNode *pNode;
466 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
467 if( pNode ){
468 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
469 pNode->zData = (u8 *)&pNode[1];
470 pNode->nRef = 1;
471 pNode->pParent = pParent;
472 pNode->isDirty = 1;
473 nodeReference(pParent);
475 return pNode;
479 ** Obtain a reference to an r-tree node.
481 static int
482 nodeAcquire(
483 Rtree *pRtree, /* R-tree structure */
484 i64 iNode, /* Node number to load */
485 RtreeNode *pParent, /* Either the parent node or NULL */
486 RtreeNode **ppNode /* OUT: Acquired node */
488 int rc;
489 int rc2 = SQLITE_OK;
490 RtreeNode *pNode;
492 /* Check if the requested node is already in the hash table. If so,
493 ** increase its reference count and return it.
495 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
496 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
497 if( pParent && !pNode->pParent ){
498 nodeReference(pParent);
499 pNode->pParent = pParent;
501 pNode->nRef++;
502 *ppNode = pNode;
503 return SQLITE_OK;
506 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
507 rc = sqlite3_step(pRtree->pReadNode);
508 if( rc==SQLITE_ROW ){
509 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
510 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
511 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
512 if( !pNode ){
513 rc2 = SQLITE_NOMEM;
514 }else{
515 pNode->pParent = pParent;
516 pNode->zData = (u8 *)&pNode[1];
517 pNode->nRef = 1;
518 pNode->iNode = iNode;
519 pNode->isDirty = 0;
520 pNode->pNext = 0;
521 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
522 nodeReference(pParent);
526 rc = sqlite3_reset(pRtree->pReadNode);
527 if( rc==SQLITE_OK ) rc = rc2;
529 /* If the root node was just loaded, set pRtree->iDepth to the height
530 ** of the r-tree structure. A height of zero means all data is stored on
531 ** the root node. A height of one means the children of the root node
532 ** are the leaves, and so on. If the depth as specified on the root node
533 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
535 if( pNode && iNode==1 ){
536 pRtree->iDepth = readInt16(pNode->zData);
537 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
538 rc = SQLITE_CORRUPT_VTAB;
542 /* If no error has occurred so far, check if the "number of entries"
543 ** field on the node is too large. If so, set the return code to
544 ** SQLITE_CORRUPT_VTAB.
546 if( pNode && rc==SQLITE_OK ){
547 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
548 rc = SQLITE_CORRUPT_VTAB;
552 if( rc==SQLITE_OK ){
553 if( pNode!=0 ){
554 nodeHashInsert(pRtree, pNode);
555 }else{
556 rc = SQLITE_CORRUPT_VTAB;
558 *ppNode = pNode;
559 }else{
560 sqlite3_free(pNode);
561 *ppNode = 0;
564 return rc;
568 ** Overwrite cell iCell of node pNode with the contents of pCell.
570 static void nodeOverwriteCell(
571 Rtree *pRtree,
572 RtreeNode *pNode,
573 RtreeCell *pCell,
574 int iCell
576 int ii;
577 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
578 p += writeInt64(p, pCell->iRowid);
579 for(ii=0; ii<(pRtree->nDim*2); ii++){
580 p += writeCoord(p, &pCell->aCoord[ii]);
582 pNode->isDirty = 1;
586 ** Remove cell the cell with index iCell from node pNode.
588 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
589 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
590 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
591 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
592 memmove(pDst, pSrc, nByte);
593 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
594 pNode->isDirty = 1;
598 ** Insert the contents of cell pCell into node pNode. If the insert
599 ** is successful, return SQLITE_OK.
601 ** If there is not enough free space in pNode, return SQLITE_FULL.
603 static int
604 nodeInsertCell(
605 Rtree *pRtree,
606 RtreeNode *pNode,
607 RtreeCell *pCell
609 int nCell; /* Current number of cells in pNode */
610 int nMaxCell; /* Maximum number of cells for pNode */
612 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
613 nCell = NCELL(pNode);
615 assert( nCell<=nMaxCell );
616 if( nCell<nMaxCell ){
617 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
618 writeInt16(&pNode->zData[2], nCell+1);
619 pNode->isDirty = 1;
622 return (nCell==nMaxCell);
626 ** If the node is dirty, write it out to the database.
628 static int
629 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
630 int rc = SQLITE_OK;
631 if( pNode->isDirty ){
632 sqlite3_stmt *p = pRtree->pWriteNode;
633 if( pNode->iNode ){
634 sqlite3_bind_int64(p, 1, pNode->iNode);
635 }else{
636 sqlite3_bind_null(p, 1);
638 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
639 sqlite3_step(p);
640 pNode->isDirty = 0;
641 rc = sqlite3_reset(p);
642 if( pNode->iNode==0 && rc==SQLITE_OK ){
643 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
644 nodeHashInsert(pRtree, pNode);
647 return rc;
651 ** Release a reference to a node. If the node is dirty and the reference
652 ** count drops to zero, the node data is written to the database.
654 static int
655 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
656 int rc = SQLITE_OK;
657 if( pNode ){
658 assert( pNode->nRef>0 );
659 pNode->nRef--;
660 if( pNode->nRef==0 ){
661 if( pNode->iNode==1 ){
662 pRtree->iDepth = -1;
664 if( pNode->pParent ){
665 rc = nodeRelease(pRtree, pNode->pParent);
667 if( rc==SQLITE_OK ){
668 rc = nodeWrite(pRtree, pNode);
670 nodeHashDelete(pRtree, pNode);
671 sqlite3_free(pNode);
674 return rc;
678 ** Return the 64-bit integer value associated with cell iCell of
679 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
680 ** an internal node, then the 64-bit integer is a child page number.
682 static i64 nodeGetRowid(
683 Rtree *pRtree,
684 RtreeNode *pNode,
685 int iCell
687 assert( iCell<NCELL(pNode) );
688 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
692 ** Return coordinate iCoord from cell iCell in node pNode.
694 static void nodeGetCoord(
695 Rtree *pRtree,
696 RtreeNode *pNode,
697 int iCell,
698 int iCoord,
699 RtreeCoord *pCoord /* Space to write result to */
701 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
705 ** Deserialize cell iCell of node pNode. Populate the structure pointed
706 ** to by pCell with the results.
708 static void nodeGetCell(
709 Rtree *pRtree,
710 RtreeNode *pNode,
711 int iCell,
712 RtreeCell *pCell
714 int ii;
715 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
716 for(ii=0; ii<pRtree->nDim*2; ii++){
717 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
722 /* Forward declaration for the function that does the work of
723 ** the virtual table module xCreate() and xConnect() methods.
725 static int rtreeInit(
726 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
730 ** Rtree virtual table module xCreate method.
732 static int rtreeCreate(
733 sqlite3 *db,
734 void *pAux,
735 int argc, const char *const*argv,
736 sqlite3_vtab **ppVtab,
737 char **pzErr
739 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
743 ** Rtree virtual table module xConnect method.
745 static int rtreeConnect(
746 sqlite3 *db,
747 void *pAux,
748 int argc, const char *const*argv,
749 sqlite3_vtab **ppVtab,
750 char **pzErr
752 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
756 ** Increment the r-tree reference count.
758 static void rtreeReference(Rtree *pRtree){
759 pRtree->nBusy++;
763 ** Decrement the r-tree reference count. When the reference count reaches
764 ** zero the structure is deleted.
766 static void rtreeRelease(Rtree *pRtree){
767 pRtree->nBusy--;
768 if( pRtree->nBusy==0 ){
769 sqlite3_finalize(pRtree->pReadNode);
770 sqlite3_finalize(pRtree->pWriteNode);
771 sqlite3_finalize(pRtree->pDeleteNode);
772 sqlite3_finalize(pRtree->pReadRowid);
773 sqlite3_finalize(pRtree->pWriteRowid);
774 sqlite3_finalize(pRtree->pDeleteRowid);
775 sqlite3_finalize(pRtree->pReadParent);
776 sqlite3_finalize(pRtree->pWriteParent);
777 sqlite3_finalize(pRtree->pDeleteParent);
778 sqlite3_free(pRtree);
783 ** Rtree virtual table module xDisconnect method.
785 static int rtreeDisconnect(sqlite3_vtab *pVtab){
786 rtreeRelease((Rtree *)pVtab);
787 return SQLITE_OK;
791 ** Rtree virtual table module xDestroy method.
793 static int rtreeDestroy(sqlite3_vtab *pVtab){
794 Rtree *pRtree = (Rtree *)pVtab;
795 int rc;
796 char *zCreate = sqlite3_mprintf(
797 "DROP TABLE '%q'.'%q_node';"
798 "DROP TABLE '%q'.'%q_rowid';"
799 "DROP TABLE '%q'.'%q_parent';",
800 pRtree->zDb, pRtree->zName,
801 pRtree->zDb, pRtree->zName,
802 pRtree->zDb, pRtree->zName
804 if( !zCreate ){
805 rc = SQLITE_NOMEM;
806 }else{
807 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
808 sqlite3_free(zCreate);
810 if( rc==SQLITE_OK ){
811 rtreeRelease(pRtree);
814 return rc;
818 ** Rtree virtual table module xOpen method.
820 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
821 int rc = SQLITE_NOMEM;
822 RtreeCursor *pCsr;
824 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
825 if( pCsr ){
826 memset(pCsr, 0, sizeof(RtreeCursor));
827 pCsr->base.pVtab = pVTab;
828 rc = SQLITE_OK;
830 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
832 return rc;
837 ** Free the RtreeCursor.aConstraint[] array and its contents.
839 static void freeCursorConstraints(RtreeCursor *pCsr){
840 if( pCsr->aConstraint ){
841 int i; /* Used to iterate through constraint array */
842 for(i=0; i<pCsr->nConstraint; i++){
843 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
844 if( pGeom ){
845 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
846 sqlite3_free(pGeom);
849 sqlite3_free(pCsr->aConstraint);
850 pCsr->aConstraint = 0;
855 ** Rtree virtual table module xClose method.
857 static int rtreeClose(sqlite3_vtab_cursor *cur){
858 Rtree *pRtree = (Rtree *)(cur->pVtab);
859 int rc;
860 RtreeCursor *pCsr = (RtreeCursor *)cur;
861 freeCursorConstraints(pCsr);
862 rc = nodeRelease(pRtree, pCsr->pNode);
863 sqlite3_free(pCsr);
864 return rc;
868 ** Rtree virtual table module xEof method.
870 ** Return non-zero if the cursor does not currently point to a valid
871 ** record (i.e if the scan has finished), or zero otherwise.
873 static int rtreeEof(sqlite3_vtab_cursor *cur){
874 RtreeCursor *pCsr = (RtreeCursor *)cur;
875 return (pCsr->pNode==0);
879 ** The r-tree constraint passed as the second argument to this function is
880 ** guaranteed to be a MATCH constraint.
882 static int testRtreeGeom(
883 Rtree *pRtree, /* R-Tree object */
884 RtreeConstraint *pConstraint, /* MATCH constraint to test */
885 RtreeCell *pCell, /* Cell to test */
886 int *pbRes /* OUT: Test result */
888 int i;
889 RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
890 int nCoord = pRtree->nDim*2;
892 assert( pConstraint->op==RTREE_MATCH );
893 assert( pConstraint->pGeom );
895 for(i=0; i<nCoord; i++){
896 aCoord[i] = DCOORD(pCell->aCoord[i]);
898 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
902 ** Cursor pCursor currently points to a cell in a non-leaf page.
903 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
904 ** (excluded) by the constraints in the pCursor->aConstraint[]
905 ** array, or false otherwise.
907 ** Return SQLITE_OK if successful or an SQLite error code if an error
908 ** occurs within a geometry callback.
910 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
911 RtreeCell cell;
912 int ii;
913 int bRes = 0;
914 int rc = SQLITE_OK;
916 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
917 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
918 RtreeConstraint *p = &pCursor->aConstraint[ii];
919 RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
920 RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
922 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
923 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
926 switch( p->op ){
927 case RTREE_LE: case RTREE_LT:
928 bRes = p->rValue<cell_min;
929 break;
931 case RTREE_GE: case RTREE_GT:
932 bRes = p->rValue>cell_max;
933 break;
935 case RTREE_EQ:
936 bRes = (p->rValue>cell_max || p->rValue<cell_min);
937 break;
939 default: {
940 assert( p->op==RTREE_MATCH );
941 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
942 bRes = !bRes;
943 break;
948 *pbEof = bRes;
949 return rc;
953 ** Test if the cell that cursor pCursor currently points to
954 ** would be filtered (excluded) by the constraints in the
955 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
956 ** returning. If the cell is not filtered (excluded) by the constraints,
957 ** set pbEof to zero.
959 ** Return SQLITE_OK if successful or an SQLite error code if an error
960 ** occurs within a geometry callback.
962 ** This function assumes that the cell is part of a leaf node.
964 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
965 RtreeCell cell;
966 int ii;
967 *pbEof = 0;
969 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
970 for(ii=0; ii<pCursor->nConstraint; ii++){
971 RtreeConstraint *p = &pCursor->aConstraint[ii];
972 RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
973 int res;
974 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
975 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
977 switch( p->op ){
978 case RTREE_LE: res = (coord<=p->rValue); break;
979 case RTREE_LT: res = (coord<p->rValue); break;
980 case RTREE_GE: res = (coord>=p->rValue); break;
981 case RTREE_GT: res = (coord>p->rValue); break;
982 case RTREE_EQ: res = (coord==p->rValue); break;
983 default: {
984 int rc;
985 assert( p->op==RTREE_MATCH );
986 rc = testRtreeGeom(pRtree, p, &cell, &res);
987 if( rc!=SQLITE_OK ){
988 return rc;
990 break;
994 if( !res ){
995 *pbEof = 1;
996 return SQLITE_OK;
1000 return SQLITE_OK;
1004 ** Cursor pCursor currently points at a node that heads a sub-tree of
1005 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
1006 ** to point to the left-most cell of the sub-tree that matches the
1007 ** configured constraints.
1009 static int descendToCell(
1010 Rtree *pRtree,
1011 RtreeCursor *pCursor,
1012 int iHeight,
1013 int *pEof /* OUT: Set to true if cannot descend */
1015 int isEof;
1016 int rc;
1017 int ii;
1018 RtreeNode *pChild;
1019 sqlite3_int64 iRowid;
1021 RtreeNode *pSavedNode = pCursor->pNode;
1022 int iSavedCell = pCursor->iCell;
1024 assert( iHeight>=0 );
1026 if( iHeight==0 ){
1027 rc = testRtreeEntry(pRtree, pCursor, &isEof);
1028 }else{
1029 rc = testRtreeCell(pRtree, pCursor, &isEof);
1031 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
1032 goto descend_to_cell_out;
1035 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
1036 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
1037 if( rc!=SQLITE_OK ){
1038 goto descend_to_cell_out;
1041 nodeRelease(pRtree, pCursor->pNode);
1042 pCursor->pNode = pChild;
1043 isEof = 1;
1044 for(ii=0; isEof && ii<NCELL(pChild); ii++){
1045 pCursor->iCell = ii;
1046 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
1047 if( rc!=SQLITE_OK ){
1048 goto descend_to_cell_out;
1052 if( isEof ){
1053 assert( pCursor->pNode==pChild );
1054 nodeReference(pSavedNode);
1055 nodeRelease(pRtree, pChild);
1056 pCursor->pNode = pSavedNode;
1057 pCursor->iCell = iSavedCell;
1060 descend_to_cell_out:
1061 *pEof = isEof;
1062 return rc;
1066 ** One of the cells in node pNode is guaranteed to have a 64-bit
1067 ** integer value equal to iRowid. Return the index of this cell.
1069 static int nodeRowidIndex(
1070 Rtree *pRtree,
1071 RtreeNode *pNode,
1072 i64 iRowid,
1073 int *piIndex
1075 int ii;
1076 int nCell = NCELL(pNode);
1077 for(ii=0; ii<nCell; ii++){
1078 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1079 *piIndex = ii;
1080 return SQLITE_OK;
1083 return SQLITE_CORRUPT_VTAB;
1087 ** Return the index of the cell containing a pointer to node pNode
1088 ** in its parent. If pNode is the root node, return -1.
1090 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1091 RtreeNode *pParent = pNode->pParent;
1092 if( pParent ){
1093 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1095 *piIndex = -1;
1096 return SQLITE_OK;
1100 ** Rtree virtual table module xNext method.
1102 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1103 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
1104 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1105 int rc = SQLITE_OK;
1107 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
1108 ** already at EOF. It is against the rules to call the xNext() method of
1109 ** a cursor that has already reached EOF.
1111 assert( pCsr->pNode );
1113 if( pCsr->iStrategy==1 ){
1114 /* This "scan" is a direct lookup by rowid. There is no next entry. */
1115 nodeRelease(pRtree, pCsr->pNode);
1116 pCsr->pNode = 0;
1117 }else{
1118 /* Move to the next entry that matches the configured constraints. */
1119 int iHeight = 0;
1120 while( pCsr->pNode ){
1121 RtreeNode *pNode = pCsr->pNode;
1122 int nCell = NCELL(pNode);
1123 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
1124 int isEof;
1125 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
1126 if( rc!=SQLITE_OK || !isEof ){
1127 return rc;
1130 pCsr->pNode = pNode->pParent;
1131 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
1132 if( rc!=SQLITE_OK ){
1133 return rc;
1135 nodeReference(pCsr->pNode);
1136 nodeRelease(pRtree, pNode);
1137 iHeight++;
1141 return rc;
1145 ** Rtree virtual table module xRowid method.
1147 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1148 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1149 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1151 assert(pCsr->pNode);
1152 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1154 return SQLITE_OK;
1158 ** Rtree virtual table module xColumn method.
1160 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1161 Rtree *pRtree = (Rtree *)cur->pVtab;
1162 RtreeCursor *pCsr = (RtreeCursor *)cur;
1164 if( i==0 ){
1165 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1166 sqlite3_result_int64(ctx, iRowid);
1167 }else{
1168 RtreeCoord c;
1169 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
1170 #ifndef SQLITE_RTREE_INT_ONLY
1171 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1172 sqlite3_result_double(ctx, c.f);
1173 }else
1174 #endif
1176 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1177 sqlite3_result_int(ctx, c.i);
1181 return SQLITE_OK;
1185 ** Use nodeAcquire() to obtain the leaf node containing the record with
1186 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1187 ** return SQLITE_OK. If there is no such record in the table, set
1188 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1189 ** to zero and return an SQLite error code.
1191 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
1192 int rc;
1193 *ppLeaf = 0;
1194 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1195 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1196 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1197 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1198 sqlite3_reset(pRtree->pReadRowid);
1199 }else{
1200 rc = sqlite3_reset(pRtree->pReadRowid);
1202 return rc;
1206 ** This function is called to configure the RtreeConstraint object passed
1207 ** as the second argument for a MATCH constraint. The value passed as the
1208 ** first argument to this function is the right-hand operand to the MATCH
1209 ** operator.
1211 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1212 RtreeMatchArg *p;
1213 sqlite3_rtree_geometry *pGeom;
1214 int nBlob;
1216 /* Check that value is actually a blob. */
1217 if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
1219 /* Check that the blob is roughly the right size. */
1220 nBlob = sqlite3_value_bytes(pValue);
1221 if( nBlob<(int)sizeof(RtreeMatchArg)
1222 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
1224 return SQLITE_ERROR;
1227 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
1228 sizeof(sqlite3_rtree_geometry) + nBlob
1230 if( !pGeom ) return SQLITE_NOMEM;
1231 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
1232 p = (RtreeMatchArg *)&pGeom[1];
1234 memcpy(p, sqlite3_value_blob(pValue), nBlob);
1235 if( p->magic!=RTREE_GEOMETRY_MAGIC
1236 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
1238 sqlite3_free(pGeom);
1239 return SQLITE_ERROR;
1242 pGeom->pContext = p->pContext;
1243 pGeom->nParam = p->nParam;
1244 pGeom->aParam = p->aParam;
1246 pCons->xGeom = p->xGeom;
1247 pCons->pGeom = pGeom;
1248 return SQLITE_OK;
1252 ** Rtree virtual table module xFilter method.
1254 static int rtreeFilter(
1255 sqlite3_vtab_cursor *pVtabCursor,
1256 int idxNum, const char *idxStr,
1257 int argc, sqlite3_value **argv
1259 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1260 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1262 RtreeNode *pRoot = 0;
1263 int ii;
1264 int rc = SQLITE_OK;
1266 rtreeReference(pRtree);
1268 freeCursorConstraints(pCsr);
1269 pCsr->iStrategy = idxNum;
1271 if( idxNum==1 ){
1272 /* Special case - lookup by rowid. */
1273 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
1274 i64 iRowid = sqlite3_value_int64(argv[0]);
1275 rc = findLeafNode(pRtree, iRowid, &pLeaf);
1276 pCsr->pNode = pLeaf;
1277 if( pLeaf ){
1278 assert( rc==SQLITE_OK );
1279 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
1281 }else{
1282 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1283 ** with the configured constraints.
1285 if( argc>0 ){
1286 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
1287 pCsr->nConstraint = argc;
1288 if( !pCsr->aConstraint ){
1289 rc = SQLITE_NOMEM;
1290 }else{
1291 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1292 assert( (idxStr==0 && argc==0)
1293 || (idxStr && (int)strlen(idxStr)==argc*2) );
1294 for(ii=0; ii<argc; ii++){
1295 RtreeConstraint *p = &pCsr->aConstraint[ii];
1296 p->op = idxStr[ii*2];
1297 p->iCoord = idxStr[ii*2+1]-'a';
1298 if( p->op==RTREE_MATCH ){
1299 /* A MATCH operator. The right-hand-side must be a blob that
1300 ** can be cast into an RtreeMatchArg object. One created using
1301 ** an sqlite3_rtree_geometry_callback() SQL user function.
1303 rc = deserializeGeometry(argv[ii], p);
1304 if( rc!=SQLITE_OK ){
1305 break;
1307 }else{
1308 #ifdef SQLITE_RTREE_INT_ONLY
1309 p->rValue = sqlite3_value_int64(argv[ii]);
1310 #else
1311 p->rValue = sqlite3_value_double(argv[ii]);
1312 #endif
1318 if( rc==SQLITE_OK ){
1319 pCsr->pNode = 0;
1320 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1322 if( rc==SQLITE_OK ){
1323 int isEof = 1;
1324 int nCell = NCELL(pRoot);
1325 pCsr->pNode = pRoot;
1326 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
1327 assert( pCsr->pNode==pRoot );
1328 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
1329 if( !isEof ){
1330 break;
1333 if( rc==SQLITE_OK && isEof ){
1334 assert( pCsr->pNode==pRoot );
1335 nodeRelease(pRtree, pRoot);
1336 pCsr->pNode = 0;
1338 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
1342 rtreeRelease(pRtree);
1343 return rc;
1347 ** Rtree virtual table module xBestIndex method. There are three
1348 ** table scan strategies to choose from (in order from most to
1349 ** least desirable):
1351 ** idxNum idxStr Strategy
1352 ** ------------------------------------------------
1353 ** 1 Unused Direct lookup by rowid.
1354 ** 2 See below R-tree query or full-table scan.
1355 ** ------------------------------------------------
1357 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1358 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1359 ** constraint used. The first two bytes of idxStr correspond to
1360 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1361 ** (argvIndex==1) etc.
1363 ** The first of each pair of bytes in idxStr identifies the constraint
1364 ** operator as follows:
1366 ** Operator Byte Value
1367 ** ----------------------
1368 ** = 0x41 ('A')
1369 ** <= 0x42 ('B')
1370 ** < 0x43 ('C')
1371 ** >= 0x44 ('D')
1372 ** > 0x45 ('E')
1373 ** MATCH 0x46 ('F')
1374 ** ----------------------
1376 ** The second of each pair of bytes identifies the coordinate column
1377 ** to which the constraint applies. The leftmost coordinate column
1378 ** is 'a', the second from the left 'b' etc.
1380 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1381 int rc = SQLITE_OK;
1382 int ii;
1384 int iIdx = 0;
1385 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
1386 memset(zIdxStr, 0, sizeof(zIdxStr));
1387 UNUSED_PARAMETER(tab);
1389 assert( pIdxInfo->idxStr==0 );
1390 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
1391 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
1393 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
1394 /* We have an equality constraint on the rowid. Use strategy 1. */
1395 int jj;
1396 for(jj=0; jj<ii; jj++){
1397 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
1398 pIdxInfo->aConstraintUsage[jj].omit = 0;
1400 pIdxInfo->idxNum = 1;
1401 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
1402 pIdxInfo->aConstraintUsage[jj].omit = 1;
1404 /* This strategy involves a two rowid lookups on an B-Tree structures
1405 ** and then a linear search of an R-Tree node. This should be
1406 ** considered almost as quick as a direct rowid lookup (for which
1407 ** sqlite uses an internal cost of 0.0).
1409 pIdxInfo->estimatedCost = 10.0;
1410 return SQLITE_OK;
1413 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
1414 u8 op;
1415 switch( p->op ){
1416 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
1417 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
1418 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
1419 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
1420 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
1421 default:
1422 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
1423 op = RTREE_MATCH;
1424 break;
1426 zIdxStr[iIdx++] = op;
1427 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
1428 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
1429 pIdxInfo->aConstraintUsage[ii].omit = 1;
1433 pIdxInfo->idxNum = 2;
1434 pIdxInfo->needToFreeIdxStr = 1;
1435 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
1436 return SQLITE_NOMEM;
1438 assert( iIdx>=0 );
1439 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
1440 return rc;
1444 ** Return the N-dimensional volumn of the cell stored in *p.
1446 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
1447 RtreeDValue area = (RtreeDValue)1;
1448 int ii;
1449 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1450 area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
1452 return area;
1456 ** Return the margin length of cell p. The margin length is the sum
1457 ** of the objects size in each dimension.
1459 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
1460 RtreeDValue margin = (RtreeDValue)0;
1461 int ii;
1462 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1463 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
1465 return margin;
1469 ** Store the union of cells p1 and p2 in p1.
1471 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1472 int ii;
1473 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1474 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1475 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
1476 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
1478 }else{
1479 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1480 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
1481 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
1487 ** Return true if the area covered by p2 is a subset of the area covered
1488 ** by p1. False otherwise.
1490 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1491 int ii;
1492 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
1493 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1494 RtreeCoord *a1 = &p1->aCoord[ii];
1495 RtreeCoord *a2 = &p2->aCoord[ii];
1496 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
1497 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
1499 return 0;
1502 return 1;
1506 ** Return the amount cell p would grow by if it were unioned with pCell.
1508 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
1509 RtreeDValue area;
1510 RtreeCell cell;
1511 memcpy(&cell, p, sizeof(RtreeCell));
1512 area = cellArea(pRtree, &cell);
1513 cellUnion(pRtree, &cell, pCell);
1514 return (cellArea(pRtree, &cell)-area);
1517 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
1518 static RtreeDValue cellOverlap(
1519 Rtree *pRtree,
1520 RtreeCell *p,
1521 RtreeCell *aCell,
1522 int nCell,
1523 int iExclude
1525 int ii;
1526 RtreeDValue overlap = 0.0;
1527 for(ii=0; ii<nCell; ii++){
1528 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1529 if( ii!=iExclude )
1530 #else
1531 assert( iExclude==-1 );
1532 UNUSED_PARAMETER(iExclude);
1533 #endif
1535 int jj;
1536 RtreeDValue o = (RtreeDValue)1;
1537 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
1538 RtreeDValue x1, x2;
1540 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
1541 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
1543 if( x2<x1 ){
1544 o = 0.0;
1545 break;
1546 }else{
1547 o = o * (x2-x1);
1550 overlap += o;
1553 return overlap;
1555 #endif
1557 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1558 static RtreeDValue cellOverlapEnlargement(
1559 Rtree *pRtree,
1560 RtreeCell *p,
1561 RtreeCell *pInsert,
1562 RtreeCell *aCell,
1563 int nCell,
1564 int iExclude
1566 RtreeDValue before, after;
1567 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1568 cellUnion(pRtree, p, pInsert);
1569 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1570 return (after-before);
1572 #endif
1576 ** This function implements the ChooseLeaf algorithm from Gutman[84].
1577 ** ChooseSubTree in r*tree terminology.
1579 static int ChooseLeaf(
1580 Rtree *pRtree, /* Rtree table */
1581 RtreeCell *pCell, /* Cell to insert into rtree */
1582 int iHeight, /* Height of sub-tree rooted at pCell */
1583 RtreeNode **ppLeaf /* OUT: Selected leaf page */
1585 int rc;
1586 int ii;
1587 RtreeNode *pNode;
1588 rc = nodeAcquire(pRtree, 1, 0, &pNode);
1590 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
1591 int iCell;
1592 sqlite3_int64 iBest = 0;
1594 RtreeDValue fMinGrowth = 0.0;
1595 RtreeDValue fMinArea = 0.0;
1596 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1597 RtreeDValue fMinOverlap = 0.0;
1598 RtreeDValue overlap;
1599 #endif
1601 int nCell = NCELL(pNode);
1602 RtreeCell cell;
1603 RtreeNode *pChild;
1605 RtreeCell *aCell = 0;
1607 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1608 if( ii==(pRtree->iDepth-1) ){
1609 int jj;
1610 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
1611 if( !aCell ){
1612 rc = SQLITE_NOMEM;
1613 nodeRelease(pRtree, pNode);
1614 pNode = 0;
1615 continue;
1617 for(jj=0; jj<nCell; jj++){
1618 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
1621 #endif
1623 /* Select the child node which will be enlarged the least if pCell
1624 ** is inserted into it. Resolve ties by choosing the entry with
1625 ** the smallest area.
1627 for(iCell=0; iCell<nCell; iCell++){
1628 int bBest = 0;
1629 RtreeDValue growth;
1630 RtreeDValue area;
1631 nodeGetCell(pRtree, pNode, iCell, &cell);
1632 growth = cellGrowth(pRtree, &cell, pCell);
1633 area = cellArea(pRtree, &cell);
1635 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1636 if( ii==(pRtree->iDepth-1) ){
1637 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
1638 }else{
1639 overlap = 0.0;
1641 if( (iCell==0)
1642 || (overlap<fMinOverlap)
1643 || (overlap==fMinOverlap && growth<fMinGrowth)
1644 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
1646 bBest = 1;
1647 fMinOverlap = overlap;
1649 #else
1650 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
1651 bBest = 1;
1653 #endif
1654 if( bBest ){
1655 fMinGrowth = growth;
1656 fMinArea = area;
1657 iBest = cell.iRowid;
1661 sqlite3_free(aCell);
1662 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
1663 nodeRelease(pRtree, pNode);
1664 pNode = pChild;
1667 *ppLeaf = pNode;
1668 return rc;
1672 ** A cell with the same content as pCell has just been inserted into
1673 ** the node pNode. This function updates the bounding box cells in
1674 ** all ancestor elements.
1676 static int AdjustTree(
1677 Rtree *pRtree, /* Rtree table */
1678 RtreeNode *pNode, /* Adjust ancestry of this node. */
1679 RtreeCell *pCell /* This cell was just inserted */
1681 RtreeNode *p = pNode;
1682 while( p->pParent ){
1683 RtreeNode *pParent = p->pParent;
1684 RtreeCell cell;
1685 int iCell;
1687 if( nodeParentIndex(pRtree, p, &iCell) ){
1688 return SQLITE_CORRUPT_VTAB;
1691 nodeGetCell(pRtree, pParent, iCell, &cell);
1692 if( !cellContains(pRtree, &cell, pCell) ){
1693 cellUnion(pRtree, &cell, pCell);
1694 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
1697 p = pParent;
1699 return SQLITE_OK;
1703 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
1705 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
1706 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
1707 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
1708 sqlite3_step(pRtree->pWriteRowid);
1709 return sqlite3_reset(pRtree->pWriteRowid);
1713 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
1715 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
1716 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
1717 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
1718 sqlite3_step(pRtree->pWriteParent);
1719 return sqlite3_reset(pRtree->pWriteParent);
1722 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
1724 #if VARIANT_GUTTMAN_LINEAR_SPLIT
1726 ** Implementation of the linear variant of the PickNext() function from
1727 ** Guttman[84].
1729 static RtreeCell *LinearPickNext(
1730 Rtree *pRtree,
1731 RtreeCell *aCell,
1732 int nCell,
1733 RtreeCell *pLeftBox,
1734 RtreeCell *pRightBox,
1735 int *aiUsed
1737 int ii;
1738 for(ii=0; aiUsed[ii]; ii++);
1739 aiUsed[ii] = 1;
1740 return &aCell[ii];
1744 ** Implementation of the linear variant of the PickSeeds() function from
1745 ** Guttman[84].
1747 static void LinearPickSeeds(
1748 Rtree *pRtree,
1749 RtreeCell *aCell,
1750 int nCell,
1751 int *piLeftSeed,
1752 int *piRightSeed
1754 int i;
1755 int iLeftSeed = 0;
1756 int iRightSeed = 1;
1757 RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
1759 /* Pick two "seed" cells from the array of cells. The algorithm used
1760 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
1761 ** indices of the two seed cells in the array are stored in local
1762 ** variables iLeftSeek and iRightSeed.
1764 for(i=0; i<pRtree->nDim; i++){
1765 RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
1766 RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
1767 RtreeDValue x3 = x1;
1768 RtreeDValue x4 = x2;
1769 int jj;
1771 int iCellLeft = 0;
1772 int iCellRight = 0;
1774 for(jj=1; jj<nCell; jj++){
1775 RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
1776 RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
1778 if( left<x1 ) x1 = left;
1779 if( right>x4 ) x4 = right;
1780 if( left>x3 ){
1781 x3 = left;
1782 iCellRight = jj;
1784 if( right<x2 ){
1785 x2 = right;
1786 iCellLeft = jj;
1790 if( x4!=x1 ){
1791 RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
1792 if( normalwidth>maxNormalInnerWidth ){
1793 iLeftSeed = iCellLeft;
1794 iRightSeed = iCellRight;
1799 *piLeftSeed = iLeftSeed;
1800 *piRightSeed = iRightSeed;
1802 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
1804 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
1806 ** Implementation of the quadratic variant of the PickNext() function from
1807 ** Guttman[84].
1809 static RtreeCell *QuadraticPickNext(
1810 Rtree *pRtree,
1811 RtreeCell *aCell,
1812 int nCell,
1813 RtreeCell *pLeftBox,
1814 RtreeCell *pRightBox,
1815 int *aiUsed
1817 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
1819 int iSelect = -1;
1820 RtreeDValue fDiff;
1821 int ii;
1822 for(ii=0; ii<nCell; ii++){
1823 if( aiUsed[ii]==0 ){
1824 RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1825 RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1826 RtreeDValue diff = FABS(right-left);
1827 if( iSelect<0 || diff>fDiff ){
1828 fDiff = diff;
1829 iSelect = ii;
1833 aiUsed[iSelect] = 1;
1834 return &aCell[iSelect];
1838 ** Implementation of the quadratic variant of the PickSeeds() function from
1839 ** Guttman[84].
1841 static void QuadraticPickSeeds(
1842 Rtree *pRtree,
1843 RtreeCell *aCell,
1844 int nCell,
1845 int *piLeftSeed,
1846 int *piRightSeed
1848 int ii;
1849 int jj;
1851 int iLeftSeed = 0;
1852 int iRightSeed = 1;
1853 RtreeDValue fWaste = 0.0;
1855 for(ii=0; ii<nCell; ii++){
1856 for(jj=ii+1; jj<nCell; jj++){
1857 RtreeDValue right = cellArea(pRtree, &aCell[jj]);
1858 RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
1859 RtreeDValue waste = growth - right;
1861 if( waste>fWaste ){
1862 iLeftSeed = ii;
1863 iRightSeed = jj;
1864 fWaste = waste;
1869 *piLeftSeed = iLeftSeed;
1870 *piRightSeed = iRightSeed;
1872 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
1875 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
1876 ** nIdx. The aIdx array contains the set of integers from 0 to
1877 ** (nIdx-1) in no particular order. This function sorts the values
1878 ** in aIdx according to the indexed values in aDistance. For
1879 ** example, assuming the inputs:
1881 ** aIdx = { 0, 1, 2, 3 }
1882 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
1884 ** this function sets the aIdx array to contain:
1886 ** aIdx = { 0, 1, 2, 3 }
1888 ** The aSpare array is used as temporary working space by the
1889 ** sorting algorithm.
1891 static void SortByDistance(
1892 int *aIdx,
1893 int nIdx,
1894 RtreeDValue *aDistance,
1895 int *aSpare
1897 if( nIdx>1 ){
1898 int iLeft = 0;
1899 int iRight = 0;
1901 int nLeft = nIdx/2;
1902 int nRight = nIdx-nLeft;
1903 int *aLeft = aIdx;
1904 int *aRight = &aIdx[nLeft];
1906 SortByDistance(aLeft, nLeft, aDistance, aSpare);
1907 SortByDistance(aRight, nRight, aDistance, aSpare);
1909 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1910 aLeft = aSpare;
1912 while( iLeft<nLeft || iRight<nRight ){
1913 if( iLeft==nLeft ){
1914 aIdx[iLeft+iRight] = aRight[iRight];
1915 iRight++;
1916 }else if( iRight==nRight ){
1917 aIdx[iLeft+iRight] = aLeft[iLeft];
1918 iLeft++;
1919 }else{
1920 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
1921 RtreeDValue fRight = aDistance[aRight[iRight]];
1922 if( fLeft<fRight ){
1923 aIdx[iLeft+iRight] = aLeft[iLeft];
1924 iLeft++;
1925 }else{
1926 aIdx[iLeft+iRight] = aRight[iRight];
1927 iRight++;
1932 #if 0
1933 /* Check that the sort worked */
1935 int jj;
1936 for(jj=1; jj<nIdx; jj++){
1937 RtreeDValue left = aDistance[aIdx[jj-1]];
1938 RtreeDValue right = aDistance[aIdx[jj]];
1939 assert( left<=right );
1942 #endif
1947 ** Arguments aIdx, aCell and aSpare all point to arrays of size
1948 ** nIdx. The aIdx array contains the set of integers from 0 to
1949 ** (nIdx-1) in no particular order. This function sorts the values
1950 ** in aIdx according to dimension iDim of the cells in aCell. The
1951 ** minimum value of dimension iDim is considered first, the
1952 ** maximum used to break ties.
1954 ** The aSpare array is used as temporary working space by the
1955 ** sorting algorithm.
1957 static void SortByDimension(
1958 Rtree *pRtree,
1959 int *aIdx,
1960 int nIdx,
1961 int iDim,
1962 RtreeCell *aCell,
1963 int *aSpare
1965 if( nIdx>1 ){
1967 int iLeft = 0;
1968 int iRight = 0;
1970 int nLeft = nIdx/2;
1971 int nRight = nIdx-nLeft;
1972 int *aLeft = aIdx;
1973 int *aRight = &aIdx[nLeft];
1975 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
1976 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
1978 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1979 aLeft = aSpare;
1980 while( iLeft<nLeft || iRight<nRight ){
1981 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
1982 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
1983 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
1984 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
1985 if( (iLeft!=nLeft) && ((iRight==nRight)
1986 || (xleft1<xright1)
1987 || (xleft1==xright1 && xleft2<xright2)
1989 aIdx[iLeft+iRight] = aLeft[iLeft];
1990 iLeft++;
1991 }else{
1992 aIdx[iLeft+iRight] = aRight[iRight];
1993 iRight++;
1997 #if 0
1998 /* Check that the sort worked */
2000 int jj;
2001 for(jj=1; jj<nIdx; jj++){
2002 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2003 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2004 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2005 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2006 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2009 #endif
2013 #if VARIANT_RSTARTREE_SPLIT
2015 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2017 static int splitNodeStartree(
2018 Rtree *pRtree,
2019 RtreeCell *aCell,
2020 int nCell,
2021 RtreeNode *pLeft,
2022 RtreeNode *pRight,
2023 RtreeCell *pBboxLeft,
2024 RtreeCell *pBboxRight
2026 int **aaSorted;
2027 int *aSpare;
2028 int ii;
2030 int iBestDim = 0;
2031 int iBestSplit = 0;
2032 RtreeDValue fBestMargin = 0.0;
2034 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2036 aaSorted = (int **)sqlite3_malloc(nByte);
2037 if( !aaSorted ){
2038 return SQLITE_NOMEM;
2041 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2042 memset(aaSorted, 0, nByte);
2043 for(ii=0; ii<pRtree->nDim; ii++){
2044 int jj;
2045 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2046 for(jj=0; jj<nCell; jj++){
2047 aaSorted[ii][jj] = jj;
2049 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2052 for(ii=0; ii<pRtree->nDim; ii++){
2053 RtreeDValue margin = 0.0;
2054 RtreeDValue fBestOverlap = 0.0;
2055 RtreeDValue fBestArea = 0.0;
2056 int iBestLeft = 0;
2057 int nLeft;
2059 for(
2060 nLeft=RTREE_MINCELLS(pRtree);
2061 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2062 nLeft++
2064 RtreeCell left;
2065 RtreeCell right;
2066 int kk;
2067 RtreeDValue overlap;
2068 RtreeDValue area;
2070 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2071 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2072 for(kk=1; kk<(nCell-1); kk++){
2073 if( kk<nLeft ){
2074 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2075 }else{
2076 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2079 margin += cellMargin(pRtree, &left);
2080 margin += cellMargin(pRtree, &right);
2081 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
2082 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2083 if( (nLeft==RTREE_MINCELLS(pRtree))
2084 || (overlap<fBestOverlap)
2085 || (overlap==fBestOverlap && area<fBestArea)
2087 iBestLeft = nLeft;
2088 fBestOverlap = overlap;
2089 fBestArea = area;
2093 if( ii==0 || margin<fBestMargin ){
2094 iBestDim = ii;
2095 fBestMargin = margin;
2096 iBestSplit = iBestLeft;
2100 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2101 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2102 for(ii=0; ii<nCell; ii++){
2103 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2104 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2105 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2106 nodeInsertCell(pRtree, pTarget, pCell);
2107 cellUnion(pRtree, pBbox, pCell);
2110 sqlite3_free(aaSorted);
2111 return SQLITE_OK;
2113 #endif
2115 #if VARIANT_GUTTMAN_SPLIT
2117 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
2119 static int splitNodeGuttman(
2120 Rtree *pRtree,
2121 RtreeCell *aCell,
2122 int nCell,
2123 RtreeNode *pLeft,
2124 RtreeNode *pRight,
2125 RtreeCell *pBboxLeft,
2126 RtreeCell *pBboxRight
2128 int iLeftSeed = 0;
2129 int iRightSeed = 1;
2130 int *aiUsed;
2131 int i;
2133 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
2134 if( !aiUsed ){
2135 return SQLITE_NOMEM;
2137 memset(aiUsed, 0, sizeof(int)*nCell);
2139 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
2141 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
2142 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
2143 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
2144 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
2145 aiUsed[iLeftSeed] = 1;
2146 aiUsed[iRightSeed] = 1;
2148 for(i=nCell-2; i>0; i--){
2149 RtreeCell *pNext;
2150 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
2151 RtreeDValue diff =
2152 cellGrowth(pRtree, pBboxLeft, pNext) -
2153 cellGrowth(pRtree, pBboxRight, pNext)
2155 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
2156 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
2158 nodeInsertCell(pRtree, pRight, pNext);
2159 cellUnion(pRtree, pBboxRight, pNext);
2160 }else{
2161 nodeInsertCell(pRtree, pLeft, pNext);
2162 cellUnion(pRtree, pBboxLeft, pNext);
2166 sqlite3_free(aiUsed);
2167 return SQLITE_OK;
2169 #endif
2171 static int updateMapping(
2172 Rtree *pRtree,
2173 i64 iRowid,
2174 RtreeNode *pNode,
2175 int iHeight
2177 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2178 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2179 if( iHeight>0 ){
2180 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2181 if( pChild ){
2182 nodeRelease(pRtree, pChild->pParent);
2183 nodeReference(pNode);
2184 pChild->pParent = pNode;
2187 return xSetMapping(pRtree, iRowid, pNode->iNode);
2190 static int SplitNode(
2191 Rtree *pRtree,
2192 RtreeNode *pNode,
2193 RtreeCell *pCell,
2194 int iHeight
2196 int i;
2197 int newCellIsRight = 0;
2199 int rc = SQLITE_OK;
2200 int nCell = NCELL(pNode);
2201 RtreeCell *aCell;
2202 int *aiUsed;
2204 RtreeNode *pLeft = 0;
2205 RtreeNode *pRight = 0;
2207 RtreeCell leftbbox;
2208 RtreeCell rightbbox;
2210 /* Allocate an array and populate it with a copy of pCell and
2211 ** all cells from node pLeft. Then zero the original node.
2213 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2214 if( !aCell ){
2215 rc = SQLITE_NOMEM;
2216 goto splitnode_out;
2218 aiUsed = (int *)&aCell[nCell+1];
2219 memset(aiUsed, 0, sizeof(int)*(nCell+1));
2220 for(i=0; i<nCell; i++){
2221 nodeGetCell(pRtree, pNode, i, &aCell[i]);
2223 nodeZero(pRtree, pNode);
2224 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2225 nCell++;
2227 if( pNode->iNode==1 ){
2228 pRight = nodeNew(pRtree, pNode);
2229 pLeft = nodeNew(pRtree, pNode);
2230 pRtree->iDepth++;
2231 pNode->isDirty = 1;
2232 writeInt16(pNode->zData, pRtree->iDepth);
2233 }else{
2234 pLeft = pNode;
2235 pRight = nodeNew(pRtree, pLeft->pParent);
2236 nodeReference(pLeft);
2239 if( !pLeft || !pRight ){
2240 rc = SQLITE_NOMEM;
2241 goto splitnode_out;
2244 memset(pLeft->zData, 0, pRtree->iNodeSize);
2245 memset(pRight->zData, 0, pRtree->iNodeSize);
2247 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
2248 if( rc!=SQLITE_OK ){
2249 goto splitnode_out;
2252 /* Ensure both child nodes have node numbers assigned to them by calling
2253 ** nodeWrite(). Node pRight always needs a node number, as it was created
2254 ** by nodeNew() above. But node pLeft sometimes already has a node number.
2255 ** In this case avoid the all to nodeWrite().
2257 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2258 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2260 goto splitnode_out;
2263 rightbbox.iRowid = pRight->iNode;
2264 leftbbox.iRowid = pLeft->iNode;
2266 if( pNode->iNode==1 ){
2267 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2268 if( rc!=SQLITE_OK ){
2269 goto splitnode_out;
2271 }else{
2272 RtreeNode *pParent = pLeft->pParent;
2273 int iCell;
2274 rc = nodeParentIndex(pRtree, pLeft, &iCell);
2275 if( rc==SQLITE_OK ){
2276 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2277 rc = AdjustTree(pRtree, pParent, &leftbbox);
2279 if( rc!=SQLITE_OK ){
2280 goto splitnode_out;
2283 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2284 goto splitnode_out;
2287 for(i=0; i<NCELL(pRight); i++){
2288 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2289 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2290 if( iRowid==pCell->iRowid ){
2291 newCellIsRight = 1;
2293 if( rc!=SQLITE_OK ){
2294 goto splitnode_out;
2297 if( pNode->iNode==1 ){
2298 for(i=0; i<NCELL(pLeft); i++){
2299 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2300 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2301 if( rc!=SQLITE_OK ){
2302 goto splitnode_out;
2305 }else if( newCellIsRight==0 ){
2306 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2309 if( rc==SQLITE_OK ){
2310 rc = nodeRelease(pRtree, pRight);
2311 pRight = 0;
2313 if( rc==SQLITE_OK ){
2314 rc = nodeRelease(pRtree, pLeft);
2315 pLeft = 0;
2318 splitnode_out:
2319 nodeRelease(pRtree, pRight);
2320 nodeRelease(pRtree, pLeft);
2321 sqlite3_free(aCell);
2322 return rc;
2326 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2327 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2328 ** the pLeaf->pParent chain all the way up to the root node.
2330 ** This operation is required when a row is deleted (or updated - an update
2331 ** is implemented as a delete followed by an insert). SQLite provides the
2332 ** rowid of the row to delete, which can be used to find the leaf on which
2333 ** the entry resides (argument pLeaf). Once the leaf is located, this
2334 ** function is called to determine its ancestry.
2336 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2337 int rc = SQLITE_OK;
2338 RtreeNode *pChild = pLeaf;
2339 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2340 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
2341 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2342 rc = sqlite3_step(pRtree->pReadParent);
2343 if( rc==SQLITE_ROW ){
2344 RtreeNode *pTest; /* Used to test for reference loops */
2345 i64 iNode; /* Node number of parent node */
2347 /* Before setting pChild->pParent, test that we are not creating a
2348 ** loop of references (as we would if, say, pChild==pParent). We don't
2349 ** want to do this as it leads to a memory leak when trying to delete
2350 ** the referenced counted node structures.
2352 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2353 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2354 if( !pTest ){
2355 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2358 rc = sqlite3_reset(pRtree->pReadParent);
2359 if( rc==SQLITE_OK ) rc = rc2;
2360 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
2361 pChild = pChild->pParent;
2363 return rc;
2366 static int deleteCell(Rtree *, RtreeNode *, int, int);
2368 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2369 int rc;
2370 int rc2;
2371 RtreeNode *pParent = 0;
2372 int iCell;
2374 assert( pNode->nRef==1 );
2376 /* Remove the entry in the parent cell. */
2377 rc = nodeParentIndex(pRtree, pNode, &iCell);
2378 if( rc==SQLITE_OK ){
2379 pParent = pNode->pParent;
2380 pNode->pParent = 0;
2381 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2383 rc2 = nodeRelease(pRtree, pParent);
2384 if( rc==SQLITE_OK ){
2385 rc = rc2;
2387 if( rc!=SQLITE_OK ){
2388 return rc;
2391 /* Remove the xxx_node entry. */
2392 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2393 sqlite3_step(pRtree->pDeleteNode);
2394 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2395 return rc;
2398 /* Remove the xxx_parent entry. */
2399 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2400 sqlite3_step(pRtree->pDeleteParent);
2401 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2402 return rc;
2405 /* Remove the node from the in-memory hash table and link it into
2406 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2408 nodeHashDelete(pRtree, pNode);
2409 pNode->iNode = iHeight;
2410 pNode->pNext = pRtree->pDeleted;
2411 pNode->nRef++;
2412 pRtree->pDeleted = pNode;
2414 return SQLITE_OK;
2417 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2418 RtreeNode *pParent = pNode->pParent;
2419 int rc = SQLITE_OK;
2420 if( pParent ){
2421 int ii;
2422 int nCell = NCELL(pNode);
2423 RtreeCell box; /* Bounding box for pNode */
2424 nodeGetCell(pRtree, pNode, 0, &box);
2425 for(ii=1; ii<nCell; ii++){
2426 RtreeCell cell;
2427 nodeGetCell(pRtree, pNode, ii, &cell);
2428 cellUnion(pRtree, &box, &cell);
2430 box.iRowid = pNode->iNode;
2431 rc = nodeParentIndex(pRtree, pNode, &ii);
2432 if( rc==SQLITE_OK ){
2433 nodeOverwriteCell(pRtree, pParent, &box, ii);
2434 rc = fixBoundingBox(pRtree, pParent);
2437 return rc;
2441 ** Delete the cell at index iCell of node pNode. After removing the
2442 ** cell, adjust the r-tree data structure if required.
2444 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2445 RtreeNode *pParent;
2446 int rc;
2448 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2449 return rc;
2452 /* Remove the cell from the node. This call just moves bytes around
2453 ** the in-memory node image, so it cannot fail.
2455 nodeDeleteCell(pRtree, pNode, iCell);
2457 /* If the node is not the tree root and now has less than the minimum
2458 ** number of cells, remove it from the tree. Otherwise, update the
2459 ** cell in the parent node so that it tightly contains the updated
2460 ** node.
2462 pParent = pNode->pParent;
2463 assert( pParent || pNode->iNode==1 );
2464 if( pParent ){
2465 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2466 rc = removeNode(pRtree, pNode, iHeight);
2467 }else{
2468 rc = fixBoundingBox(pRtree, pNode);
2472 return rc;
2475 static int Reinsert(
2476 Rtree *pRtree,
2477 RtreeNode *pNode,
2478 RtreeCell *pCell,
2479 int iHeight
2481 int *aOrder;
2482 int *aSpare;
2483 RtreeCell *aCell;
2484 RtreeDValue *aDistance;
2485 int nCell;
2486 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
2487 int iDim;
2488 int ii;
2489 int rc = SQLITE_OK;
2490 int n;
2492 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
2494 nCell = NCELL(pNode)+1;
2495 n = (nCell+1)&(~1);
2497 /* Allocate the buffers used by this operation. The allocation is
2498 ** relinquished before this function returns.
2500 aCell = (RtreeCell *)sqlite3_malloc(n * (
2501 sizeof(RtreeCell) + /* aCell array */
2502 sizeof(int) + /* aOrder array */
2503 sizeof(int) + /* aSpare array */
2504 sizeof(RtreeDValue) /* aDistance array */
2506 if( !aCell ){
2507 return SQLITE_NOMEM;
2509 aOrder = (int *)&aCell[n];
2510 aSpare = (int *)&aOrder[n];
2511 aDistance = (RtreeDValue *)&aSpare[n];
2513 for(ii=0; ii<nCell; ii++){
2514 if( ii==(nCell-1) ){
2515 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2516 }else{
2517 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2519 aOrder[ii] = ii;
2520 for(iDim=0; iDim<pRtree->nDim; iDim++){
2521 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2522 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2525 for(iDim=0; iDim<pRtree->nDim; iDim++){
2526 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
2529 for(ii=0; ii<nCell; ii++){
2530 aDistance[ii] = 0.0;
2531 for(iDim=0; iDim<pRtree->nDim; iDim++){
2532 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
2533 DCOORD(aCell[ii].aCoord[iDim*2]));
2534 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2538 SortByDistance(aOrder, nCell, aDistance, aSpare);
2539 nodeZero(pRtree, pNode);
2541 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2542 RtreeCell *p = &aCell[aOrder[ii]];
2543 nodeInsertCell(pRtree, pNode, p);
2544 if( p->iRowid==pCell->iRowid ){
2545 if( iHeight==0 ){
2546 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2547 }else{
2548 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2552 if( rc==SQLITE_OK ){
2553 rc = fixBoundingBox(pRtree, pNode);
2555 for(; rc==SQLITE_OK && ii<nCell; ii++){
2556 /* Find a node to store this cell in. pNode->iNode currently contains
2557 ** the height of the sub-tree headed by the cell.
2559 RtreeNode *pInsert;
2560 RtreeCell *p = &aCell[aOrder[ii]];
2561 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2562 if( rc==SQLITE_OK ){
2563 int rc2;
2564 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2565 rc2 = nodeRelease(pRtree, pInsert);
2566 if( rc==SQLITE_OK ){
2567 rc = rc2;
2572 sqlite3_free(aCell);
2573 return rc;
2577 ** Insert cell pCell into node pNode. Node pNode is the head of a
2578 ** subtree iHeight high (leaf nodes have iHeight==0).
2580 static int rtreeInsertCell(
2581 Rtree *pRtree,
2582 RtreeNode *pNode,
2583 RtreeCell *pCell,
2584 int iHeight
2586 int rc = SQLITE_OK;
2587 if( iHeight>0 ){
2588 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2589 if( pChild ){
2590 nodeRelease(pRtree, pChild->pParent);
2591 nodeReference(pNode);
2592 pChild->pParent = pNode;
2595 if( nodeInsertCell(pRtree, pNode, pCell) ){
2596 #if VARIANT_RSTARTREE_REINSERT
2597 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
2598 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2599 }else{
2600 pRtree->iReinsertHeight = iHeight;
2601 rc = Reinsert(pRtree, pNode, pCell, iHeight);
2603 #else
2604 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2605 #endif
2606 }else{
2607 rc = AdjustTree(pRtree, pNode, pCell);
2608 if( rc==SQLITE_OK ){
2609 if( iHeight==0 ){
2610 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
2611 }else{
2612 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
2616 return rc;
2619 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
2620 int ii;
2621 int rc = SQLITE_OK;
2622 int nCell = NCELL(pNode);
2624 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
2625 RtreeNode *pInsert;
2626 RtreeCell cell;
2627 nodeGetCell(pRtree, pNode, ii, &cell);
2629 /* Find a node to store this cell in. pNode->iNode currently contains
2630 ** the height of the sub-tree headed by the cell.
2632 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
2633 if( rc==SQLITE_OK ){
2634 int rc2;
2635 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
2636 rc2 = nodeRelease(pRtree, pInsert);
2637 if( rc==SQLITE_OK ){
2638 rc = rc2;
2642 return rc;
2646 ** Select a currently unused rowid for a new r-tree record.
2648 static int newRowid(Rtree *pRtree, i64 *piRowid){
2649 int rc;
2650 sqlite3_bind_null(pRtree->pWriteRowid, 1);
2651 sqlite3_bind_null(pRtree->pWriteRowid, 2);
2652 sqlite3_step(pRtree->pWriteRowid);
2653 rc = sqlite3_reset(pRtree->pWriteRowid);
2654 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
2655 return rc;
2659 ** Remove the entry with rowid=iDelete from the r-tree structure.
2661 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
2662 int rc; /* Return code */
2663 RtreeNode *pLeaf; /* Leaf node containing record iDelete */
2664 int iCell; /* Index of iDelete cell in pLeaf */
2665 RtreeNode *pRoot; /* Root node of rtree structure */
2668 /* Obtain a reference to the root node to initialise Rtree.iDepth */
2669 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
2671 /* Obtain a reference to the leaf node that contains the entry
2672 ** about to be deleted.
2674 if( rc==SQLITE_OK ){
2675 rc = findLeafNode(pRtree, iDelete, &pLeaf);
2678 /* Delete the cell in question from the leaf node. */
2679 if( rc==SQLITE_OK ){
2680 int rc2;
2681 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
2682 if( rc==SQLITE_OK ){
2683 rc = deleteCell(pRtree, pLeaf, iCell, 0);
2685 rc2 = nodeRelease(pRtree, pLeaf);
2686 if( rc==SQLITE_OK ){
2687 rc = rc2;
2691 /* Delete the corresponding entry in the <rtree>_rowid table. */
2692 if( rc==SQLITE_OK ){
2693 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
2694 sqlite3_step(pRtree->pDeleteRowid);
2695 rc = sqlite3_reset(pRtree->pDeleteRowid);
2698 /* Check if the root node now has exactly one child. If so, remove
2699 ** it, schedule the contents of the child for reinsertion and
2700 ** reduce the tree height by one.
2702 ** This is equivalent to copying the contents of the child into
2703 ** the root node (the operation that Gutman's paper says to perform
2704 ** in this scenario).
2706 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
2707 int rc2;
2708 RtreeNode *pChild;
2709 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
2710 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
2711 if( rc==SQLITE_OK ){
2712 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
2714 rc2 = nodeRelease(pRtree, pChild);
2715 if( rc==SQLITE_OK ) rc = rc2;
2716 if( rc==SQLITE_OK ){
2717 pRtree->iDepth--;
2718 writeInt16(pRoot->zData, pRtree->iDepth);
2719 pRoot->isDirty = 1;
2723 /* Re-insert the contents of any underfull nodes removed from the tree. */
2724 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
2725 if( rc==SQLITE_OK ){
2726 rc = reinsertNodeContent(pRtree, pLeaf);
2728 pRtree->pDeleted = pLeaf->pNext;
2729 sqlite3_free(pLeaf);
2732 /* Release the reference to the root node. */
2733 if( rc==SQLITE_OK ){
2734 rc = nodeRelease(pRtree, pRoot);
2735 }else{
2736 nodeRelease(pRtree, pRoot);
2739 return rc;
2743 ** Rounding constants for float->double conversion.
2745 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
2746 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
2748 #if !defined(SQLITE_RTREE_INT_ONLY)
2750 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
2751 ** while taking care to round toward negative or positive, respectively.
2753 static RtreeValue rtreeValueDown(sqlite3_value *v){
2754 double d = sqlite3_value_double(v);
2755 float f = (float)d;
2756 if( f>d ){
2757 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
2759 return f;
2761 static RtreeValue rtreeValueUp(sqlite3_value *v){
2762 double d = sqlite3_value_double(v);
2763 float f = (float)d;
2764 if( f<d ){
2765 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
2767 return f;
2769 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
2773 ** The xUpdate method for rtree module virtual tables.
2775 static int rtreeUpdate(
2776 sqlite3_vtab *pVtab,
2777 int nData,
2778 sqlite3_value **azData,
2779 sqlite_int64 *pRowid
2781 Rtree *pRtree = (Rtree *)pVtab;
2782 int rc = SQLITE_OK;
2783 RtreeCell cell; /* New cell to insert if nData>1 */
2784 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
2786 rtreeReference(pRtree);
2787 assert(nData>=1);
2789 /* Constraint handling. A write operation on an r-tree table may return
2790 ** SQLITE_CONSTRAINT for two reasons:
2792 ** 1. A duplicate rowid value, or
2793 ** 2. The supplied data violates the "x2>=x1" constraint.
2795 ** In the first case, if the conflict-handling mode is REPLACE, then
2796 ** the conflicting row can be removed before proceeding. In the second
2797 ** case, SQLITE_CONSTRAINT must be returned regardless of the
2798 ** conflict-handling mode specified by the user.
2800 if( nData>1 ){
2801 int ii;
2803 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
2804 assert( nData==(pRtree->nDim*2 + 3) );
2805 #ifndef SQLITE_RTREE_INT_ONLY
2806 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2807 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
2808 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
2809 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
2810 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
2811 rc = SQLITE_CONSTRAINT;
2812 goto constraint;
2815 }else
2816 #endif
2818 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
2819 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
2820 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
2821 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
2822 rc = SQLITE_CONSTRAINT;
2823 goto constraint;
2828 /* If a rowid value was supplied, check if it is already present in
2829 ** the table. If so, the constraint has failed. */
2830 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
2831 cell.iRowid = sqlite3_value_int64(azData[2]);
2832 if( sqlite3_value_type(azData[0])==SQLITE_NULL
2833 || sqlite3_value_int64(azData[0])!=cell.iRowid
2835 int steprc;
2836 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
2837 steprc = sqlite3_step(pRtree->pReadRowid);
2838 rc = sqlite3_reset(pRtree->pReadRowid);
2839 if( SQLITE_ROW==steprc ){
2840 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
2841 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
2842 }else{
2843 rc = SQLITE_CONSTRAINT;
2844 goto constraint;
2848 bHaveRowid = 1;
2852 /* If azData[0] is not an SQL NULL value, it is the rowid of a
2853 ** record to delete from the r-tree table. The following block does
2854 ** just that.
2856 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
2857 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
2860 /* If the azData[] array contains more than one element, elements
2861 ** (azData[2]..azData[argc-1]) contain a new record to insert into
2862 ** the r-tree structure.
2864 if( rc==SQLITE_OK && nData>1 ){
2865 /* Insert the new record into the r-tree */
2866 RtreeNode *pLeaf;
2868 /* Figure out the rowid of the new row. */
2869 if( bHaveRowid==0 ){
2870 rc = newRowid(pRtree, &cell.iRowid);
2872 *pRowid = cell.iRowid;
2874 if( rc==SQLITE_OK ){
2875 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
2877 if( rc==SQLITE_OK ){
2878 int rc2;
2879 pRtree->iReinsertHeight = -1;
2880 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
2881 rc2 = nodeRelease(pRtree, pLeaf);
2882 if( rc==SQLITE_OK ){
2883 rc = rc2;
2888 constraint:
2889 rtreeRelease(pRtree);
2890 return rc;
2894 ** The xRename method for rtree module virtual tables.
2896 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
2897 Rtree *pRtree = (Rtree *)pVtab;
2898 int rc = SQLITE_NOMEM;
2899 char *zSql = sqlite3_mprintf(
2900 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
2901 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
2902 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
2903 , pRtree->zDb, pRtree->zName, zNewName
2904 , pRtree->zDb, pRtree->zName, zNewName
2905 , pRtree->zDb, pRtree->zName, zNewName
2907 if( zSql ){
2908 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
2909 sqlite3_free(zSql);
2911 return rc;
2914 static sqlite3_module rtreeModule = {
2915 0, /* iVersion */
2916 rtreeCreate, /* xCreate - create a table */
2917 rtreeConnect, /* xConnect - connect to an existing table */
2918 rtreeBestIndex, /* xBestIndex - Determine search strategy */
2919 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
2920 rtreeDestroy, /* xDestroy - Drop a table */
2921 rtreeOpen, /* xOpen - open a cursor */
2922 rtreeClose, /* xClose - close a cursor */
2923 rtreeFilter, /* xFilter - configure scan constraints */
2924 rtreeNext, /* xNext - advance a cursor */
2925 rtreeEof, /* xEof */
2926 rtreeColumn, /* xColumn - read data */
2927 rtreeRowid, /* xRowid - read data */
2928 rtreeUpdate, /* xUpdate - write data */
2929 0, /* xBegin - begin transaction */
2930 0, /* xSync - sync transaction */
2931 0, /* xCommit - commit transaction */
2932 0, /* xRollback - rollback transaction */
2933 0, /* xFindFunction - function overloading */
2934 rtreeRename, /* xRename - rename the table */
2935 0, /* xSavepoint */
2936 0, /* xRelease */
2937 0 /* xRollbackTo */
2940 static int rtreeSqlInit(
2941 Rtree *pRtree,
2942 sqlite3 *db,
2943 const char *zDb,
2944 const char *zPrefix,
2945 int isCreate
2947 int rc = SQLITE_OK;
2949 #define N_STATEMENT 9
2950 static const char *azSql[N_STATEMENT] = {
2951 /* Read and write the xxx_node table */
2952 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
2953 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
2954 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
2956 /* Read and write the xxx_rowid table */
2957 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
2958 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
2959 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
2961 /* Read and write the xxx_parent table */
2962 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
2963 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
2964 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
2966 sqlite3_stmt **appStmt[N_STATEMENT];
2967 int i;
2969 pRtree->db = db;
2971 if( isCreate ){
2972 char *zCreate = sqlite3_mprintf(
2973 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
2974 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
2975 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
2976 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
2977 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
2979 if( !zCreate ){
2980 return SQLITE_NOMEM;
2982 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
2983 sqlite3_free(zCreate);
2984 if( rc!=SQLITE_OK ){
2985 return rc;
2989 appStmt[0] = &pRtree->pReadNode;
2990 appStmt[1] = &pRtree->pWriteNode;
2991 appStmt[2] = &pRtree->pDeleteNode;
2992 appStmt[3] = &pRtree->pReadRowid;
2993 appStmt[4] = &pRtree->pWriteRowid;
2994 appStmt[5] = &pRtree->pDeleteRowid;
2995 appStmt[6] = &pRtree->pReadParent;
2996 appStmt[7] = &pRtree->pWriteParent;
2997 appStmt[8] = &pRtree->pDeleteParent;
2999 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
3000 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
3001 if( zSql ){
3002 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
3003 }else{
3004 rc = SQLITE_NOMEM;
3006 sqlite3_free(zSql);
3009 return rc;
3013 ** The second argument to this function contains the text of an SQL statement
3014 ** that returns a single integer value. The statement is compiled and executed
3015 ** using database connection db. If successful, the integer value returned
3016 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
3017 ** code is returned and the value of *piVal after returning is not defined.
3019 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
3020 int rc = SQLITE_NOMEM;
3021 if( zSql ){
3022 sqlite3_stmt *pStmt = 0;
3023 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3024 if( rc==SQLITE_OK ){
3025 if( SQLITE_ROW==sqlite3_step(pStmt) ){
3026 *piVal = sqlite3_column_int(pStmt, 0);
3028 rc = sqlite3_finalize(pStmt);
3031 return rc;
3035 ** This function is called from within the xConnect() or xCreate() method to
3036 ** determine the node-size used by the rtree table being created or connected
3037 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
3038 ** Otherwise, an SQLite error code is returned.
3040 ** If this function is being called as part of an xConnect(), then the rtree
3041 ** table already exists. In this case the node-size is determined by inspecting
3042 ** the root node of the tree.
3044 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
3045 ** This ensures that each node is stored on a single database page. If the
3046 ** database page-size is so large that more than RTREE_MAXCELLS entries
3047 ** would fit in a single node, use a smaller node-size.
3049 static int getNodeSize(
3050 sqlite3 *db, /* Database handle */
3051 Rtree *pRtree, /* Rtree handle */
3052 int isCreate /* True for xCreate, false for xConnect */
3054 int rc;
3055 char *zSql;
3056 if( isCreate ){
3057 int iPageSize = 0;
3058 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
3059 rc = getIntFromStmt(db, zSql, &iPageSize);
3060 if( rc==SQLITE_OK ){
3061 pRtree->iNodeSize = iPageSize-64;
3062 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
3063 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
3066 }else{
3067 zSql = sqlite3_mprintf(
3068 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
3069 pRtree->zDb, pRtree->zName
3071 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
3074 sqlite3_free(zSql);
3075 return rc;
3079 ** This function is the implementation of both the xConnect and xCreate
3080 ** methods of the r-tree virtual table.
3082 ** argv[0] -> module name
3083 ** argv[1] -> database name
3084 ** argv[2] -> table name
3085 ** argv[...] -> column names...
3087 static int rtreeInit(
3088 sqlite3 *db, /* Database connection */
3089 void *pAux, /* One of the RTREE_COORD_* constants */
3090 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
3091 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
3092 char **pzErr, /* OUT: Error message, if any */
3093 int isCreate /* True for xCreate, false for xConnect */
3095 int rc = SQLITE_OK;
3096 Rtree *pRtree;
3097 int nDb; /* Length of string argv[1] */
3098 int nName; /* Length of string argv[2] */
3099 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
3101 const char *aErrMsg[] = {
3102 0, /* 0 */
3103 "Wrong number of columns for an rtree table", /* 1 */
3104 "Too few columns for an rtree table", /* 2 */
3105 "Too many columns for an rtree table" /* 3 */
3108 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
3109 if( aErrMsg[iErr] ){
3110 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3111 return SQLITE_ERROR;
3114 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
3116 /* Allocate the sqlite3_vtab structure */
3117 nDb = (int)strlen(argv[1]);
3118 nName = (int)strlen(argv[2]);
3119 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
3120 if( !pRtree ){
3121 return SQLITE_NOMEM;
3123 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
3124 pRtree->nBusy = 1;
3125 pRtree->base.pModule = &rtreeModule;
3126 pRtree->zDb = (char *)&pRtree[1];
3127 pRtree->zName = &pRtree->zDb[nDb+1];
3128 pRtree->nDim = (argc-4)/2;
3129 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
3130 pRtree->eCoordType = eCoordType;
3131 memcpy(pRtree->zDb, argv[1], nDb);
3132 memcpy(pRtree->zName, argv[2], nName);
3134 /* Figure out the node size to use. */
3135 rc = getNodeSize(db, pRtree, isCreate);
3137 /* Create/Connect to the underlying relational database schema. If
3138 ** that is successful, call sqlite3_declare_vtab() to configure
3139 ** the r-tree table schema.
3141 if( rc==SQLITE_OK ){
3142 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
3143 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3144 }else{
3145 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
3146 char *zTmp;
3147 int ii;
3148 for(ii=4; zSql && ii<argc; ii++){
3149 zTmp = zSql;
3150 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
3151 sqlite3_free(zTmp);
3153 if( zSql ){
3154 zTmp = zSql;
3155 zSql = sqlite3_mprintf("%s);", zTmp);
3156 sqlite3_free(zTmp);
3158 if( !zSql ){
3159 rc = SQLITE_NOMEM;
3160 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3161 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3163 sqlite3_free(zSql);
3167 if( rc==SQLITE_OK ){
3168 *ppVtab = (sqlite3_vtab *)pRtree;
3169 }else{
3170 rtreeRelease(pRtree);
3172 return rc;
3177 ** Implementation of a scalar function that decodes r-tree nodes to
3178 ** human readable strings. This can be used for debugging and analysis.
3180 ** The scalar function takes two arguments, a blob of data containing
3181 ** an r-tree node, and the number of dimensions the r-tree indexes.
3182 ** For a two-dimensional r-tree structure called "rt", to deserialize
3183 ** all nodes, a statement like:
3185 ** SELECT rtreenode(2, data) FROM rt_node;
3187 ** The human readable string takes the form of a Tcl list with one
3188 ** entry for each cell in the r-tree node. Each entry is itself a
3189 ** list, containing the 8-byte rowid/pageno followed by the
3190 ** <num-dimension>*2 coordinates.
3192 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3193 char *zText = 0;
3194 RtreeNode node;
3195 Rtree tree;
3196 int ii;
3198 UNUSED_PARAMETER(nArg);
3199 memset(&node, 0, sizeof(RtreeNode));
3200 memset(&tree, 0, sizeof(Rtree));
3201 tree.nDim = sqlite3_value_int(apArg[0]);
3202 tree.nBytesPerCell = 8 + 8 * tree.nDim;
3203 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3205 for(ii=0; ii<NCELL(&node); ii++){
3206 char zCell[512];
3207 int nCell = 0;
3208 RtreeCell cell;
3209 int jj;
3211 nodeGetCell(&tree, &node, ii, &cell);
3212 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
3213 nCell = (int)strlen(zCell);
3214 for(jj=0; jj<tree.nDim*2; jj++){
3215 #ifndef SQLITE_RTREE_INT_ONLY
3216 sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
3217 (double)cell.aCoord[jj].f);
3218 #else
3219 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
3220 cell.aCoord[jj].i);
3221 #endif
3222 nCell = (int)strlen(zCell);
3225 if( zText ){
3226 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
3227 sqlite3_free(zText);
3228 zText = zTextNew;
3229 }else{
3230 zText = sqlite3_mprintf("{%s}", zCell);
3234 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
3237 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3238 UNUSED_PARAMETER(nArg);
3239 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3240 || sqlite3_value_bytes(apArg[0])<2
3242 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3243 }else{
3244 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3245 sqlite3_result_int(ctx, readInt16(zBlob));
3250 ** Register the r-tree module with database handle db. This creates the
3251 ** virtual table module "rtree" and the debugging/analysis scalar
3252 ** function "rtreenode".
3254 int sqlite3RtreeInit(sqlite3 *db){
3255 const int utf8 = SQLITE_UTF8;
3256 int rc;
3258 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
3259 if( rc==SQLITE_OK ){
3260 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
3262 if( rc==SQLITE_OK ){
3263 #ifdef SQLITE_RTREE_INT_ONLY
3264 void *c = (void *)RTREE_COORD_INT32;
3265 #else
3266 void *c = (void *)RTREE_COORD_REAL32;
3267 #endif
3268 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
3270 if( rc==SQLITE_OK ){
3271 void *c = (void *)RTREE_COORD_INT32;
3272 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
3275 return rc;
3279 ** A version of sqlite3_free() that can be used as a callback. This is used
3280 ** in two places - as the destructor for the blob value returned by the
3281 ** invocation of a geometry function, and as the destructor for the geometry
3282 ** functions themselves.
3284 static void doSqlite3Free(void *p){
3285 sqlite3_free(p);
3289 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
3290 ** scalar user function. This C function is the callback used for all such
3291 ** registered SQL functions.
3293 ** The scalar user functions return a blob that is interpreted by r-tree
3294 ** table MATCH operators.
3296 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
3297 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
3298 RtreeMatchArg *pBlob;
3299 int nBlob;
3301 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
3302 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
3303 if( !pBlob ){
3304 sqlite3_result_error_nomem(ctx);
3305 }else{
3306 int i;
3307 pBlob->magic = RTREE_GEOMETRY_MAGIC;
3308 pBlob->xGeom = pGeomCtx->xGeom;
3309 pBlob->pContext = pGeomCtx->pContext;
3310 pBlob->nParam = nArg;
3311 for(i=0; i<nArg; i++){
3312 #ifdef SQLITE_RTREE_INT_ONLY
3313 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
3314 #else
3315 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
3316 #endif
3318 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
3323 ** Register a new geometry function for use with the r-tree MATCH operator.
3325 int sqlite3_rtree_geometry_callback(
3326 sqlite3 *db,
3327 const char *zGeom,
3328 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
3329 void *pContext
3331 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
3333 /* Allocate and populate the context object. */
3334 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
3335 if( !pGeomCtx ) return SQLITE_NOMEM;
3336 pGeomCtx->xGeom = xGeom;
3337 pGeomCtx->pContext = pContext;
3339 /* Create the new user-function. Register a destructor function to delete
3340 ** the context object when it is no longer required. */
3341 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
3342 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
3346 #if !SQLITE_CORE
3347 int sqlite3_extension_init(
3348 sqlite3 *db,
3349 char **pzErrMsg,
3350 const sqlite3_api_routines *pApi
3352 SQLITE_EXTENSION_INIT2(pApi)
3353 return sqlite3RtreeInit(db);
3355 #endif
3357 #endif