4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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
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
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
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
86 #if VARIANT_GUTTMAN_LINEAR_SPLIT
87 #define PickNext LinearPickNext
88 #define PickSeeds LinearPickSeeds
89 #define AssignCells splitNodeGuttman
91 #if VARIANT_RSTARTREE_SPLIT
92 #define AssignCells splitNodeStartree
95 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
100 #include "sqlite3ext.h"
101 SQLITE_EXTENSION_INIT1
109 #ifndef SQLITE_AMALGAMATION
110 #include "sqlite3rtree.h"
111 typedef sqlite3_int64 i64;
112 typedef unsigned char u8;
113 typedef unsigned int u32;
116 /* The following macro is used to suppress compiler warnings.
118 #ifndef UNUSED_PARAMETER
119 # define UNUSED_PARAMETER(x) (void)(x)
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
141 ** An rtree virtual-table object.
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).
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;
181 /* Possible values for eCoordType: */
182 #define RTREE_COORD_REAL32 0
183 #define RTREE_COORD_INT32 1
186 ** The minimum number of cells allowed for a node is a third of the
187 ** maximum. In Gutman's notation:
191 ** If an R*-tree "Reinsert" operation is required, the same number of
192 ** cells are removed from the overfull node and reinserted into the tree.
194 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
195 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
196 #define RTREE_MAXCELLS 51
199 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
200 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
201 ** Therefore all non-root nodes must contain at least 3 entries. Since
202 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
205 #define RTREE_MAX_DEPTH 40
208 ** An rtree cursor object.
211 sqlite3_vtab_cursor base;
212 RtreeNode *pNode; /* Node cursor is currently pointing at */
213 int iCell; /* Index of current cell in pNode */
214 int iStrategy; /* Copy of idxNum search parameter */
215 int nConstraint; /* Number of entries in aConstraint */
216 RtreeConstraint *aConstraint; /* Search constraints. */
225 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
226 ** formatted as a double. This macro assumes that local variable pRtree points
227 ** to the Rtree structure associated with the RtreeCoord.
229 #define DCOORD(coord) ( \
230 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
231 ((double)coord.f) : \
236 ** A search constraint.
238 struct RtreeConstraint {
239 int iCoord; /* Index of constrained coordinate */
240 int op; /* Constraining operation */
241 double rValue; /* Constraint value. */
242 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
243 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
246 /* Possible values for RtreeConstraint.op */
247 #define RTREE_EQ 0x41
248 #define RTREE_LE 0x42
249 #define RTREE_LT 0x43
250 #define RTREE_GE 0x44
251 #define RTREE_GT 0x45
252 #define RTREE_MATCH 0x46
255 ** An rtree structure node.
258 RtreeNode *pParent; /* Parent node */
263 RtreeNode *pNext; /* Next node in this hash chain */
265 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
268 ** Structure to store a deserialized rtree record.
272 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
277 ** Value for the first field of every RtreeMatchArg object. The MATCH
278 ** operator tests that the first field of a blob operand matches this
279 ** value to avoid operating on invalid blobs (which could cause a segfault).
281 #define RTREE_GEOMETRY_MAGIC 0x891245AB
284 ** An instance of this structure must be supplied as a blob argument to
285 ** the right-hand-side of an SQL MATCH operator used to constrain an
288 struct RtreeMatchArg {
289 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
290 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
297 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
298 ** a single instance of the following structure is allocated. It is used
299 ** as the context for the user-function created by by s_r_g_c(). The object
300 ** is eventually deleted by the destructor mechanism provided by
301 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
302 ** the geometry callback function).
304 struct RtreeGeomCallback {
305 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
310 # define MAX(x,y) ((x) < (y) ? (y) : (x))
313 # define MIN(x,y) ((x) > (y) ? (y) : (x))
317 ** Functions to deserialize a 16 bit integer, 32 bit real number and
318 ** 64 bit integer. The deserialized value is returned.
320 static int readInt16(u8 *p){
321 return (p[0]<<8) + p[1];
323 static void readCoord(u8 *p, RtreeCoord *pCoord){
325 (((u32)p[0]) << 24) +
326 (((u32)p[1]) << 16) +
332 static i64 readInt64(u8 *p){
334 (((i64)p[0]) << 56) +
335 (((i64)p[1]) << 48) +
336 (((i64)p[2]) << 40) +
337 (((i64)p[3]) << 32) +
338 (((i64)p[4]) << 24) +
339 (((i64)p[5]) << 16) +
346 ** Functions to serialize a 16 bit integer, 32 bit real number and
347 ** 64 bit integer. The value returned is the number of bytes written
348 ** to the argument buffer (always 2, 4 and 8 respectively).
350 static int writeInt16(u8 *p, int i){
355 static int writeCoord(u8 *p, RtreeCoord *pCoord){
357 assert( sizeof(RtreeCoord)==4 );
358 assert( sizeof(u32)==4 );
366 static int writeInt64(u8 *p, i64 i){
379 ** Increment the reference count of node p.
381 static void nodeReference(RtreeNode *p){
388 ** Clear the content of node p (set all bytes to 0x00).
390 static void nodeZero(Rtree *pRtree, RtreeNode *p){
391 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
396 ** Given a node number iNode, return the corresponding key to use
397 ** in the Rtree.aHash table.
399 static int nodeHash(i64 iNode){
401 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
402 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
407 ** Search the node hash table for node iNode. If found, return a pointer
408 ** to it. Otherwise, return 0.
410 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
412 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
417 ** Add node pNode to the node hash table.
419 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
421 assert( pNode->pNext==0 );
422 iHash = nodeHash(pNode->iNode);
423 pNode->pNext = pRtree->aHash[iHash];
424 pRtree->aHash[iHash] = pNode;
428 ** Remove node pNode from the node hash table.
430 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
432 if( pNode->iNode!=0 ){
433 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
434 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
441 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
442 ** indicating that node has not yet been assigned a node number. It is
443 ** assigned a node number when nodeWrite() is called to write the
444 ** node contents out to the database.
446 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
448 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
450 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
451 pNode->zData = (u8 *)&pNode[1];
453 pNode->pParent = pParent;
455 nodeReference(pParent);
461 ** Obtain a reference to an r-tree node.
465 Rtree *pRtree, /* R-tree structure */
466 i64 iNode, /* Node number to load */
467 RtreeNode *pParent, /* Either the parent node or NULL */
468 RtreeNode **ppNode /* OUT: Acquired node */
474 /* Check if the requested node is already in the hash table. If so,
475 ** increase its reference count and return it.
477 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
478 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
479 if( pParent && !pNode->pParent ){
480 nodeReference(pParent);
481 pNode->pParent = pParent;
488 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
489 rc = sqlite3_step(pRtree->pReadNode);
490 if( rc==SQLITE_ROW ){
491 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
492 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
493 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
497 pNode->pParent = pParent;
498 pNode->zData = (u8 *)&pNode[1];
500 pNode->iNode = iNode;
503 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
504 nodeReference(pParent);
508 rc = sqlite3_reset(pRtree->pReadNode);
509 if( rc==SQLITE_OK ) rc = rc2;
511 /* If the root node was just loaded, set pRtree->iDepth to the height
512 ** of the r-tree structure. A height of zero means all data is stored on
513 ** the root node. A height of one means the children of the root node
514 ** are the leaves, and so on. If the depth as specified on the root node
515 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
517 if( pNode && iNode==1 ){
518 pRtree->iDepth = readInt16(pNode->zData);
519 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
524 /* If no error has occurred so far, check if the "number of entries"
525 ** field on the node is too large. If so, set the return code to
528 if( pNode && rc==SQLITE_OK ){
529 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
536 nodeHashInsert(pRtree, pNode);
550 ** Overwrite cell iCell of node pNode with the contents of pCell.
552 static void nodeOverwriteCell(
559 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
560 p += writeInt64(p, pCell->iRowid);
561 for(ii=0; ii<(pRtree->nDim*2); ii++){
562 p += writeCoord(p, &pCell->aCoord[ii]);
568 ** Remove cell the cell with index iCell from node pNode.
570 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
571 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
572 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
573 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
574 memmove(pDst, pSrc, nByte);
575 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
580 ** Insert the contents of cell pCell into node pNode. If the insert
581 ** is successful, return SQLITE_OK.
583 ** If there is not enough free space in pNode, return SQLITE_FULL.
591 int nCell; /* Current number of cells in pNode */
592 int nMaxCell; /* Maximum number of cells for pNode */
594 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
595 nCell = NCELL(pNode);
597 assert( nCell<=nMaxCell );
598 if( nCell<nMaxCell ){
599 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
600 writeInt16(&pNode->zData[2], nCell+1);
604 return (nCell==nMaxCell);
608 ** If the node is dirty, write it out to the database.
611 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
613 if( pNode->isDirty ){
614 sqlite3_stmt *p = pRtree->pWriteNode;
616 sqlite3_bind_int64(p, 1, pNode->iNode);
618 sqlite3_bind_null(p, 1);
620 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
623 rc = sqlite3_reset(p);
624 if( pNode->iNode==0 && rc==SQLITE_OK ){
625 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
626 nodeHashInsert(pRtree, pNode);
633 ** Release a reference to a node. If the node is dirty and the reference
634 ** count drops to zero, the node data is written to the database.
637 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
640 assert( pNode->nRef>0 );
642 if( pNode->nRef==0 ){
643 if( pNode->iNode==1 ){
646 if( pNode->pParent ){
647 rc = nodeRelease(pRtree, pNode->pParent);
650 rc = nodeWrite(pRtree, pNode);
652 nodeHashDelete(pRtree, pNode);
660 ** Return the 64-bit integer value associated with cell iCell of
661 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
662 ** an internal node, then the 64-bit integer is a child page number.
664 static i64 nodeGetRowid(
669 assert( iCell<NCELL(pNode) );
670 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
674 ** Return coordinate iCoord from cell iCell in node pNode.
676 static void nodeGetCoord(
681 RtreeCoord *pCoord /* Space to write result to */
683 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
687 ** Deserialize cell iCell of node pNode. Populate the structure pointed
688 ** to by pCell with the results.
690 static void nodeGetCell(
697 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
698 for(ii=0; ii<pRtree->nDim*2; ii++){
699 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
704 /* Forward declaration for the function that does the work of
705 ** the virtual table module xCreate() and xConnect() methods.
707 static int rtreeInit(
708 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
712 ** Rtree virtual table module xCreate method.
714 static int rtreeCreate(
717 int argc, const char *const*argv,
718 sqlite3_vtab **ppVtab,
721 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
725 ** Rtree virtual table module xConnect method.
727 static int rtreeConnect(
730 int argc, const char *const*argv,
731 sqlite3_vtab **ppVtab,
734 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
738 ** Increment the r-tree reference count.
740 static void rtreeReference(Rtree *pRtree){
745 ** Decrement the r-tree reference count. When the reference count reaches
746 ** zero the structure is deleted.
748 static void rtreeRelease(Rtree *pRtree){
750 if( pRtree->nBusy==0 ){
751 sqlite3_finalize(pRtree->pReadNode);
752 sqlite3_finalize(pRtree->pWriteNode);
753 sqlite3_finalize(pRtree->pDeleteNode);
754 sqlite3_finalize(pRtree->pReadRowid);
755 sqlite3_finalize(pRtree->pWriteRowid);
756 sqlite3_finalize(pRtree->pDeleteRowid);
757 sqlite3_finalize(pRtree->pReadParent);
758 sqlite3_finalize(pRtree->pWriteParent);
759 sqlite3_finalize(pRtree->pDeleteParent);
760 sqlite3_free(pRtree);
765 ** Rtree virtual table module xDisconnect method.
767 static int rtreeDisconnect(sqlite3_vtab *pVtab){
768 rtreeRelease((Rtree *)pVtab);
773 ** Rtree virtual table module xDestroy method.
775 static int rtreeDestroy(sqlite3_vtab *pVtab){
776 Rtree *pRtree = (Rtree *)pVtab;
778 char *zCreate = sqlite3_mprintf(
779 "DROP TABLE '%q'.'%q_node';"
780 "DROP TABLE '%q'.'%q_rowid';"
781 "DROP TABLE '%q'.'%q_parent';",
782 pRtree->zDb, pRtree->zName,
783 pRtree->zDb, pRtree->zName,
784 pRtree->zDb, pRtree->zName
789 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
790 sqlite3_free(zCreate);
793 rtreeRelease(pRtree);
800 ** Rtree virtual table module xOpen method.
802 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
803 int rc = SQLITE_NOMEM;
806 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
808 memset(pCsr, 0, sizeof(RtreeCursor));
809 pCsr->base.pVtab = pVTab;
812 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
819 ** Free the RtreeCursor.aConstraint[] array and its contents.
821 static void freeCursorConstraints(RtreeCursor *pCsr){
822 if( pCsr->aConstraint ){
823 int i; /* Used to iterate through constraint array */
824 for(i=0; i<pCsr->nConstraint; i++){
825 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
827 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
831 sqlite3_free(pCsr->aConstraint);
832 pCsr->aConstraint = 0;
837 ** Rtree virtual table module xClose method.
839 static int rtreeClose(sqlite3_vtab_cursor *cur){
840 Rtree *pRtree = (Rtree *)(cur->pVtab);
842 RtreeCursor *pCsr = (RtreeCursor *)cur;
843 freeCursorConstraints(pCsr);
844 rc = nodeRelease(pRtree, pCsr->pNode);
850 ** Rtree virtual table module xEof method.
852 ** Return non-zero if the cursor does not currently point to a valid
853 ** record (i.e if the scan has finished), or zero otherwise.
855 static int rtreeEof(sqlite3_vtab_cursor *cur){
856 RtreeCursor *pCsr = (RtreeCursor *)cur;
857 return (pCsr->pNode==0);
861 ** The r-tree constraint passed as the second argument to this function is
862 ** guaranteed to be a MATCH constraint.
864 static int testRtreeGeom(
865 Rtree *pRtree, /* R-Tree object */
866 RtreeConstraint *pConstraint, /* MATCH constraint to test */
867 RtreeCell *pCell, /* Cell to test */
868 int *pbRes /* OUT: Test result */
871 double aCoord[RTREE_MAX_DIMENSIONS*2];
872 int nCoord = pRtree->nDim*2;
874 assert( pConstraint->op==RTREE_MATCH );
875 assert( pConstraint->pGeom );
877 for(i=0; i<nCoord; i++){
878 aCoord[i] = DCOORD(pCell->aCoord[i]);
880 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
884 ** Cursor pCursor currently points to a cell in a non-leaf page.
885 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
886 ** (excluded) by the constraints in the pCursor->aConstraint[]
887 ** array, or false otherwise.
889 ** Return SQLITE_OK if successful or an SQLite error code if an error
890 ** occurs within a geometry callback.
892 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
898 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
899 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
900 RtreeConstraint *p = &pCursor->aConstraint[ii];
901 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
902 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
904 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
905 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
909 case RTREE_LE: case RTREE_LT:
910 bRes = p->rValue<cell_min;
913 case RTREE_GE: case RTREE_GT:
914 bRes = p->rValue>cell_max;
918 bRes = (p->rValue>cell_max || p->rValue<cell_min);
922 assert( p->op==RTREE_MATCH );
923 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
935 ** Test if the cell that cursor pCursor currently points to
936 ** would be filtered (excluded) by the constraints in the
937 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
938 ** returning. If the cell is not filtered (excluded) by the constraints,
939 ** set pbEof to zero.
941 ** Return SQLITE_OK if successful or an SQLite error code if an error
942 ** occurs within a geometry callback.
944 ** This function assumes that the cell is part of a leaf node.
946 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
951 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
952 for(ii=0; ii<pCursor->nConstraint; ii++){
953 RtreeConstraint *p = &pCursor->aConstraint[ii];
954 double coord = DCOORD(cell.aCoord[p->iCoord]);
956 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
957 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
960 case RTREE_LE: res = (coord<=p->rValue); break;
961 case RTREE_LT: res = (coord<p->rValue); break;
962 case RTREE_GE: res = (coord>=p->rValue); break;
963 case RTREE_GT: res = (coord>p->rValue); break;
964 case RTREE_EQ: res = (coord==p->rValue); break;
967 assert( p->op==RTREE_MATCH );
968 rc = testRtreeGeom(pRtree, p, &cell, &res);
986 ** Cursor pCursor currently points at a node that heads a sub-tree of
987 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
988 ** to point to the left-most cell of the sub-tree that matches the
989 ** configured constraints.
991 static int descendToCell(
993 RtreeCursor *pCursor,
995 int *pEof /* OUT: Set to true if cannot descend */
1001 sqlite3_int64 iRowid;
1003 RtreeNode *pSavedNode = pCursor->pNode;
1004 int iSavedCell = pCursor->iCell;
1006 assert( iHeight>=0 );
1009 rc = testRtreeEntry(pRtree, pCursor, &isEof);
1011 rc = testRtreeCell(pRtree, pCursor, &isEof);
1013 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
1014 goto descend_to_cell_out;
1017 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
1018 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
1019 if( rc!=SQLITE_OK ){
1020 goto descend_to_cell_out;
1023 nodeRelease(pRtree, pCursor->pNode);
1024 pCursor->pNode = pChild;
1026 for(ii=0; isEof && ii<NCELL(pChild); ii++){
1027 pCursor->iCell = ii;
1028 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
1029 if( rc!=SQLITE_OK ){
1030 goto descend_to_cell_out;
1035 assert( pCursor->pNode==pChild );
1036 nodeReference(pSavedNode);
1037 nodeRelease(pRtree, pChild);
1038 pCursor->pNode = pSavedNode;
1039 pCursor->iCell = iSavedCell;
1042 descend_to_cell_out:
1048 ** One of the cells in node pNode is guaranteed to have a 64-bit
1049 ** integer value equal to iRowid. Return the index of this cell.
1051 static int nodeRowidIndex(
1058 int nCell = NCELL(pNode);
1059 for(ii=0; ii<nCell; ii++){
1060 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1065 return SQLITE_CORRUPT;
1069 ** Return the index of the cell containing a pointer to node pNode
1070 ** in its parent. If pNode is the root node, return -1.
1072 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1073 RtreeNode *pParent = pNode->pParent;
1075 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1082 ** Rtree virtual table module xNext method.
1084 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1085 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
1086 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1089 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
1090 ** already at EOF. It is against the rules to call the xNext() method of
1091 ** a cursor that has already reached EOF.
1093 assert( pCsr->pNode );
1095 if( pCsr->iStrategy==1 ){
1096 /* This "scan" is a direct lookup by rowid. There is no next entry. */
1097 nodeRelease(pRtree, pCsr->pNode);
1100 /* Move to the next entry that matches the configured constraints. */
1102 while( pCsr->pNode ){
1103 RtreeNode *pNode = pCsr->pNode;
1104 int nCell = NCELL(pNode);
1105 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
1107 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
1108 if( rc!=SQLITE_OK || !isEof ){
1112 pCsr->pNode = pNode->pParent;
1113 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
1114 if( rc!=SQLITE_OK ){
1117 nodeReference(pCsr->pNode);
1118 nodeRelease(pRtree, pNode);
1127 ** Rtree virtual table module xRowid method.
1129 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1130 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1131 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1133 assert(pCsr->pNode);
1134 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1140 ** Rtree virtual table module xColumn method.
1142 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1143 Rtree *pRtree = (Rtree *)cur->pVtab;
1144 RtreeCursor *pCsr = (RtreeCursor *)cur;
1147 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
1148 sqlite3_result_int64(ctx, iRowid);
1151 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
1152 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1153 sqlite3_result_double(ctx, c.f);
1155 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1156 sqlite3_result_int(ctx, c.i);
1164 ** Use nodeAcquire() to obtain the leaf node containing the record with
1165 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1166 ** return SQLITE_OK. If there is no such record in the table, set
1167 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1168 ** to zero and return an SQLite error code.
1170 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
1173 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1174 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1175 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1176 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1177 sqlite3_reset(pRtree->pReadRowid);
1179 rc = sqlite3_reset(pRtree->pReadRowid);
1185 ** This function is called to configure the RtreeConstraint object passed
1186 ** as the second argument for a MATCH constraint. The value passed as the
1187 ** first argument to this function is the right-hand operand to the MATCH
1190 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1192 sqlite3_rtree_geometry *pGeom;
1195 /* Check that value is actually a blob. */
1196 if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
1198 /* Check that the blob is roughly the right size. */
1199 nBlob = sqlite3_value_bytes(pValue);
1200 if( nBlob<(int)sizeof(RtreeMatchArg)
1201 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
1203 return SQLITE_ERROR;
1206 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
1207 sizeof(sqlite3_rtree_geometry) + nBlob
1209 if( !pGeom ) return SQLITE_NOMEM;
1210 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
1211 p = (RtreeMatchArg *)&pGeom[1];
1213 memcpy(p, sqlite3_value_blob(pValue), nBlob);
1214 if( p->magic!=RTREE_GEOMETRY_MAGIC
1215 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
1217 sqlite3_free(pGeom);
1218 return SQLITE_ERROR;
1221 pGeom->pContext = p->pContext;
1222 pGeom->nParam = p->nParam;
1223 pGeom->aParam = p->aParam;
1225 pCons->xGeom = p->xGeom;
1226 pCons->pGeom = pGeom;
1231 ** Rtree virtual table module xFilter method.
1233 static int rtreeFilter(
1234 sqlite3_vtab_cursor *pVtabCursor,
1235 int idxNum, const char *idxStr,
1236 int argc, sqlite3_value **argv
1238 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1239 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1241 RtreeNode *pRoot = 0;
1245 rtreeReference(pRtree);
1247 freeCursorConstraints(pCsr);
1248 pCsr->iStrategy = idxNum;
1251 /* Special case - lookup by rowid. */
1252 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
1253 i64 iRowid = sqlite3_value_int64(argv[0]);
1254 rc = findLeafNode(pRtree, iRowid, &pLeaf);
1255 pCsr->pNode = pLeaf;
1257 assert( rc==SQLITE_OK );
1258 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
1261 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1262 ** with the configured constraints.
1265 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
1266 pCsr->nConstraint = argc;
1267 if( !pCsr->aConstraint ){
1270 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1271 assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
1272 for(ii=0; ii<argc; ii++){
1273 RtreeConstraint *p = &pCsr->aConstraint[ii];
1274 p->op = idxStr[ii*2];
1275 p->iCoord = idxStr[ii*2+1]-'a';
1276 if( p->op==RTREE_MATCH ){
1277 /* A MATCH operator. The right-hand-side must be a blob that
1278 ** can be cast into an RtreeMatchArg object. One created using
1279 ** an sqlite3_rtree_geometry_callback() SQL user function.
1281 rc = deserializeGeometry(argv[ii], p);
1282 if( rc!=SQLITE_OK ){
1286 p->rValue = sqlite3_value_double(argv[ii]);
1292 if( rc==SQLITE_OK ){
1294 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1296 if( rc==SQLITE_OK ){
1298 int nCell = NCELL(pRoot);
1299 pCsr->pNode = pRoot;
1300 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
1301 assert( pCsr->pNode==pRoot );
1302 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
1307 if( rc==SQLITE_OK && isEof ){
1308 assert( pCsr->pNode==pRoot );
1309 nodeRelease(pRtree, pRoot);
1312 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
1316 rtreeRelease(pRtree);
1321 ** Rtree virtual table module xBestIndex method. There are three
1322 ** table scan strategies to choose from (in order from most to
1323 ** least desirable):
1325 ** idxNum idxStr Strategy
1326 ** ------------------------------------------------
1327 ** 1 Unused Direct lookup by rowid.
1328 ** 2 See below R-tree query or full-table scan.
1329 ** ------------------------------------------------
1331 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1332 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1333 ** constraint used. The first two bytes of idxStr correspond to
1334 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1335 ** (argvIndex==1) etc.
1337 ** The first of each pair of bytes in idxStr identifies the constraint
1338 ** operator as follows:
1340 ** Operator Byte Value
1341 ** ----------------------
1348 ** ----------------------
1350 ** The second of each pair of bytes identifies the coordinate column
1351 ** to which the constraint applies. The leftmost coordinate column
1352 ** is 'a', the second from the left 'b' etc.
1354 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1359 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
1360 memset(zIdxStr, 0, sizeof(zIdxStr));
1361 UNUSED_PARAMETER(tab);
1363 assert( pIdxInfo->idxStr==0 );
1364 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
1365 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
1367 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
1368 /* We have an equality constraint on the rowid. Use strategy 1. */
1370 for(jj=0; jj<ii; jj++){
1371 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
1372 pIdxInfo->aConstraintUsage[jj].omit = 0;
1374 pIdxInfo->idxNum = 1;
1375 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
1376 pIdxInfo->aConstraintUsage[jj].omit = 1;
1378 /* This strategy involves a two rowid lookups on an B-Tree structures
1379 ** and then a linear search of an R-Tree node. This should be
1380 ** considered almost as quick as a direct rowid lookup (for which
1381 ** sqlite uses an internal cost of 0.0).
1383 pIdxInfo->estimatedCost = 10.0;
1387 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
1390 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
1391 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
1392 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
1393 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
1394 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
1396 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
1400 zIdxStr[iIdx++] = op;
1401 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
1402 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
1403 pIdxInfo->aConstraintUsage[ii].omit = 1;
1407 pIdxInfo->idxNum = 2;
1408 pIdxInfo->needToFreeIdxStr = 1;
1409 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
1410 return SQLITE_NOMEM;
1413 pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
1418 ** Return the N-dimensional volumn of the cell stored in *p.
1420 static float cellArea(Rtree *pRtree, RtreeCell *p){
1423 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1424 area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
1430 ** Return the margin length of cell p. The margin length is the sum
1431 ** of the objects size in each dimension.
1433 static float cellMargin(Rtree *pRtree, RtreeCell *p){
1436 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1437 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
1443 ** Store the union of cells p1 and p2 in p1.
1445 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1447 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1448 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1449 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
1450 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
1453 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1454 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
1455 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
1461 ** Return true if the area covered by p2 is a subset of the area covered
1462 ** by p1. False otherwise.
1464 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
1466 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
1467 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
1468 RtreeCoord *a1 = &p1->aCoord[ii];
1469 RtreeCoord *a2 = &p2->aCoord[ii];
1470 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
1471 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
1480 ** Return the amount cell p would grow by if it were unioned with pCell.
1482 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
1485 memcpy(&cell, p, sizeof(RtreeCell));
1486 area = cellArea(pRtree, &cell);
1487 cellUnion(pRtree, &cell, pCell);
1488 return (cellArea(pRtree, &cell)-area);
1491 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
1492 static float cellOverlap(
1500 float overlap = 0.0;
1501 for(ii=0; ii<nCell; ii++){
1502 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1505 assert( iExclude==-1 );
1506 UNUSED_PARAMETER(iExclude);
1511 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
1515 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
1516 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
1532 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1533 static float cellOverlapEnlargement(
1543 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1544 cellUnion(pRtree, p, pInsert);
1545 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
1546 return after-before;
1552 ** This function implements the ChooseLeaf algorithm from Gutman[84].
1553 ** ChooseSubTree in r*tree terminology.
1555 static int ChooseLeaf(
1556 Rtree *pRtree, /* Rtree table */
1557 RtreeCell *pCell, /* Cell to insert into rtree */
1558 int iHeight, /* Height of sub-tree rooted at pCell */
1559 RtreeNode **ppLeaf /* OUT: Selected leaf page */
1564 rc = nodeAcquire(pRtree, 1, 0, &pNode);
1566 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
1568 sqlite3_int64 iBest;
1574 int nCell = NCELL(pNode);
1578 RtreeCell *aCell = 0;
1580 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1581 if( ii==(pRtree->iDepth-1) ){
1583 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
1586 nodeRelease(pRtree, pNode);
1590 for(jj=0; jj<nCell; jj++){
1591 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
1596 /* Select the child node which will be enlarged the least if pCell
1597 ** is inserted into it. Resolve ties by choosing the entry with
1598 ** the smallest area.
1600 for(iCell=0; iCell<nCell; iCell++){
1604 float overlap = 0.0;
1605 nodeGetCell(pRtree, pNode, iCell, &cell);
1606 growth = cellGrowth(pRtree, &cell, pCell);
1607 area = cellArea(pRtree, &cell);
1609 #if VARIANT_RSTARTREE_CHOOSESUBTREE
1610 if( ii==(pRtree->iDepth-1) ){
1611 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
1614 || (overlap<fMinOverlap)
1615 || (overlap==fMinOverlap && growth<fMinGrowth)
1616 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
1621 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
1626 fMinOverlap = overlap;
1627 fMinGrowth = growth;
1629 iBest = cell.iRowid;
1633 sqlite3_free(aCell);
1634 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
1635 nodeRelease(pRtree, pNode);
1644 ** A cell with the same content as pCell has just been inserted into
1645 ** the node pNode. This function updates the bounding box cells in
1646 ** all ancestor elements.
1648 static int AdjustTree(
1649 Rtree *pRtree, /* Rtree table */
1650 RtreeNode *pNode, /* Adjust ancestry of this node. */
1651 RtreeCell *pCell /* This cell was just inserted */
1653 RtreeNode *p = pNode;
1654 while( p->pParent ){
1655 RtreeNode *pParent = p->pParent;
1659 if( nodeParentIndex(pRtree, p, &iCell) ){
1660 return SQLITE_CORRUPT;
1663 nodeGetCell(pRtree, pParent, iCell, &cell);
1664 if( !cellContains(pRtree, &cell, pCell) ){
1665 cellUnion(pRtree, &cell, pCell);
1666 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
1675 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
1677 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
1678 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
1679 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
1680 sqlite3_step(pRtree->pWriteRowid);
1681 return sqlite3_reset(pRtree->pWriteRowid);
1685 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
1687 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
1688 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
1689 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
1690 sqlite3_step(pRtree->pWriteParent);
1691 return sqlite3_reset(pRtree->pWriteParent);
1694 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
1696 #if VARIANT_GUTTMAN_LINEAR_SPLIT
1698 ** Implementation of the linear variant of the PickNext() function from
1701 static RtreeCell *LinearPickNext(
1705 RtreeCell *pLeftBox,
1706 RtreeCell *pRightBox,
1710 for(ii=0; aiUsed[ii]; ii++);
1716 ** Implementation of the linear variant of the PickSeeds() function from
1719 static void LinearPickSeeds(
1729 float maxNormalInnerWidth = 0.0;
1731 /* Pick two "seed" cells from the array of cells. The algorithm used
1732 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
1733 ** indices of the two seed cells in the array are stored in local
1734 ** variables iLeftSeek and iRightSeed.
1736 for(i=0; i<pRtree->nDim; i++){
1737 float x1 = DCOORD(aCell[0].aCoord[i*2]);
1738 float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
1746 for(jj=1; jj<nCell; jj++){
1747 float left = DCOORD(aCell[jj].aCoord[i*2]);
1748 float right = DCOORD(aCell[jj].aCoord[i*2+1]);
1750 if( left<x1 ) x1 = left;
1751 if( right>x4 ) x4 = right;
1763 float normalwidth = (x3 - x2) / (x4 - x1);
1764 if( normalwidth>maxNormalInnerWidth ){
1765 iLeftSeed = iCellLeft;
1766 iRightSeed = iCellRight;
1771 *piLeftSeed = iLeftSeed;
1772 *piRightSeed = iRightSeed;
1774 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
1776 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
1778 ** Implementation of the quadratic variant of the PickNext() function from
1781 static RtreeCell *QuadraticPickNext(
1785 RtreeCell *pLeftBox,
1786 RtreeCell *pRightBox,
1789 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
1794 for(ii=0; ii<nCell; ii++){
1795 if( aiUsed[ii]==0 ){
1796 float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1797 float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
1798 float diff = FABS(right-left);
1799 if( iSelect<0 || diff>fDiff ){
1805 aiUsed[iSelect] = 1;
1806 return &aCell[iSelect];
1810 ** Implementation of the quadratic variant of the PickSeeds() function from
1813 static void QuadraticPickSeeds(
1827 for(ii=0; ii<nCell; ii++){
1828 for(jj=ii+1; jj<nCell; jj++){
1829 float right = cellArea(pRtree, &aCell[jj]);
1830 float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
1831 float waste = growth - right;
1841 *piLeftSeed = iLeftSeed;
1842 *piRightSeed = iRightSeed;
1844 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
1847 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
1848 ** nIdx. The aIdx array contains the set of integers from 0 to
1849 ** (nIdx-1) in no particular order. This function sorts the values
1850 ** in aIdx according to the indexed values in aDistance. For
1851 ** example, assuming the inputs:
1853 ** aIdx = { 0, 1, 2, 3 }
1854 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
1856 ** this function sets the aIdx array to contain:
1858 ** aIdx = { 0, 1, 2, 3 }
1860 ** The aSpare array is used as temporary working space by the
1861 ** sorting algorithm.
1863 static void SortByDistance(
1874 int nRight = nIdx-nLeft;
1876 int *aRight = &aIdx[nLeft];
1878 SortByDistance(aLeft, nLeft, aDistance, aSpare);
1879 SortByDistance(aRight, nRight, aDistance, aSpare);
1881 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1884 while( iLeft<nLeft || iRight<nRight ){
1886 aIdx[iLeft+iRight] = aRight[iRight];
1888 }else if( iRight==nRight ){
1889 aIdx[iLeft+iRight] = aLeft[iLeft];
1892 float fLeft = aDistance[aLeft[iLeft]];
1893 float fRight = aDistance[aRight[iRight]];
1895 aIdx[iLeft+iRight] = aLeft[iLeft];
1898 aIdx[iLeft+iRight] = aRight[iRight];
1905 /* Check that the sort worked */
1908 for(jj=1; jj<nIdx; jj++){
1909 float left = aDistance[aIdx[jj-1]];
1910 float right = aDistance[aIdx[jj]];
1911 assert( left<=right );
1919 ** Arguments aIdx, aCell and aSpare all point to arrays of size
1920 ** nIdx. The aIdx array contains the set of integers from 0 to
1921 ** (nIdx-1) in no particular order. This function sorts the values
1922 ** in aIdx according to dimension iDim of the cells in aCell. The
1923 ** minimum value of dimension iDim is considered first, the
1924 ** maximum used to break ties.
1926 ** The aSpare array is used as temporary working space by the
1927 ** sorting algorithm.
1929 static void SortByDimension(
1943 int nRight = nIdx-nLeft;
1945 int *aRight = &aIdx[nLeft];
1947 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
1948 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
1950 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
1952 while( iLeft<nLeft || iRight<nRight ){
1953 double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
1954 double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
1955 double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
1956 double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
1957 if( (iLeft!=nLeft) && ((iRight==nRight)
1959 || (xleft1==xright1 && xleft2<xright2)
1961 aIdx[iLeft+iRight] = aLeft[iLeft];
1964 aIdx[iLeft+iRight] = aRight[iRight];
1970 /* Check that the sort worked */
1973 for(jj=1; jj<nIdx; jj++){
1974 float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
1975 float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
1976 float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
1977 float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
1978 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
1985 #if VARIANT_RSTARTREE_SPLIT
1987 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
1989 static int splitNodeStartree(
1995 RtreeCell *pBboxLeft,
1996 RtreeCell *pBboxRight
2006 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2008 aaSorted = (int **)sqlite3_malloc(nByte);
2010 return SQLITE_NOMEM;
2013 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2014 memset(aaSorted, 0, nByte);
2015 for(ii=0; ii<pRtree->nDim; ii++){
2017 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2018 for(jj=0; jj<nCell; jj++){
2019 aaSorted[ii][jj] = jj;
2021 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2024 for(ii=0; ii<pRtree->nDim; ii++){
2032 nLeft=RTREE_MINCELLS(pRtree);
2033 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2042 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2043 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2044 for(kk=1; kk<(nCell-1); kk++){
2046 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2048 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2051 margin += cellMargin(pRtree, &left);
2052 margin += cellMargin(pRtree, &right);
2053 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
2054 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2055 if( (nLeft==RTREE_MINCELLS(pRtree))
2056 || (overlap<fBestOverlap)
2057 || (overlap==fBestOverlap && area<fBestArea)
2060 fBestOverlap = overlap;
2065 if( ii==0 || margin<fBestMargin ){
2067 fBestMargin = margin;
2068 iBestSplit = iBestLeft;
2072 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2073 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2074 for(ii=0; ii<nCell; ii++){
2075 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2076 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2077 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2078 nodeInsertCell(pRtree, pTarget, pCell);
2079 cellUnion(pRtree, pBbox, pCell);
2082 sqlite3_free(aaSorted);
2087 #if VARIANT_GUTTMAN_SPLIT
2089 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
2091 static int splitNodeGuttman(
2097 RtreeCell *pBboxLeft,
2098 RtreeCell *pBboxRight
2105 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
2107 return SQLITE_NOMEM;
2109 memset(aiUsed, 0, sizeof(int)*nCell);
2111 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
2113 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
2114 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
2115 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
2116 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
2117 aiUsed[iLeftSeed] = 1;
2118 aiUsed[iRightSeed] = 1;
2120 for(i=nCell-2; i>0; i--){
2122 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
2124 cellGrowth(pRtree, pBboxLeft, pNext) -
2125 cellGrowth(pRtree, pBboxRight, pNext)
2127 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
2128 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
2130 nodeInsertCell(pRtree, pRight, pNext);
2131 cellUnion(pRtree, pBboxRight, pNext);
2133 nodeInsertCell(pRtree, pLeft, pNext);
2134 cellUnion(pRtree, pBboxLeft, pNext);
2138 sqlite3_free(aiUsed);
2143 static int updateMapping(
2149 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2150 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2152 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2154 nodeRelease(pRtree, pChild->pParent);
2155 nodeReference(pNode);
2156 pChild->pParent = pNode;
2159 return xSetMapping(pRtree, iRowid, pNode->iNode);
2162 static int SplitNode(
2169 int newCellIsRight = 0;
2172 int nCell = NCELL(pNode);
2176 RtreeNode *pLeft = 0;
2177 RtreeNode *pRight = 0;
2180 RtreeCell rightbbox;
2182 /* Allocate an array and populate it with a copy of pCell and
2183 ** all cells from node pLeft. Then zero the original node.
2185 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2190 aiUsed = (int *)&aCell[nCell+1];
2191 memset(aiUsed, 0, sizeof(int)*(nCell+1));
2192 for(i=0; i<nCell; i++){
2193 nodeGetCell(pRtree, pNode, i, &aCell[i]);
2195 nodeZero(pRtree, pNode);
2196 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2199 if( pNode->iNode==1 ){
2200 pRight = nodeNew(pRtree, pNode);
2201 pLeft = nodeNew(pRtree, pNode);
2204 writeInt16(pNode->zData, pRtree->iDepth);
2207 pRight = nodeNew(pRtree, pLeft->pParent);
2208 nodeReference(pLeft);
2211 if( !pLeft || !pRight ){
2216 memset(pLeft->zData, 0, pRtree->iNodeSize);
2217 memset(pRight->zData, 0, pRtree->iNodeSize);
2219 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
2220 if( rc!=SQLITE_OK ){
2224 /* Ensure both child nodes have node numbers assigned to them by calling
2225 ** nodeWrite(). Node pRight always needs a node number, as it was created
2226 ** by nodeNew() above. But node pLeft sometimes already has a node number.
2227 ** In this case avoid the all to nodeWrite().
2229 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2230 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2235 rightbbox.iRowid = pRight->iNode;
2236 leftbbox.iRowid = pLeft->iNode;
2238 if( pNode->iNode==1 ){
2239 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2240 if( rc!=SQLITE_OK ){
2244 RtreeNode *pParent = pLeft->pParent;
2246 rc = nodeParentIndex(pRtree, pLeft, &iCell);
2247 if( rc==SQLITE_OK ){
2248 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2249 rc = AdjustTree(pRtree, pParent, &leftbbox);
2251 if( rc!=SQLITE_OK ){
2255 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2259 for(i=0; i<NCELL(pRight); i++){
2260 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2261 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2262 if( iRowid==pCell->iRowid ){
2265 if( rc!=SQLITE_OK ){
2269 if( pNode->iNode==1 ){
2270 for(i=0; i<NCELL(pLeft); i++){
2271 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2272 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2273 if( rc!=SQLITE_OK ){
2277 }else if( newCellIsRight==0 ){
2278 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2281 if( rc==SQLITE_OK ){
2282 rc = nodeRelease(pRtree, pRight);
2285 if( rc==SQLITE_OK ){
2286 rc = nodeRelease(pRtree, pLeft);
2291 nodeRelease(pRtree, pRight);
2292 nodeRelease(pRtree, pLeft);
2293 sqlite3_free(aCell);
2298 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2299 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2300 ** the pLeaf->pParent chain all the way up to the root node.
2302 ** This operation is required when a row is deleted (or updated - an update
2303 ** is implemented as a delete followed by an insert). SQLite provides the
2304 ** rowid of the row to delete, which can be used to find the leaf on which
2305 ** the entry resides (argument pLeaf). Once the leaf is located, this
2306 ** function is called to determine its ancestry.
2308 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2310 RtreeNode *pChild = pLeaf;
2311 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2312 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
2313 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2314 rc = sqlite3_step(pRtree->pReadParent);
2315 if( rc==SQLITE_ROW ){
2316 RtreeNode *pTest; /* Used to test for reference loops */
2317 i64 iNode; /* Node number of parent node */
2319 /* Before setting pChild->pParent, test that we are not creating a
2320 ** loop of references (as we would if, say, pChild==pParent). We don't
2321 ** want to do this as it leads to a memory leak when trying to delete
2322 ** the referenced counted node structures.
2324 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2325 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2327 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2330 rc = sqlite3_reset(pRtree->pReadParent);
2331 if( rc==SQLITE_OK ) rc = rc2;
2332 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
2333 pChild = pChild->pParent;
2338 static int deleteCell(Rtree *, RtreeNode *, int, int);
2340 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2346 assert( pNode->nRef==1 );
2348 /* Remove the entry in the parent cell. */
2349 rc = nodeParentIndex(pRtree, pNode, &iCell);
2350 if( rc==SQLITE_OK ){
2351 pParent = pNode->pParent;
2353 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2355 rc2 = nodeRelease(pRtree, pParent);
2356 if( rc==SQLITE_OK ){
2359 if( rc!=SQLITE_OK ){
2363 /* Remove the xxx_node entry. */
2364 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2365 sqlite3_step(pRtree->pDeleteNode);
2366 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2370 /* Remove the xxx_parent entry. */
2371 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2372 sqlite3_step(pRtree->pDeleteParent);
2373 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2377 /* Remove the node from the in-memory hash table and link it into
2378 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2380 nodeHashDelete(pRtree, pNode);
2381 pNode->iNode = iHeight;
2382 pNode->pNext = pRtree->pDeleted;
2384 pRtree->pDeleted = pNode;
2389 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2390 RtreeNode *pParent = pNode->pParent;
2394 int nCell = NCELL(pNode);
2395 RtreeCell box; /* Bounding box for pNode */
2396 nodeGetCell(pRtree, pNode, 0, &box);
2397 for(ii=1; ii<nCell; ii++){
2399 nodeGetCell(pRtree, pNode, ii, &cell);
2400 cellUnion(pRtree, &box, &cell);
2402 box.iRowid = pNode->iNode;
2403 rc = nodeParentIndex(pRtree, pNode, &ii);
2404 if( rc==SQLITE_OK ){
2405 nodeOverwriteCell(pRtree, pParent, &box, ii);
2406 rc = fixBoundingBox(pRtree, pParent);
2413 ** Delete the cell at index iCell of node pNode. After removing the
2414 ** cell, adjust the r-tree data structure if required.
2416 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2420 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2424 /* Remove the cell from the node. This call just moves bytes around
2425 ** the in-memory node image, so it cannot fail.
2427 nodeDeleteCell(pRtree, pNode, iCell);
2429 /* If the node is not the tree root and now has less than the minimum
2430 ** number of cells, remove it from the tree. Otherwise, update the
2431 ** cell in the parent node so that it tightly contains the updated
2434 pParent = pNode->pParent;
2435 assert( pParent || pNode->iNode==1 );
2437 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2438 rc = removeNode(pRtree, pNode, iHeight);
2440 rc = fixBoundingBox(pRtree, pNode);
2447 static int Reinsert(
2458 float aCenterCoord[RTREE_MAX_DIMENSIONS];
2463 memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
2465 nCell = NCELL(pNode)+1;
2467 /* Allocate the buffers used by this operation. The allocation is
2468 ** relinquished before this function returns.
2470 aCell = (RtreeCell *)sqlite3_malloc(nCell * (
2471 sizeof(RtreeCell) + /* aCell array */
2472 sizeof(int) + /* aOrder array */
2473 sizeof(int) + /* aSpare array */
2474 sizeof(float) /* aDistance array */
2477 return SQLITE_NOMEM;
2479 aOrder = (int *)&aCell[nCell];
2480 aSpare = (int *)&aOrder[nCell];
2481 aDistance = (float *)&aSpare[nCell];
2483 for(ii=0; ii<nCell; ii++){
2484 if( ii==(nCell-1) ){
2485 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2487 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2490 for(iDim=0; iDim<pRtree->nDim; iDim++){
2491 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2492 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2495 for(iDim=0; iDim<pRtree->nDim; iDim++){
2496 aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
2499 for(ii=0; ii<nCell; ii++){
2500 aDistance[ii] = 0.0;
2501 for(iDim=0; iDim<pRtree->nDim; iDim++){
2502 float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
2503 DCOORD(aCell[ii].aCoord[iDim*2]);
2504 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2508 SortByDistance(aOrder, nCell, aDistance, aSpare);
2509 nodeZero(pRtree, pNode);
2511 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2512 RtreeCell *p = &aCell[aOrder[ii]];
2513 nodeInsertCell(pRtree, pNode, p);
2514 if( p->iRowid==pCell->iRowid ){
2516 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2518 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2522 if( rc==SQLITE_OK ){
2523 rc = fixBoundingBox(pRtree, pNode);
2525 for(; rc==SQLITE_OK && ii<nCell; ii++){
2526 /* Find a node to store this cell in. pNode->iNode currently contains
2527 ** the height of the sub-tree headed by the cell.
2530 RtreeCell *p = &aCell[aOrder[ii]];
2531 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2532 if( rc==SQLITE_OK ){
2534 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2535 rc2 = nodeRelease(pRtree, pInsert);
2536 if( rc==SQLITE_OK ){
2542 sqlite3_free(aCell);
2547 ** Insert cell pCell into node pNode. Node pNode is the head of a
2548 ** subtree iHeight high (leaf nodes have iHeight==0).
2550 static int rtreeInsertCell(
2558 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2560 nodeRelease(pRtree, pChild->pParent);
2561 nodeReference(pNode);
2562 pChild->pParent = pNode;
2565 if( nodeInsertCell(pRtree, pNode, pCell) ){
2566 #if VARIANT_RSTARTREE_REINSERT
2567 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
2568 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2570 pRtree->iReinsertHeight = iHeight;
2571 rc = Reinsert(pRtree, pNode, pCell, iHeight);
2574 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2577 rc = AdjustTree(pRtree, pNode, pCell);
2578 if( rc==SQLITE_OK ){
2580 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
2582 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
2589 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
2592 int nCell = NCELL(pNode);
2594 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
2597 nodeGetCell(pRtree, pNode, ii, &cell);
2599 /* Find a node to store this cell in. pNode->iNode currently contains
2600 ** the height of the sub-tree headed by the cell.
2602 rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
2603 if( rc==SQLITE_OK ){
2605 rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
2606 rc2 = nodeRelease(pRtree, pInsert);
2607 if( rc==SQLITE_OK ){
2616 ** Select a currently unused rowid for a new r-tree record.
2618 static int newRowid(Rtree *pRtree, i64 *piRowid){
2620 sqlite3_bind_null(pRtree->pWriteRowid, 1);
2621 sqlite3_bind_null(pRtree->pWriteRowid, 2);
2622 sqlite3_step(pRtree->pWriteRowid);
2623 rc = sqlite3_reset(pRtree->pWriteRowid);
2624 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
2629 ** The xUpdate method for rtree module virtual tables.
2631 static int rtreeUpdate(
2632 sqlite3_vtab *pVtab,
2634 sqlite3_value **azData,
2635 sqlite_int64 *pRowid
2637 Rtree *pRtree = (Rtree *)pVtab;
2640 rtreeReference(pRtree);
2644 /* If azData[0] is not an SQL NULL value, it is the rowid of a
2645 ** record to delete from the r-tree table. The following block does
2648 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
2649 i64 iDelete; /* The rowid to delete */
2650 RtreeNode *pLeaf; /* Leaf node containing record iDelete */
2651 int iCell; /* Index of iDelete cell in pLeaf */
2654 /* Obtain a reference to the root node to initialise Rtree.iDepth */
2655 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
2657 /* Obtain a reference to the leaf node that contains the entry
2658 ** about to be deleted.
2660 if( rc==SQLITE_OK ){
2661 iDelete = sqlite3_value_int64(azData[0]);
2662 rc = findLeafNode(pRtree, iDelete, &pLeaf);
2665 /* Delete the cell in question from the leaf node. */
2666 if( rc==SQLITE_OK ){
2668 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
2669 if( rc==SQLITE_OK ){
2670 rc = deleteCell(pRtree, pLeaf, iCell, 0);
2672 rc2 = nodeRelease(pRtree, pLeaf);
2673 if( rc==SQLITE_OK ){
2678 /* Delete the corresponding entry in the <rtree>_rowid table. */
2679 if( rc==SQLITE_OK ){
2680 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
2681 sqlite3_step(pRtree->pDeleteRowid);
2682 rc = sqlite3_reset(pRtree->pDeleteRowid);
2685 /* Check if the root node now has exactly one child. If so, remove
2686 ** it, schedule the contents of the child for reinsertion and
2687 ** reduce the tree height by one.
2689 ** This is equivalent to copying the contents of the child into
2690 ** the root node (the operation that Gutman's paper says to perform
2691 ** in this scenario).
2693 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
2696 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
2697 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
2698 if( rc==SQLITE_OK ){
2699 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
2701 rc2 = nodeRelease(pRtree, pChild);
2702 if( rc==SQLITE_OK ) rc = rc2;
2703 if( rc==SQLITE_OK ){
2705 writeInt16(pRoot->zData, pRtree->iDepth);
2710 /* Re-insert the contents of any underfull nodes removed from the tree. */
2711 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
2712 if( rc==SQLITE_OK ){
2713 rc = reinsertNodeContent(pRtree, pLeaf);
2715 pRtree->pDeleted = pLeaf->pNext;
2716 sqlite3_free(pLeaf);
2719 /* Release the reference to the root node. */
2720 if( rc==SQLITE_OK ){
2721 rc = nodeRelease(pRtree, pRoot);
2723 nodeRelease(pRtree, pRoot);
2727 /* If the azData[] array contains more than one element, elements
2728 ** (azData[2]..azData[argc-1]) contain a new record to insert into
2729 ** the r-tree structure.
2731 if( rc==SQLITE_OK && nData>1 ){
2732 /* Insert a new record into the r-tree */
2737 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
2738 assert( nData==(pRtree->nDim*2 + 3) );
2739 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2740 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
2741 cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
2742 cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
2743 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
2744 rc = SQLITE_CONSTRAINT;
2749 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
2750 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
2751 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
2752 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
2753 rc = SQLITE_CONSTRAINT;
2759 /* Figure out the rowid of the new row. */
2760 if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
2761 rc = newRowid(pRtree, &cell.iRowid);
2763 cell.iRowid = sqlite3_value_int64(azData[2]);
2764 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
2765 if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
2766 sqlite3_reset(pRtree->pReadRowid);
2767 rc = SQLITE_CONSTRAINT;
2770 rc = sqlite3_reset(pRtree->pReadRowid);
2772 *pRowid = cell.iRowid;
2774 if( rc==SQLITE_OK ){
2775 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
2777 if( rc==SQLITE_OK ){
2779 pRtree->iReinsertHeight = -1;
2780 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
2781 rc2 = nodeRelease(pRtree, pLeaf);
2782 if( rc==SQLITE_OK ){
2789 rtreeRelease(pRtree);
2794 ** The xRename method for rtree module virtual tables.
2796 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
2797 Rtree *pRtree = (Rtree *)pVtab;
2798 int rc = SQLITE_NOMEM;
2799 char *zSql = sqlite3_mprintf(
2800 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
2801 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
2802 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
2803 , pRtree->zDb, pRtree->zName, zNewName
2804 , pRtree->zDb, pRtree->zName, zNewName
2805 , pRtree->zDb, pRtree->zName, zNewName
2808 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
2814 static sqlite3_module rtreeModule = {
2816 rtreeCreate, /* xCreate - create a table */
2817 rtreeConnect, /* xConnect - connect to an existing table */
2818 rtreeBestIndex, /* xBestIndex - Determine search strategy */
2819 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
2820 rtreeDestroy, /* xDestroy - Drop a table */
2821 rtreeOpen, /* xOpen - open a cursor */
2822 rtreeClose, /* xClose - close a cursor */
2823 rtreeFilter, /* xFilter - configure scan constraints */
2824 rtreeNext, /* xNext - advance a cursor */
2825 rtreeEof, /* xEof */
2826 rtreeColumn, /* xColumn - read data */
2827 rtreeRowid, /* xRowid - read data */
2828 rtreeUpdate, /* xUpdate - write data */
2829 0, /* xBegin - begin transaction */
2830 0, /* xSync - sync transaction */
2831 0, /* xCommit - commit transaction */
2832 0, /* xRollback - rollback transaction */
2833 0, /* xFindFunction - function overloading */
2834 rtreeRename /* xRename - rename the table */
2837 static int rtreeSqlInit(
2841 const char *zPrefix,
2846 #define N_STATEMENT 9
2847 static const char *azSql[N_STATEMENT] = {
2848 /* Read and write the xxx_node table */
2849 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
2850 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
2851 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
2853 /* Read and write the xxx_rowid table */
2854 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
2855 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
2856 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
2858 /* Read and write the xxx_parent table */
2859 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
2860 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
2861 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
2863 sqlite3_stmt **appStmt[N_STATEMENT];
2869 char *zCreate = sqlite3_mprintf(
2870 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
2871 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
2872 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
2873 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
2874 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
2877 return SQLITE_NOMEM;
2879 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
2880 sqlite3_free(zCreate);
2881 if( rc!=SQLITE_OK ){
2886 appStmt[0] = &pRtree->pReadNode;
2887 appStmt[1] = &pRtree->pWriteNode;
2888 appStmt[2] = &pRtree->pDeleteNode;
2889 appStmt[3] = &pRtree->pReadRowid;
2890 appStmt[4] = &pRtree->pWriteRowid;
2891 appStmt[5] = &pRtree->pDeleteRowid;
2892 appStmt[6] = &pRtree->pReadParent;
2893 appStmt[7] = &pRtree->pWriteParent;
2894 appStmt[8] = &pRtree->pDeleteParent;
2896 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
2897 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
2899 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
2910 ** The second argument to this function contains the text of an SQL statement
2911 ** that returns a single integer value. The statement is compiled and executed
2912 ** using database connection db. If successful, the integer value returned
2913 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
2914 ** code is returned and the value of *piVal after returning is not defined.
2916 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
2917 int rc = SQLITE_NOMEM;
2919 sqlite3_stmt *pStmt = 0;
2920 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
2921 if( rc==SQLITE_OK ){
2922 if( SQLITE_ROW==sqlite3_step(pStmt) ){
2923 *piVal = sqlite3_column_int(pStmt, 0);
2925 rc = sqlite3_finalize(pStmt);
2932 ** This function is called from within the xConnect() or xCreate() method to
2933 ** determine the node-size used by the rtree table being created or connected
2934 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
2935 ** Otherwise, an SQLite error code is returned.
2937 ** If this function is being called as part of an xConnect(), then the rtree
2938 ** table already exists. In this case the node-size is determined by inspecting
2939 ** the root node of the tree.
2941 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
2942 ** This ensures that each node is stored on a single database page. If the
2943 ** database page-size is so large that more than RTREE_MAXCELLS entries
2944 ** would fit in a single node, use a smaller node-size.
2946 static int getNodeSize(
2947 sqlite3 *db, /* Database handle */
2948 Rtree *pRtree, /* Rtree handle */
2949 int isCreate /* True for xCreate, false for xConnect */
2955 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
2956 rc = getIntFromStmt(db, zSql, &iPageSize);
2957 if( rc==SQLITE_OK ){
2958 pRtree->iNodeSize = iPageSize-64;
2959 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
2960 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
2964 zSql = sqlite3_mprintf(
2965 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
2966 pRtree->zDb, pRtree->zName
2968 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
2976 ** This function is the implementation of both the xConnect and xCreate
2977 ** methods of the r-tree virtual table.
2979 ** argv[0] -> module name
2980 ** argv[1] -> database name
2981 ** argv[2] -> table name
2982 ** argv[...] -> column names...
2984 static int rtreeInit(
2985 sqlite3 *db, /* Database connection */
2986 void *pAux, /* One of the RTREE_COORD_* constants */
2987 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
2988 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
2989 char **pzErr, /* OUT: Error message, if any */
2990 int isCreate /* True for xCreate, false for xConnect */
2994 int nDb; /* Length of string argv[1] */
2995 int nName; /* Length of string argv[2] */
2996 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
2998 const char *aErrMsg[] = {
3000 "Wrong number of columns for an rtree table", /* 1 */
3001 "Too few columns for an rtree table", /* 2 */
3002 "Too many columns for an rtree table" /* 3 */
3005 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
3006 if( aErrMsg[iErr] ){
3007 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3008 return SQLITE_ERROR;
3011 /* Allocate the sqlite3_vtab structure */
3012 nDb = strlen(argv[1]);
3013 nName = strlen(argv[2]);
3014 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
3016 return SQLITE_NOMEM;
3018 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
3020 pRtree->base.pModule = &rtreeModule;
3021 pRtree->zDb = (char *)&pRtree[1];
3022 pRtree->zName = &pRtree->zDb[nDb+1];
3023 pRtree->nDim = (argc-4)/2;
3024 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
3025 pRtree->eCoordType = eCoordType;
3026 memcpy(pRtree->zDb, argv[1], nDb);
3027 memcpy(pRtree->zName, argv[2], nName);
3029 /* Figure out the node size to use. */
3030 rc = getNodeSize(db, pRtree, isCreate);
3032 /* Create/Connect to the underlying relational database schema. If
3033 ** that is successful, call sqlite3_declare_vtab() to configure
3034 ** the r-tree table schema.
3036 if( rc==SQLITE_OK ){
3037 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
3038 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3040 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
3043 for(ii=4; zSql && ii<argc; ii++){
3045 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
3050 zSql = sqlite3_mprintf("%s);", zTmp);
3055 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3056 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3062 if( rc==SQLITE_OK ){
3063 *ppVtab = (sqlite3_vtab *)pRtree;
3065 rtreeRelease(pRtree);
3072 ** Implementation of a scalar function that decodes r-tree nodes to
3073 ** human readable strings. This can be used for debugging and analysis.
3075 ** The scalar function takes two arguments, a blob of data containing
3076 ** an r-tree node, and the number of dimensions the r-tree indexes.
3077 ** For a two-dimensional r-tree structure called "rt", to deserialize
3078 ** all nodes, a statement like:
3080 ** SELECT rtreenode(2, data) FROM rt_node;
3082 ** The human readable string takes the form of a Tcl list with one
3083 ** entry for each cell in the r-tree node. Each entry is itself a
3084 ** list, containing the 8-byte rowid/pageno followed by the
3085 ** <num-dimension>*2 coordinates.
3087 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3093 UNUSED_PARAMETER(nArg);
3094 memset(&node, 0, sizeof(RtreeNode));
3095 memset(&tree, 0, sizeof(Rtree));
3096 tree.nDim = sqlite3_value_int(apArg[0]);
3097 tree.nBytesPerCell = 8 + 8 * tree.nDim;
3098 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3100 for(ii=0; ii<NCELL(&node); ii++){
3106 nodeGetCell(&tree, &node, ii, &cell);
3107 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
3108 nCell = strlen(zCell);
3109 for(jj=0; jj<tree.nDim*2; jj++){
3110 sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
3111 nCell = strlen(zCell);
3115 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
3116 sqlite3_free(zText);
3119 zText = sqlite3_mprintf("{%s}", zCell);
3123 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
3126 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3127 UNUSED_PARAMETER(nArg);
3128 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3129 || sqlite3_value_bytes(apArg[0])<2
3131 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3133 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3134 sqlite3_result_int(ctx, readInt16(zBlob));
3139 ** Register the r-tree module with database handle db. This creates the
3140 ** virtual table module "rtree" and the debugging/analysis scalar
3141 ** function "rtreenode".
3143 int sqlite3RtreeInit(sqlite3 *db){
3144 const int utf8 = SQLITE_UTF8;
3147 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
3148 if( rc==SQLITE_OK ){
3149 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
3151 if( rc==SQLITE_OK ){
3152 void *c = (void *)RTREE_COORD_REAL32;
3153 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
3155 if( rc==SQLITE_OK ){
3156 void *c = (void *)RTREE_COORD_INT32;
3157 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
3164 ** A version of sqlite3_free() that can be used as a callback. This is used
3165 ** in two places - as the destructor for the blob value returned by the
3166 ** invocation of a geometry function, and as the destructor for the geometry
3167 ** functions themselves.
3169 static void doSqlite3Free(void *p){
3174 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
3175 ** scalar user function. This C function is the callback used for all such
3176 ** registered SQL functions.
3178 ** The scalar user functions return a blob that is interpreted by r-tree
3179 ** table MATCH operators.
3181 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
3182 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
3183 RtreeMatchArg *pBlob;
3186 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
3187 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
3189 sqlite3_result_error_nomem(ctx);
3192 pBlob->magic = RTREE_GEOMETRY_MAGIC;
3193 pBlob->xGeom = pGeomCtx->xGeom;
3194 pBlob->pContext = pGeomCtx->pContext;
3195 pBlob->nParam = nArg;
3196 for(i=0; i<nArg; i++){
3197 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
3199 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
3204 ** Register a new geometry function for use with the r-tree MATCH operator.
3206 int sqlite3_rtree_geometry_callback(
3209 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
3212 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
3214 /* Allocate and populate the context object. */
3215 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
3216 if( !pGeomCtx ) return SQLITE_NOMEM;
3217 pGeomCtx->xGeom = xGeom;
3218 pGeomCtx->pContext = pContext;
3220 /* Create the new user-function. Register a destructor function to delete
3221 ** the context object when it is no longer required. */
3222 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
3223 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
3228 int sqlite3_extension_init(
3231 const sqlite3_api_routines *pApi
3233 SQLITE_EXTENSION_INIT2(pApi)
3234 return sqlite3RtreeInit(db);