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