interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / rtree / rtree.c

4581 lines · 145179 bytes Raw Blame History
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. If the r-tree contains auxiliary columns, those are stored
35** on the end of the %_rowid table.
36**
37** The root node of an r-tree always exists, even if the r-tree table is
38** empty. The nodeno of the root node is always 1. All other nodes in the
39** table must be the same size as the root node. The content of each node
40** is formatted as follows:
41**
42** 1. If the node is the root node (node 1), then the first 2 bytes
43** of the node contain the tree depth as a big-endian integer.
44** For non-root nodes, the first 2 bytes are left unused.
45**
46** 2. The next 2 bytes contain the number of entries currently
47** stored in the node.
48**
49** 3. The remainder of the node contains the node entries. Each entry
50** consists of a single 8-byte integer followed by an even number
51** of 4-byte coordinates. For leaf nodes the integer is the rowid
52** of a record. For internal nodes it is the node number of a
53** child page.
54*/
55
56#if !defined(SQLITE_CORE) \
57 || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
58
59#ifndef SQLITE_CORE
60 #include "sqlite3ext.h"
61 SQLITE_EXTENSION_INIT1
62#else
63 #include "sqlite3.h"
64#endif
65sqlite3_int64 sqlite3GetToken(const unsigned char*,int*); /* In SQLite core */
66
67#include <stddef.h>
68
69/*
70** If building separately, we will need some setup that is normally
71** found in sqliteInt.h
72*/
73#if !defined(SQLITE_AMALGAMATION)
74#include "sqlite3rtree.h"
75typedef sqlite3_int64 i64;
76typedef sqlite3_uint64 u64;
77typedef unsigned char u8;
78typedef unsigned short u16;
79typedef unsigned int u32;
80#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
81# define NDEBUG 1
82#endif
83#if defined(NDEBUG) && defined(SQLITE_DEBUG)
84# undef NDEBUG
85#endif
86#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
87# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
88#endif
89#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
90# define ALWAYS(X) (1)
91# define NEVER(X) (0)
92#elif !defined(NDEBUG)
93# define ALWAYS(X) ((X)?1:(assert(0),0))
94# define NEVER(X) ((X)?(assert(0),1):0)
95#else
96# define ALWAYS(X) (X)
97# define NEVER(X) (X)
98#endif
99#ifndef offsetof
100# define offsetof(ST,M) ((size_t)((char*)&((ST*)0)->M - (char*)0))
101#endif
102#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
103# define FLEXARRAY
104#else
105# define FLEXARRAY 1
106#endif
107#endif /* !defined(SQLITE_AMALGAMATION) */
108
109/* Macro to check for 4-byte alignment. Only used inside of assert() */
110#ifdef SQLITE_DEBUG
111# define FOUR_BYTE_ALIGNED(X) ((((char*)(X) - (char*)0) & 3)==0)
112#endif
113
114#include <string.h>
115#include <stdio.h>
116#include <assert.h>
117#include <stdlib.h>
118
119/* The following macro is used to suppress compiler warnings.
120*/
121#ifndef UNUSED_PARAMETER
122# define UNUSED_PARAMETER(x) (void)(x)
123#endif
124
125typedef struct Rtree Rtree;
126typedef struct RtreeCursor RtreeCursor;
127typedef struct RtreeNode RtreeNode;
128typedef struct RtreeCell RtreeCell;
129typedef struct RtreeConstraint RtreeConstraint;
130typedef struct RtreeMatchArg RtreeMatchArg;
131typedef struct RtreeGeomCallback RtreeGeomCallback;
132typedef union RtreeCoord RtreeCoord;
133typedef struct RtreeSearchPoint RtreeSearchPoint;
134
135/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
136#define RTREE_MAX_DIMENSIONS 5
137
138/* Maximum number of auxiliary columns */
139#define RTREE_MAX_AUX_COLUMN 100
140
141/* Size of hash table Rtree.aHash. This hash table is not expected to
142** ever contain very many entries, so a fixed number of buckets is
143** used.
144*/
145#define HASHSIZE 97
146
147/* The xBestIndex method of this virtual table requires an estimate of
148** the number of rows in the virtual table to calculate the costs of
149** various strategies. If possible, this estimate is loaded from the
150** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
151** Otherwise, if no sqlite_stat1 entry is available, use
152** RTREE_DEFAULT_ROWEST.
153*/
154#define RTREE_DEFAULT_ROWEST 1048576
155#define RTREE_MIN_ROWEST 100
156
157/*
158** An rtree virtual-table object.
159*/
160struct Rtree {
161 sqlite3_vtab base; /* Base class. Must be first */
162 sqlite3 *db; /* Host database connection */
163 int iNodeSize; /* Size in bytes of each node in the node table */
164 u8 nDim; /* Number of dimensions */
165 u8 nDim2; /* Twice the number of dimensions */
166 u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
167 u8 nBytesPerCell; /* Bytes consumed per cell */
168 u8 inWrTrans; /* True if inside write transaction */
169 u16 nAux; /* # of auxiliary columns in %_rowid */
170#ifdef SQLITE_ENABLE_GEOPOLY
171 u8 nAuxNotNull; /* Number of initial not-null aux columns */
172#endif
173#ifdef SQLITE_DEBUG
174 u8 bCorrupt; /* Shadow table corruption detected */
175#endif
176 int iDepth; /* Current depth of the r-tree structure */
177 char *zDb; /* Name of database containing r-tree table */
178 char *zName; /* Name of r-tree table */
179 char *zNodeName; /* Name of the %_node table */
180 u32 nBusy; /* Current number of users of this structure */
181 i64 nRowEst; /* Estimated number of rows in this table */
182 u32 nCursor; /* Number of open cursors */
183 u32 nNodeRef; /* Number RtreeNodes with positive nRef */
184 char *zReadAuxSql; /* SQL for statement to read aux data */
185
186 /* List of nodes removed during a CondenseTree operation. List is
187 ** linked together via the pointer normally used for hash chains -
188 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
189 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
190 */
191 RtreeNode *pDeleted;
192
193 /* Blob I/O on xxx_node */
194 sqlite3_blob *pNodeBlob;
195
196 /* Statements to read/write/delete a record from xxx_node */
197 sqlite3_stmt *pWriteNode;
198 sqlite3_stmt *pDeleteNode;
199
200 /* Statements to read/write/delete a record from xxx_rowid */
201 sqlite3_stmt *pReadRowid;
202 sqlite3_stmt *pWriteRowid;
203 sqlite3_stmt *pDeleteRowid;
204
205 /* Statements to read/write/delete a record from xxx_parent */
206 sqlite3_stmt *pReadParent;
207 sqlite3_stmt *pWriteParent;
208 sqlite3_stmt *pDeleteParent;
209
210 /* Statement for writing to the "aux:" fields, if there are any */
211 sqlite3_stmt *pWriteAux;
212
213 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
214};
215
216/* Possible values for Rtree.eCoordType: */
217#define RTREE_COORD_REAL32 0
218#define RTREE_COORD_INT32 1
219
220/*
221** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
222** only deal with integer coordinates. No floating point operations
223** will be done.
224*/
225#ifdef SQLITE_RTREE_INT_ONLY
226 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
227 typedef int RtreeValue; /* Low accuracy coordinate */
228# define RTREE_ZERO 0
229#else
230 typedef double RtreeDValue; /* High accuracy coordinate */
231 typedef float RtreeValue; /* Low accuracy coordinate */
232# define RTREE_ZERO 0.0
233#endif
234
235/*
236** Set the Rtree.bCorrupt flag
237*/
238#ifdef SQLITE_DEBUG
239# define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
240#else
241# define RTREE_IS_CORRUPT(X)
242#endif
243
244/*
245** When doing a search of an r-tree, instances of the following structure
246** record intermediate results from the tree walk.
247**
248** The id is always a node-id. For iLevel>=1 the id is the node-id of
249** the node that the RtreeSearchPoint represents. When iLevel==0, however,
250** the id is of the parent node and the cell that RtreeSearchPoint
251** represents is the iCell-th entry in the parent node.
252*/
253struct RtreeSearchPoint {
254 RtreeDValue rScore; /* The score for this node. Smallest goes first. */
255 sqlite3_int64 id; /* Node ID */
256 u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
257 u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
258 u8 iCell; /* Cell index within the node */
259};
260
261/*
262** The minimum number of cells allowed for a node is a third of the
263** maximum. In Gutman's notation:
264**
265** m = M/3
266**
267** If an R*-tree "Reinsert" operation is required, the same number of
268** cells are removed from the overfull node and reinserted into the tree.
269*/
270#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
271#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
272#define RTREE_MAXCELLS 51
273
274/*
275** The smallest possible node-size is (512-64)==448 bytes. And the largest
276** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
277** Therefore all non-root nodes must contain at least 3 entries. Since
278** 3^40 is greater than 2^64, an r-tree structure always has a depth of
279** 40 or less.
280*/
281#define RTREE_MAX_DEPTH 40
282
283
284/*
285** Number of entries in the cursor RtreeNode cache. The first entry is
286** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
287** entries cache the RtreeNode for the first elements of the priority queue.
288*/
289#define RTREE_CACHE_SZ 5
290
291/*
292** An rtree cursor object.
293*/
294struct RtreeCursor {
295 sqlite3_vtab_cursor base; /* Base class. Must be first */
296 u8 atEOF; /* True if at end of search */
297 u8 bPoint; /* True if sPoint is valid */
298 u8 bAuxValid; /* True if pReadAux is valid */
299 int iStrategy; /* Copy of idxNum search parameter */
300 int nConstraint; /* Number of entries in aConstraint */
301 RtreeConstraint *aConstraint; /* Search constraints. */
302 int nPointAlloc; /* Number of slots allocated for aPoint[] */
303 int nPoint; /* Number of slots used in aPoint[] */
304 int mxLevel; /* iLevel value for root of the tree */
305 RtreeSearchPoint *aPoint; /* Priority queue for search points */
306 sqlite3_stmt *pReadAux; /* Statement to read aux-data */
307 RtreeSearchPoint sPoint; /* Cached next search point */
308 RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
309 u32 anQueue[RTREE_MAX_DEPTH+2]; /* Number of queued entries by iLevel */
310};
311
312/* Return the Rtree of a RtreeCursor */
313#define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
314
315/*
316** A coordinate can be either a floating point number or a integer. All
317** coordinates within a single R-Tree are always of the same time.
318*/
319union RtreeCoord {
320 RtreeValue f; /* Floating point value */
321 int i; /* Integer value */
322 u32 u; /* Unsigned for byte-order conversions */
323};
324
325/*
326** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
327** formatted as a RtreeDValue (double or int64). This macro assumes that local
328** variable pRtree points to the Rtree structure associated with the
329** RtreeCoord.
330*/
331#ifdef SQLITE_RTREE_INT_ONLY
332# define DCOORD(coord) ((RtreeDValue)coord.i)
333#else
334# define DCOORD(coord) ( \
335 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
336 ((double)coord.f) : \
337 ((double)coord.i) \
338 )
339#endif
340
341/*
342** A search constraint.
343*/
344struct RtreeConstraint {
345 int iCoord; /* Index of constrained coordinate */
346 int op; /* Constraining operation */
347 union {
348 RtreeDValue rValue; /* Constraint value. */
349 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
350 int (*xQueryFunc)(sqlite3_rtree_query_info*);
351 } u;
352 sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
353};
354
355/* Possible values for RtreeConstraint.op */
356#define RTREE_EQ 0x41 /* A */
357#define RTREE_LE 0x42 /* B */
358#define RTREE_LT 0x43 /* C */
359#define RTREE_GE 0x44 /* D */
360#define RTREE_GT 0x45 /* E */
361#define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
362#define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
363
364/* Special operators available only on cursors. Needs to be consecutive
365** with the normal values above, but must be less than RTREE_MATCH. These
366** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
367** x<'xyz' (RTREE_TRUE) */
368#define RTREE_TRUE 0x3f /* ? */
369#define RTREE_FALSE 0x40 /* @ */
370
371/*
372** An rtree structure node.
373*/
374struct RtreeNode {
375 RtreeNode *pParent; /* Parent node */
376 i64 iNode; /* The node number */
377 int nRef; /* Number of references to this node */
378 int isDirty; /* True if the node needs to be written to disk */
379 u8 *zData; /* Content of the node, as should be on disk */
380 RtreeNode *pNext; /* Next node in this hash collision chain */
381};
382
383/* Return the number of cells in a node */
384#define NCELL(pNode) readInt16(&(pNode)->zData[2])
385
386/*
387** A single cell from a node, deserialized
388*/
389struct RtreeCell {
390 i64 iRowid; /* Node or entry ID */
391 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
392};
393
394
395/*
396** This object becomes the sqlite3_user_data() for the SQL functions
397** that are created by sqlite3_rtree_geometry_callback() and
398** sqlite3_rtree_query_callback() and which appear on the right of MATCH
399** operators in order to constrain a search.
400**
401** xGeom and xQueryFunc are the callback functions. Exactly one of
402** xGeom and xQueryFunc fields is non-NULL, depending on whether the
403** SQL function was created using sqlite3_rtree_geometry_callback() or
404** sqlite3_rtree_query_callback().
405**
406** This object is deleted automatically by the destructor mechanism in
407** sqlite3_create_function_v2().
408*/
409struct RtreeGeomCallback {
410 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
411 int (*xQueryFunc)(sqlite3_rtree_query_info*);
412 void (*xDestructor)(void*);
413 void *pContext;
414};
415
416/*
417** An instance of this structure (in the form of a BLOB) is returned by
418** the SQL functions that sqlite3_rtree_geometry_callback() and
419** sqlite3_rtree_query_callback() create, and is read as the right-hand
420** operand to the MATCH operator of an R-Tree.
421*/
422struct RtreeMatchArg {
423 u32 iSize; /* Size of this object */
424 RtreeGeomCallback cb; /* Info about the callback functions */
425 int nParam; /* Number of parameters to the SQL function */
426 sqlite3_value **apSqlParam; /* Original SQL parameter values */
427 RtreeDValue aParam[FLEXARRAY]; /* Values for parameters to the SQL function */
428};
429
430/* Size of an RtreeMatchArg object with N parameters */
431#define SZ_RTREEMATCHARG(N) \
432 (offsetof(RtreeMatchArg,aParam)+(N)*sizeof(RtreeDValue))
433
434#ifndef MAX
435# define MAX(x,y) ((x) < (y) ? (y) : (x))
436#endif
437#ifndef MIN
438# define MIN(x,y) ((x) > (y) ? (y) : (x))
439#endif
440
441/* What version of GCC is being used. 0 means GCC is not being used .
442** Note that the GCC_VERSION macro will also be set correctly when using
443** clang, since clang works hard to be gcc compatible. So the gcc
444** optimizations will also work when compiling with clang.
445*/
446#ifndef GCC_VERSION
447#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
448# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
449#else
450# define GCC_VERSION 0
451#endif
452#endif
453
454/* The testcase() macro should already be defined in the amalgamation. If
455** it is not, make it a no-op.
456*/
457#ifndef SQLITE_AMALGAMATION
458# if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
459 unsigned int sqlite3RtreeTestcase = 0;
460# define testcase(X) if( X ){ sqlite3RtreeTestcase += __LINE__; }
461# else
462# define testcase(X)
463# endif
464#endif
465
466/*
467** Make sure that the compiler intrinsics we desire are enabled when
468** compiling with an appropriate version of MSVC unless prevented by
469** the SQLITE_DISABLE_INTRINSIC define.
470*/
471#if !defined(SQLITE_DISABLE_INTRINSIC)
472# if defined(_MSC_VER) && _MSC_VER>=1400
473# if !defined(_WIN32_WCE)
474# include <intrin.h>
475# pragma intrinsic(_byteswap_ulong)
476# pragma intrinsic(_byteswap_uint64)
477# else
478# include <cmnintrin.h>
479# endif
480# endif
481#endif
482
483/*
484** Macros to determine whether the machine is big or little endian,
485** and whether or not that determination is run-time or compile-time.
486**
487** For best performance, an attempt is made to guess at the byte-order
488** using C-preprocessor macros. If that is unsuccessful, or if
489** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
490** at run-time.
491*/
492#ifndef SQLITE_BYTEORDER /* Replicate changes at tag-20230904a */
493# if defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
494# define SQLITE_BYTEORDER 4321
495# elif defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
496# define SQLITE_BYTEORDER 1234
497# elif defined(__BIG_ENDIAN__) && __BIG_ENDIAN__==1
498# define SQLITE_BYTEORDER 4321
499# elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
500 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
501 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
502 defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
503# define SQLITE_BYTEORDER 1234
504# elif defined(sparc) || defined(__ARMEB__) || defined(__AARCH64EB__)
505# define SQLITE_BYTEORDER 4321
506# else
507# define SQLITE_BYTEORDER 0
508# endif
509#endif
510
511
512/* What version of MSVC is being used. 0 means MSVC is not being used */
513#ifndef MSVC_VERSION
514#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
515# define MSVC_VERSION _MSC_VER
516#else
517# define MSVC_VERSION 0
518#endif
519#endif
520
521/*
522** Functions to deserialize a 16 bit integer, 32 bit real number and
523** 64 bit integer. The deserialized value is returned.
524*/
525static int readInt16(u8 *p){
526 return (p[0]<<8) + p[1];
527}
528static void readCoord(u8 *p, RtreeCoord *pCoord){
529 assert( FOUR_BYTE_ALIGNED(p) );
530#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
531 pCoord->u = _byteswap_ulong(*(u32*)p);
532#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
533 pCoord->u = __builtin_bswap32(*(u32*)p);
534#elif SQLITE_BYTEORDER==4321
535 pCoord->u = *(u32*)p;
536#else
537 pCoord->u = (
538 (((u32)p[0]) << 24) +
539 (((u32)p[1]) << 16) +
540 (((u32)p[2]) << 8) +
541 (((u32)p[3]) << 0)
542 );
543#endif
544}
545
546static i64 readInt64(u8 *p){
547#if defined(SQLITE_AMALGAMATION)
548 return (i64)sqlite3Get8byte(p);
549#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
550 u64 x;
551 memcpy(&x, p, 8);
552 return (i64)_byteswap_uint64(x);
553#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
554 u64 x;
555 memcpy(&x, p, 8);
556 return (i64)__builtin_bswap64(x);
557#elif SQLITE_BYTEORDER==4321
558 i64 x;
559 memcpy(&x, p, 8);
560 return x;
561#else
562 return (i64)(
563 (((u64)p[0]) << 56) +
564 (((u64)p[1]) << 48) +
565 (((u64)p[2]) << 40) +
566 (((u64)p[3]) << 32) +
567 (((u64)p[4]) << 24) +
568 (((u64)p[5]) << 16) +
569 (((u64)p[6]) << 8) +
570 (((u64)p[7]) << 0)
571 );
572#endif
573}
574
575/*
576** Functions to serialize a 16 bit integer, 32 bit real number and
577** 64 bit integer. The value returned is the number of bytes written
578** to the argument buffer (always 2, 4 and 8 respectively).
579*/
580static void writeInt16(u8 *p, int i){
581 p[0] = (i>> 8)&0xFF;
582 p[1] = (i>> 0)&0xFF;
583}
584static int writeCoord(u8 *p, RtreeCoord *pCoord){
585 u32 i;
586 assert( FOUR_BYTE_ALIGNED(p) );
587 assert( sizeof(RtreeCoord)==4 );
588 assert( sizeof(u32)==4 );
589#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
590 i = __builtin_bswap32(pCoord->u);
591 memcpy(p, &i, 4);
592#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
593 i = _byteswap_ulong(pCoord->u);
594 memcpy(p, &i, 4);
595#elif SQLITE_BYTEORDER==4321
596 i = pCoord->u;
597 memcpy(p, &i, 4);
598#else
599 i = pCoord->u;
600 p[0] = (i>>24)&0xFF;
601 p[1] = (i>>16)&0xFF;
602 p[2] = (i>> 8)&0xFF;
603 p[3] = (i>> 0)&0xFF;
604#endif
605 return 4;
606}
607static int writeInt64(u8 *p, i64 i){
608#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
609 i = (i64)__builtin_bswap64((u64)i);
610 memcpy(p, &i, 8);
611#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
612 i = (i64)_byteswap_uint64((u64)i);
613 memcpy(p, &i, 8);
614#elif SQLITE_BYTEORDER==4321
615 memcpy(p, &i, 8);
616#else
617 p[0] = (i>>56)&0xFF;
618 p[1] = (i>>48)&0xFF;
619 p[2] = (i>>40)&0xFF;
620 p[3] = (i>>32)&0xFF;
621 p[4] = (i>>24)&0xFF;
622 p[5] = (i>>16)&0xFF;
623 p[6] = (i>> 8)&0xFF;
624 p[7] = (i>> 0)&0xFF;
625#endif
626 return 8;
627}
628
629/*
630** Translate pVal into a 32-bit integer. If pVal is an integer
631** that is larger than 32 bits, the cap it at the largest or
632** smallest 32-bit integer.
633*/
634static int rtreeValueInt32(sqlite3_value *pVal){
635 i64 v64 = sqlite3_value_int64(pVal);
636 if( v64>2147483647 ) return 2147483647;
637 if( v64<-2147483648LL ) return (int)-2147483648LL;
638 return (int)v64;
639}
640
641/*
642** Increment the reference count of node p.
643*/
644static void nodeReference(RtreeNode *p){
645 if( p ){
646 assert( p->nRef>0 );
647 p->nRef++;
648 }
649}
650
651/*
652** Clear the content of node p (set all bytes to 0x00).
653*/
654static void nodeZero(Rtree *pRtree, RtreeNode *p){
655 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
656 p->isDirty = 1;
657}
658
659/*
660** Given a node number iNode, return the corresponding key to use
661** in the Rtree.aHash table.
662*/
663static unsigned int nodeHash(i64 iNode){
664 return ((unsigned)iNode) % HASHSIZE;
665}
666
667/*
668** Search the node hash table for node iNode. If found, return a pointer
669** to it. Otherwise, return 0.
670*/
671static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
672 RtreeNode *p;
673 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
674 return p;
675}
676
677/*
678** Add node pNode to the node hash table.
679*/
680static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
681 int iHash;
682 assert( pNode->pNext==0 );
683 iHash = nodeHash(pNode->iNode);
684 pNode->pNext = pRtree->aHash[iHash];
685 pRtree->aHash[iHash] = pNode;
686}
687
688/*
689** Remove node pNode from the node hash table.
690*/
691static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
692 RtreeNode **pp;
693 if( pNode->iNode!=0 ){
694 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
695 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
696 *pp = pNode->pNext;
697 pNode->pNext = 0;
698 }
699}
700
701/*
702** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
703** indicating that node has not yet been assigned a node number. It is
704** assigned a node number when nodeWrite() is called to write the
705** node contents out to the database.
706*/
707static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
708 RtreeNode *pNode;
709 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
710 if( pNode ){
711 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
712 pNode->zData = (u8 *)&pNode[1];
713 pNode->nRef = 1;
714 pRtree->nNodeRef++;
715 pNode->pParent = pParent;
716 pNode->isDirty = 1;
717 nodeReference(pParent);
718 }
719 return pNode;
720}
721
722/*
723** Clear the Rtree.pNodeBlob object
724*/
725static void nodeBlobReset(Rtree *pRtree){
726 sqlite3_blob *pBlob = pRtree->pNodeBlob;
727 pRtree->pNodeBlob = 0;
728 sqlite3_blob_close(pBlob);
729}
730
731/*
732** Obtain a reference to an r-tree node.
733*/
734static int nodeAcquire(
735 Rtree *pRtree, /* R-tree structure */
736 i64 iNode, /* Node number to load */
737 RtreeNode *pParent, /* Either the parent node or NULL */
738 RtreeNode **ppNode /* OUT: Acquired node */
739){
740 int rc = SQLITE_OK;
741 RtreeNode *pNode = 0;
742
743 /* Check if the requested node is already in the hash table. If so,
744 ** increase its reference count and return it.
745 */
746 if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
747 if( pParent && ALWAYS(pParent!=pNode->pParent) ){
748 RTREE_IS_CORRUPT(pRtree);
749 return SQLITE_CORRUPT_VTAB;
750 }
751 pNode->nRef++;
752 *ppNode = pNode;
753 return SQLITE_OK;
754 }
755
756 if( pRtree->pNodeBlob ){
757 sqlite3_blob *pBlob = pRtree->pNodeBlob;
758 pRtree->pNodeBlob = 0;
759 rc = sqlite3_blob_reopen(pBlob, iNode);
760 pRtree->pNodeBlob = pBlob;
761 if( rc ){
762 nodeBlobReset(pRtree);
763 if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
764 }
765 }
766 if( pRtree->pNodeBlob==0 ){
767 rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, pRtree->zNodeName,
768 "data", iNode, 0,
769 &pRtree->pNodeBlob);
770 }
771 if( rc ){
772 *ppNode = 0;
773 /* If unable to open an sqlite3_blob on the desired row, that can only
774 ** be because the shadow tables hold erroneous data. */
775 if( rc==SQLITE_ERROR ){
776 rc = SQLITE_CORRUPT_VTAB;
777 RTREE_IS_CORRUPT(pRtree);
778 }
779 }else if( iNode<=0 ){
780 RTREE_IS_CORRUPT(pRtree);
781 rc = SQLITE_CORRUPT_VTAB;
782 }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
783 pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
784 if( !pNode ){
785 rc = SQLITE_NOMEM;
786 }else{
787 pNode->pParent = pParent;
788 pNode->zData = (u8 *)&pNode[1];
789 pNode->nRef = 1;
790 pRtree->nNodeRef++;
791 pNode->iNode = iNode;
792 pNode->isDirty = 0;
793 pNode->pNext = 0;
794 rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
795 pRtree->iNodeSize, 0);
796 }
797 }
798
799 /* If the root node was just loaded, set pRtree->iDepth to the height
800 ** of the r-tree structure. A height of zero means all data is stored on
801 ** the root node. A height of one means the children of the root node
802 ** are the leaves, and so on. If the depth as specified on the root node
803 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
804 */
805 if( rc==SQLITE_OK && pNode && iNode==1 ){
806 pRtree->iDepth = readInt16(pNode->zData);
807 if( pRtree->iDepth>=RTREE_MAX_DEPTH ){
808 rc = SQLITE_CORRUPT_VTAB;
809 RTREE_IS_CORRUPT(pRtree);
810 }
811 }
812
813 /* If no error has occurred so far, check if the "number of entries"
814 ** field on the node is too large. If so, set the return code to
815 ** SQLITE_CORRUPT_VTAB.
816 */
817 if( pNode && rc==SQLITE_OK ){
818 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
819 rc = SQLITE_CORRUPT_VTAB;
820 RTREE_IS_CORRUPT(pRtree);
821 }
822 }
823
824 if( rc==SQLITE_OK ){
825 if( pNode!=0 ){
826 nodeReference(pParent);
827 nodeHashInsert(pRtree, pNode);
828 }else{
829 rc = SQLITE_CORRUPT_VTAB;
830 RTREE_IS_CORRUPT(pRtree);
831 }
832 *ppNode = pNode;
833 }else{
834 nodeBlobReset(pRtree);
835 if( pNode ){
836 pRtree->nNodeRef--;
837 sqlite3_free(pNode);
838 }
839 *ppNode = 0;
840 }
841
842 return rc;
843}
844
845/*
846** Overwrite cell iCell of node pNode with the contents of pCell.
847*/
848static void nodeOverwriteCell(
849 Rtree *pRtree, /* The overall R-Tree */
850 RtreeNode *pNode, /* The node into which the cell is to be written */
851 RtreeCell *pCell, /* The cell to write */
852 int iCell /* Index into pNode into which pCell is written */
853){
854 int ii;
855 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
856 p += writeInt64(p, pCell->iRowid);
857 for(ii=0; ii<pRtree->nDim2; ii++){
858 p += writeCoord(p, &pCell->aCoord[ii]);
859 }
860 pNode->isDirty = 1;
861}
862
863/*
864** Remove the cell with index iCell from node pNode.
865*/
866static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
867 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
868 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
869 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
870 memmove(pDst, pSrc, nByte);
871 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
872 pNode->isDirty = 1;
873}
874
875/*
876** Insert the contents of cell pCell into node pNode. If the insert
877** is successful, return SQLITE_OK.
878**
879** If there is not enough free space in pNode, return SQLITE_FULL.
880*/
881static int nodeInsertCell(
882 Rtree *pRtree, /* The overall R-Tree */
883 RtreeNode *pNode, /* Write new cell into this node */
884 RtreeCell *pCell /* The cell to be inserted */
885){
886 int nCell; /* Current number of cells in pNode */
887 int nMaxCell; /* Maximum number of cells for pNode */
888
889 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
890 nCell = NCELL(pNode);
891
892 assert( nCell<=nMaxCell );
893 if( nCell<nMaxCell ){
894 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
895 writeInt16(&pNode->zData[2], nCell+1);
896 pNode->isDirty = 1;
897 }
898
899 return (nCell==nMaxCell);
900}
901
902/*
903** If the node is dirty, write it out to the database.
904*/
905static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
906 int rc = SQLITE_OK;
907 if( pNode->isDirty ){
908 sqlite3_stmt *p = pRtree->pWriteNode;
909 if( pNode->iNode ){
910 sqlite3_bind_int64(p, 1, pNode->iNode);
911 }else{
912 sqlite3_bind_null(p, 1);
913 }
914 rc = sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize,
915 SQLITE_STATIC);
916 if( rc!=SQLITE_OK ) return rc;
917 sqlite3_step(p);
918 pNode->isDirty = 0;
919 rc = sqlite3_reset(p);
920 sqlite3_bind_null(p, 2);
921 if( pNode->iNode==0 && rc==SQLITE_OK ){
922 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
923 if( pNode->iNode==0 ){
924 /* If the SQL statement has succeeded but sqlite3_last_insert_rowid()
925 ** returns 0, then the shadow table schema has been corrupted somehow
926 ** (e.g. the %_node table has been replaced by a WITHOUT ROWID table).
927 ** It would be dangerous to continue in this case as the hash table
928 ** implementation assumes iNode==0 means that the node is not part
929 ** of the hash table. */
930 rc = SQLITE_CORRUPT_VTAB;
931 }else{
932 nodeHashInsert(pRtree, pNode);
933 }
934 }
935 }
936 return rc;
937}
938
939/*
940** Release a reference to a node. If the node is dirty and the reference
941** count drops to zero, the node data is written to the database.
942*/
943static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
944 int rc = SQLITE_OK;
945 if( pNode ){
946 assert( pNode->nRef>0 );
947 assert( pRtree->nNodeRef>0 );
948 pNode->nRef--;
949 if( pNode->nRef==0 ){
950 pRtree->nNodeRef--;
951 if( pNode->iNode==1 ){
952 pRtree->iDepth = -1;
953 }
954 if( pNode->pParent ){
955 rc = nodeRelease(pRtree, pNode->pParent);
956 }
957 if( rc==SQLITE_OK ){
958 rc = nodeWrite(pRtree, pNode);
959 }
960 nodeHashDelete(pRtree, pNode);
961 sqlite3_free(pNode);
962 }
963 }
964 return rc;
965}
966
967/*
968** Return the 64-bit integer value associated with cell iCell of
969** node pNode. If pNode is a leaf node, this is a rowid. If it is
970** an internal node, then the 64-bit integer is a child page number.
971*/
972static i64 nodeGetRowid(
973 Rtree *pRtree, /* The overall R-Tree */
974 RtreeNode *pNode, /* The node from which to extract the ID */
975 int iCell /* The cell index from which to extract the ID */
976){
977 assert( iCell<NCELL(pNode) );
978 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
979}
980
981/*
982** Return coordinate iCoord from cell iCell in node pNode.
983*/
984static void nodeGetCoord(
985 Rtree *pRtree, /* The overall R-Tree */
986 RtreeNode *pNode, /* The node from which to extract a coordinate */
987 int iCell, /* The index of the cell within the node */
988 int iCoord, /* Which coordinate to extract */
989 RtreeCoord *pCoord /* OUT: Space to write result to */
990){
991 assert( iCell<NCELL(pNode) );
992 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
993}
994
995/*
996** Deserialize cell iCell of node pNode. Populate the structure pointed
997** to by pCell with the results.
998*/
999static void nodeGetCell(
1000 Rtree *pRtree, /* The overall R-Tree */
1001 RtreeNode *pNode, /* The node containing the cell to be read */
1002 int iCell, /* Index of the cell within the node */
1003 RtreeCell *pCell /* OUT: Write the cell contents here */
1004){
1005 u8 *pData;
1006 RtreeCoord *pCoord;
1007 int ii = 0;
1008 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
1009 pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
1010 pCoord = pCell->aCoord;
1011 do{
1012 readCoord(pData, &pCoord[ii]);
1013 readCoord(pData+4, &pCoord[ii+1]);
1014 pData += 8;
1015 ii += 2;
1016 }while( ii<pRtree->nDim2 );
1017}
1018
1019
1020/* Forward declaration for the function that does the work of
1021** the virtual table module xCreate() and xConnect() methods.
1022*/
1023static int rtreeInit(
1024 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
1025);
1026
1027/*
1028** Rtree virtual table module xCreate method.
1029*/
1030static int rtreeCreate(
1031 sqlite3 *db,
1032 void *pAux,
1033 int argc, const char *const*argv,
1034 sqlite3_vtab **ppVtab,
1035 char **pzErr
1036){
1037 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
1038}
1039
1040/*
1041** Rtree virtual table module xConnect method.
1042*/
1043static int rtreeConnect(
1044 sqlite3 *db,
1045 void *pAux,
1046 int argc, const char *const*argv,
1047 sqlite3_vtab **ppVtab,
1048 char **pzErr
1049){
1050 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
1051}
1052
1053/*
1054** Increment the r-tree reference count.
1055*/
1056static void rtreeReference(Rtree *pRtree){
1057 pRtree->nBusy++;
1058}
1059
1060/*
1061** Decrement the r-tree reference count. When the reference count reaches
1062** zero the structure is deleted.
1063*/
1064static void rtreeRelease(Rtree *pRtree){
1065 pRtree->nBusy--;
1066 if( pRtree->nBusy==0 ){
1067 pRtree->inWrTrans = 0;
1068 assert( pRtree->nCursor==0 );
1069 nodeBlobReset(pRtree);
1070 if( pRtree->nNodeRef ){
1071 int i;
1072 assert( pRtree->bCorrupt );
1073 for(i=0; i<HASHSIZE; i++){
1074 while( pRtree->aHash[i] ){
1075 RtreeNode *pNext = pRtree->aHash[i]->pNext;
1076 sqlite3_free(pRtree->aHash[i]);
1077 pRtree->aHash[i] = pNext;
1078 }
1079 }
1080 }
1081 sqlite3_finalize(pRtree->pWriteNode);
1082 sqlite3_finalize(pRtree->pDeleteNode);
1083 sqlite3_finalize(pRtree->pReadRowid);
1084 sqlite3_finalize(pRtree->pWriteRowid);
1085 sqlite3_finalize(pRtree->pDeleteRowid);
1086 sqlite3_finalize(pRtree->pReadParent);
1087 sqlite3_finalize(pRtree->pWriteParent);
1088 sqlite3_finalize(pRtree->pDeleteParent);
1089 sqlite3_finalize(pRtree->pWriteAux);
1090 sqlite3_free(pRtree->zReadAuxSql);
1091 sqlite3_free(pRtree);
1092 }
1093}
1094
1095/*
1096** Rtree virtual table module xDisconnect method.
1097*/
1098static int rtreeDisconnect(sqlite3_vtab *pVtab){
1099 rtreeRelease((Rtree *)pVtab);
1100 return SQLITE_OK;
1101}
1102
1103/*
1104** Rtree virtual table module xDestroy method.
1105*/
1106static int rtreeDestroy(sqlite3_vtab *pVtab){
1107 Rtree *pRtree = (Rtree *)pVtab;
1108 int rc;
1109 char *zCreate = sqlite3_mprintf(
1110 "DROP TABLE '%q'.'%q_node';"
1111 "DROP TABLE '%q'.'%q_rowid';"
1112 "DROP TABLE '%q'.'%q_parent';",
1113 pRtree->zDb, pRtree->zName,
1114 pRtree->zDb, pRtree->zName,
1115 pRtree->zDb, pRtree->zName
1116 );
1117 if( !zCreate ){
1118 rc = SQLITE_NOMEM;
1119 }else{
1120 nodeBlobReset(pRtree);
1121 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
1122 sqlite3_free(zCreate);
1123 }
1124 if( rc==SQLITE_OK ){
1125 rtreeRelease(pRtree);
1126 }
1127
1128 return rc;
1129}
1130
1131/*
1132** Rtree virtual table module xOpen method.
1133*/
1134static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
1135 int rc = SQLITE_NOMEM;
1136 Rtree *pRtree = (Rtree *)pVTab;
1137 RtreeCursor *pCsr;
1138
1139 pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
1140 if( pCsr ){
1141 memset(pCsr, 0, sizeof(RtreeCursor));
1142 pCsr->base.pVtab = pVTab;
1143 rc = SQLITE_OK;
1144 pRtree->nCursor++;
1145 }
1146 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
1147
1148 return rc;
1149}
1150
1151
1152/*
1153** Reset a cursor back to its initial state.
1154*/
1155static void resetCursor(RtreeCursor *pCsr){
1156 Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
1157 int ii;
1158 sqlite3_stmt *pStmt;
1159 if( pCsr->aConstraint ){
1160 int i; /* Used to iterate through constraint array */
1161 for(i=0; i<pCsr->nConstraint; i++){
1162 sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
1163 if( pInfo ){
1164 if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
1165 sqlite3_free(pInfo);
1166 }
1167 }
1168 sqlite3_free(pCsr->aConstraint);
1169 pCsr->aConstraint = 0;
1170 }
1171 for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
1172 sqlite3_free(pCsr->aPoint);
1173 pStmt = pCsr->pReadAux;
1174 memset(pCsr, 0, sizeof(RtreeCursor));
1175 pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
1176 pCsr->pReadAux = pStmt;
1177
1178 /* The following will only fail if the previous sqlite3_step() call failed,
1179 ** in which case the error has already been caught. This statement never
1180 ** encounters an error within an sqlite3_column_xxx() function, as it
1181 ** calls sqlite3_column_value(), which does not use malloc(). So it is safe
1182 ** to ignore the error code here. */
1183 sqlite3_reset(pStmt);
1184}
1185
1186/*
1187** Rtree virtual table module xClose method.
1188*/
1189static int rtreeClose(sqlite3_vtab_cursor *cur){
1190 Rtree *pRtree = (Rtree *)(cur->pVtab);
1191 RtreeCursor *pCsr = (RtreeCursor *)cur;
1192 assert( pRtree->nCursor>0 );
1193 resetCursor(pCsr);
1194 sqlite3_finalize(pCsr->pReadAux);
1195 sqlite3_free(pCsr);
1196 pRtree->nCursor--;
1197 if( pRtree->nCursor==0 && pRtree->inWrTrans==0 ){
1198 nodeBlobReset(pRtree);
1199 }
1200 return SQLITE_OK;
1201}
1202
1203/*
1204** Rtree virtual table module xEof method.
1205**
1206** Return non-zero if the cursor does not currently point to a valid
1207** record (i.e if the scan has finished), or zero otherwise.
1208*/
1209static int rtreeEof(sqlite3_vtab_cursor *cur){
1210 RtreeCursor *pCsr = (RtreeCursor *)cur;
1211 return pCsr->atEOF;
1212}
1213
1214/*
1215** Convert raw bits from the on-disk RTree record into a coordinate value.
1216** The on-disk format is big-endian and needs to be converted for little-
1217** endian platforms. The on-disk record stores integer coordinates if
1218** eInt is true and it stores 32-bit floating point records if eInt is
1219** false. a[] is the four bytes of the on-disk record to be decoded.
1220** Store the results in "r".
1221**
1222** There are five versions of this macro. The last one is generic. The
1223** other four are various architectures-specific optimizations.
1224*/
1225#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
1226#define RTREE_DECODE_COORD(eInt, a, r) { \
1227 RtreeCoord c; /* Coordinate decoded */ \
1228 c.u = _byteswap_ulong(*(u32*)a); \
1229 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1230}
1231#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
1232#define RTREE_DECODE_COORD(eInt, a, r) { \
1233 RtreeCoord c; /* Coordinate decoded */ \
1234 c.u = __builtin_bswap32(*(u32*)a); \
1235 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1236}
1237#elif SQLITE_BYTEORDER==1234
1238#define RTREE_DECODE_COORD(eInt, a, r) { \
1239 RtreeCoord c; /* Coordinate decoded */ \
1240 memcpy(&c.u,a,4); \
1241 c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
1242 ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
1243 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1244}
1245#elif SQLITE_BYTEORDER==4321
1246#define RTREE_DECODE_COORD(eInt, a, r) { \
1247 RtreeCoord c; /* Coordinate decoded */ \
1248 memcpy(&c.u,a,4); \
1249 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1250}
1251#else
1252#define RTREE_DECODE_COORD(eInt, a, r) { \
1253 RtreeCoord c; /* Coordinate decoded */ \
1254 c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
1255 +((u32)a[2]<<8) + a[3]; \
1256 r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
1257}
1258#endif
1259
1260/*
1261** Check the RTree node or entry given by pCellData and p against the MATCH
1262** constraint pConstraint.
1263*/
1264static int rtreeCallbackConstraint(
1265 RtreeConstraint *pConstraint, /* The constraint to test */
1266 int eInt, /* True if RTree holding integer coordinates */
1267 u8 *pCellData, /* Raw cell content */
1268 RtreeSearchPoint *pSearch, /* Container of this cell */
1269 sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
1270 int *peWithin /* OUT: visibility of the cell */
1271){
1272 sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
1273 int nCoord = pInfo->nCoord; /* No. of coordinates */
1274 int rc; /* Callback return code */
1275 RtreeCoord c; /* Translator union */
1276 sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
1277
1278 assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
1279 assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
1280
1281 if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
1282 pInfo->iRowid = readInt64(pCellData);
1283 }
1284 pCellData += 8;
1285#ifndef SQLITE_RTREE_INT_ONLY
1286 if( eInt==0 ){
1287 switch( nCoord ){
1288 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
1289 readCoord(pCellData+32, &c); aCoord[8] = c.f;
1290 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
1291 readCoord(pCellData+24, &c); aCoord[6] = c.f;
1292 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
1293 readCoord(pCellData+16, &c); aCoord[4] = c.f;
1294 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
1295 readCoord(pCellData+8, &c); aCoord[2] = c.f;
1296 default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
1297 readCoord(pCellData, &c); aCoord[0] = c.f;
1298 }
1299 }else
1300#endif
1301 {
1302 switch( nCoord ){
1303 case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
1304 readCoord(pCellData+32, &c); aCoord[8] = c.i;
1305 case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
1306 readCoord(pCellData+24, &c); aCoord[6] = c.i;
1307 case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
1308 readCoord(pCellData+16, &c); aCoord[4] = c.i;
1309 case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
1310 readCoord(pCellData+8, &c); aCoord[2] = c.i;
1311 default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
1312 readCoord(pCellData, &c); aCoord[0] = c.i;
1313 }
1314 }
1315 if( pConstraint->op==RTREE_MATCH ){
1316 int eWithin = 0;
1317 rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
1318 nCoord, aCoord, &eWithin);
1319 if( eWithin==0 ) *peWithin = NOT_WITHIN;
1320 *prScore = RTREE_ZERO;
1321 }else{
1322 pInfo->aCoord = aCoord;
1323 pInfo->iLevel = pSearch->iLevel - 1;
1324 pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
1325 pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
1326 rc = pConstraint->u.xQueryFunc(pInfo);
1327 if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
1328 if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
1329 *prScore = pInfo->rScore;
1330 }
1331 }
1332 return rc;
1333}
1334
1335/*
1336** Check the internal RTree node given by pCellData against constraint p.
1337** If this constraint cannot be satisfied by any child within the node,
1338** set *peWithin to NOT_WITHIN.
1339*/
1340static void rtreeNonleafConstraint(
1341 RtreeConstraint *p, /* The constraint to test */
1342 int eInt, /* True if RTree holds integer coordinates */
1343 u8 *pCellData, /* Raw cell content as appears on disk */
1344 int *peWithin /* Adjust downward, as appropriate */
1345){
1346 sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
1347
1348 /* p->iCoord might point to either a lower or upper bound coordinate
1349 ** in a coordinate pair. But make pCellData point to the lower bound.
1350 */
1351 pCellData += 8 + 4*(p->iCoord&0xfe);
1352
1353 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1354 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1355 || p->op==RTREE_FALSE );
1356 assert( FOUR_BYTE_ALIGNED(pCellData) );
1357 switch( p->op ){
1358 case RTREE_TRUE: return; /* Always satisfied */
1359 case RTREE_FALSE: break; /* Never satisfied */
1360 case RTREE_EQ:
1361 RTREE_DECODE_COORD(eInt, pCellData, val);
1362 /* val now holds the lower bound of the coordinate pair */
1363 if( p->u.rValue>=val ){
1364 pCellData += 4;
1365 RTREE_DECODE_COORD(eInt, pCellData, val);
1366 /* val now holds the upper bound of the coordinate pair */
1367 if( p->u.rValue<=val ) return;
1368 }
1369 break;
1370 case RTREE_LE:
1371 case RTREE_LT:
1372 RTREE_DECODE_COORD(eInt, pCellData, val);
1373 /* val now holds the lower bound of the coordinate pair */
1374 if( p->u.rValue>=val ) return;
1375 break;
1376
1377 default:
1378 pCellData += 4;
1379 RTREE_DECODE_COORD(eInt, pCellData, val);
1380 /* val now holds the upper bound of the coordinate pair */
1381 if( p->u.rValue<=val ) return;
1382 break;
1383 }
1384 *peWithin = NOT_WITHIN;
1385}
1386
1387/*
1388** Check the leaf RTree cell given by pCellData against constraint p.
1389** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
1390** If the constraint is satisfied, leave *peWithin unchanged.
1391**
1392** The constraint is of the form: xN op $val
1393**
1394** The op is given by p->op. The xN is p->iCoord-th coordinate in
1395** pCellData. $val is given by p->u.rValue.
1396*/
1397static void rtreeLeafConstraint(
1398 RtreeConstraint *p, /* The constraint to test */
1399 int eInt, /* True if RTree holds integer coordinates */
1400 u8 *pCellData, /* Raw cell content as appears on disk */
1401 int *peWithin /* Adjust downward, as appropriate */
1402){
1403 RtreeDValue xN; /* Coordinate value converted to a double */
1404
1405 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1406 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1407 || p->op==RTREE_FALSE );
1408 pCellData += 8 + p->iCoord*4;
1409 assert( FOUR_BYTE_ALIGNED(pCellData) );
1410 RTREE_DECODE_COORD(eInt, pCellData, xN);
1411 switch( p->op ){
1412 case RTREE_TRUE: return; /* Always satisfied */
1413 case RTREE_FALSE: break; /* Never satisfied */
1414 case RTREE_LE: if( xN <= p->u.rValue ) return; break;
1415 case RTREE_LT: if( xN < p->u.rValue ) return; break;
1416 case RTREE_GE: if( xN >= p->u.rValue ) return; break;
1417 case RTREE_GT: if( xN > p->u.rValue ) return; break;
1418 default: if( xN == p->u.rValue ) return; break;
1419 }
1420 *peWithin = NOT_WITHIN;
1421}
1422
1423/*
1424** One of the cells in node pNode is guaranteed to have a 64-bit
1425** integer value equal to iRowid. Return the index of this cell.
1426*/
1427static int nodeRowidIndex(
1428 Rtree *pRtree,
1429 RtreeNode *pNode,
1430 i64 iRowid,
1431 int *piIndex
1432){
1433 int ii;
1434 int nCell = NCELL(pNode);
1435 assert( nCell<65536 && nCell>=0 );
1436 for(ii=0; ii<nCell; ii++){
1437 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1438 *piIndex = ii;
1439 return SQLITE_OK;
1440 }
1441 }
1442 RTREE_IS_CORRUPT(pRtree);
1443 return SQLITE_CORRUPT_VTAB;
1444}
1445
1446/*
1447** Return the index of the cell containing a pointer to node pNode
1448** in its parent. If pNode is the root node, return -1.
1449*/
1450static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1451 RtreeNode *pParent = pNode->pParent;
1452 if( ALWAYS(pParent) ){
1453 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
1454 }else{
1455 *piIndex = -1;
1456 return SQLITE_OK;
1457 }
1458}
1459
1460/*
1461** Compare two search points. Return negative, zero, or positive if the first
1462** is less than, equal to, or greater than the second.
1463**
1464** The rScore is the primary key. Smaller rScore values come first.
1465** If the rScore is a tie, then use iLevel as the tie breaker with smaller
1466** iLevel values coming first. In this way, if rScore is the same for all
1467** SearchPoints, then iLevel becomes the deciding factor and the result
1468** is a depth-first search, which is the desired default behavior.
1469*/
1470static int rtreeSearchPointCompare(
1471 const RtreeSearchPoint *pA,
1472 const RtreeSearchPoint *pB
1473){
1474 if( pA->rScore<pB->rScore ) return -1;
1475 if( pA->rScore>pB->rScore ) return +1;
1476 if( pA->iLevel<pB->iLevel ) return -1;
1477 if( pA->iLevel>pB->iLevel ) return +1;
1478 return 0;
1479}
1480
1481/*
1482** Interchange two search points in a cursor.
1483*/
1484static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
1485 RtreeSearchPoint t = p->aPoint[i];
1486 assert( i<j );
1487 p->aPoint[i] = p->aPoint[j];
1488 p->aPoint[j] = t;
1489 i++; j++;
1490 if( i<RTREE_CACHE_SZ ){
1491 if( j>=RTREE_CACHE_SZ ){
1492 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1493 p->aNode[i] = 0;
1494 }else{
1495 RtreeNode *pTemp = p->aNode[i];
1496 p->aNode[i] = p->aNode[j];
1497 p->aNode[j] = pTemp;
1498 }
1499 }
1500}
1501
1502/*
1503** Return the search point with the lowest current score.
1504*/
1505static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
1506 return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
1507}
1508
1509/*
1510** Get the RtreeNode for the search point with the lowest score.
1511*/
1512static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
1513 sqlite3_int64 id;
1514 int ii = 1 - pCur->bPoint;
1515 assert( ii==0 || ii==1 );
1516 assert( pCur->bPoint || pCur->nPoint );
1517 if( pCur->aNode[ii]==0 ){
1518 assert( pRC!=0 );
1519 id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
1520 *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
1521 }
1522 return pCur->aNode[ii];
1523}
1524
1525/*
1526** Push a new element onto the priority queue
1527*/
1528static RtreeSearchPoint *rtreeEnqueue(
1529 RtreeCursor *pCur, /* The cursor */
1530 RtreeDValue rScore, /* Score for the new search point */
1531 u8 iLevel /* Level for the new search point */
1532){
1533 int i, j;
1534 RtreeSearchPoint *pNew;
1535 if( pCur->nPoint>=pCur->nPointAlloc ){
1536 int nNew = pCur->nPointAlloc*2 + 8;
1537 pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
1538 if( pNew==0 ) return 0;
1539 pCur->aPoint = pNew;
1540 pCur->nPointAlloc = nNew;
1541 }
1542 i = pCur->nPoint++;
1543 pNew = pCur->aPoint + i;
1544 pNew->rScore = rScore;
1545 pNew->iLevel = iLevel;
1546 assert( iLevel<=RTREE_MAX_DEPTH );
1547 while( i>0 ){
1548 RtreeSearchPoint *pParent;
1549 j = (i-1)/2;
1550 pParent = pCur->aPoint + j;
1551 if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
1552 rtreeSearchPointSwap(pCur, j, i);
1553 i = j;
1554 pNew = pParent;
1555 }
1556 return pNew;
1557}
1558
1559/*
1560** Allocate a new RtreeSearchPoint and return a pointer to it. Return
1561** NULL if malloc fails.
1562*/
1563static RtreeSearchPoint *rtreeSearchPointNew(
1564 RtreeCursor *pCur, /* The cursor */
1565 RtreeDValue rScore, /* Score for the new search point */
1566 u8 iLevel /* Level for the new search point */
1567){
1568 RtreeSearchPoint *pNew, *pFirst;
1569 pFirst = rtreeSearchPointFirst(pCur);
1570 pCur->anQueue[iLevel]++;
1571 if( pFirst==0
1572 || pFirst->rScore>rScore
1573 || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
1574 ){
1575 if( pCur->bPoint ){
1576 int ii;
1577 pNew = rtreeEnqueue(pCur, rScore, iLevel);
1578 if( pNew==0 ) return 0;
1579 ii = (int)(pNew - pCur->aPoint) + 1;
1580 assert( ii==1 );
1581 if( ALWAYS(ii<RTREE_CACHE_SZ) ){
1582 assert( pCur->aNode[ii]==0 );
1583 pCur->aNode[ii] = pCur->aNode[0];
1584 }else{
1585 nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
1586 }
1587 pCur->aNode[0] = 0;
1588 *pNew = pCur->sPoint;
1589 }
1590 pCur->sPoint.rScore = rScore;
1591 pCur->sPoint.iLevel = iLevel;
1592 pCur->bPoint = 1;
1593 return &pCur->sPoint;
1594 }else{
1595 return rtreeEnqueue(pCur, rScore, iLevel);
1596 }
1597}
1598
1599#if 0
1600/* Tracing routines for the RtreeSearchPoint queue */
1601static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
1602 if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
1603 printf(" %d.%05lld.%02d %g %d",
1604 p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
1605 );
1606 idx++;
1607 if( idx<RTREE_CACHE_SZ ){
1608 printf(" %p\n", pCur->aNode[idx]);
1609 }else{
1610 printf("\n");
1611 }
1612}
1613static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
1614 int ii;
1615 printf("=== %9s ", zPrefix);
1616 if( pCur->bPoint ){
1617 tracePoint(&pCur->sPoint, -1, pCur);
1618 }
1619 for(ii=0; ii<pCur->nPoint; ii++){
1620 if( ii>0 || pCur->bPoint ) printf(" ");
1621 tracePoint(&pCur->aPoint[ii], ii, pCur);
1622 }
1623}
1624# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
1625#else
1626# define RTREE_QUEUE_TRACE(A,B) /* no-op */
1627#endif
1628
1629/* Remove the search point with the lowest current score.
1630*/
1631static void rtreeSearchPointPop(RtreeCursor *p){
1632 int i, j, k, n;
1633 i = 1 - p->bPoint;
1634 assert( i==0 || i==1 );
1635 if( p->aNode[i] ){
1636 nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
1637 p->aNode[i] = 0;
1638 }
1639 if( p->bPoint ){
1640 p->anQueue[p->sPoint.iLevel]--;
1641 p->bPoint = 0;
1642 }else if( ALWAYS(p->nPoint) ){
1643 p->anQueue[p->aPoint[0].iLevel]--;
1644 n = --p->nPoint;
1645 p->aPoint[0] = p->aPoint[n];
1646 if( n<RTREE_CACHE_SZ-1 ){
1647 p->aNode[1] = p->aNode[n+1];
1648 p->aNode[n+1] = 0;
1649 }
1650 i = 0;
1651 while( (j = i*2+1)<n ){
1652 k = j+1;
1653 if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
1654 if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
1655 rtreeSearchPointSwap(p, i, k);
1656 i = k;
1657 }else{
1658 break;
1659 }
1660 }else{
1661 if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
1662 rtreeSearchPointSwap(p, i, j);
1663 i = j;
1664 }else{
1665 break;
1666 }
1667 }
1668 }
1669 }
1670}
1671
1672
1673/*
1674** Continue the search on cursor pCur until the front of the queue
1675** contains an entry suitable for returning as a result-set row,
1676** or until the RtreeSearchPoint queue is empty, indicating that the
1677** query has completed.
1678*/
1679static int rtreeStepToLeaf(RtreeCursor *pCur){
1680 RtreeSearchPoint *p;
1681 Rtree *pRtree = RTREE_OF_CURSOR(pCur);
1682 RtreeNode *pNode;
1683 int eWithin;
1684 int rc = SQLITE_OK;
1685 int nCell;
1686 int nConstraint = pCur->nConstraint;
1687 int ii;
1688 int eInt;
1689 RtreeSearchPoint x;
1690
1691 eInt = pRtree->eCoordType==RTREE_COORD_INT32;
1692 while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
1693 u8 *pCellData;
1694 pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
1695 if( rc ) return rc;
1696 nCell = NCELL(pNode);
1697 if( nCell>RTREE_MAXCELLS ){
1698 RTREE_IS_CORRUPT(pRtree);
1699 return SQLITE_CORRUPT_VTAB;
1700 }
1701 pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
1702 while( p->iCell<nCell ){
1703 sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
1704 eWithin = FULLY_WITHIN;
1705 for(ii=0; ii<nConstraint; ii++){
1706 RtreeConstraint *pConstraint = pCur->aConstraint + ii;
1707 if( pConstraint->op>=RTREE_MATCH ){
1708 rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
1709 &rScore, &eWithin);
1710 if( rc ) return rc;
1711 }else if( p->iLevel==1 ){
1712 rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
1713 }else{
1714 rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
1715 }
1716 if( eWithin==NOT_WITHIN ){
1717 p->iCell++;
1718 pCellData += pRtree->nBytesPerCell;
1719 break;
1720 }
1721 }
1722 if( eWithin==NOT_WITHIN ) continue;
1723 p->iCell++;
1724 x.iLevel = p->iLevel - 1;
1725 if( x.iLevel ){
1726 x.id = readInt64(pCellData);
1727 for(ii=0; ii<pCur->nPoint; ii++){
1728 if( pCur->aPoint[ii].id==x.id ){
1729 RTREE_IS_CORRUPT(pRtree);
1730 return SQLITE_CORRUPT_VTAB;
1731 }
1732 }
1733 x.iCell = 0;
1734 }else{
1735 x.id = p->id;
1736 x.iCell = p->iCell - 1;
1737 }
1738 if( p->iCell>=nCell ){
1739 RTREE_QUEUE_TRACE(pCur, "POP-S:");
1740 rtreeSearchPointPop(pCur);
1741 }
1742 if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
1743 p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
1744 if( p==0 ) return SQLITE_NOMEM;
1745 p->eWithin = (u8)eWithin;
1746 p->id = x.id;
1747 p->iCell = x.iCell;
1748 RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
1749 break;
1750 }
1751 if( p->iCell>=nCell ){
1752 RTREE_QUEUE_TRACE(pCur, "POP-Se:");
1753 rtreeSearchPointPop(pCur);
1754 }
1755 }
1756 pCur->atEOF = p==0;
1757 return SQLITE_OK;
1758}
1759
1760/*
1761** Rtree virtual table module xNext method.
1762*/
1763static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1764 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1765 int rc = SQLITE_OK;
1766
1767 /* Move to the next entry that matches the configured constraints. */
1768 RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
1769 if( pCsr->bAuxValid ){
1770 pCsr->bAuxValid = 0;
1771 sqlite3_reset(pCsr->pReadAux);
1772 }
1773 rtreeSearchPointPop(pCsr);
1774 rc = rtreeStepToLeaf(pCsr);
1775 return rc;
1776}
1777
1778/*
1779** Rtree virtual table module xRowid method.
1780*/
1781static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1782 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1783 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1784 int rc = SQLITE_OK;
1785 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1786 if( rc==SQLITE_OK && ALWAYS(p) ){
1787 if( p->iCell>=NCELL(pNode) ){
1788 rc = SQLITE_ABORT;
1789 }else{
1790 *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
1791 }
1792 }
1793 return rc;
1794}
1795
1796/*
1797** Rtree virtual table module xColumn method.
1798*/
1799static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1800 Rtree *pRtree = (Rtree *)cur->pVtab;
1801 RtreeCursor *pCsr = (RtreeCursor *)cur;
1802 RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
1803 RtreeCoord c;
1804 int rc = SQLITE_OK;
1805 RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
1806
1807 if( rc ) return rc;
1808 if( NEVER(p==0) ) return SQLITE_OK;
1809 if( p->iCell>=NCELL(pNode) ) return SQLITE_ABORT;
1810 if( i==0 ){
1811 /* If this is an UPDATE that does not assign a value to the first
1812 ** column, leave it as a "no-change" value. This allows rtreeUpdate()
1813 ** to take the new rowid from aData[1] instead. */
1814 if( sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
1815 sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
1816 }else if( i<=pRtree->nDim2 ){
1817 nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
1818#ifndef SQLITE_RTREE_INT_ONLY
1819 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
1820 sqlite3_result_double(ctx, c.f);
1821 }else
1822#endif
1823 {
1824 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
1825 sqlite3_result_int(ctx, c.i);
1826 }
1827 }else{
1828 if( !pCsr->bAuxValid ){
1829 if( pCsr->pReadAux==0 ){
1830 rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
1831 &pCsr->pReadAux, 0);
1832 if( rc ) return rc;
1833 }
1834 sqlite3_bind_int64(pCsr->pReadAux, 1,
1835 nodeGetRowid(pRtree, pNode, p->iCell));
1836 rc = sqlite3_step(pCsr->pReadAux);
1837 if( rc==SQLITE_ROW ){
1838 pCsr->bAuxValid = 1;
1839 }else{
1840 sqlite3_reset(pCsr->pReadAux);
1841 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1842 return rc;
1843 }
1844 }
1845 sqlite3_result_value(ctx,
1846 sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
1847 }
1848 return SQLITE_OK;
1849}
1850
1851/*
1852** Use nodeAcquire() to obtain the leaf node containing the record with
1853** rowid iRowid. If successful, set *ppLeaf to point to the node and
1854** return SQLITE_OK. If there is no such record in the table, set
1855** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1856** to zero and return an SQLite error code.
1857*/
1858static int findLeafNode(
1859 Rtree *pRtree, /* RTree to search */
1860 i64 iRowid, /* The rowid searching for */
1861 RtreeNode **ppLeaf, /* Write the node here */
1862 sqlite3_int64 *piNode /* Write the node-id here */
1863){
1864 int rc;
1865 *ppLeaf = 0;
1866 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1867 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1868 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
1869 if( piNode ) *piNode = iNode;
1870 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1871 sqlite3_reset(pRtree->pReadRowid);
1872 }else{
1873 rc = sqlite3_reset(pRtree->pReadRowid);
1874 }
1875 return rc;
1876}
1877
1878/*
1879** This function is called to configure the RtreeConstraint object passed
1880** as the second argument for a MATCH constraint. The value passed as the
1881** first argument to this function is the right-hand operand to the MATCH
1882** operator.
1883*/
1884static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
1885 RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
1886 sqlite3_rtree_query_info *pInfo; /* Callback information */
1887
1888 pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
1889 if( pSrc==0 ) return SQLITE_ERROR;
1890 pInfo = (sqlite3_rtree_query_info*)
1891 sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
1892 if( !pInfo ) return SQLITE_NOMEM;
1893 memset(pInfo, 0, sizeof(*pInfo));
1894 pBlob = (RtreeMatchArg*)&pInfo[1];
1895 memcpy(pBlob, pSrc, pSrc->iSize);
1896 pInfo->pContext = pBlob->cb.pContext;
1897 pInfo->nParam = pBlob->nParam;
1898 pInfo->aParam = pBlob->aParam;
1899 pInfo->apSqlParam = pBlob->apSqlParam;
1900
1901 if( pBlob->cb.xGeom ){
1902 pCons->u.xGeom = pBlob->cb.xGeom;
1903 }else{
1904 pCons->op = RTREE_QUERY;
1905 pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
1906 }
1907 pCons->pInfo = pInfo;
1908 return SQLITE_OK;
1909}
1910
1911int sqlite3IntFloatCompare(i64,double);
1912
1913/*
1914** Argument pVal is the right-hand side of a "rowid = ?" constraint. If
1915** there is an integer that compares equal to pVal, set *piRowid to it and
1916** return 1. Otherwise - pVal is NULL, a blob, a non-numeric text value or
1917** a real value that is not an integer - return 0.
1918*/
1919static int rtreeRowidEqValue(sqlite3_value *pVal, i64 *piRowid){
1920 int eType = sqlite3_value_numeric_type(pVal);
1921 *piRowid = sqlite3_value_int64(pVal);
1922 return eType==SQLITE_INTEGER
1923 || (eType==SQLITE_FLOAT
1924 && 0==sqlite3IntFloatCompare(*piRowid, sqlite3_value_double(pVal)));
1925}
1926
1927/*
1928** Rtree virtual table module xFilter method.
1929*/
1930static int rtreeFilter(
1931 sqlite3_vtab_cursor *pVtabCursor,
1932 int idxNum, const char *idxStr,
1933 int argc, sqlite3_value **argv
1934){
1935 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1936 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1937 RtreeNode *pRoot = 0;
1938 int ii;
1939 int rc = SQLITE_OK;
1940 int iCell = 0;
1941
1942 rtreeReference(pRtree);
1943
1944 /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
1945 resetCursor(pCsr);
1946
1947 pCsr->iStrategy = idxNum;
1948 if( idxNum==1 ){
1949 /* Special case - lookup by rowid. */
1950 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
1951 RtreeSearchPoint *p; /* Search point for the leaf */
1952 i64 iRowid;
1953 i64 iNode = 0;
1954 if( rtreeRowidEqValue(argv[0], &iRowid) ){
1955 rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
1956 }else{
1957 rc = SQLITE_OK;
1958 pLeaf = 0;
1959 }
1960 if( rc==SQLITE_OK && pLeaf!=0 ){
1961 p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
1962 assert( p!=0 ); /* Always returns pCsr->sPoint */
1963 pCsr->aNode[0] = pLeaf;
1964 p->id = iNode;
1965 p->eWithin = PARTLY_WITHIN;
1966 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
1967 p->iCell = (u8)iCell;
1968 RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
1969 }else{
1970 pCsr->atEOF = 1;
1971 }
1972 }else{
1973 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1974 ** with the configured constraints.
1975 */
1976 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
1977 if( rc==SQLITE_OK && argc>0 ){
1978 pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
1979 pCsr->nConstraint = argc;
1980 if( !pCsr->aConstraint ){
1981 rc = SQLITE_NOMEM;
1982 }else{
1983 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
1984 memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
1985 assert( (idxStr==0 && argc==0)
1986 || (idxStr && (int)strlen(idxStr)==argc*2) );
1987 for(ii=0; ii<argc; ii++){
1988 RtreeConstraint *p = &pCsr->aConstraint[ii];
1989 int eType = sqlite3_value_numeric_type(argv[ii]);
1990 p->op = idxStr[ii*2];
1991 p->iCoord = idxStr[ii*2+1]-'0';
1992 if( p->op>=RTREE_MATCH ){
1993 /* A MATCH operator. The right-hand-side must be a blob that
1994 ** can be cast into an RtreeMatchArg object. One created using
1995 ** an sqlite3_rtree_geometry_callback() SQL user function.
1996 */
1997 rc = deserializeGeometry(argv[ii], p);
1998 if( rc!=SQLITE_OK ){
1999 break;
2000 }
2001 p->pInfo->nCoord = pRtree->nDim2;
2002 p->pInfo->anQueue = pCsr->anQueue;
2003 p->pInfo->mxLevel = pRtree->iDepth + 1;
2004 }else if( eType==SQLITE_INTEGER ){
2005 sqlite3_int64 iVal = sqlite3_value_int64(argv[ii]);
2006#ifdef SQLITE_RTREE_INT_ONLY
2007 p->u.rValue = iVal;
2008#else
2009 p->u.rValue = (double)iVal;
2010 if( iVal>=((sqlite3_int64)1)<<48
2011 || iVal<=-(((sqlite3_int64)1)<<48)
2012 ){
2013 if( p->op==RTREE_LT ) p->op = RTREE_LE;
2014 if( p->op==RTREE_GT ) p->op = RTREE_GE;
2015 }
2016#endif
2017 }else if( eType==SQLITE_FLOAT ){
2018#ifdef SQLITE_RTREE_INT_ONLY
2019 p->u.rValue = sqlite3_value_int64(argv[ii]);
2020#else
2021 p->u.rValue = sqlite3_value_double(argv[ii]);
2022#endif
2023 }else{
2024 p->u.rValue = RTREE_ZERO;
2025 if( eType==SQLITE_NULL ){
2026 p->op = RTREE_FALSE;
2027 }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
2028 p->op = RTREE_TRUE;
2029 }else{
2030 p->op = RTREE_FALSE;
2031 }
2032 }
2033 }
2034 }
2035 }
2036 if( rc==SQLITE_OK ){
2037 RtreeSearchPoint *pNew;
2038 assert( pCsr->bPoint==0 ); /* Due to the resetCursor() call above */
2039 pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
2040 if( NEVER(pNew==0) ){ /* Because pCsr->bPoint was FALSE */
2041 return SQLITE_NOMEM;
2042 }
2043 pNew->id = 1;
2044 pNew->iCell = 0;
2045 pNew->eWithin = PARTLY_WITHIN;
2046 assert( pCsr->bPoint==1 );
2047 pCsr->aNode[0] = pRoot;
2048 pRoot = 0;
2049 RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
2050 rc = rtreeStepToLeaf(pCsr);
2051 }
2052 }
2053
2054 nodeRelease(pRtree, pRoot);
2055 rtreeRelease(pRtree);
2056 return rc;
2057}
2058
2059/*
2060** Rtree virtual table module xBestIndex method. There are three
2061** table scan strategies to choose from (in order from most to
2062** least desirable):
2063**
2064** idxNum idxStr Strategy
2065** ------------------------------------------------
2066** 1 Unused Direct lookup by rowid.
2067** 2 See below R-tree query or full-table scan.
2068** ------------------------------------------------
2069**
2070** If strategy 1 is used, then idxStr is not meaningful. If strategy
2071** 2 is used, idxStr is formatted to contain 2 bytes for each
2072** constraint used. The first two bytes of idxStr correspond to
2073** the constraint in sqlite3_index_info.aConstraintUsage[] with
2074** (argvIndex==1) etc.
2075**
2076** The first of each pair of bytes in idxStr identifies the constraint
2077** operator as follows:
2078**
2079** Operator Byte Value
2080** ----------------------
2081** = 0x41 ('A')
2082** <= 0x42 ('B')
2083** < 0x43 ('C')
2084** >= 0x44 ('D')
2085** > 0x45 ('E')
2086** MATCH 0x46 ('F')
2087** ----------------------
2088**
2089** The second of each pair of bytes identifies the coordinate column
2090** to which the constraint applies. The leftmost coordinate column
2091** is 'a', the second from the left 'b' etc.
2092*/
2093static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
2094 Rtree *pRtree = (Rtree*)tab;
2095 int rc = SQLITE_OK;
2096 int ii;
2097 int bMatch = 0; /* True if there exists a MATCH constraint */
2098 i64 nRow; /* Estimated rows returned by this scan */
2099
2100 int iIdx = 0;
2101 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
2102 memset(zIdxStr, 0, sizeof(zIdxStr));
2103
2104 /* Check if there exists a MATCH constraint - even an unusable one. If there
2105 ** is, do not consider the lookup-by-rowid plan as using such a plan would
2106 ** require the VDBE to evaluate the MATCH constraint, which is not currently
2107 ** possible. */
2108 for(ii=0; ii<pIdxInfo->nConstraint; ii++){
2109 if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
2110 bMatch = 1;
2111 }
2112 }
2113
2114 assert( pIdxInfo->idxStr==0 );
2115 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
2116 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
2117
2118 if( bMatch==0 && p->usable
2119 && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
2120 ){
2121 /* We have an equality constraint on the rowid. Use strategy 1. */
2122 int jj;
2123 for(jj=0; jj<ii; jj++){
2124 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
2125 pIdxInfo->aConstraintUsage[jj].omit = 0;
2126 }
2127 pIdxInfo->idxNum = 1;
2128 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
2129 pIdxInfo->aConstraintUsage[jj].omit = 1;
2130
2131 /* This strategy involves a two rowid lookups on an B-Tree structures
2132 ** and then a linear search of an R-Tree node. This should be
2133 ** considered almost as quick as a direct rowid lookup (for which
2134 ** sqlite uses an internal cost of 0.0). It is expected to return
2135 ** a single row.
2136 */
2137 pIdxInfo->estimatedCost = 30.0;
2138 pIdxInfo->estimatedRows = 1;
2139 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
2140 return SQLITE_OK;
2141 }
2142
2143 if( p->usable
2144 && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
2145 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
2146 ){
2147 u8 op;
2148 u8 doOmit = 1;
2149 switch( p->op ){
2150 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; doOmit = 0; break;
2151 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; doOmit = 0; break;
2152 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
2153 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; doOmit = 0; break;
2154 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
2155 case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
2156 default: op = 0; break;
2157 }
2158 if( op ){
2159 zIdxStr[iIdx++] = op;
2160 zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
2161 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
2162 pIdxInfo->aConstraintUsage[ii].omit = doOmit;
2163 }
2164 }
2165 }
2166
2167 pIdxInfo->idxNum = 2;
2168 pIdxInfo->needToFreeIdxStr = 1;
2169 if( iIdx>0 ){
2170 pIdxInfo->idxStr = sqlite3_malloc( iIdx+1 );
2171 if( pIdxInfo->idxStr==0 ){
2172 return SQLITE_NOMEM;
2173 }
2174 memcpy(pIdxInfo->idxStr, zIdxStr, iIdx+1);
2175 }
2176
2177 nRow = pRtree->nRowEst >> (iIdx/2);
2178 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
2179 pIdxInfo->estimatedRows = nRow;
2180
2181 return rc;
2182}
2183
2184/*
2185** Return the N-dimensional volume of the cell stored in *p.
2186*/
2187static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
2188 RtreeDValue area = (RtreeDValue)1;
2189 assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
2190#ifndef SQLITE_RTREE_INT_ONLY
2191 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2192 switch( pRtree->nDim ){
2193 case 5: area = p->aCoord[9].f - p->aCoord[8].f;
2194 case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
2195 case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
2196 case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
2197 default: area *= p->aCoord[1].f - p->aCoord[0].f;
2198 }
2199 }else
2200#endif
2201 {
2202 switch( pRtree->nDim ){
2203 case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
2204 case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
2205 case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
2206 case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
2207 default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
2208 }
2209 }
2210 return area;
2211}
2212
2213/*
2214** Return the margin length of cell p. The margin length is the sum
2215** of the objects size in each dimension.
2216*/
2217static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
2218 RtreeDValue margin = 0;
2219 int ii = pRtree->nDim2 - 2;
2220 do{
2221 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
2222 ii -= 2;
2223 }while( ii>=0 );
2224 return margin;
2225}
2226
2227/*
2228** Store the union of cells p1 and p2 in p1.
2229*/
2230static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2231 int ii = 0;
2232 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
2233 do{
2234 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
2235 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
2236 ii += 2;
2237 }while( ii<pRtree->nDim2 );
2238 }else{
2239 do{
2240 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
2241 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
2242 ii += 2;
2243 }while( ii<pRtree->nDim2 );
2244 }
2245}
2246
2247/*
2248** Return true if the area covered by p2 is a subset of the area covered
2249** by p1. False otherwise.
2250*/
2251static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2252 int ii;
2253 if( pRtree->eCoordType==RTREE_COORD_INT32 ){
2254 for(ii=0; ii<pRtree->nDim2; ii+=2){
2255 RtreeCoord *a1 = &p1->aCoord[ii];
2256 RtreeCoord *a2 = &p2->aCoord[ii];
2257 if( a2[0].i<a1[0].i || a2[1].i>a1[1].i ) return 0;
2258 }
2259 }else{
2260 for(ii=0; ii<pRtree->nDim2; ii+=2){
2261 RtreeCoord *a1 = &p1->aCoord[ii];
2262 RtreeCoord *a2 = &p2->aCoord[ii];
2263 if( a2[0].f<a1[0].f || a2[1].f>a1[1].f ) return 0;
2264 }
2265 }
2266 return 1;
2267}
2268
2269static RtreeDValue cellOverlap(
2270 Rtree *pRtree,
2271 RtreeCell *p,
2272 RtreeCell *aCell,
2273 int nCell
2274){
2275 int ii;
2276 RtreeDValue overlap = RTREE_ZERO;
2277 for(ii=0; ii<nCell; ii++){
2278 int jj;
2279 RtreeDValue o = (RtreeDValue)1;
2280 for(jj=0; jj<pRtree->nDim2; jj+=2){
2281 RtreeDValue x1, x2;
2282 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
2283 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
2284 if( x2<x1 ){
2285 o = (RtreeDValue)0;
2286 break;
2287 }else{
2288 o = o * (x2-x1);
2289 }
2290 }
2291 overlap += o;
2292 }
2293 return overlap;
2294}
2295
2296
2297/*
2298** This function implements the ChooseLeaf algorithm from Gutman[84].
2299** ChooseSubTree in r*tree terminology.
2300*/
2301static int ChooseLeaf(
2302 Rtree *pRtree, /* Rtree table */
2303 RtreeCell *pCell, /* Cell to insert into rtree */
2304 int iHeight, /* Height of sub-tree rooted at pCell */
2305 RtreeNode **ppLeaf /* OUT: Selected leaf page */
2306){
2307 int rc;
2308 int ii;
2309 RtreeNode *pNode = 0;
2310 rc = nodeAcquire(pRtree, 1, 0, &pNode);
2311
2312 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
2313 int iCell;
2314 sqlite3_int64 iBest = 0;
2315 int bFound = 0;
2316 RtreeDValue fMinGrowth = RTREE_ZERO;
2317 RtreeDValue fMinArea = RTREE_ZERO;
2318 int nCell = NCELL(pNode);
2319 RtreeNode *pChild = 0;
2320
2321 /* First check to see if there is are any cells in pNode that completely
2322 ** contains pCell. If two or more cells in pNode completely contain pCell
2323 ** then pick the smallest.
2324 */
2325 for(iCell=0; iCell<nCell; iCell++){
2326 RtreeCell cell;
2327 nodeGetCell(pRtree, pNode, iCell, &cell);
2328 if( cellContains(pRtree, &cell, pCell) ){
2329 RtreeDValue area = cellArea(pRtree, &cell);
2330 if( bFound==0 || area<fMinArea ){
2331 iBest = cell.iRowid;
2332 fMinArea = area;
2333 bFound = 1;
2334 }
2335 }
2336 }
2337 if( !bFound ){
2338 /* No cells of pNode will completely contain pCell. So pick the
2339 ** cell of pNode that grows by the least amount when pCell is added.
2340 ** Break ties by selecting the smaller cell.
2341 */
2342 for(iCell=0; iCell<nCell; iCell++){
2343 RtreeCell cell;
2344 RtreeDValue growth;
2345 RtreeDValue area;
2346 nodeGetCell(pRtree, pNode, iCell, &cell);
2347 area = cellArea(pRtree, &cell);
2348 cellUnion(pRtree, &cell, pCell);
2349 growth = cellArea(pRtree, &cell)-area;
2350 if( iCell==0
2351 || growth<fMinGrowth
2352 || (growth==fMinGrowth && area<fMinArea)
2353 ){
2354 fMinGrowth = growth;
2355 fMinArea = area;
2356 iBest = cell.iRowid;
2357 }
2358 }
2359 }
2360
2361 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
2362 nodeRelease(pRtree, pNode);
2363 pNode = pChild;
2364 }
2365
2366 *ppLeaf = pNode;
2367 return rc;
2368}
2369
2370/*
2371** A cell with the same content as pCell has just been inserted into
2372** the node pNode. This function updates the bounding box cells in
2373** all ancestor elements.
2374*/
2375static int AdjustTree(
2376 Rtree *pRtree, /* Rtree table */
2377 RtreeNode *pNode, /* Adjust ancestry of this node. */
2378 RtreeCell *pCell /* This cell was just inserted */
2379){
2380 RtreeNode *p = pNode;
2381 int cnt = 0;
2382 int rc;
2383 while( p->pParent ){
2384 RtreeNode *pParent = p->pParent;
2385 RtreeCell cell;
2386 int iCell;
2387
2388 cnt++;
2389 if( cnt>100 ){
2390 RTREE_IS_CORRUPT(pRtree);
2391 return SQLITE_CORRUPT_VTAB;
2392 }
2393 rc = nodeParentIndex(pRtree, p, &iCell);
2394 if( NEVER(rc!=SQLITE_OK) ){
2395 RTREE_IS_CORRUPT(pRtree);
2396 return SQLITE_CORRUPT_VTAB;
2397 }
2398
2399 nodeGetCell(pRtree, pParent, iCell, &cell);
2400 if( !cellContains(pRtree, &cell, pCell) ){
2401 cellUnion(pRtree, &cell, pCell);
2402 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
2403 }
2404
2405 p = pParent;
2406 }
2407 return SQLITE_OK;
2408}
2409
2410/*
2411** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
2412*/
2413static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
2414 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
2415 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
2416 sqlite3_step(pRtree->pWriteRowid);
2417 return sqlite3_reset(pRtree->pWriteRowid);
2418}
2419
2420/*
2421** Write mapping (iNode->iPar) to the <rtree>_parent table.
2422*/
2423static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
2424 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
2425 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
2426 sqlite3_step(pRtree->pWriteParent);
2427 return sqlite3_reset(pRtree->pWriteParent);
2428}
2429
2430static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
2431
2432
2433
2434/*
2435** Arguments aIdx, aCell and aSpare all point to arrays of size
2436** nIdx. The aIdx array contains the set of integers from 0 to
2437** (nIdx-1) in no particular order. This function sorts the values
2438** in aIdx according to dimension iDim of the cells in aCell. The
2439** minimum value of dimension iDim is considered first, the
2440** maximum used to break ties.
2441**
2442** The aSpare array is used as temporary working space by the
2443** sorting algorithm.
2444*/
2445static void SortByDimension(
2446 Rtree *pRtree,
2447 int *aIdx,
2448 int nIdx,
2449 int iDim,
2450 RtreeCell *aCell,
2451 int *aSpare
2452){
2453 if( nIdx>1 ){
2454
2455 int iLeft = 0;
2456 int iRight = 0;
2457
2458 int nLeft = nIdx/2;
2459 int nRight = nIdx-nLeft;
2460 int *aLeft = aIdx;
2461 int *aRight = &aIdx[nLeft];
2462
2463 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
2464 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
2465
2466 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2467 aLeft = aSpare;
2468 while( iLeft<nLeft || iRight<nRight ){
2469 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
2470 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
2471 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
2472 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
2473 if( (iLeft!=nLeft) && ((iRight==nRight)
2474 || (xleft1<xright1)
2475 || (xleft1==xright1 && xleft2<xright2)
2476 )){
2477 aIdx[iLeft+iRight] = aLeft[iLeft];
2478 iLeft++;
2479 }else{
2480 aIdx[iLeft+iRight] = aRight[iRight];
2481 iRight++;
2482 }
2483 }
2484
2485#if 0
2486 /* Check that the sort worked */
2487 {
2488 int jj;
2489 for(jj=1; jj<nIdx; jj++){
2490 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2491 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2492 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2493 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2494 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2495 }
2496 }
2497#endif
2498 }
2499}
2500
2501/*
2502** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2503*/
2504static int splitNodeStartree(
2505 Rtree *pRtree,
2506 RtreeCell *aCell,
2507 int nCell,
2508 RtreeNode *pLeft,
2509 RtreeNode *pRight,
2510 RtreeCell *pBboxLeft,
2511 RtreeCell *pBboxRight
2512){
2513 int **aaSorted;
2514 int *aSpare;
2515 int ii;
2516
2517 int iBestDim = 0;
2518 int iBestSplit = 0;
2519 RtreeDValue fBestMargin = RTREE_ZERO;
2520
2521 sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2522
2523 aaSorted = (int **)sqlite3_malloc64(nByte);
2524 if( !aaSorted ){
2525 return SQLITE_NOMEM;
2526 }
2527
2528 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2529 memset(aaSorted, 0, nByte);
2530 for(ii=0; ii<pRtree->nDim; ii++){
2531 int jj;
2532 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2533 for(jj=0; jj<nCell; jj++){
2534 aaSorted[ii][jj] = jj;
2535 }
2536 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2537 }
2538
2539 for(ii=0; ii<pRtree->nDim; ii++){
2540 RtreeDValue margin = RTREE_ZERO;
2541 RtreeDValue fBestOverlap = RTREE_ZERO;
2542 RtreeDValue fBestArea = RTREE_ZERO;
2543 int iBestLeft = 0;
2544 int nLeft;
2545
2546 for(
2547 nLeft=RTREE_MINCELLS(pRtree);
2548 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2549 nLeft++
2550 ){
2551 RtreeCell left;
2552 RtreeCell right;
2553 int kk;
2554 RtreeDValue overlap;
2555 RtreeDValue area;
2556
2557 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2558 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2559 for(kk=1; kk<(nCell-1); kk++){
2560 if( kk<nLeft ){
2561 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2562 }else{
2563 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2564 }
2565 }
2566 margin += cellMargin(pRtree, &left);
2567 margin += cellMargin(pRtree, &right);
2568 overlap = cellOverlap(pRtree, &left, &right, 1);
2569 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2570 if( (nLeft==RTREE_MINCELLS(pRtree))
2571 || (overlap<fBestOverlap)
2572 || (overlap==fBestOverlap && area<fBestArea)
2573 ){
2574 iBestLeft = nLeft;
2575 fBestOverlap = overlap;
2576 fBestArea = area;
2577 }
2578 }
2579
2580 if( ii==0 || margin<fBestMargin ){
2581 iBestDim = ii;
2582 fBestMargin = margin;
2583 iBestSplit = iBestLeft;
2584 }
2585 }
2586
2587 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2588 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2589 for(ii=0; ii<nCell; ii++){
2590 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2591 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2592 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2593 nodeInsertCell(pRtree, pTarget, pCell);
2594 cellUnion(pRtree, pBbox, pCell);
2595 }
2596
2597 sqlite3_free(aaSorted);
2598 return SQLITE_OK;
2599}
2600
2601
2602static int updateMapping(
2603 Rtree *pRtree,
2604 i64 iRowid,
2605 RtreeNode *pNode,
2606 int iHeight
2607){
2608 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2609 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2610 if( iHeight>0 ){
2611 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
2612 RtreeNode *p;
2613 for(p=pNode; p; p=p->pParent){
2614 if( p==pChild ) return SQLITE_CORRUPT_VTAB;
2615 }
2616 if( pChild ){
2617 nodeRelease(pRtree, pChild->pParent);
2618 nodeReference(pNode);
2619 pChild->pParent = pNode;
2620 }
2621 }
2622 if( NEVER(pNode==0) ) return SQLITE_ERROR;
2623 return xSetMapping(pRtree, iRowid, pNode->iNode);
2624}
2625
2626static int SplitNode(
2627 Rtree *pRtree,
2628 RtreeNode *pNode,
2629 RtreeCell *pCell,
2630 int iHeight
2631){
2632 int i;
2633 int newCellIsRight = 0;
2634
2635 int rc = SQLITE_OK;
2636 int nCell = NCELL(pNode);
2637 RtreeCell *aCell;
2638 int *aiUsed;
2639
2640 RtreeNode *pLeft = 0;
2641 RtreeNode *pRight = 0;
2642
2643 RtreeCell leftbbox;
2644 RtreeCell rightbbox;
2645
2646 /* Allocate an array and populate it with a copy of pCell and
2647 ** all cells from node pLeft. Then zero the original node.
2648 */
2649 aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2650 if( !aCell ){
2651 rc = SQLITE_NOMEM;
2652 goto splitnode_out;
2653 }
2654 aiUsed = (int *)&aCell[nCell+1];
2655 memset(aiUsed, 0, sizeof(int)*(nCell+1));
2656 for(i=0; i<nCell; i++){
2657 nodeGetCell(pRtree, pNode, i, &aCell[i]);
2658 }
2659 nodeZero(pRtree, pNode);
2660 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2661 nCell++;
2662
2663 if( pNode->iNode==1 ){
2664 pRight = nodeNew(pRtree, pNode);
2665 pLeft = nodeNew(pRtree, pNode);
2666 pRtree->iDepth++;
2667 pNode->isDirty = 1;
2668 writeInt16(pNode->zData, pRtree->iDepth);
2669 }else{
2670 pLeft = pNode;
2671 pRight = nodeNew(pRtree, pLeft->pParent);
2672 pLeft->nRef++;
2673 }
2674
2675 if( !pLeft || !pRight ){
2676 rc = SQLITE_NOMEM;
2677 goto splitnode_out;
2678 }
2679
2680 memset(pLeft->zData, 0, pRtree->iNodeSize);
2681 memset(pRight->zData, 0, pRtree->iNodeSize);
2682
2683 rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
2684 &leftbbox, &rightbbox);
2685 if( rc!=SQLITE_OK ){
2686 goto splitnode_out;
2687 }
2688
2689 /* Ensure both child nodes have node numbers assigned to them by calling
2690 ** nodeWrite(). Node pRight always needs a node number, as it was created
2691 ** by nodeNew() above. But node pLeft sometimes already has a node number.
2692 ** In this case avoid the all to nodeWrite().
2693 */
2694 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2695 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2696 ){
2697 goto splitnode_out;
2698 }
2699
2700 rightbbox.iRowid = pRight->iNode;
2701 leftbbox.iRowid = pLeft->iNode;
2702
2703 if( pNode->iNode==1 ){
2704 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2705 if( rc!=SQLITE_OK ){
2706 goto splitnode_out;
2707 }
2708 }else{
2709 RtreeNode *pParent = pLeft->pParent;
2710 int iCell;
2711 rc = nodeParentIndex(pRtree, pLeft, &iCell);
2712 if( ALWAYS(rc==SQLITE_OK) ){
2713 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2714 rc = AdjustTree(pRtree, pParent, &leftbbox);
2715 assert( rc==SQLITE_OK );
2716 }
2717 if( NEVER(rc!=SQLITE_OK) ){
2718 goto splitnode_out;
2719 }
2720 }
2721 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2722 goto splitnode_out;
2723 }
2724
2725 for(i=0; i<NCELL(pRight); i++){
2726 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2727 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2728 if( iRowid==pCell->iRowid ){
2729 newCellIsRight = 1;
2730 }
2731 if( rc!=SQLITE_OK ){
2732 goto splitnode_out;
2733 }
2734 }
2735 if( pNode->iNode==1 ){
2736 for(i=0; i<NCELL(pLeft); i++){
2737 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2738 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2739 if( rc!=SQLITE_OK ){
2740 goto splitnode_out;
2741 }
2742 }
2743 }else if( newCellIsRight==0 ){
2744 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2745 }
2746
2747splitnode_out:
2748 nodeRelease(pRtree, pRight);
2749 nodeRelease(pRtree, pLeft);
2750 sqlite3_free(aCell);
2751 return rc;
2752}
2753
2754/*
2755** If node pLeaf is not the root of the r-tree and its pParent pointer is
2756** still NULL, load all ancestor nodes of pLeaf into memory and populate
2757** the pLeaf->pParent chain all the way up to the root node.
2758**
2759** This operation is required when a row is deleted (or updated - an update
2760** is implemented as a delete followed by an insert). SQLite provides the
2761** rowid of the row to delete, which can be used to find the leaf on which
2762** the entry resides (argument pLeaf). Once the leaf is located, this
2763** function is called to determine its ancestry.
2764*/
2765static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2766 int rc = SQLITE_OK;
2767 RtreeNode *pChild = pLeaf;
2768 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2769 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
2770 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2771 rc = sqlite3_step(pRtree->pReadParent);
2772 if( rc==SQLITE_ROW ){
2773 RtreeNode *pTest; /* Used to test for reference loops */
2774 i64 iNode; /* Node number of parent node */
2775
2776 /* Before setting pChild->pParent, test that we are not creating a
2777 ** loop of references (as we would if, say, pChild==pParent). We don't
2778 ** want to do this as it leads to a memory leak when trying to delete
2779 ** the referenced counted node structures.
2780 */
2781 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2782 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
2783 if( pTest==0 ){
2784 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2785 }
2786 }
2787 rc = sqlite3_reset(pRtree->pReadParent);
2788 if( rc==SQLITE_OK ) rc = rc2;
2789 if( rc==SQLITE_OK && !pChild->pParent ){
2790 RTREE_IS_CORRUPT(pRtree);
2791 rc = SQLITE_CORRUPT_VTAB;
2792 }
2793 pChild = pChild->pParent;
2794 }
2795 return rc;
2796}
2797
2798static int deleteCell(Rtree *, RtreeNode *, int, int);
2799
2800static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2801 int rc;
2802 int rc2;
2803 RtreeNode *pParent = 0;
2804 int iCell;
2805
2806 assert( pNode->nRef==1 );
2807
2808 /* Remove the entry in the parent cell. */
2809 rc = nodeParentIndex(pRtree, pNode, &iCell);
2810 if( rc==SQLITE_OK ){
2811 pParent = pNode->pParent;
2812 pNode->pParent = 0;
2813 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2814 testcase( rc!=SQLITE_OK );
2815 }
2816 rc2 = nodeRelease(pRtree, pParent);
2817 if( rc==SQLITE_OK ){
2818 rc = rc2;
2819 }
2820 if( rc!=SQLITE_OK ){
2821 return rc;
2822 }
2823
2824 /* Remove the xxx_node entry. */
2825 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2826 sqlite3_step(pRtree->pDeleteNode);
2827 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2828 return rc;
2829 }
2830
2831 /* Remove the xxx_parent entry. */
2832 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2833 sqlite3_step(pRtree->pDeleteParent);
2834 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2835 return rc;
2836 }
2837
2838 /* Remove the node from the in-memory hash table and link it into
2839 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2840 */
2841 nodeHashDelete(pRtree, pNode);
2842 pNode->iNode = iHeight;
2843 pNode->pNext = pRtree->pDeleted;
2844 pNode->nRef++;
2845 pRtree->pDeleted = pNode;
2846
2847 return SQLITE_OK;
2848}
2849
2850static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2851 RtreeNode *pParent = pNode->pParent;
2852 int rc = SQLITE_OK;
2853 if( pParent ){
2854 int ii;
2855 int nCell = NCELL(pNode);
2856 RtreeCell box; /* Bounding box for pNode */
2857 nodeGetCell(pRtree, pNode, 0, &box);
2858 for(ii=1; ii<nCell; ii++){
2859 RtreeCell cell;
2860 nodeGetCell(pRtree, pNode, ii, &cell);
2861 cellUnion(pRtree, &box, &cell);
2862 }
2863 box.iRowid = pNode->iNode;
2864 rc = nodeParentIndex(pRtree, pNode, &ii);
2865 if( rc==SQLITE_OK ){
2866 nodeOverwriteCell(pRtree, pParent, &box, ii);
2867 rc = fixBoundingBox(pRtree, pParent);
2868 }
2869 }
2870 return rc;
2871}
2872
2873/*
2874** Delete the cell at index iCell of node pNode. After removing the
2875** cell, adjust the r-tree data structure if required.
2876*/
2877static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2878 RtreeNode *pParent;
2879 int rc;
2880
2881 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2882 return rc;
2883 }
2884
2885 /* Remove the cell from the node. This call just moves bytes around
2886 ** the in-memory node image, so it cannot fail.
2887 */
2888 nodeDeleteCell(pRtree, pNode, iCell);
2889
2890 /* If the node is not the tree root and now has less than the minimum
2891 ** number of cells, remove it from the tree. Otherwise, update the
2892 ** cell in the parent node so that it tightly contains the updated
2893 ** node.
2894 */
2895 pParent = pNode->pParent;
2896 assert( pParent || pNode->iNode==1 );
2897 if( pParent ){
2898 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2899 rc = removeNode(pRtree, pNode, iHeight);
2900 }else{
2901 rc = fixBoundingBox(pRtree, pNode);
2902 }
2903 }
2904
2905 return rc;
2906}
2907
2908/*
2909** Insert cell pCell into node pNode. Node pNode is the head of a
2910** subtree iHeight high (leaf nodes have iHeight==0).
2911*/
2912static int rtreeInsertCell(
2913 Rtree *pRtree,
2914 RtreeNode *pNode,
2915 RtreeCell *pCell,
2916 int iHeight
2917){
2918 int rc = SQLITE_OK;
2919 if( iHeight>0 ){
2920 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2921 if( pChild ){
2922 nodeRelease(pRtree, pChild->pParent);
2923 nodeReference(pNode);
2924 pChild->pParent = pNode;
2925 }
2926 }
2927 if( nodeInsertCell(pRtree, pNode, pCell) ){
2928 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2929 }else{
2930 rc = AdjustTree(pRtree, pNode, pCell);
2931 if( rc==SQLITE_OK ){
2932 if( iHeight==0 ){
2933 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
2934 }else{
2935 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
2936 }
2937 }
2938 }
2939 return rc;
2940}
2941
2942static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
2943 int ii;
2944 int rc = SQLITE_OK;
2945 int nCell = NCELL(pNode);
2946
2947 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
2948 RtreeNode *pInsert;
2949 RtreeCell cell;
2950 nodeGetCell(pRtree, pNode, ii, &cell);
2951
2952 /* Find a node to store this cell in. pNode->iNode currently contains
2953 ** the height of the sub-tree headed by the cell.
2954 */
2955 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
2956 if( rc==SQLITE_OK ){
2957 int rc2;
2958 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
2959 rc2 = nodeRelease(pRtree, pInsert);
2960 if( rc==SQLITE_OK ){
2961 rc = rc2;
2962 }
2963 }
2964 }
2965 return rc;
2966}
2967
2968/*
2969** Select a currently unused rowid for a new r-tree record.
2970*/
2971static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
2972 int rc;
2973 sqlite3_bind_null(pRtree->pWriteRowid, 1);
2974 sqlite3_bind_null(pRtree->pWriteRowid, 2);
2975 sqlite3_step(pRtree->pWriteRowid);
2976 rc = sqlite3_reset(pRtree->pWriteRowid);
2977 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
2978 return rc;
2979}
2980
2981/*
2982** Remove the entry with rowid=iDelete from the r-tree structure.
2983*/
2984static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
2985 int rc; /* Return code */
2986 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
2987 int iCell; /* Index of iDelete cell in pLeaf */
2988 RtreeNode *pRoot = 0; /* Root node of rtree structure */
2989
2990
2991 /* Obtain a reference to the root node to initialize Rtree.iDepth */
2992 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
2993
2994 /* Obtain a reference to the leaf node that contains the entry
2995 ** about to be deleted.
2996 */
2997 if( rc==SQLITE_OK ){
2998 rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
2999 }
3000
3001#ifdef CORRUPT_DB
3002 assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
3003#endif
3004
3005 /* Delete the cell in question from the leaf node. */
3006 if( rc==SQLITE_OK && pLeaf ){
3007 int rc2;
3008 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
3009 if( rc==SQLITE_OK ){
3010 rc = deleteCell(pRtree, pLeaf, iCell, 0);
3011 }
3012 rc2 = nodeRelease(pRtree, pLeaf);
3013 if( rc==SQLITE_OK ){
3014 rc = rc2;
3015 }
3016 }
3017
3018 /* Delete the corresponding entry in the <rtree>_rowid table. */
3019 if( rc==SQLITE_OK ){
3020 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
3021 sqlite3_step(pRtree->pDeleteRowid);
3022 rc = sqlite3_reset(pRtree->pDeleteRowid);
3023 }
3024
3025 /* Check if the root node now has exactly one child. If so, remove
3026 ** it, schedule the contents of the child for reinsertion and
3027 ** reduce the tree height by one.
3028 **
3029 ** This is equivalent to copying the contents of the child into
3030 ** the root node (the operation that Gutman's paper says to perform
3031 ** in this scenario).
3032 */
3033 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
3034 int rc2;
3035 RtreeNode *pChild = 0;
3036 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
3037 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); /* tag-20210916a */
3038 if( rc==SQLITE_OK ){
3039 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
3040 }
3041 rc2 = nodeRelease(pRtree, pChild);
3042 if( rc==SQLITE_OK ) rc = rc2;
3043 if( rc==SQLITE_OK ){
3044 pRtree->iDepth--;
3045 writeInt16(pRoot->zData, pRtree->iDepth);
3046 pRoot->isDirty = 1;
3047 }
3048 }
3049
3050 /* Re-insert the contents of any underfull nodes removed from the tree. */
3051 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
3052 if( rc==SQLITE_OK ){
3053 rc = reinsertNodeContent(pRtree, pLeaf);
3054 }
3055 pRtree->pDeleted = pLeaf->pNext;
3056 pRtree->nNodeRef--;
3057 sqlite3_free(pLeaf);
3058 }
3059
3060 /* Release the reference to the root node. */
3061 if( rc==SQLITE_OK ){
3062 rc = nodeRelease(pRtree, pRoot);
3063 }else{
3064 nodeRelease(pRtree, pRoot);
3065 }
3066
3067 return rc;
3068}
3069
3070#if !defined(SQLITE_RTREE_INT_ONLY)
3071/*
3072** Convert an sqlite3_value into an RtreeValue (presumably a float)
3073** while taking care to round toward negative or positive, respectively.
3074*/
3075static RtreeValue rtreeValueDown(sqlite3_value *v){
3076 double d = sqlite3_value_double(v);
3077 float f = (float)d;
3078 if( f>d ){
3079 unsigned int x;
3080 memcpy(&x, &f, 4);
3081 x = (x & 0x80000000)!=0 ? x+1 : x-1;
3082 memcpy(&f, &x, 4);
3083 }
3084 return f;
3085}
3086static RtreeValue rtreeValueUp(sqlite3_value *v){
3087 double d = sqlite3_value_double(v);
3088 float f = (float)d;
3089 if( f<d ){
3090 unsigned int x;
3091 memcpy(&x, &f, 4);
3092 x = (x & 0x80000000)!=0 ? x-1 : x+1;
3093 memcpy(&f, &x, 4);
3094 }
3095 return f;
3096}
3097#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
3098
3099#if !defined(SQLITE_RTREE_INT_ONLY) && defined(SQLITE_DEBUG)
3100/*
3101** SQL function: rtree_round32(V,F)
3102**
3103** Convert the floating point value V to the nearest 32-bit float
3104** and return that 32-bit float value. Round up if F is true, or
3105** down if F is falsed.
3106**
3107** Debugging and testing use only.
3108*/
3109static void rtreeRoundFunc(
3110 sqlite3_context *ctx,
3111 int nArg,
3112 sqlite3_value **apArg
3113){
3114 float f;
3115 if( sqlite3_value_int(apArg[1]) ){
3116 f = rtreeValueUp(apArg[0]);
3117 }else{
3118 f = rtreeValueDown(apArg[0]);
3119 }
3120 sqlite3_result_double(ctx, (double)f);
3121}
3122#endif /* !defined(SQLITE_RTREE_INT_ONLY) && defined(SQLITE_DEBUG) */
3123
3124/*
3125** A constraint has failed while inserting a row into an rtree table.
3126** Assuming no OOM error occurs, this function sets the error message
3127** (at pRtree->base.zErrMsg) to an appropriate value and returns
3128** SQLITE_CONSTRAINT.
3129**
3130** Parameter iCol is the index of the leftmost column involved in the
3131** constraint failure. If it is 0, then the constraint that failed is
3132** the unique constraint on the id column. Otherwise, it is the rtree
3133** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
3134**
3135** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
3136*/
3137static int rtreeConstraintError(Rtree *pRtree, int iCol){
3138 sqlite3_stmt *pStmt = 0;
3139 char *zSql;
3140 int rc;
3141
3142 assert( iCol==0 || iCol%2 );
3143 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
3144 if( zSql ){
3145 rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
3146 }else{
3147 rc = SQLITE_NOMEM;
3148 }
3149 sqlite3_free(zSql);
3150
3151 if( rc==SQLITE_OK ){
3152 if( iCol==0 ){
3153 const char *zCol = sqlite3_column_name(pStmt, 0);
3154 pRtree->base.zErrMsg = sqlite3_mprintf(
3155 "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
3156 );
3157 }else{
3158 const char *zCol1 = sqlite3_column_name(pStmt, iCol);
3159 const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
3160 pRtree->base.zErrMsg = sqlite3_mprintf(
3161 "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
3162 );
3163 }
3164 }
3165
3166 sqlite3_finalize(pStmt);
3167 return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
3168}
3169
3170
3171
3172/*
3173** The xUpdate method for rtree module virtual tables.
3174*/
3175static int rtreeUpdate(
3176 sqlite3_vtab *pVtab,
3177 int nData,
3178 sqlite3_value **aData,
3179 sqlite_int64 *pRowid
3180){
3181 Rtree *pRtree = (Rtree *)pVtab;
3182 int rc = SQLITE_OK;
3183 RtreeCell cell; /* New cell to insert if nData>1 */
3184 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
3185
3186 if( pRtree->nNodeRef ){
3187 /* Unable to write to the btree while another cursor is reading from it,
3188 ** since the write might do a rebalance which would disrupt the read
3189 ** cursor. */
3190 return SQLITE_LOCKED_VTAB;
3191 }
3192 rtreeReference(pRtree);
3193 assert(nData>=1);
3194
3195 memset(&cell, 0, sizeof(cell));
3196
3197 /* Constraint handling. A write operation on an r-tree table may return
3198 ** SQLITE_CONSTRAINT for two reasons:
3199 **
3200 ** 1. A duplicate rowid value, or
3201 ** 2. The supplied data violates the "x2>=x1" constraint.
3202 **
3203 ** In the first case, if the conflict-handling mode is REPLACE, then
3204 ** the conflicting row can be removed before proceeding. In the second
3205 ** case, SQLITE_CONSTRAINT must be returned regardless of the
3206 ** conflict-handling mode specified by the user.
3207 */
3208 if( nData>1 ){
3209 int ii;
3210 int nn = nData - 4;
3211 sqlite3_value *pNewRowid; /* Value of the new rowid, or NULL */
3212
3213 if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
3214 /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
3215 **
3216 ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
3217 ** with "column" that are interpreted as table constraints.
3218 ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
3219 ** This problem was discovered after years of use, so we silently ignore
3220 ** these kinds of misdeclared tables to avoid breaking any legacy.
3221 */
3222
3223#ifndef SQLITE_RTREE_INT_ONLY
3224 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
3225 for(ii=0; ii<nn; ii+=2){
3226 cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
3227 cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
3228 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
3229 rc = rtreeConstraintError(pRtree, ii+1);
3230 goto constraint;
3231 }
3232 }
3233 }else
3234#endif
3235 {
3236 for(ii=0; ii<nn; ii+=2){
3237 cell.aCoord[ii].i = rtreeValueInt32(aData[ii+3]);
3238 cell.aCoord[ii+1].i = rtreeValueInt32(aData[ii+4]);
3239 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
3240 rc = rtreeConstraintError(pRtree, ii+1);
3241 goto constraint;
3242 }
3243 }
3244 }
3245
3246 /* The new rowid is normally the value of the first column, aData[2].
3247 ** But SQLite does not treat that column as an alias for the rowid,
3248 ** so a new rowid assigned using the name "rowid", "oid" or "_rowid_"
3249 ** is passed in aData[1]. Use aData[1] if aData[2] is a "no-change"
3250 ** value (an UPDATE that does not assign the first column - see
3251 ** rtreeColumn()), or if aData[2] is NULL in an INSERT. */
3252 pNewRowid = aData[2];
3253 if( sqlite3_value_nochange(pNewRowid)
3254 || (sqlite3_value_type(aData[0])==SQLITE_NULL
3255 && sqlite3_value_type(pNewRowid)==SQLITE_NULL)
3256 ){
3257 pNewRowid = aData[1];
3258 }
3259
3260 /* If a rowid value was supplied, check if it is already present in
3261 ** the table. If so, the constraint has failed. */
3262 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL ){
3263 cell.iRowid = sqlite3_value_int64(pNewRowid);
3264 if( sqlite3_value_type(aData[0])==SQLITE_NULL
3265 || sqlite3_value_int64(aData[0])!=cell.iRowid
3266 ){
3267 int steprc;
3268 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
3269 steprc = sqlite3_step(pRtree->pReadRowid);
3270 rc = sqlite3_reset(pRtree->pReadRowid);
3271 if( SQLITE_ROW==steprc ){
3272 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
3273 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
3274 }else{
3275 rc = rtreeConstraintError(pRtree, 0);
3276 goto constraint;
3277 }
3278 }
3279 }
3280 bHaveRowid = 1;
3281 }
3282 }
3283
3284 /* If aData[0] is not an SQL NULL value, it is the rowid of a
3285 ** record to delete from the r-tree table. The following block does
3286 ** just that.
3287 */
3288 if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
3289 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
3290 }
3291
3292 /* If the aData[] array contains more than one element, elements
3293 ** (aData[2]..aData[argc-1]) contain a new record to insert into
3294 ** the r-tree structure.
3295 */
3296 if( rc==SQLITE_OK && nData>1 ){
3297 /* Insert the new record into the r-tree */
3298 RtreeNode *pLeaf = 0;
3299
3300 /* Figure out the rowid of the new row. */
3301 if( bHaveRowid==0 ){
3302 rc = rtreeNewRowid(pRtree, &cell.iRowid);
3303 }
3304 *pRowid = cell.iRowid;
3305
3306 if( rc==SQLITE_OK ){
3307 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
3308 }
3309 if( rc==SQLITE_OK ){
3310 int rc2;
3311 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
3312 rc2 = nodeRelease(pRtree, pLeaf);
3313 if( rc==SQLITE_OK ){
3314 rc = rc2;
3315 }
3316 }
3317 if( rc==SQLITE_OK && pRtree->nAux ){
3318 sqlite3_stmt *pUp = pRtree->pWriteAux;
3319 int jj;
3320 sqlite3_bind_int64(pUp, 1, *pRowid);
3321 for(jj=0; jj<pRtree->nAux; jj++){
3322 sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
3323 }
3324 sqlite3_step(pUp);
3325 rc = sqlite3_reset(pUp);
3326 }
3327 }
3328
3329constraint:
3330 rtreeRelease(pRtree);
3331 return rc;
3332}
3333
3334/*
3335** Called when a transaction starts.
3336*/
3337static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
3338 Rtree *pRtree = (Rtree *)pVtab;
3339 assert( pRtree->inWrTrans==0 );
3340 pRtree->inWrTrans = 1;
3341 return SQLITE_OK;
3342}
3343
3344/*
3345** Called when a transaction completes (either by COMMIT or ROLLBACK).
3346** The sqlite3_blob object should be released at this point.
3347*/
3348static int rtreeEndTransaction(sqlite3_vtab *pVtab){
3349 Rtree *pRtree = (Rtree *)pVtab;
3350 pRtree->inWrTrans = 0;
3351 nodeBlobReset(pRtree);
3352 return SQLITE_OK;
3353}
3354static int rtreeRollback(sqlite3_vtab *pVtab){
3355 return rtreeEndTransaction(pVtab);
3356}
3357
3358/*
3359** The xRename method for rtree module virtual tables.
3360*/
3361static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
3362 Rtree *pRtree = (Rtree *)pVtab;
3363 int rc = SQLITE_NOMEM;
3364 char *zSql = sqlite3_mprintf(
3365 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
3366 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
3367 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
3368 , pRtree->zDb, pRtree->zName, zNewName
3369 , pRtree->zDb, pRtree->zName, zNewName
3370 , pRtree->zDb, pRtree->zName, zNewName
3371 );
3372 if( zSql ){
3373 nodeBlobReset(pRtree);
3374 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
3375 sqlite3_free(zSql);
3376 }
3377 return rc;
3378}
3379
3380/*
3381** The xSavepoint method.
3382**
3383** This module does not need to do anything to support savepoints. However,
3384** it uses this hook to close any open blob handle. This is done because a
3385** DROP TABLE command - which fortunately always opens a savepoint - cannot
3386** succeed if there are any open blob handles. i.e. if the blob handle were
3387** not closed here, the following would fail:
3388**
3389** BEGIN;
3390** INSERT INTO rtree...
3391** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
3392** COMMIT;
3393*/
3394static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
3395 Rtree *pRtree = (Rtree *)pVtab;
3396 u8 iwt = pRtree->inWrTrans;
3397 UNUSED_PARAMETER(iSavepoint);
3398 pRtree->inWrTrans = 0;
3399 nodeBlobReset(pRtree);
3400 pRtree->inWrTrans = iwt;
3401 return SQLITE_OK;
3402}
3403
3404/*
3405** This function populates the pRtree->nRowEst variable with an estimate
3406** of the number of rows in the virtual table. If possible, this is based
3407** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
3408*/
3409static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
3410 const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
3411 char *zSql;
3412 sqlite3_stmt *p;
3413 int rc;
3414 i64 nRow = RTREE_MIN_ROWEST;
3415
3416 rc = sqlite3_table_column_metadata(
3417 db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
3418 );
3419 if( rc!=SQLITE_OK ){
3420 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
3421 return rc==SQLITE_ERROR ? SQLITE_OK : rc;
3422 }
3423 zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
3424 if( zSql==0 ){
3425 rc = SQLITE_NOMEM;
3426 }else{
3427 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
3428 if( rc==SQLITE_OK ){
3429 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
3430 rc = sqlite3_finalize(p);
3431 }
3432 sqlite3_free(zSql);
3433 }
3434 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
3435 return rc;
3436}
3437
3438
3439/*
3440** Return true if zName is the extension on one of the shadow tables used
3441** by this module.
3442*/
3443static int rtreeShadowName(const char *zName){
3444 static const char *azName[] = {
3445 "node", "parent", "rowid"
3446 };
3447 unsigned int i;
3448 for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
3449 if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
3450 }
3451 return 0;
3452}
3453
3454/* Forward declaration */
3455static int rtreeIntegrity(sqlite3_vtab*, const char*, const char*, int, char**);
3456
3457static sqlite3_module rtreeModule = {
3458 4, /* iVersion */
3459 rtreeCreate, /* xCreate - create a table */
3460 rtreeConnect, /* xConnect - connect to an existing table */
3461 rtreeBestIndex, /* xBestIndex - Determine search strategy */
3462 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
3463 rtreeDestroy, /* xDestroy - Drop a table */
3464 rtreeOpen, /* xOpen - open a cursor */
3465 rtreeClose, /* xClose - close a cursor */
3466 rtreeFilter, /* xFilter - configure scan constraints */
3467 rtreeNext, /* xNext - advance a cursor */
3468 rtreeEof, /* xEof */
3469 rtreeColumn, /* xColumn - read data */
3470 rtreeRowid, /* xRowid - read data */
3471 rtreeUpdate, /* xUpdate - write data */
3472 rtreeBeginTransaction, /* xBegin - begin transaction */
3473 rtreeEndTransaction, /* xSync - sync transaction */
3474 rtreeEndTransaction, /* xCommit - commit transaction */
3475 rtreeRollback, /* xRollback - rollback transaction */
3476 0, /* xFindFunction - function overloading */
3477 rtreeRename, /* xRename - rename the table */
3478 rtreeSavepoint, /* xSavepoint */
3479 0, /* xRelease */
3480 0, /* xRollbackTo */
3481 rtreeShadowName, /* xShadowName */
3482 rtreeIntegrity /* xIntegrity */
3483};
3484
3485static int rtreeSqlInit(
3486 Rtree *pRtree,
3487 sqlite3 *db,
3488 const char *zDb,
3489 const char *zPrefix,
3490 int isCreate
3491){
3492 int rc = SQLITE_OK;
3493
3494 #define N_STATEMENT 8
3495 static const char *azSql[N_STATEMENT] = {
3496 /* Write the xxx_node table */
3497 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
3498 "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
3499
3500 /* Read and write the xxx_rowid table */
3501 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3502 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
3503 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3504
3505 /* Read and write the xxx_parent table */
3506 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
3507 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
3508 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
3509 };
3510 sqlite3_stmt **appStmt[N_STATEMENT];
3511 int i;
3512 const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
3513
3514 pRtree->db = db;
3515
3516 if( isCreate ){
3517 char *zCreate;
3518 sqlite3_str *p = sqlite3_str_new(db);
3519 int ii;
3520 sqlite3_str_appendf(p,
3521 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
3522 zDb, zPrefix);
3523 for(ii=0; ii<pRtree->nAux; ii++){
3524 sqlite3_str_appendf(p,",a%d",ii);
3525 }
3526 sqlite3_str_appendf(p,
3527 ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
3528 zDb, zPrefix);
3529 sqlite3_str_appendf(p,
3530 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
3531 zDb, zPrefix);
3532 sqlite3_str_appendf(p,
3533 "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
3534 zDb, zPrefix, pRtree->iNodeSize);
3535 zCreate = sqlite3_str_finish(p);
3536 if( !zCreate ){
3537 return SQLITE_NOMEM;
3538 }
3539 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
3540 sqlite3_free(zCreate);
3541 if( rc!=SQLITE_OK ){
3542 return rc;
3543 }
3544 }
3545
3546 appStmt[0] = &pRtree->pWriteNode;
3547 appStmt[1] = &pRtree->pDeleteNode;
3548 appStmt[2] = &pRtree->pReadRowid;
3549 appStmt[3] = &pRtree->pWriteRowid;
3550 appStmt[4] = &pRtree->pDeleteRowid;
3551 appStmt[5] = &pRtree->pReadParent;
3552 appStmt[6] = &pRtree->pWriteParent;
3553 appStmt[7] = &pRtree->pDeleteParent;
3554
3555 rc = rtreeQueryStat1(db, pRtree);
3556 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
3557 char *zSql;
3558 const char *zFormat;
3559 if( i!=3 || pRtree->nAux==0 ){
3560 zFormat = azSql[i];
3561 }else {
3562 /* An UPSERT is very slightly slower than REPLACE, but it is needed
3563 ** if there are auxiliary columns */
3564 zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
3565 "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
3566 }
3567 zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
3568 if( zSql ){
3569 rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
3570 }else{
3571 rc = SQLITE_NOMEM;
3572 }
3573 sqlite3_free(zSql);
3574 }
3575 if( pRtree->nAux && rc!=SQLITE_NOMEM ){
3576 pRtree->zReadAuxSql = sqlite3_mprintf(
3577 "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
3578 zDb, zPrefix);
3579 if( pRtree->zReadAuxSql==0 ){
3580 rc = SQLITE_NOMEM;
3581 }else{
3582 sqlite3_str *p = sqlite3_str_new(db);
3583 int ii;
3584 char *zSql;
3585 sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
3586 for(ii=0; ii<pRtree->nAux; ii++){
3587 if( ii ) sqlite3_str_append(p, ",", 1);
3588#ifdef SQLITE_ENABLE_GEOPOLY
3589 if( ii<pRtree->nAuxNotNull ){
3590 sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
3591 }else
3592#endif
3593 {
3594 sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
3595 }
3596 }
3597 sqlite3_str_appendf(p, " WHERE rowid=?1");
3598 zSql = sqlite3_str_finish(p);
3599 if( zSql==0 ){
3600 rc = SQLITE_NOMEM;
3601 }else{
3602 rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
3603 sqlite3_free(zSql);
3604 }
3605 }
3606 }
3607
3608 return rc;
3609}
3610
3611/*
3612** The second argument to this function contains the text of an SQL statement
3613** that returns a single integer value. The statement is compiled and executed
3614** using database connection db. If successful, the integer value returned
3615** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
3616** code is returned and the value of *piVal after returning is not defined.
3617*/
3618static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
3619 int rc = SQLITE_NOMEM;
3620 if( zSql ){
3621 sqlite3_stmt *pStmt = 0;
3622 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
3623 if( rc==SQLITE_OK ){
3624 if( SQLITE_ROW==sqlite3_step(pStmt) ){
3625 *piVal = sqlite3_column_int(pStmt, 0);
3626 }
3627 rc = sqlite3_finalize(pStmt);
3628 }
3629 }
3630 return rc;
3631}
3632
3633/*
3634** This function is called from within the xConnect() or xCreate() method to
3635** determine the node-size used by the rtree table being created or connected
3636** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
3637** Otherwise, an SQLite error code is returned.
3638**
3639** If this function is being called as part of an xConnect(), then the rtree
3640** table already exists. In this case the node-size is determined by inspecting
3641** the root node of the tree.
3642**
3643** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
3644** This ensures that each node is stored on a single database page. If the
3645** database page-size is so large that more than RTREE_MAXCELLS entries
3646** would fit in a single node, use a smaller node-size.
3647*/
3648static int getNodeSize(
3649 sqlite3 *db, /* Database handle */
3650 Rtree *pRtree, /* Rtree handle */
3651 int isCreate, /* True for xCreate, false for xConnect */
3652 char **pzErr /* OUT: Error message, if any */
3653){
3654 int rc;
3655 char *zSql;
3656 if( isCreate ){
3657 int iPageSize = 0;
3658 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
3659 rc = getIntFromStmt(db, zSql, &iPageSize);
3660 if( rc==SQLITE_OK ){
3661 pRtree->iNodeSize = iPageSize-64;
3662 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
3663 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
3664 }
3665 }else{
3666 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3667 }
3668 }else{
3669 zSql = sqlite3_mprintf(
3670 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
3671 pRtree->zDb, pRtree->zName
3672 );
3673 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
3674 if( rc!=SQLITE_OK ){
3675 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3676 }else if( pRtree->iNodeSize<(512-64) ){
3677 rc = SQLITE_CORRUPT_VTAB;
3678 RTREE_IS_CORRUPT(pRtree);
3679 *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
3680 pRtree->zName);
3681 }
3682 }
3683
3684 sqlite3_free(zSql);
3685 return rc;
3686}
3687
3688/*
3689** Return the length of a token
3690*/
3691static int rtreeTokenLength(const char *z){
3692 int dummy = 0;
3693 return sqlite3GetToken((const unsigned char*)z,&dummy);
3694}
3695
3696/*
3697** This function is the implementation of both the xConnect and xCreate
3698** methods of the r-tree virtual table.
3699**
3700** argv[0] -> module name
3701** argv[1] -> database name
3702** argv[2] -> table name
3703** argv[...] -> column names...
3704*/
3705static int rtreeInit(
3706 sqlite3 *db, /* Database connection */
3707 void *pAux, /* One of the RTREE_COORD_* constants */
3708 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
3709 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
3710 char **pzErr, /* OUT: Error message, if any */
3711 int isCreate /* True for xCreate, false for xConnect */
3712){
3713 int rc = SQLITE_OK;
3714 Rtree *pRtree;
3715 int nDb; /* Length of string argv[1] */
3716 int nName; /* Length of string argv[2] */
3717 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
3718 sqlite3_str *pSql;
3719 char *zSql;
3720 int ii = 4;
3721 int iErr;
3722
3723 const char *aErrMsg[] = {
3724 0, /* 0 */
3725 "Wrong number of columns for an rtree table", /* 1 */
3726 "Too few columns for an rtree table", /* 2 */
3727 "Too many columns for an rtree table", /* 3 */
3728 "Auxiliary rtree columns must be last" /* 4 */
3729 };
3730
3731 assert( RTREE_MAX_AUX_COLUMN<256 );
3732 if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
3733 *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
3734 return SQLITE_ERROR;
3735 }
3736
3737 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
3738 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
3739
3740
3741 /* Allocate the sqlite3_vtab structure */
3742 nDb = (int)strlen(argv[1]);
3743 nName = (int)strlen(argv[2]);
3744 pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName*2+8);
3745 if( !pRtree ){
3746 return SQLITE_NOMEM;
3747 }
3748 memset(pRtree, 0, sizeof(Rtree)+nDb+nName*2+8);
3749 pRtree->nBusy = 1;
3750 pRtree->base.pModule = &rtreeModule;
3751 pRtree->zDb = (char *)&pRtree[1];
3752 pRtree->zName = &pRtree->zDb[nDb+1];
3753 pRtree->zNodeName = &pRtree->zName[nName+1];
3754 pRtree->eCoordType = (u8)eCoordType;
3755 memcpy(pRtree->zDb, argv[1], nDb);
3756 memcpy(pRtree->zName, argv[2], nName);
3757 memcpy(pRtree->zNodeName, argv[2], nName);
3758 memcpy(&pRtree->zNodeName[nName], "_node", 6);
3759
3760
3761 /* Create/Connect to the underlying relational database schema. If
3762 ** that is successful, call sqlite3_declare_vtab() to configure
3763 ** the r-tree table schema.
3764 */
3765 pSql = sqlite3_str_new(db);
3766 sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
3767 rtreeTokenLength(argv[3]), argv[3]);
3768 for(ii=4; ii<argc; ii++){
3769 const char *zArg = argv[ii];
3770 if( zArg[0]=='+' ){
3771 pRtree->nAux++;
3772 sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
3773 }else if( pRtree->nAux>0 ){
3774 break;
3775 }else{
3776 static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
3777 pRtree->nDim2++;
3778 sqlite3_str_appendf(pSql, azFormat[eCoordType],
3779 rtreeTokenLength(zArg), zArg);
3780 }
3781 }
3782 sqlite3_str_appendf(pSql, ");");
3783 zSql = sqlite3_str_finish(pSql);
3784 if( !zSql ){
3785 rc = SQLITE_NOMEM;
3786 }else if( ii<argc ){
3787 *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
3788 rc = SQLITE_ERROR;
3789 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
3790 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3791 }
3792 sqlite3_free(zSql);
3793 if( rc ) goto rtreeInit_fail;
3794 pRtree->nDim = pRtree->nDim2/2;
3795 if( pRtree->nDim<1 ){
3796 iErr = 2;
3797 }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
3798 iErr = 3;
3799 }else if( pRtree->nDim2 % 2 ){
3800 iErr = 1;
3801 }else{
3802 iErr = 0;
3803 }
3804 if( iErr ){
3805 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3806 goto rtreeInit_fail;
3807 }
3808 pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
3809
3810 /* Figure out the node size to use. */
3811 rc = getNodeSize(db, pRtree, isCreate, pzErr);
3812 if( rc ) goto rtreeInit_fail;
3813 rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
3814 if( rc ){
3815 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3816 goto rtreeInit_fail;
3817 }
3818
3819 *ppVtab = (sqlite3_vtab *)pRtree;
3820 return SQLITE_OK;
3821
3822rtreeInit_fail:
3823 if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
3824 assert( *ppVtab==0 );
3825 assert( pRtree->nBusy==1 );
3826 rtreeRelease(pRtree);
3827 return rc;
3828}
3829
3830
3831/*
3832** Implementation of a scalar function that decodes r-tree nodes to
3833** human readable strings. This can be used for debugging and analysis.
3834**
3835** The scalar function takes two arguments: (1) the number of dimensions
3836** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
3837** an r-tree node. For a two-dimensional r-tree structure called "rt", to
3838** deserialize all nodes, a statement like:
3839**
3840** SELECT rtreenode(2, data) FROM rt_node;
3841**
3842** The human readable string takes the form of a Tcl list with one
3843** entry for each cell in the r-tree node. Each entry is itself a
3844** list, containing the 8-byte rowid/pageno followed by the
3845** <num-dimension>*2 coordinates.
3846*/
3847static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3848 RtreeNode node;
3849 Rtree tree;
3850 int ii;
3851 int nData;
3852 int errCode;
3853 sqlite3_str *pOut;
3854 i64 nDim64;
3855
3856 UNUSED_PARAMETER(nArg);
3857 memset(&node, 0, sizeof(RtreeNode));
3858 memset(&tree, 0, sizeof(Rtree));
3859 nDim64 = sqlite3_value_int64(apArg[0]);
3860 if( nDim64<1 || nDim64>5 ) return;
3861 tree.nDim = (u8)nDim64;
3862 tree.nDim2 = tree.nDim*2;
3863 tree.nBytesPerCell = 8 + 8 * tree.nDim;
3864 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
3865 if( node.zData==0 ) return;
3866 nData = sqlite3_value_bytes(apArg[1]);
3867 if( nData<4 ) return;
3868 if( nData<4+NCELL(&node)*tree.nBytesPerCell ) return;
3869
3870 pOut = sqlite3_str_new(0);
3871 for(ii=0; ii<NCELL(&node); ii++){
3872 RtreeCell cell;
3873 int jj;
3874
3875 nodeGetCell(&tree, &node, ii, &cell);
3876 if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
3877 sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
3878 for(jj=0; jj<tree.nDim2; jj++){
3879#ifndef SQLITE_RTREE_INT_ONLY
3880 sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
3881#else
3882 sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
3883#endif
3884 }
3885 sqlite3_str_append(pOut, "}", 1);
3886 }
3887 errCode = sqlite3_str_errcode(pOut);
3888 sqlite3_result_error_code(ctx, errCode);
3889 sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
3890}
3891
3892/* This routine implements an SQL function that returns the "depth" parameter
3893** from the front of a blob that is an r-tree node. For example:
3894**
3895** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
3896**
3897** The depth value is 0 for all nodes other than the root node, and the root
3898** node always has nodeno=1, so the example above is the primary use for this
3899** routine. This routine is intended for testing and analysis only.
3900*/
3901static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3902 UNUSED_PARAMETER(nArg);
3903 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3904 || sqlite3_value_bytes(apArg[0])<2
3905
3906 ){
3907 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3908 }else{
3909 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3910 if( zBlob ){
3911 sqlite3_result_int(ctx, readInt16(zBlob));
3912 }else{
3913 sqlite3_result_error_nomem(ctx);
3914 }
3915 }
3916}
3917
3918/*
3919** Context object passed between the various routines that make up the
3920** implementation of integrity-check function rtreecheck().
3921*/
3922typedef struct RtreeCheck RtreeCheck;
3923struct RtreeCheck {
3924 sqlite3 *db; /* Database handle */
3925 const char *zDb; /* Database containing rtree table */
3926 const char *zTab; /* Name of rtree table */
3927 int bInt; /* True for rtree_i32 table */
3928 int nDim; /* Number of dimensions for this rtree tbl */
3929 sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
3930 sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
3931 int nLeaf; /* Number of leaf cells in table */
3932 int nNonLeaf; /* Number of non-leaf cells in table */
3933 int rc; /* Return code */
3934 char *zReport; /* Message to report */
3935 int nErr; /* Number of lines in zReport */
3936};
3937
3938#define RTREE_CHECK_MAX_ERROR 100
3939
3940/*
3941** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
3942** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
3943*/
3944static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
3945 int rc = sqlite3_reset(pStmt);
3946 if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
3947}
3948
3949/*
3950** The second and subsequent arguments to this function are a format string
3951** and printf style arguments. This function formats the string and attempts
3952** to compile it as an SQL statement.
3953**
3954** If successful, a pointer to the new SQL statement is returned. Otherwise,
3955** NULL is returned and an error code left in RtreeCheck.rc.
3956*/
3957static sqlite3_stmt *rtreeCheckPrepare(
3958 RtreeCheck *pCheck, /* RtreeCheck object */
3959 const char *zFmt, ... /* Format string and trailing args */
3960){
3961 va_list ap;
3962 char *z;
3963 sqlite3_stmt *pRet = 0;
3964
3965 va_start(ap, zFmt);
3966 z = sqlite3_vmprintf(zFmt, ap);
3967
3968 if( pCheck->rc==SQLITE_OK ){
3969 if( z==0 ){
3970 pCheck->rc = SQLITE_NOMEM;
3971 }else{
3972 pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
3973 }
3974 }
3975
3976 sqlite3_free(z);
3977 va_end(ap);
3978 return pRet;
3979}
3980
3981/*
3982** The second and subsequent arguments to this function are a printf()
3983** style format string and arguments. This function formats the string and
3984** appends it to the report being accumulated in pCheck.
3985*/
3986static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
3987 va_list ap;
3988 va_start(ap, zFmt);
3989 if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
3990 char *z = sqlite3_vmprintf(zFmt, ap);
3991 if( z==0 ){
3992 pCheck->rc = SQLITE_NOMEM;
3993 }else{
3994 pCheck->zReport = sqlite3_mprintf("%z%s%z",
3995 pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
3996 );
3997 if( pCheck->zReport==0 ){
3998 pCheck->rc = SQLITE_NOMEM;
3999 }
4000 }
4001 pCheck->nErr++;
4002 }
4003 va_end(ap);
4004}
4005
4006/*
4007** This function is a no-op if there is already an error code stored
4008** in the RtreeCheck object indicated by the first argument. NULL is
4009** returned in this case.
4010**
4011** Otherwise, the contents of rtree table node iNode are loaded from
4012** the database and copied into a buffer obtained from sqlite3_malloc().
4013** If no error occurs, a pointer to the buffer is returned and (*pnNode)
4014** is set to the size of the buffer in bytes.
4015**
4016** Or, if an error does occur, NULL is returned and an error code left
4017** in the RtreeCheck object. The final value of *pnNode is undefined in
4018** this case.
4019*/
4020static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
4021 u8 *pRet = 0; /* Return value */
4022
4023 if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
4024 pCheck->pGetNode = rtreeCheckPrepare(pCheck,
4025 "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
4026 pCheck->zDb, pCheck->zTab
4027 );
4028 }
4029
4030 if( pCheck->rc==SQLITE_OK ){
4031 sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
4032 if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
4033 int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
4034 const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
4035 pRet = sqlite3_malloc64(nNode);
4036 if( pRet==0 ){
4037 pCheck->rc = SQLITE_NOMEM;
4038 }else{
4039 memcpy(pRet, pNode, nNode);
4040 *pnNode = nNode;
4041 }
4042 }
4043 rtreeCheckReset(pCheck, pCheck->pGetNode);
4044 if( pCheck->rc==SQLITE_OK && pRet==0 ){
4045 rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
4046 }
4047 }
4048
4049 return pRet;
4050}
4051
4052/*
4053** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
4054** (if bLeaf==1) table contains a specified entry. The schemas of the
4055** two tables are:
4056**
4057** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
4058** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
4059**
4060** In both cases, this function checks that there exists an entry with
4061** IPK value iKey and the second column set to iVal.
4062**
4063*/
4064static void rtreeCheckMapping(
4065 RtreeCheck *pCheck, /* RtreeCheck object */
4066 int bLeaf, /* True for a leaf cell, false for interior */
4067 i64 iKey, /* Key for mapping */
4068 i64 iVal /* Expected value for mapping */
4069){
4070 int rc;
4071 sqlite3_stmt *pStmt;
4072 const char *azSql[2] = {
4073 "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
4074 "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
4075 };
4076
4077 assert( bLeaf==0 || bLeaf==1 );
4078 if( pCheck->aCheckMapping[bLeaf]==0 ){
4079 pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
4080 azSql[bLeaf], pCheck->zDb, pCheck->zTab
4081 );
4082 }
4083 if( pCheck->rc!=SQLITE_OK ) return;
4084
4085 pStmt = pCheck->aCheckMapping[bLeaf];
4086 sqlite3_bind_int64(pStmt, 1, iKey);
4087 rc = sqlite3_step(pStmt);
4088 if( rc==SQLITE_DONE ){
4089 rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
4090 iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
4091 );
4092 }else if( rc==SQLITE_ROW ){
4093 i64 ii = sqlite3_column_int64(pStmt, 0);
4094 if( ii!=iVal ){
4095 rtreeCheckAppendMsg(pCheck,
4096 "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
4097 iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
4098 );
4099 }
4100 }
4101 rtreeCheckReset(pCheck, pStmt);
4102}
4103
4104/*
4105** Argument pCell points to an array of coordinates stored on an rtree page.
4106** This function checks that the coordinates are internally consistent (no
4107** x1>x2 conditions) and adds an error message to the RtreeCheck object
4108** if they are not.
4109**
4110** Additionally, if pParent is not NULL, then it is assumed to point to
4111** the array of coordinates on the parent page that bound the page
4112** containing pCell. In this case it is also verified that the two
4113** sets of coordinates are mutually consistent and an error message added
4114** to the RtreeCheck object if they are not.
4115*/
4116static void rtreeCheckCellCoord(
4117 RtreeCheck *pCheck,
4118 i64 iNode, /* Node id to use in error messages */
4119 int iCell, /* Cell number to use in error messages */
4120 u8 *pCell, /* Pointer to cell coordinates */
4121 u8 *pParent /* Pointer to parent coordinates */
4122){
4123 RtreeCoord c1, c2;
4124 RtreeCoord p1, p2;
4125 int i;
4126
4127 for(i=0; i<pCheck->nDim; i++){
4128 readCoord(&pCell[4*2*i], &c1);
4129 readCoord(&pCell[4*(2*i + 1)], &c2);
4130
4131 /* printf("%e, %e\n", c1.u.f, c2.u.f); */
4132 if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
4133 rtreeCheckAppendMsg(pCheck,
4134 "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
4135 );
4136 }
4137
4138 if( pParent ){
4139 readCoord(&pParent[4*2*i], &p1);
4140 readCoord(&pParent[4*(2*i + 1)], &p2);
4141
4142 if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
4143 || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
4144 ){
4145 rtreeCheckAppendMsg(pCheck,
4146 "Dimension %d of cell %d on node %lld is corrupt relative to parent"
4147 , i, iCell, iNode
4148 );
4149 }
4150 }
4151 }
4152}
4153
4154/*
4155** Run rtreecheck() checks on node iNode, which is at depth iDepth within
4156** the r-tree structure. Argument aParent points to the array of coordinates
4157** that bound node iNode on the parent node.
4158**
4159** If any problems are discovered, an error message is appended to the
4160** report accumulated in the RtreeCheck object.
4161*/
4162static void rtreeCheckNode(
4163 RtreeCheck *pCheck,
4164 int iDepth, /* Depth of iNode (0==leaf) */
4165 u8 *aParent, /* Buffer containing parent coords */
4166 i64 iNode /* Node to check */
4167){
4168 u8 *aNode = 0;
4169 int nNode = 0;
4170
4171 assert( iNode==1 || aParent!=0 );
4172 assert( pCheck->nDim>0 );
4173
4174 aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
4175 if( aNode ){
4176 if( nNode<4 ){
4177 rtreeCheckAppendMsg(pCheck,
4178 "Node %lld is too small (%d bytes)", iNode, nNode
4179 );
4180 }else{
4181 int nCell; /* Number of cells on page */
4182 int i; /* Used to iterate through cells */
4183 if( aParent==0 ){
4184 iDepth = readInt16(aNode);
4185 if( iDepth>RTREE_MAX_DEPTH ){
4186 rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
4187 sqlite3_free(aNode);
4188 return;
4189 }
4190 }
4191 nCell = readInt16(&aNode[2]);
4192 if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
4193 rtreeCheckAppendMsg(pCheck,
4194 "Node %lld is too small for cell count of %d (%d bytes)",
4195 iNode, nCell, nNode
4196 );
4197 }else{
4198 for(i=0; i<nCell; i++){
4199 u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
4200 i64 iVal = readInt64(pCell);
4201 rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
4202
4203 if( iDepth>0 ){
4204 rtreeCheckMapping(pCheck, 0, iVal, iNode);
4205 rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
4206 pCheck->nNonLeaf++;
4207 }else{
4208 rtreeCheckMapping(pCheck, 1, iVal, iNode);
4209 pCheck->nLeaf++;
4210 }
4211 }
4212 }
4213 }
4214 sqlite3_free(aNode);
4215 }
4216}
4217
4218/*
4219** The second argument to this function must be either "_rowid" or
4220** "_parent". This function checks that the number of entries in the
4221** %_rowid or %_parent table is exactly nExpect. If not, it adds
4222** an error message to the report in the RtreeCheck object indicated
4223** by the first argument.
4224*/
4225static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
4226 if( pCheck->rc==SQLITE_OK ){
4227 sqlite3_stmt *pCount;
4228 pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
4229 pCheck->zDb, pCheck->zTab, zTbl
4230 );
4231 if( pCount ){
4232 if( sqlite3_step(pCount)==SQLITE_ROW ){
4233 i64 nActual = sqlite3_column_int64(pCount, 0);
4234 if( nActual!=nExpect ){
4235 rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
4236 " - expected %lld, actual %lld" , zTbl, nExpect, nActual
4237 );
4238 }
4239 }
4240 pCheck->rc = sqlite3_finalize(pCount);
4241 }
4242 }
4243}
4244
4245/*
4246** This function does the bulk of the work for the rtree integrity-check.
4247** It is called by rtreecheck(), which is the SQL function implementation.
4248*/
4249static int rtreeCheckTable(
4250 sqlite3 *db, /* Database handle to access db through */
4251 const char *zDb, /* Name of db ("main", "temp" etc.) */
4252 const char *zTab, /* Name of rtree table to check */
4253 char **pzReport /* OUT: sqlite3_malloc'd report text */
4254){
4255 RtreeCheck check; /* Common context for various routines */
4256 sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
4257 int nAux = 0; /* Number of extra columns. */
4258
4259 /* Initialize the context object */
4260 memset(&check, 0, sizeof(check));
4261 check.db = db;
4262 check.zDb = zDb;
4263 check.zTab = zTab;
4264
4265 /* Find the number of auxiliary columns */
4266 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
4267 if( pStmt ){
4268 nAux = sqlite3_column_count(pStmt) - 2;
4269 sqlite3_finalize(pStmt);
4270 }else
4271 if( check.rc!=SQLITE_NOMEM ){
4272 check.rc = SQLITE_OK;
4273 }
4274
4275 /* Find number of dimensions in the rtree table. */
4276 pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
4277 if( pStmt ){
4278 int rc;
4279 check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
4280 if( check.nDim<1 ){
4281 rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
4282 }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
4283 check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
4284 }
4285 rc = sqlite3_finalize(pStmt);
4286 if( rc!=SQLITE_CORRUPT ) check.rc = rc;
4287 }
4288
4289 /* Do the actual integrity-check */
4290 if( check.nDim>=1 ){
4291 if( check.rc==SQLITE_OK ){
4292 rtreeCheckNode(&check, 0, 0, 1);
4293 }
4294 rtreeCheckCount(&check, "_rowid", check.nLeaf);
4295 rtreeCheckCount(&check, "_parent", check.nNonLeaf);
4296 }
4297
4298 /* Finalize SQL statements used by the integrity-check */
4299 sqlite3_finalize(check.pGetNode);
4300 sqlite3_finalize(check.aCheckMapping[0]);
4301 sqlite3_finalize(check.aCheckMapping[1]);
4302
4303 *pzReport = check.zReport;
4304 return check.rc;
4305}
4306
4307/*
4308** Implementation of the xIntegrity method for Rtree.
4309*/
4310static int rtreeIntegrity(
4311 sqlite3_vtab *pVtab, /* The virtual table to check */
4312 const char *zSchema, /* Schema in which the virtual table lives */
4313 const char *zName, /* Name of the virtual table */
4314 int isQuick, /* True for a quick_check */
4315 char **pzErr /* Write results here */
4316){
4317 Rtree *pRtree = (Rtree*)pVtab;
4318 int rc;
4319 assert( pzErr!=0 && *pzErr==0 );
4320 UNUSED_PARAMETER(zSchema);
4321 UNUSED_PARAMETER(zName);
4322 UNUSED_PARAMETER(isQuick);
4323 rc = rtreeCheckTable(pRtree->db, pRtree->zDb, pRtree->zName, pzErr);
4324 if( rc==SQLITE_OK && *pzErr ){
4325 *pzErr = sqlite3_mprintf("In RTree %s.%s:\n%z",
4326 pRtree->zDb, pRtree->zName, *pzErr);
4327 if( (*pzErr)==0 ) rc = SQLITE_NOMEM;
4328 }
4329 return rc;
4330}
4331
4332/*
4333** Usage:
4334**
4335** rtreecheck(<rtree-table>);
4336** rtreecheck(<database>, <rtree-table>);
4337**
4338** Invoking this SQL function runs an integrity-check on the named rtree
4339** table. The integrity-check verifies the following:
4340**
4341** 1. For each cell in the r-tree structure (%_node table), that:
4342**
4343** a) for each dimension, (coord1 <= coord2).
4344**
4345** b) unless the cell is on the root node, that the cell is bounded
4346** by the parent cell on the parent node.
4347**
4348** c) for leaf nodes, that there is an entry in the %_rowid
4349** table corresponding to the cell's rowid value that
4350** points to the correct node.
4351**
4352** d) for cells on non-leaf nodes, that there is an entry in the
4353** %_parent table mapping from the cell's child node to the
4354** node that it resides on.
4355**
4356** 2. That there are the same number of entries in the %_rowid table
4357** as there are leaf cells in the r-tree structure, and that there
4358** is a leaf cell that corresponds to each entry in the %_rowid table.
4359**
4360** 3. That there are the same number of entries in the %_parent table
4361** as there are non-leaf cells in the r-tree structure, and that
4362** there is a non-leaf cell that corresponds to each entry in the
4363** %_parent table.
4364*/
4365static void rtreecheck(
4366 sqlite3_context *ctx,
4367 int nArg,
4368 sqlite3_value **apArg
4369){
4370 if( nArg!=1 && nArg!=2 ){
4371 sqlite3_result_error(ctx,
4372 "wrong number of arguments to function rtreecheck()", -1
4373 );
4374 }else{
4375 int rc;
4376 char *zReport = 0;
4377 const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
4378 const char *zTab;
4379 if( nArg==1 ){
4380 zTab = zDb;
4381 zDb = "main";
4382 }else{
4383 zTab = (const char*)sqlite3_value_text(apArg[1]);
4384 }
4385 rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
4386 if( rc==SQLITE_OK ){
4387 sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
4388 }else{
4389 sqlite3_result_error_code(ctx, rc);
4390 }
4391 sqlite3_free(zReport);
4392 }
4393}
4394
4395/* Conditionally include the geopoly code */
4396#ifdef SQLITE_ENABLE_GEOPOLY
4397# include "geopoly.c"
4398#endif
4399
4400/*
4401** Register the r-tree module with database handle db. This creates the
4402** virtual table module "rtree" and the debugging/analysis scalar
4403** function "rtreenode".
4404*/
4405int sqlite3RtreeInit(sqlite3 *db){
4406 const int utf8 = SQLITE_UTF8;
4407 int rc;
4408
4409 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
4410 if( rc==SQLITE_OK ){
4411 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
4412 }
4413 if( rc==SQLITE_OK ){
4414 rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
4415 }
4416#if defined(SQLITE_DEBUG) && !defined(SQLITE_RTREE_INT_ONLY)
4417 if( rc==SQLITE_OK ){
4418 rc = sqlite3_create_function(db, "rtree_round", 2, utf8, 0,
4419 rtreeRoundFunc, 0, 0);
4420 }
4421#endif /* SQLITE_DEBUG && !SQLITE_RTREE_INT_ONLY */
4422 if( rc==SQLITE_OK ){
4423#ifdef SQLITE_RTREE_INT_ONLY
4424 void *c = (void *)RTREE_COORD_INT32;
4425#else
4426 void *c = (void *)RTREE_COORD_REAL32;
4427#endif
4428 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
4429 }
4430 if( rc==SQLITE_OK ){
4431 void *c = (void *)RTREE_COORD_INT32;
4432 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
4433 }
4434#ifdef SQLITE_ENABLE_GEOPOLY
4435 if( rc==SQLITE_OK ){
4436 rc = sqlite3_geopoly_init(db);
4437 }
4438#endif
4439
4440 return rc;
4441}
4442
4443/*
4444** This routine deletes the RtreeGeomCallback object that was attached
4445** one of the SQL functions create by sqlite3_rtree_geometry_callback()
4446** or sqlite3_rtree_query_callback(). In other words, this routine is the
4447** destructor for an RtreeGeomCallback objecct. This routine is called when
4448** the corresponding SQL function is deleted.
4449*/
4450static void rtreeFreeCallback(void *p){
4451 RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
4452 if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
4453 sqlite3_free(p);
4454}
4455
4456/*
4457** This routine frees the BLOB that is returned by geomCallback().
4458*/
4459static void rtreeMatchArgFree(void *pArg){
4460 int i;
4461 RtreeMatchArg *p = (RtreeMatchArg*)pArg;
4462 for(i=0; i<p->nParam; i++){
4463 sqlite3_value_free(p->apSqlParam[i]);
4464 }
4465 sqlite3_free(p);
4466}
4467
4468/*
4469** Each call to sqlite3_rtree_geometry_callback() or
4470** sqlite3_rtree_query_callback() creates an ordinary SQLite
4471** scalar function that is implemented by this routine.
4472**
4473** All this function does is construct an RtreeMatchArg object that
4474** contains the geometry-checking callback routines and a list of
4475** parameters to this function, then return that RtreeMatchArg object
4476** as a BLOB.
4477**
4478** The R-Tree MATCH operator will read the returned BLOB, deserialize
4479** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
4480** out which elements of the R-Tree should be returned by the query.
4481*/
4482static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
4483 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
4484 RtreeMatchArg *pBlob;
4485 sqlite3_int64 nBlob;
4486 int memErr = 0;
4487
4488 nBlob = SZ_RTREEMATCHARG(nArg) + nArg*sizeof(sqlite3_value*);
4489 pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
4490 if( !pBlob ){
4491 sqlite3_result_error_nomem(ctx);
4492 }else{
4493 int i;
4494 pBlob->iSize = nBlob;
4495 pBlob->cb = pGeomCtx[0];
4496 pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
4497 pBlob->nParam = nArg;
4498 for(i=0; i<nArg; i++){
4499 pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
4500 if( pBlob->apSqlParam[i]==0 ) memErr = 1;
4501#ifdef SQLITE_RTREE_INT_ONLY
4502 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
4503#else
4504 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
4505#endif
4506 }
4507 if( memErr ){
4508 sqlite3_result_error_nomem(ctx);
4509 rtreeMatchArgFree(pBlob);
4510 }else{
4511 sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
4512 }
4513 }
4514}
4515
4516/*
4517** Register a new geometry function for use with the r-tree MATCH operator.
4518*/
4519int sqlite3_rtree_geometry_callback(
4520 sqlite3 *db, /* Register SQL function on this connection */
4521 const char *zGeom, /* Name of the new SQL function */
4522 int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
4523 void *pContext /* Extra data associated with the callback */
4524){
4525 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
4526
4527 /* Allocate and populate the context object. */
4528 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4529 if( !pGeomCtx ) return SQLITE_NOMEM;
4530 pGeomCtx->xGeom = xGeom;
4531 pGeomCtx->xQueryFunc = 0;
4532 pGeomCtx->xDestructor = 0;
4533 pGeomCtx->pContext = pContext;
4534 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
4535 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4536 );
4537}
4538
4539/*
4540** Register a new 2nd-generation geometry function for use with the
4541** r-tree MATCH operator.
4542*/
4543int sqlite3_rtree_query_callback(
4544 sqlite3 *db, /* Register SQL function on this connection */
4545 const char *zQueryFunc, /* Name of new SQL function */
4546 int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
4547 void *pContext, /* Extra data passed into the callback */
4548 void (*xDestructor)(void*) /* Destructor for the extra data */
4549){
4550 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
4551
4552 /* Allocate and populate the context object. */
4553 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
4554 if( !pGeomCtx ){
4555 if( xDestructor ) xDestructor(pContext);
4556 return SQLITE_NOMEM;
4557 }
4558 pGeomCtx->xGeom = 0;
4559 pGeomCtx->xQueryFunc = xQueryFunc;
4560 pGeomCtx->xDestructor = xDestructor;
4561 pGeomCtx->pContext = pContext;
4562 return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
4563 (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
4564 );
4565}
4566
4567#ifndef SQLITE_CORE
4568#ifdef _WIN32
4569__declspec(dllexport)
4570#endif
4571int sqlite3_rtree_init(
4572 sqlite3 *db,
4573 char **pzErrMsg,
4574 const sqlite3_api_routines *pApi
4575){
4576 SQLITE_EXTENSION_INIT2(pApi)
4577 return sqlite3RtreeInit(db);
4578}
4579#endif
4580
4581#endif