Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(80)

Side by Side Diff: third_party/sqlite/sqlite-src-3170000/ext/rtree/rtree.c

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

Powered by Google App Engine
This is Rietveld 408576698