1ebaecc14Sdanielk1977 /*
2ebaecc14Sdanielk1977 ** 2001 September 15
3ebaecc14Sdanielk1977 **
4ebaecc14Sdanielk1977 ** The author disclaims copyright to this source code. In place of
5ebaecc14Sdanielk1977 ** a legal notice, here is a blessing:
6ebaecc14Sdanielk1977 **
7ebaecc14Sdanielk1977 ** May you do good and not evil.
8ebaecc14Sdanielk1977 ** May you find forgiveness for yourself and forgive others.
9ebaecc14Sdanielk1977 ** May you share freely, never taking more than you give.
10ebaecc14Sdanielk1977 **
11ebaecc14Sdanielk1977 *************************************************************************
12ebaecc14Sdanielk1977 ** This file contains code for implementations of the r-tree and r*-tree
13ebaecc14Sdanielk1977 ** algorithms packaged as an SQLite virtual table module.
14ebaecc14Sdanielk1977 */
15ebaecc14Sdanielk1977
16bd188afdSdan /*
17bd188afdSdan ** Database Format of R-Tree Tables
18bd188afdSdan ** --------------------------------
19bd188afdSdan **
20bd188afdSdan ** The data structure for a single virtual r-tree table is stored in three
21bd188afdSdan ** native SQLite tables declared as follows. In each case, the '%' character
22bd188afdSdan ** in the table name is replaced with the user-supplied name of the r-tree
23bd188afdSdan ** table.
24bd188afdSdan **
25bd188afdSdan ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
26bd188afdSdan ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
277578456cSdrh ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
28bd188afdSdan **
29bd188afdSdan ** The data for each node of the r-tree structure is stored in the %_node
30bd188afdSdan ** table. For each node that is not the root node of the r-tree, there is
31bd188afdSdan ** an entry in the %_parent table associating the node with its parent.
32bd188afdSdan ** And for each row of data in the table, there is an entry in the %_rowid
33bd188afdSdan ** table that maps from the entries rowid to the id of the node that it
347578456cSdrh ** is stored on. If the r-tree contains auxiliary columns, those are stored
357578456cSdrh ** on the end of the %_rowid table.
36bd188afdSdan **
37bd188afdSdan ** The root node of an r-tree always exists, even if the r-tree table is
38bd188afdSdan ** empty. The nodeno of the root node is always 1. All other nodes in the
39bd188afdSdan ** table must be the same size as the root node. The content of each node
40bd188afdSdan ** is formatted as follows:
41bd188afdSdan **
42bd188afdSdan ** 1. If the node is the root node (node 1), then the first 2 bytes
43bd188afdSdan ** of the node contain the tree depth as a big-endian integer.
44bd188afdSdan ** For non-root nodes, the first 2 bytes are left unused.
45bd188afdSdan **
46bd188afdSdan ** 2. The next 2 bytes contain the number of entries currently
47bd188afdSdan ** stored in the node.
48bd188afdSdan **
49bd188afdSdan ** 3. The remainder of the node contains the node entries. Each entry
50bd188afdSdan ** consists of a single 8-byte integer followed by an even number
51bd188afdSdan ** of 4-byte coordinates. For leaf nodes the integer is the rowid
52bd188afdSdan ** of a record. For internal nodes it is the node number of a
53bd188afdSdan ** child page.
54bd188afdSdan */
55bd188afdSdan
562f949354Sdan #if !defined(SQLITE_CORE) \
572f949354Sdan || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
58ebaecc14Sdanielk1977
59ebaecc14Sdanielk1977 #ifndef SQLITE_CORE
60ebaecc14Sdanielk1977 #include "sqlite3ext.h"
61ebaecc14Sdanielk1977 SQLITE_EXTENSION_INIT1
62ebaecc14Sdanielk1977 #else
63ebaecc14Sdanielk1977 #include "sqlite3.h"
64ebaecc14Sdanielk1977 #endif
650a64ddbeSdrh int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
66ebaecc14Sdanielk1977
6704bd2c83Sdrh /*
6804bd2c83Sdrh ** If building separately, we will need some setup that is normally
6904bd2c83Sdrh ** found in sqliteInt.h
7004bd2c83Sdrh */
7104bd2c83Sdrh #if !defined(SQLITE_AMALGAMATION)
72d9e430e9Sdan #include "sqlite3rtree.h"
73ebaecc14Sdanielk1977 typedef sqlite3_int64 i64;
749fcb6ddcSdan typedef sqlite3_uint64 u64;
75ebaecc14Sdanielk1977 typedef unsigned char u8;
7665e6b0ddSdrh typedef unsigned short u16;
77ebaecc14Sdanielk1977 typedef unsigned int u32;
78f446a7a8Sdan #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
79f446a7a8Sdan # define NDEBUG 1
807cb53b0fSdrh #endif
81f446a7a8Sdan #if defined(NDEBUG) && defined(SQLITE_DEBUG)
82f446a7a8Sdan # undef NDEBUG
83f446a7a8Sdan #endif
8404bd2c83Sdrh #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
8511a9ad56Sdrh # define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
8611a9ad56Sdrh #endif
8711a9ad56Sdrh #if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
8804bd2c83Sdrh # define ALWAYS(X) (1)
8904bd2c83Sdrh # define NEVER(X) (0)
9004bd2c83Sdrh #elif !defined(NDEBUG)
9104bd2c83Sdrh # define ALWAYS(X) ((X)?1:(assert(0),0))
9204bd2c83Sdrh # define NEVER(X) ((X)?(assert(0),1):0)
9304bd2c83Sdrh #else
9404bd2c83Sdrh # define ALWAYS(X) (X)
9504bd2c83Sdrh # define NEVER(X) (X)
96f446a7a8Sdan #endif
9704bd2c83Sdrh #endif /* !defined(SQLITE_AMALGAMATION) */
98f446a7a8Sdan
99f446a7a8Sdan #include <string.h>
100f446a7a8Sdan #include <stdio.h>
101f446a7a8Sdan #include <assert.h>
102cec5f1d1Smistachkin #include <stdlib.h>
103ebaecc14Sdanielk1977
1046ea28d6dSdrh /* The following macro is used to suppress compiler warnings.
1056ea28d6dSdrh */
1066ea28d6dSdrh #ifndef UNUSED_PARAMETER
1076ea28d6dSdrh # define UNUSED_PARAMETER(x) (void)(x)
1086ea28d6dSdrh #endif
1096ea28d6dSdrh
110ebaecc14Sdanielk1977 typedef struct Rtree Rtree;
111ebaecc14Sdanielk1977 typedef struct RtreeCursor RtreeCursor;
112ebaecc14Sdanielk1977 typedef struct RtreeNode RtreeNode;
113ebaecc14Sdanielk1977 typedef struct RtreeCell RtreeCell;
114ebaecc14Sdanielk1977 typedef struct RtreeConstraint RtreeConstraint;
1159977edc7Sdan typedef struct RtreeMatchArg RtreeMatchArg;
1169977edc7Sdan typedef struct RtreeGeomCallback RtreeGeomCallback;
1173ddb5a51Sdanielk1977 typedef union RtreeCoord RtreeCoord;
11865e6b0ddSdrh typedef struct RtreeSearchPoint RtreeSearchPoint;
119ebaecc14Sdanielk1977
120ebaecc14Sdanielk1977 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
121ebaecc14Sdanielk1977 #define RTREE_MAX_DIMENSIONS 5
122ebaecc14Sdanielk1977
123252f3961Sdrh /* Maximum number of auxiliary columns */
124252f3961Sdrh #define RTREE_MAX_AUX_COLUMN 100
125252f3961Sdrh
126ebaecc14Sdanielk1977 /* Size of hash table Rtree.aHash. This hash table is not expected to
127ebaecc14Sdanielk1977 ** ever contain very many entries, so a fixed number of buckets is
128ebaecc14Sdanielk1977 ** used.
129ebaecc14Sdanielk1977 */
13065e6b0ddSdrh #define HASHSIZE 97
131ebaecc14Sdanielk1977
132a9f5815bSdan /* The xBestIndex method of this virtual table requires an estimate of
133a9f5815bSdan ** the number of rows in the virtual table to calculate the costs of
134a9f5815bSdan ** various strategies. If possible, this estimate is loaded from the
135a9f5815bSdan ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
136a9f5815bSdan ** Otherwise, if no sqlite_stat1 entry is available, use
137a9f5815bSdan ** RTREE_DEFAULT_ROWEST.
138a9f5815bSdan */
139a9f5815bSdan #define RTREE_DEFAULT_ROWEST 1048576
140a9f5815bSdan #define RTREE_MIN_ROWEST 100
141a9f5815bSdan
142ebaecc14Sdanielk1977 /*
143ebaecc14Sdanielk1977 ** An rtree virtual-table object.
144ebaecc14Sdanielk1977 */
145ebaecc14Sdanielk1977 struct Rtree {
14665e6b0ddSdrh sqlite3_vtab base; /* Base class. Must be first */
147ebaecc14Sdanielk1977 sqlite3 *db; /* Host database connection */
148ebaecc14Sdanielk1977 int iNodeSize; /* Size in bytes of each node in the node table */
14965e6b0ddSdrh u8 nDim; /* Number of dimensions */
1500e6f67b7Sdrh u8 nDim2; /* Twice the number of dimensions */
15165e6b0ddSdrh u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
15265e6b0ddSdrh u8 nBytesPerCell; /* Bytes consumed per cell */
1532033d1c8Sdrh u8 inWrTrans; /* True if inside write transaction */
154e2971965Sdrh u8 nAux; /* # of auxiliary columns in %_rowid */
1558e4616c2Sdrh #ifdef SQLITE_ENABLE_GEOPOLY
15617f19eadSdrh u8 nAuxNotNull; /* Number of initial not-null aux columns */
1578e4616c2Sdrh #endif
158fb077f3cSdrh #ifdef SQLITE_DEBUG
159fb077f3cSdrh u8 bCorrupt; /* Shadow table corruption detected */
160fb077f3cSdrh #endif
161ebaecc14Sdanielk1977 int iDepth; /* Current depth of the r-tree structure */
162ebaecc14Sdanielk1977 char *zDb; /* Name of database containing r-tree table */
163ebaecc14Sdanielk1977 char *zName; /* Name of r-tree table */
1642033d1c8Sdrh u32 nBusy; /* Current number of users of this structure */
165a9f5815bSdan i64 nRowEst; /* Estimated number of rows in this table */
1662033d1c8Sdrh u32 nCursor; /* Number of open cursors */
167c8c9cdd9Sdrh u32 nNodeRef; /* Number RtreeNodes with positive nRef */
168e2971965Sdrh char *zReadAuxSql; /* SQL for statement to read aux data */
169ebaecc14Sdanielk1977
170ebaecc14Sdanielk1977 /* List of nodes removed during a CondenseTree operation. List is
171ebaecc14Sdanielk1977 ** linked together via the pointer normally used for hash chains -
172ebaecc14Sdanielk1977 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
173ebaecc14Sdanielk1977 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
174ebaecc14Sdanielk1977 */
175ebaecc14Sdanielk1977 RtreeNode *pDeleted;
176ebaecc14Sdanielk1977 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
177ebaecc14Sdanielk1977
1786d683c5cSdrh /* Blob I/O on xxx_node */
1796d683c5cSdrh sqlite3_blob *pNodeBlob;
1806d683c5cSdrh
181ebaecc14Sdanielk1977 /* Statements to read/write/delete a record from xxx_node */
182ebaecc14Sdanielk1977 sqlite3_stmt *pWriteNode;
183ebaecc14Sdanielk1977 sqlite3_stmt *pDeleteNode;
184ebaecc14Sdanielk1977
185ebaecc14Sdanielk1977 /* Statements to read/write/delete a record from xxx_rowid */
186ebaecc14Sdanielk1977 sqlite3_stmt *pReadRowid;
187ebaecc14Sdanielk1977 sqlite3_stmt *pWriteRowid;
188ebaecc14Sdanielk1977 sqlite3_stmt *pDeleteRowid;
189ebaecc14Sdanielk1977
190ebaecc14Sdanielk1977 /* Statements to read/write/delete a record from xxx_parent */
191ebaecc14Sdanielk1977 sqlite3_stmt *pReadParent;
192ebaecc14Sdanielk1977 sqlite3_stmt *pWriteParent;
193ebaecc14Sdanielk1977 sqlite3_stmt *pDeleteParent;
1943ddb5a51Sdanielk1977
195e2971965Sdrh /* Statement for writing to the "aux:" fields, if there are any */
196e2971965Sdrh sqlite3_stmt *pWriteAux;
197e2971965Sdrh
19865e6b0ddSdrh RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
199ebaecc14Sdanielk1977 };
200ebaecc14Sdanielk1977
20165e6b0ddSdrh /* Possible values for Rtree.eCoordType: */
2023ddb5a51Sdanielk1977 #define RTREE_COORD_REAL32 0
2033ddb5a51Sdanielk1977 #define RTREE_COORD_INT32 1
2043ddb5a51Sdanielk1977
205ebaecc14Sdanielk1977 /*
206f439fbdaSdrh ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
207f439fbdaSdrh ** only deal with integer coordinates. No floating point operations
208f439fbdaSdrh ** will be done.
209f439fbdaSdrh */
210f439fbdaSdrh #ifdef SQLITE_RTREE_INT_ONLY
211f439fbdaSdrh typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
212f439fbdaSdrh typedef int RtreeValue; /* Low accuracy coordinate */
21365e6b0ddSdrh # define RTREE_ZERO 0
214f439fbdaSdrh #else
215f439fbdaSdrh typedef double RtreeDValue; /* High accuracy coordinate */
216f439fbdaSdrh typedef float RtreeValue; /* Low accuracy coordinate */
21765e6b0ddSdrh # define RTREE_ZERO 0.0
218f439fbdaSdrh #endif
219f439fbdaSdrh
220f439fbdaSdrh /*
221fb077f3cSdrh ** Set the Rtree.bCorrupt flag
222fb077f3cSdrh */
223fb077f3cSdrh #ifdef SQLITE_DEBUG
224fb077f3cSdrh # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
225fb077f3cSdrh #else
226fb077f3cSdrh # define RTREE_IS_CORRUPT(X)
227fb077f3cSdrh #endif
228fb077f3cSdrh
229fb077f3cSdrh /*
23065e6b0ddSdrh ** When doing a search of an r-tree, instances of the following structure
23165e6b0ddSdrh ** record intermediate results from the tree walk.
23265e6b0ddSdrh **
23365e6b0ddSdrh ** The id is always a node-id. For iLevel>=1 the id is the node-id of
23465e6b0ddSdrh ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
23565e6b0ddSdrh ** the id is of the parent node and the cell that RtreeSearchPoint
23665e6b0ddSdrh ** represents is the iCell-th entry in the parent node.
23765e6b0ddSdrh */
23865e6b0ddSdrh struct RtreeSearchPoint {
23965e6b0ddSdrh RtreeDValue rScore; /* The score for this node. Smallest goes first. */
24065e6b0ddSdrh sqlite3_int64 id; /* Node ID */
24165e6b0ddSdrh u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
24265e6b0ddSdrh u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
24365e6b0ddSdrh u8 iCell; /* Cell index within the node */
24465e6b0ddSdrh };
24565e6b0ddSdrh
24665e6b0ddSdrh /*
247ebaecc14Sdanielk1977 ** The minimum number of cells allowed for a node is a third of the
248ebaecc14Sdanielk1977 ** maximum. In Gutman's notation:
249ebaecc14Sdanielk1977 **
250ebaecc14Sdanielk1977 ** m = M/3
251ebaecc14Sdanielk1977 **
252ebaecc14Sdanielk1977 ** If an R*-tree "Reinsert" operation is required, the same number of
253ebaecc14Sdanielk1977 ** cells are removed from the overfull node and reinserted into the tree.
254ebaecc14Sdanielk1977 */
255ebaecc14Sdanielk1977 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
256ebaecc14Sdanielk1977 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
257ebaecc14Sdanielk1977 #define RTREE_MAXCELLS 51
258ebaecc14Sdanielk1977
259ebaecc14Sdanielk1977 /*
260bd188afdSdan ** The smallest possible node-size is (512-64)==448 bytes. And the largest
261bd188afdSdan ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
262bd188afdSdan ** Therefore all non-root nodes must contain at least 3 entries. Since
2631917e92fSdan ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
264bd188afdSdan ** 40 or less.
265bd188afdSdan */
266bd188afdSdan #define RTREE_MAX_DEPTH 40
267bd188afdSdan
26865e6b0ddSdrh
26965e6b0ddSdrh /*
27065e6b0ddSdrh ** Number of entries in the cursor RtreeNode cache. The first entry is
27165e6b0ddSdrh ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
27265e6b0ddSdrh ** entries cache the RtreeNode for the first elements of the priority queue.
27365e6b0ddSdrh */
27465e6b0ddSdrh #define RTREE_CACHE_SZ 5
27565e6b0ddSdrh
276bd188afdSdan /*
277ebaecc14Sdanielk1977 ** An rtree cursor object.
278ebaecc14Sdanielk1977 */
279ebaecc14Sdanielk1977 struct RtreeCursor {
28065e6b0ddSdrh sqlite3_vtab_cursor base; /* Base class. Must be first */
28165e6b0ddSdrh u8 atEOF; /* True if at end of search */
28265e6b0ddSdrh u8 bPoint; /* True if sPoint is valid */
283e2971965Sdrh u8 bAuxValid; /* True if pReadAux is valid */
284ebaecc14Sdanielk1977 int iStrategy; /* Copy of idxNum search parameter */
285ebaecc14Sdanielk1977 int nConstraint; /* Number of entries in aConstraint */
286ebaecc14Sdanielk1977 RtreeConstraint *aConstraint; /* Search constraints. */
28765e6b0ddSdrh int nPointAlloc; /* Number of slots allocated for aPoint[] */
28865e6b0ddSdrh int nPoint; /* Number of slots used in aPoint[] */
28965e6b0ddSdrh int mxLevel; /* iLevel value for root of the tree */
29065e6b0ddSdrh RtreeSearchPoint *aPoint; /* Priority queue for search points */
291e2971965Sdrh sqlite3_stmt *pReadAux; /* Statement to read aux-data */
29265e6b0ddSdrh RtreeSearchPoint sPoint; /* Cached next search point */
29365e6b0ddSdrh RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
29465e6b0ddSdrh u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
295ebaecc14Sdanielk1977 };
296ebaecc14Sdanielk1977
29765e6b0ddSdrh /* Return the Rtree of a RtreeCursor */
29865e6b0ddSdrh #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
29965e6b0ddSdrh
30065e6b0ddSdrh /*
30165e6b0ddSdrh ** A coordinate can be either a floating point number or a integer. All
30265e6b0ddSdrh ** coordinates within a single R-Tree are always of the same time.
30365e6b0ddSdrh */
3043ddb5a51Sdanielk1977 union RtreeCoord {
30565e6b0ddSdrh RtreeValue f; /* Floating point value */
30665e6b0ddSdrh int i; /* Integer value */
30765e6b0ddSdrh u32 u; /* Unsigned for byte-order conversions */
3083ddb5a51Sdanielk1977 };
3093ddb5a51Sdanielk1977
3103ddb5a51Sdanielk1977 /*
3113ddb5a51Sdanielk1977 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
312f439fbdaSdrh ** formatted as a RtreeDValue (double or int64). This macro assumes that local
313f439fbdaSdrh ** variable pRtree points to the Rtree structure associated with the
314f439fbdaSdrh ** RtreeCoord.
3153ddb5a51Sdanielk1977 */
316f439fbdaSdrh #ifdef SQLITE_RTREE_INT_ONLY
317f439fbdaSdrh # define DCOORD(coord) ((RtreeDValue)coord.i)
318f439fbdaSdrh #else
3193ddb5a51Sdanielk1977 # define DCOORD(coord) ( \
3203ddb5a51Sdanielk1977 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
3213ddb5a51Sdanielk1977 ((double)coord.f) : \
3223ddb5a51Sdanielk1977 ((double)coord.i) \
3233ddb5a51Sdanielk1977 )
324f439fbdaSdrh #endif
3253ddb5a51Sdanielk1977
326ebaecc14Sdanielk1977 /*
327ebaecc14Sdanielk1977 ** A search constraint.
328ebaecc14Sdanielk1977 */
329ebaecc14Sdanielk1977 struct RtreeConstraint {
330ebaecc14Sdanielk1977 int iCoord; /* Index of constrained coordinate */
331ebaecc14Sdanielk1977 int op; /* Constraining operation */
33265e6b0ddSdrh union {
333f439fbdaSdrh RtreeDValue rValue; /* Constraint value. */
334f439fbdaSdrh int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
33565e6b0ddSdrh int (*xQueryFunc)(sqlite3_rtree_query_info*);
33665e6b0ddSdrh } u;
33765e6b0ddSdrh sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
338ebaecc14Sdanielk1977 };
339ebaecc14Sdanielk1977
340ebaecc14Sdanielk1977 /* Possible values for RtreeConstraint.op */
34165e6b0ddSdrh #define RTREE_EQ 0x41 /* A */
34265e6b0ddSdrh #define RTREE_LE 0x42 /* B */
34365e6b0ddSdrh #define RTREE_LT 0x43 /* C */
34465e6b0ddSdrh #define RTREE_GE 0x44 /* D */
34565e6b0ddSdrh #define RTREE_GT 0x45 /* E */
34665e6b0ddSdrh #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
34765e6b0ddSdrh #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
34865e6b0ddSdrh
349674a9b34Sdrh /* Special operators available only on cursors. Needs to be consecutive
350674a9b34Sdrh ** with the normal values above, but must be less than RTREE_MATCH. These
351674a9b34Sdrh ** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
352674a9b34Sdrh ** x<'xyz' (RTREE_TRUE) */
353674a9b34Sdrh #define RTREE_TRUE 0x3f /* ? */
354674a9b34Sdrh #define RTREE_FALSE 0x40 /* @ */
355ebaecc14Sdanielk1977
356ebaecc14Sdanielk1977 /*
357ebaecc14Sdanielk1977 ** An rtree structure node.
358ebaecc14Sdanielk1977 */
359ebaecc14Sdanielk1977 struct RtreeNode {
360ebaecc14Sdanielk1977 RtreeNode *pParent; /* Parent node */
36165e6b0ddSdrh i64 iNode; /* The node number */
36265e6b0ddSdrh int nRef; /* Number of references to this node */
36365e6b0ddSdrh int isDirty; /* True if the node needs to be written to disk */
36465e6b0ddSdrh u8 *zData; /* Content of the node, as should be on disk */
36565e6b0ddSdrh RtreeNode *pNext; /* Next node in this hash collision chain */
366ebaecc14Sdanielk1977 };
36765e6b0ddSdrh
36865e6b0ddSdrh /* Return the number of cells in a node */
369ebaecc14Sdanielk1977 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
370ebaecc14Sdanielk1977
371ebaecc14Sdanielk1977 /*
37265e6b0ddSdrh ** A single cell from a node, deserialized
373ebaecc14Sdanielk1977 */
374ebaecc14Sdanielk1977 struct RtreeCell {
37565e6b0ddSdrh i64 iRowid; /* Node or entry ID */
37665e6b0ddSdrh RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
37765e6b0ddSdrh };
37865e6b0ddSdrh
37965e6b0ddSdrh
38065e6b0ddSdrh /*
38165e6b0ddSdrh ** This object becomes the sqlite3_user_data() for the SQL functions
38265e6b0ddSdrh ** that are created by sqlite3_rtree_geometry_callback() and
38365e6b0ddSdrh ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
38465e6b0ddSdrh ** operators in order to constrain a search.
38565e6b0ddSdrh **
38665e6b0ddSdrh ** xGeom and xQueryFunc are the callback functions. Exactly one of
38765e6b0ddSdrh ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
38865e6b0ddSdrh ** SQL function was created using sqlite3_rtree_geometry_callback() or
38965e6b0ddSdrh ** sqlite3_rtree_query_callback().
39065e6b0ddSdrh **
39165e6b0ddSdrh ** This object is deleted automatically by the destructor mechanism in
39265e6b0ddSdrh ** sqlite3_create_function_v2().
39365e6b0ddSdrh */
39465e6b0ddSdrh struct RtreeGeomCallback {
39565e6b0ddSdrh int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
39665e6b0ddSdrh int (*xQueryFunc)(sqlite3_rtree_query_info*);
39765e6b0ddSdrh void (*xDestructor)(void*);
39865e6b0ddSdrh void *pContext;
399ebaecc14Sdanielk1977 };
400ebaecc14Sdanielk1977
4019508daa9Sdan /*
40265e6b0ddSdrh ** An instance of this structure (in the form of a BLOB) is returned by
40365e6b0ddSdrh ** the SQL functions that sqlite3_rtree_geometry_callback() and
40465e6b0ddSdrh ** sqlite3_rtree_query_callback() create, and is read as the right-hand
40565e6b0ddSdrh ** operand to the MATCH operator of an R-Tree.
4069508daa9Sdan */
4079977edc7Sdan struct RtreeMatchArg {
40822930062Sdrh u32 iSize; /* Size of this object */
40965e6b0ddSdrh RtreeGeomCallback cb; /* Info about the callback functions */
41065e6b0ddSdrh int nParam; /* Number of parameters to the SQL function */
4114f03f413Sdrh sqlite3_value **apSqlParam; /* Original SQL parameter values */
41265e6b0ddSdrh RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
4139977edc7Sdan };
4149977edc7Sdan
4157ab49bfdSdrh #ifndef MAX
416ebaecc14Sdanielk1977 # define MAX(x,y) ((x) < (y) ? (y) : (x))
4177ab49bfdSdrh #endif
4187ab49bfdSdrh #ifndef MIN
419ebaecc14Sdanielk1977 # define MIN(x,y) ((x) > (y) ? (y) : (x))
4207ab49bfdSdrh #endif
421ebaecc14Sdanielk1977
422dc5ece86Sdrh /* What version of GCC is being used. 0 means GCC is not being used .
423dc5ece86Sdrh ** Note that the GCC_VERSION macro will also be set correctly when using
424dc5ece86Sdrh ** clang, since clang works hard to be gcc compatible. So the gcc
425dc5ece86Sdrh ** optimizations will also work when compiling with clang.
426dc5ece86Sdrh */
42703626e38Sdrh #ifndef GCC_VERSION
428a39284bfSdrh #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
42903626e38Sdrh # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
43003626e38Sdrh #else
43103626e38Sdrh # define GCC_VERSION 0
43203626e38Sdrh #endif
43303626e38Sdrh #endif
43403626e38Sdrh
43503626e38Sdrh /* The testcase() macro should already be defined in the amalgamation. If
43603626e38Sdrh ** it is not, make it a no-op.
43703626e38Sdrh */
438fe05491bSdrh #ifndef SQLITE_AMALGAMATION
4399fdd66e3Sdrh # if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_DEBUG)
4408a0c4276Sdrh unsigned int sqlite3RtreeTestcase = 0;
4418a0c4276Sdrh # define testcase(X) if( X ){ sqlite3RtreeTestcase += __LINE__; }
4428a0c4276Sdrh # else
44303626e38Sdrh # define testcase(X)
44403626e38Sdrh # endif
4458a0c4276Sdrh #endif
44603626e38Sdrh
44703626e38Sdrh /*
448cec5f1d1Smistachkin ** Make sure that the compiler intrinsics we desire are enabled when
449cec5f1d1Smistachkin ** compiling with an appropriate version of MSVC unless prevented by
450cec5f1d1Smistachkin ** the SQLITE_DISABLE_INTRINSIC define.
451cec5f1d1Smistachkin */
452cec5f1d1Smistachkin #if !defined(SQLITE_DISABLE_INTRINSIC)
453cec5f1d1Smistachkin # if defined(_MSC_VER) && _MSC_VER>=1400
454cec5f1d1Smistachkin # if !defined(_WIN32_WCE)
455cec5f1d1Smistachkin # include <intrin.h>
456cec5f1d1Smistachkin # pragma intrinsic(_byteswap_ulong)
457cec5f1d1Smistachkin # pragma intrinsic(_byteswap_uint64)
458cec5f1d1Smistachkin # else
459cec5f1d1Smistachkin # include <cmnintrin.h>
460cec5f1d1Smistachkin # endif
461cec5f1d1Smistachkin # endif
462cec5f1d1Smistachkin #endif
463cec5f1d1Smistachkin
464cec5f1d1Smistachkin /*
46503626e38Sdrh ** Macros to determine whether the machine is big or little endian,
46603626e38Sdrh ** and whether or not that determination is run-time or compile-time.
46703626e38Sdrh **
46803626e38Sdrh ** For best performance, an attempt is made to guess at the byte-order
46903626e38Sdrh ** using C-preprocessor macros. If that is unsuccessful, or if
47003626e38Sdrh ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
47103626e38Sdrh ** at run-time.
47203626e38Sdrh */
47303626e38Sdrh #ifndef SQLITE_BYTEORDER
474a39284bfSdrh #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
47503626e38Sdrh defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
47603626e38Sdrh defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
477a39284bfSdrh defined(__arm__)
47803626e38Sdrh # define SQLITE_BYTEORDER 1234
479a39284bfSdrh #elif defined(sparc) || defined(__ppc__)
48003626e38Sdrh # define SQLITE_BYTEORDER 4321
481364ca6a9Sdrh #else
48203626e38Sdrh # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
48303626e38Sdrh #endif
484364ca6a9Sdrh #endif
48503626e38Sdrh
48603626e38Sdrh
48703626e38Sdrh /* What version of MSVC is being used. 0 means MSVC is not being used */
48803626e38Sdrh #ifndef MSVC_VERSION
489a39284bfSdrh #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
49003626e38Sdrh # define MSVC_VERSION _MSC_VER
49103626e38Sdrh #else
49203626e38Sdrh # define MSVC_VERSION 0
49303626e38Sdrh #endif
49403626e38Sdrh #endif
49503626e38Sdrh
496ebaecc14Sdanielk1977 /*
497ebaecc14Sdanielk1977 ** Functions to deserialize a 16 bit integer, 32 bit real number and
498ebaecc14Sdanielk1977 ** 64 bit integer. The deserialized value is returned.
499ebaecc14Sdanielk1977 */
readInt16(u8 * p)500ebaecc14Sdanielk1977 static int readInt16(u8 *p){
501ebaecc14Sdanielk1977 return (p[0]<<8) + p[1];
502ebaecc14Sdanielk1977 }
readCoord(u8 * p,RtreeCoord * pCoord)5033ddb5a51Sdanielk1977 static void readCoord(u8 *p, RtreeCoord *pCoord){
50403626e38Sdrh assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
50503626e38Sdrh #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
50603626e38Sdrh pCoord->u = _byteswap_ulong(*(u32*)p);
507dc5ece86Sdrh #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
50803626e38Sdrh pCoord->u = __builtin_bswap32(*(u32*)p);
50903626e38Sdrh #elif SQLITE_BYTEORDER==4321
51003626e38Sdrh pCoord->u = *(u32*)p;
51114494fa7Sdrh #else
512068a251dSdrh pCoord->u = (
513ebaecc14Sdanielk1977 (((u32)p[0]) << 24) +
514ebaecc14Sdanielk1977 (((u32)p[1]) << 16) +
515ebaecc14Sdanielk1977 (((u32)p[2]) << 8) +
516ebaecc14Sdanielk1977 (((u32)p[3]) << 0)
517ebaecc14Sdanielk1977 );
51814494fa7Sdrh #endif
519ebaecc14Sdanielk1977 }
readInt64(u8 * p)520ebaecc14Sdanielk1977 static i64 readInt64(u8 *p){
52103626e38Sdrh #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
52203626e38Sdrh u64 x;
52303626e38Sdrh memcpy(&x, p, 8);
52403626e38Sdrh return (i64)_byteswap_uint64(x);
525dc5ece86Sdrh #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
52603626e38Sdrh u64 x;
52703626e38Sdrh memcpy(&x, p, 8);
52803626e38Sdrh return (i64)__builtin_bswap64(x);
52903626e38Sdrh #elif SQLITE_BYTEORDER==4321
53003626e38Sdrh i64 x;
53103626e38Sdrh memcpy(&x, p, 8);
53203626e38Sdrh return x;
53303626e38Sdrh #else
5346b904f5eSdan return (i64)(
5356b904f5eSdan (((u64)p[0]) << 56) +
5366b904f5eSdan (((u64)p[1]) << 48) +
5376b904f5eSdan (((u64)p[2]) << 40) +
5386b904f5eSdan (((u64)p[3]) << 32) +
5396b904f5eSdan (((u64)p[4]) << 24) +
5406b904f5eSdan (((u64)p[5]) << 16) +
5416b904f5eSdan (((u64)p[6]) << 8) +
5426b904f5eSdan (((u64)p[7]) << 0)
543ebaecc14Sdanielk1977 );
54403626e38Sdrh #endif
545ebaecc14Sdanielk1977 }
546ebaecc14Sdanielk1977
547ebaecc14Sdanielk1977 /*
548ebaecc14Sdanielk1977 ** Functions to serialize a 16 bit integer, 32 bit real number and
549ebaecc14Sdanielk1977 ** 64 bit integer. The value returned is the number of bytes written
550ebaecc14Sdanielk1977 ** to the argument buffer (always 2, 4 and 8 respectively).
551ebaecc14Sdanielk1977 */
writeInt16(u8 * p,int i)552a39284bfSdrh static void writeInt16(u8 *p, int i){
553ebaecc14Sdanielk1977 p[0] = (i>> 8)&0xFF;
554ebaecc14Sdanielk1977 p[1] = (i>> 0)&0xFF;
555ebaecc14Sdanielk1977 }
writeCoord(u8 * p,RtreeCoord * pCoord)5563ddb5a51Sdanielk1977 static int writeCoord(u8 *p, RtreeCoord *pCoord){
557ebaecc14Sdanielk1977 u32 i;
55803626e38Sdrh assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
5593ddb5a51Sdanielk1977 assert( sizeof(RtreeCoord)==4 );
560ebaecc14Sdanielk1977 assert( sizeof(u32)==4 );
561dc5ece86Sdrh #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
56203626e38Sdrh i = __builtin_bswap32(pCoord->u);
56303626e38Sdrh memcpy(p, &i, 4);
56403626e38Sdrh #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
56503626e38Sdrh i = _byteswap_ulong(pCoord->u);
56603626e38Sdrh memcpy(p, &i, 4);
56703626e38Sdrh #elif SQLITE_BYTEORDER==4321
56803626e38Sdrh i = pCoord->u;
56903626e38Sdrh memcpy(p, &i, 4);
57003626e38Sdrh #else
571068a251dSdrh i = pCoord->u;
572ebaecc14Sdanielk1977 p[0] = (i>>24)&0xFF;
573ebaecc14Sdanielk1977 p[1] = (i>>16)&0xFF;
574ebaecc14Sdanielk1977 p[2] = (i>> 8)&0xFF;
575ebaecc14Sdanielk1977 p[3] = (i>> 0)&0xFF;
57603626e38Sdrh #endif
577ebaecc14Sdanielk1977 return 4;
578ebaecc14Sdanielk1977 }
writeInt64(u8 * p,i64 i)579ebaecc14Sdanielk1977 static int writeInt64(u8 *p, i64 i){
580dc5ece86Sdrh #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
58103626e38Sdrh i = (i64)__builtin_bswap64((u64)i);
58203626e38Sdrh memcpy(p, &i, 8);
58303626e38Sdrh #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
58403626e38Sdrh i = (i64)_byteswap_uint64((u64)i);
58503626e38Sdrh memcpy(p, &i, 8);
58603626e38Sdrh #elif SQLITE_BYTEORDER==4321
58703626e38Sdrh memcpy(p, &i, 8);
58803626e38Sdrh #else
589ebaecc14Sdanielk1977 p[0] = (i>>56)&0xFF;
590ebaecc14Sdanielk1977 p[1] = (i>>48)&0xFF;
591ebaecc14Sdanielk1977 p[2] = (i>>40)&0xFF;
592ebaecc14Sdanielk1977 p[3] = (i>>32)&0xFF;
593ebaecc14Sdanielk1977 p[4] = (i>>24)&0xFF;
594ebaecc14Sdanielk1977 p[5] = (i>>16)&0xFF;
595ebaecc14Sdanielk1977 p[6] = (i>> 8)&0xFF;
596ebaecc14Sdanielk1977 p[7] = (i>> 0)&0xFF;
59703626e38Sdrh #endif
598ebaecc14Sdanielk1977 return 8;
599ebaecc14Sdanielk1977 }
600ebaecc14Sdanielk1977
601ebaecc14Sdanielk1977 /*
602ebaecc14Sdanielk1977 ** Increment the reference count of node p.
603ebaecc14Sdanielk1977 */
nodeReference(RtreeNode * p)604ebaecc14Sdanielk1977 static void nodeReference(RtreeNode *p){
605ebaecc14Sdanielk1977 if( p ){
606c8c9cdd9Sdrh assert( p->nRef>0 );
607ebaecc14Sdanielk1977 p->nRef++;
608ebaecc14Sdanielk1977 }
609ebaecc14Sdanielk1977 }
610ebaecc14Sdanielk1977
611ebaecc14Sdanielk1977 /*
612ebaecc14Sdanielk1977 ** Clear the content of node p (set all bytes to 0x00).
613ebaecc14Sdanielk1977 */
nodeZero(Rtree * pRtree,RtreeNode * p)614ebaecc14Sdanielk1977 static void nodeZero(Rtree *pRtree, RtreeNode *p){
615ebaecc14Sdanielk1977 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
616ebaecc14Sdanielk1977 p->isDirty = 1;
617ebaecc14Sdanielk1977 }
618ebaecc14Sdanielk1977
619ebaecc14Sdanielk1977 /*
620ebaecc14Sdanielk1977 ** Given a node number iNode, return the corresponding key to use
621ebaecc14Sdanielk1977 ** in the Rtree.aHash table.
622ebaecc14Sdanielk1977 */
nodeHash(i64 iNode)623687e2007Sdrh static unsigned int nodeHash(i64 iNode){
624687e2007Sdrh return ((unsigned)iNode) % HASHSIZE;
625ebaecc14Sdanielk1977 }
626ebaecc14Sdanielk1977
627ebaecc14Sdanielk1977 /*
628ebaecc14Sdanielk1977 ** Search the node hash table for node iNode. If found, return a pointer
629ebaecc14Sdanielk1977 ** to it. Otherwise, return 0.
630ebaecc14Sdanielk1977 */
nodeHashLookup(Rtree * pRtree,i64 iNode)631ebaecc14Sdanielk1977 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
632ebaecc14Sdanielk1977 RtreeNode *p;
633ebaecc14Sdanielk1977 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
634ebaecc14Sdanielk1977 return p;
635ebaecc14Sdanielk1977 }
636ebaecc14Sdanielk1977
637ebaecc14Sdanielk1977 /*
638ebaecc14Sdanielk1977 ** Add node pNode to the node hash table.
639ebaecc14Sdanielk1977 */
nodeHashInsert(Rtree * pRtree,RtreeNode * pNode)640ebaecc14Sdanielk1977 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
641ebaecc14Sdanielk1977 int iHash;
642ebaecc14Sdanielk1977 assert( pNode->pNext==0 );
643ebaecc14Sdanielk1977 iHash = nodeHash(pNode->iNode);
644ebaecc14Sdanielk1977 pNode->pNext = pRtree->aHash[iHash];
645ebaecc14Sdanielk1977 pRtree->aHash[iHash] = pNode;
646ebaecc14Sdanielk1977 }
647ebaecc14Sdanielk1977
648ebaecc14Sdanielk1977 /*
649ebaecc14Sdanielk1977 ** Remove node pNode from the node hash table.
650ebaecc14Sdanielk1977 */
nodeHashDelete(Rtree * pRtree,RtreeNode * pNode)651ebaecc14Sdanielk1977 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
652ebaecc14Sdanielk1977 RtreeNode **pp;
653ebaecc14Sdanielk1977 if( pNode->iNode!=0 ){
654ebaecc14Sdanielk1977 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
655ebaecc14Sdanielk1977 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
656ebaecc14Sdanielk1977 *pp = pNode->pNext;
657ebaecc14Sdanielk1977 pNode->pNext = 0;
658ebaecc14Sdanielk1977 }
659ebaecc14Sdanielk1977 }
660ebaecc14Sdanielk1977
661ebaecc14Sdanielk1977 /*
662ebaecc14Sdanielk1977 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
663ebaecc14Sdanielk1977 ** indicating that node has not yet been assigned a node number. It is
664ebaecc14Sdanielk1977 ** assigned a node number when nodeWrite() is called to write the
665ebaecc14Sdanielk1977 ** node contents out to the database.
666ebaecc14Sdanielk1977 */
nodeNew(Rtree * pRtree,RtreeNode * pParent)66792e01aafSdan static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
668ebaecc14Sdanielk1977 RtreeNode *pNode;
6692d77d80aSdrh pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
670ebaecc14Sdanielk1977 if( pNode ){
67192e01aafSdan memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
672ebaecc14Sdanielk1977 pNode->zData = (u8 *)&pNode[1];
673ebaecc14Sdanielk1977 pNode->nRef = 1;
674c8c9cdd9Sdrh pRtree->nNodeRef++;
675ebaecc14Sdanielk1977 pNode->pParent = pParent;
676ebaecc14Sdanielk1977 pNode->isDirty = 1;
677ebaecc14Sdanielk1977 nodeReference(pParent);
678ebaecc14Sdanielk1977 }
679ebaecc14Sdanielk1977 return pNode;
680ebaecc14Sdanielk1977 }
681ebaecc14Sdanielk1977
682ebaecc14Sdanielk1977 /*
6836d683c5cSdrh ** Clear the Rtree.pNodeBlob object
6846d683c5cSdrh */
nodeBlobReset(Rtree * pRtree)6856d683c5cSdrh static void nodeBlobReset(Rtree *pRtree){
6862033d1c8Sdrh if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
687413e207eSdrh sqlite3_blob *pBlob = pRtree->pNodeBlob;
6886d683c5cSdrh pRtree->pNodeBlob = 0;
689413e207eSdrh sqlite3_blob_close(pBlob);
6906d683c5cSdrh }
6916d683c5cSdrh }
6926d683c5cSdrh
6936d683c5cSdrh /*
694ebaecc14Sdanielk1977 ** Obtain a reference to an r-tree node.
695ebaecc14Sdanielk1977 */
nodeAcquire(Rtree * pRtree,i64 iNode,RtreeNode * pParent,RtreeNode ** ppNode)69665e6b0ddSdrh static int nodeAcquire(
697ebaecc14Sdanielk1977 Rtree *pRtree, /* R-tree structure */
698ebaecc14Sdanielk1977 i64 iNode, /* Node number to load */
699ebaecc14Sdanielk1977 RtreeNode *pParent, /* Either the parent node or NULL */
700ebaecc14Sdanielk1977 RtreeNode **ppNode /* OUT: Acquired node */
701ebaecc14Sdanielk1977 ){
7026d683c5cSdrh int rc = SQLITE_OK;
7036d683c5cSdrh RtreeNode *pNode = 0;
704ebaecc14Sdanielk1977
705ebaecc14Sdanielk1977 /* Check if the requested node is already in the hash table. If so,
706ebaecc14Sdanielk1977 ** increase its reference count and return it.
707ebaecc14Sdanielk1977 */
708c8c9cdd9Sdrh if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
70983569e2eSdrh if( pParent && pParent!=pNode->pParent ){
7108fbcb048Sdrh RTREE_IS_CORRUPT(pRtree);
7118fbcb048Sdrh return SQLITE_CORRUPT_VTAB;
712ebaecc14Sdanielk1977 }
713ebaecc14Sdanielk1977 pNode->nRef++;
714ebaecc14Sdanielk1977 *ppNode = pNode;
715ebaecc14Sdanielk1977 return SQLITE_OK;
716ebaecc14Sdanielk1977 }
717ebaecc14Sdanielk1977
7186d683c5cSdrh if( pRtree->pNodeBlob ){
7196d683c5cSdrh sqlite3_blob *pBlob = pRtree->pNodeBlob;
7206d683c5cSdrh pRtree->pNodeBlob = 0;
7216d683c5cSdrh rc = sqlite3_blob_reopen(pBlob, iNode);
7226d683c5cSdrh pRtree->pNodeBlob = pBlob;
7236d683c5cSdrh if( rc ){
7246d683c5cSdrh nodeBlobReset(pRtree);
7252033d1c8Sdrh if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
7266d683c5cSdrh }
7276d683c5cSdrh }
7286d683c5cSdrh if( pRtree->pNodeBlob==0 ){
7296d683c5cSdrh char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
7306d683c5cSdrh if( zTab==0 ) return SQLITE_NOMEM;
7316d683c5cSdrh rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
7326d683c5cSdrh &pRtree->pNodeBlob);
7336d683c5cSdrh sqlite3_free(zTab);
7346d683c5cSdrh }
7356d683c5cSdrh if( rc ){
7366d683c5cSdrh nodeBlobReset(pRtree);
7376d683c5cSdrh *ppNode = 0;
7382033d1c8Sdrh /* If unable to open an sqlite3_blob on the desired row, that can only
7392033d1c8Sdrh ** be because the shadow tables hold erroneous data. */
740fb077f3cSdrh if( rc==SQLITE_ERROR ){
741fb077f3cSdrh rc = SQLITE_CORRUPT_VTAB;
742fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
743fb077f3cSdrh }
7446d683c5cSdrh }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
7452d77d80aSdrh pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
746ebaecc14Sdanielk1977 if( !pNode ){
7476d683c5cSdrh rc = SQLITE_NOMEM;
748bd188afdSdan }else{
749ebaecc14Sdanielk1977 pNode->pParent = pParent;
750ebaecc14Sdanielk1977 pNode->zData = (u8 *)&pNode[1];
751ebaecc14Sdanielk1977 pNode->nRef = 1;
752c8c9cdd9Sdrh pRtree->nNodeRef++;
753ebaecc14Sdanielk1977 pNode->iNode = iNode;
754ebaecc14Sdanielk1977 pNode->isDirty = 0;
755ebaecc14Sdanielk1977 pNode->pNext = 0;
7566d683c5cSdrh rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
7576d683c5cSdrh pRtree->iNodeSize, 0);
758ebaecc14Sdanielk1977 }
759bd188afdSdan }
760ebaecc14Sdanielk1977
761bd188afdSdan /* If the root node was just loaded, set pRtree->iDepth to the height
762bd188afdSdan ** of the r-tree structure. A height of zero means all data is stored on
763bd188afdSdan ** the root node. A height of one means the children of the root node
764bd188afdSdan ** are the leaves, and so on. If the depth as specified on the root node
765bd188afdSdan ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
766bd188afdSdan */
7678e4616c2Sdrh if( rc==SQLITE_OK && pNode && iNode==1 ){
768ebaecc14Sdanielk1977 pRtree->iDepth = readInt16(pNode->zData);
769bd188afdSdan if( pRtree->iDepth>RTREE_MAX_DEPTH ){
770133d7dabSdan rc = SQLITE_CORRUPT_VTAB;
771fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
772bd188afdSdan }
773ebaecc14Sdanielk1977 }
774ebaecc14Sdanielk1977
775bd188afdSdan /* If no error has occurred so far, check if the "number of entries"
776bd188afdSdan ** field on the node is too large. If so, set the return code to
777133d7dabSdan ** SQLITE_CORRUPT_VTAB.
778bd188afdSdan */
779bd188afdSdan if( pNode && rc==SQLITE_OK ){
780bd188afdSdan if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
781133d7dabSdan rc = SQLITE_CORRUPT_VTAB;
782fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
783bd188afdSdan }
784bd188afdSdan }
785bd188afdSdan
786bd188afdSdan if( rc==SQLITE_OK ){
787ee2c813bSdrh if( pNode!=0 ){
788c0f16202Sdrh nodeReference(pParent);
789ebaecc14Sdanielk1977 nodeHashInsert(pRtree, pNode);
790bd188afdSdan }else{
791133d7dabSdan rc = SQLITE_CORRUPT_VTAB;
792fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
793ee2c813bSdrh }
794bd188afdSdan *ppNode = pNode;
795bd188afdSdan }else{
796c8c9cdd9Sdrh if( pNode ){
797c8c9cdd9Sdrh pRtree->nNodeRef--;
798bd188afdSdan sqlite3_free(pNode);
799c8c9cdd9Sdrh }
800bd188afdSdan *ppNode = 0;
801bd188afdSdan }
802ebaecc14Sdanielk1977
803ebaecc14Sdanielk1977 return rc;
804ebaecc14Sdanielk1977 }
805ebaecc14Sdanielk1977
806ebaecc14Sdanielk1977 /*
807ebaecc14Sdanielk1977 ** Overwrite cell iCell of node pNode with the contents of pCell.
808ebaecc14Sdanielk1977 */
nodeOverwriteCell(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell,int iCell)809ebaecc14Sdanielk1977 static void nodeOverwriteCell(
81065e6b0ddSdrh Rtree *pRtree, /* The overall R-Tree */
81165e6b0ddSdrh RtreeNode *pNode, /* The node into which the cell is to be written */
81265e6b0ddSdrh RtreeCell *pCell, /* The cell to write */
81365e6b0ddSdrh int iCell /* Index into pNode into which pCell is written */
814ebaecc14Sdanielk1977 ){
815ebaecc14Sdanielk1977 int ii;
816ebaecc14Sdanielk1977 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
817ebaecc14Sdanielk1977 p += writeInt64(p, pCell->iRowid);
8180e6f67b7Sdrh for(ii=0; ii<pRtree->nDim2; ii++){
8193ddb5a51Sdanielk1977 p += writeCoord(p, &pCell->aCoord[ii]);
820ebaecc14Sdanielk1977 }
821ebaecc14Sdanielk1977 pNode->isDirty = 1;
822ebaecc14Sdanielk1977 }
823ebaecc14Sdanielk1977
824ebaecc14Sdanielk1977 /*
82565e6b0ddSdrh ** Remove the cell with index iCell from node pNode.
826ebaecc14Sdanielk1977 */
nodeDeleteCell(Rtree * pRtree,RtreeNode * pNode,int iCell)827ebaecc14Sdanielk1977 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
828ebaecc14Sdanielk1977 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
829ebaecc14Sdanielk1977 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
830ebaecc14Sdanielk1977 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
831ebaecc14Sdanielk1977 memmove(pDst, pSrc, nByte);
832ebaecc14Sdanielk1977 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
833ebaecc14Sdanielk1977 pNode->isDirty = 1;
834ebaecc14Sdanielk1977 }
835ebaecc14Sdanielk1977
836ebaecc14Sdanielk1977 /*
837ebaecc14Sdanielk1977 ** Insert the contents of cell pCell into node pNode. If the insert
838ebaecc14Sdanielk1977 ** is successful, return SQLITE_OK.
839ebaecc14Sdanielk1977 **
840ebaecc14Sdanielk1977 ** If there is not enough free space in pNode, return SQLITE_FULL.
841ebaecc14Sdanielk1977 */
nodeInsertCell(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell)84265e6b0ddSdrh static int nodeInsertCell(
84365e6b0ddSdrh Rtree *pRtree, /* The overall R-Tree */
84465e6b0ddSdrh RtreeNode *pNode, /* Write new cell into this node */
84565e6b0ddSdrh RtreeCell *pCell /* The cell to be inserted */
846ebaecc14Sdanielk1977 ){
847ebaecc14Sdanielk1977 int nCell; /* Current number of cells in pNode */
848ebaecc14Sdanielk1977 int nMaxCell; /* Maximum number of cells for pNode */
849ebaecc14Sdanielk1977
850ebaecc14Sdanielk1977 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
851ebaecc14Sdanielk1977 nCell = NCELL(pNode);
852ebaecc14Sdanielk1977
853ebaecc14Sdanielk1977 assert( nCell<=nMaxCell );
854ebaecc14Sdanielk1977 if( nCell<nMaxCell ){
855ebaecc14Sdanielk1977 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
856ebaecc14Sdanielk1977 writeInt16(&pNode->zData[2], nCell+1);
857ebaecc14Sdanielk1977 pNode->isDirty = 1;
858ebaecc14Sdanielk1977 }
859ebaecc14Sdanielk1977
860ebaecc14Sdanielk1977 return (nCell==nMaxCell);
861ebaecc14Sdanielk1977 }
862ebaecc14Sdanielk1977
863ebaecc14Sdanielk1977 /*
864ebaecc14Sdanielk1977 ** If the node is dirty, write it out to the database.
865ebaecc14Sdanielk1977 */
nodeWrite(Rtree * pRtree,RtreeNode * pNode)86665e6b0ddSdrh static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
867ebaecc14Sdanielk1977 int rc = SQLITE_OK;
868ebaecc14Sdanielk1977 if( pNode->isDirty ){
869ebaecc14Sdanielk1977 sqlite3_stmt *p = pRtree->pWriteNode;
870ebaecc14Sdanielk1977 if( pNode->iNode ){
871ebaecc14Sdanielk1977 sqlite3_bind_int64(p, 1, pNode->iNode);
872ebaecc14Sdanielk1977 }else{
873ebaecc14Sdanielk1977 sqlite3_bind_null(p, 1);
874ebaecc14Sdanielk1977 }
875ebaecc14Sdanielk1977 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
876ebaecc14Sdanielk1977 sqlite3_step(p);
877ebaecc14Sdanielk1977 pNode->isDirty = 0;
878ebaecc14Sdanielk1977 rc = sqlite3_reset(p);
879eab0e103Sdan sqlite3_bind_null(p, 2);
880ebaecc14Sdanielk1977 if( pNode->iNode==0 && rc==SQLITE_OK ){
881ebaecc14Sdanielk1977 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
882ebaecc14Sdanielk1977 nodeHashInsert(pRtree, pNode);
883ebaecc14Sdanielk1977 }
884ebaecc14Sdanielk1977 }
885ebaecc14Sdanielk1977 return rc;
886ebaecc14Sdanielk1977 }
887ebaecc14Sdanielk1977
888ebaecc14Sdanielk1977 /*
889ebaecc14Sdanielk1977 ** Release a reference to a node. If the node is dirty and the reference
890ebaecc14Sdanielk1977 ** count drops to zero, the node data is written to the database.
891ebaecc14Sdanielk1977 */
nodeRelease(Rtree * pRtree,RtreeNode * pNode)89265e6b0ddSdrh static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
893ebaecc14Sdanielk1977 int rc = SQLITE_OK;
894ebaecc14Sdanielk1977 if( pNode ){
895ebaecc14Sdanielk1977 assert( pNode->nRef>0 );
896c8c9cdd9Sdrh assert( pRtree->nNodeRef>0 );
897ebaecc14Sdanielk1977 pNode->nRef--;
898ebaecc14Sdanielk1977 if( pNode->nRef==0 ){
899c8c9cdd9Sdrh pRtree->nNodeRef--;
900ebaecc14Sdanielk1977 if( pNode->iNode==1 ){
901ebaecc14Sdanielk1977 pRtree->iDepth = -1;
902ebaecc14Sdanielk1977 }
903ebaecc14Sdanielk1977 if( pNode->pParent ){
904ebaecc14Sdanielk1977 rc = nodeRelease(pRtree, pNode->pParent);
905ebaecc14Sdanielk1977 }
906ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
907ebaecc14Sdanielk1977 rc = nodeWrite(pRtree, pNode);
908ebaecc14Sdanielk1977 }
909ebaecc14Sdanielk1977 nodeHashDelete(pRtree, pNode);
910ebaecc14Sdanielk1977 sqlite3_free(pNode);
911ebaecc14Sdanielk1977 }
912ebaecc14Sdanielk1977 }
913ebaecc14Sdanielk1977 return rc;
914ebaecc14Sdanielk1977 }
915ebaecc14Sdanielk1977
916ebaecc14Sdanielk1977 /*
917ebaecc14Sdanielk1977 ** Return the 64-bit integer value associated with cell iCell of
918ebaecc14Sdanielk1977 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
919ebaecc14Sdanielk1977 ** an internal node, then the 64-bit integer is a child page number.
920ebaecc14Sdanielk1977 */
nodeGetRowid(Rtree * pRtree,RtreeNode * pNode,int iCell)921ebaecc14Sdanielk1977 static i64 nodeGetRowid(
92265e6b0ddSdrh Rtree *pRtree, /* The overall R-Tree */
92365e6b0ddSdrh RtreeNode *pNode, /* The node from which to extract the ID */
92465e6b0ddSdrh int iCell /* The cell index from which to extract the ID */
925ebaecc14Sdanielk1977 ){
926ebaecc14Sdanielk1977 assert( iCell<NCELL(pNode) );
927ebaecc14Sdanielk1977 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
928ebaecc14Sdanielk1977 }
929ebaecc14Sdanielk1977
930ebaecc14Sdanielk1977 /*
931ebaecc14Sdanielk1977 ** Return coordinate iCoord from cell iCell in node pNode.
932ebaecc14Sdanielk1977 */
nodeGetCoord(Rtree * pRtree,RtreeNode * pNode,int iCell,int iCoord,RtreeCoord * pCoord)9333ddb5a51Sdanielk1977 static void nodeGetCoord(
93465e6b0ddSdrh Rtree *pRtree, /* The overall R-Tree */
93565e6b0ddSdrh RtreeNode *pNode, /* The node from which to extract a coordinate */
93665e6b0ddSdrh int iCell, /* The index of the cell within the node */
93765e6b0ddSdrh int iCoord, /* Which coordinate to extract */
93865e6b0ddSdrh RtreeCoord *pCoord /* OUT: Space to write result to */
939ebaecc14Sdanielk1977 ){
9403ddb5a51Sdanielk1977 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
941ebaecc14Sdanielk1977 }
942ebaecc14Sdanielk1977
943ebaecc14Sdanielk1977 /*
944ebaecc14Sdanielk1977 ** Deserialize cell iCell of node pNode. Populate the structure pointed
945ebaecc14Sdanielk1977 ** to by pCell with the results.
946ebaecc14Sdanielk1977 */
nodeGetCell(Rtree * pRtree,RtreeNode * pNode,int iCell,RtreeCell * pCell)947ebaecc14Sdanielk1977 static void nodeGetCell(
94865e6b0ddSdrh Rtree *pRtree, /* The overall R-Tree */
94965e6b0ddSdrh RtreeNode *pNode, /* The node containing the cell to be read */
95065e6b0ddSdrh int iCell, /* Index of the cell within the node */
95165e6b0ddSdrh RtreeCell *pCell /* OUT: Write the cell contents here */
952ebaecc14Sdanielk1977 ){
95365e6b0ddSdrh u8 *pData;
95465e6b0ddSdrh RtreeCoord *pCoord;
95514494fa7Sdrh int ii = 0;
956ebaecc14Sdanielk1977 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
95765e6b0ddSdrh pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
95865e6b0ddSdrh pCoord = pCell->aCoord;
95914494fa7Sdrh do{
96014494fa7Sdrh readCoord(pData, &pCoord[ii]);
96114494fa7Sdrh readCoord(pData+4, &pCoord[ii+1]);
96214494fa7Sdrh pData += 8;
96314494fa7Sdrh ii += 2;
9640e6f67b7Sdrh }while( ii<pRtree->nDim2 );
965ebaecc14Sdanielk1977 }
966ebaecc14Sdanielk1977
967ebaecc14Sdanielk1977
968ebaecc14Sdanielk1977 /* Forward declaration for the function that does the work of
969ebaecc14Sdanielk1977 ** the virtual table module xCreate() and xConnect() methods.
970ebaecc14Sdanielk1977 */
971ebaecc14Sdanielk1977 static int rtreeInit(
972a7435e31Sdanielk1977 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
973ebaecc14Sdanielk1977 );
974ebaecc14Sdanielk1977
975ebaecc14Sdanielk1977 /*
976ebaecc14Sdanielk1977 ** Rtree virtual table module xCreate method.
977ebaecc14Sdanielk1977 */
rtreeCreate(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)978ebaecc14Sdanielk1977 static int rtreeCreate(
979ebaecc14Sdanielk1977 sqlite3 *db,
980ebaecc14Sdanielk1977 void *pAux,
981ebaecc14Sdanielk1977 int argc, const char *const*argv,
982ebaecc14Sdanielk1977 sqlite3_vtab **ppVtab,
983ebaecc14Sdanielk1977 char **pzErr
984ebaecc14Sdanielk1977 ){
985a7435e31Sdanielk1977 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
986ebaecc14Sdanielk1977 }
987ebaecc14Sdanielk1977
988ebaecc14Sdanielk1977 /*
989ebaecc14Sdanielk1977 ** Rtree virtual table module xConnect method.
990ebaecc14Sdanielk1977 */
rtreeConnect(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr)991ebaecc14Sdanielk1977 static int rtreeConnect(
992ebaecc14Sdanielk1977 sqlite3 *db,
993ebaecc14Sdanielk1977 void *pAux,
994ebaecc14Sdanielk1977 int argc, const char *const*argv,
995ebaecc14Sdanielk1977 sqlite3_vtab **ppVtab,
996ebaecc14Sdanielk1977 char **pzErr
997ebaecc14Sdanielk1977 ){
998a7435e31Sdanielk1977 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
999ebaecc14Sdanielk1977 }
1000ebaecc14Sdanielk1977
1001ebaecc14Sdanielk1977 /*
1002ebaecc14Sdanielk1977 ** Increment the r-tree reference count.
1003ebaecc14Sdanielk1977 */
rtreeReference(Rtree * pRtree)1004ebaecc14Sdanielk1977 static void rtreeReference(Rtree *pRtree){
1005ebaecc14Sdanielk1977 pRtree->nBusy++;
1006ebaecc14Sdanielk1977 }
1007ebaecc14Sdanielk1977
1008ebaecc14Sdanielk1977 /*
1009ebaecc14Sdanielk1977 ** Decrement the r-tree reference count. When the reference count reaches
1010ebaecc14Sdanielk1977 ** zero the structure is deleted.
1011ebaecc14Sdanielk1977 */
rtreeRelease(Rtree * pRtree)1012ebaecc14Sdanielk1977 static void rtreeRelease(Rtree *pRtree){
1013ebaecc14Sdanielk1977 pRtree->nBusy--;
1014ebaecc14Sdanielk1977 if( pRtree->nBusy==0 ){
10152033d1c8Sdrh pRtree->inWrTrans = 0;
1016c8c9cdd9Sdrh assert( pRtree->nCursor==0 );
10176d683c5cSdrh nodeBlobReset(pRtree);
1018fb077f3cSdrh assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
1019ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pWriteNode);
1020ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pDeleteNode);
1021ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pReadRowid);
1022ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pWriteRowid);
1023ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pDeleteRowid);
1024ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pReadParent);
1025ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pWriteParent);
1026ebaecc14Sdanielk1977 sqlite3_finalize(pRtree->pDeleteParent);
1027e2971965Sdrh sqlite3_finalize(pRtree->pWriteAux);
1028e2971965Sdrh sqlite3_free(pRtree->zReadAuxSql);
1029ebaecc14Sdanielk1977 sqlite3_free(pRtree);
1030ebaecc14Sdanielk1977 }
1031ebaecc14Sdanielk1977 }
1032ebaecc14Sdanielk1977
1033ebaecc14Sdanielk1977 /*
1034ebaecc14Sdanielk1977 ** Rtree virtual table module xDisconnect method.
1035ebaecc14Sdanielk1977 */
rtreeDisconnect(sqlite3_vtab * pVtab)1036ebaecc14Sdanielk1977 static int rtreeDisconnect(sqlite3_vtab *pVtab){
1037ebaecc14Sdanielk1977 rtreeRelease((Rtree *)pVtab);
1038ebaecc14Sdanielk1977 return SQLITE_OK;
1039ebaecc14Sdanielk1977 }
1040ebaecc14Sdanielk1977
1041ebaecc14Sdanielk1977 /*
1042ebaecc14Sdanielk1977 ** Rtree virtual table module xDestroy method.
1043ebaecc14Sdanielk1977 */
rtreeDestroy(sqlite3_vtab * pVtab)1044ebaecc14Sdanielk1977 static int rtreeDestroy(sqlite3_vtab *pVtab){
1045ebaecc14Sdanielk1977 Rtree *pRtree = (Rtree *)pVtab;
1046ebaecc14Sdanielk1977 int rc;
1047ebaecc14Sdanielk1977 char *zCreate = sqlite3_mprintf(
1048ebaecc14Sdanielk1977 "DROP TABLE '%q'.'%q_node';"
1049ebaecc14Sdanielk1977 "DROP TABLE '%q'.'%q_rowid';"
1050ebaecc14Sdanielk1977 "DROP TABLE '%q'.'%q_parent';",
1051ebaecc14Sdanielk1977 pRtree->zDb, pRtree->zName,
1052ebaecc14Sdanielk1977 pRtree->zDb, pRtree->zName,
1053ebaecc14Sdanielk1977 pRtree->zDb, pRtree->zName
1054ebaecc14Sdanielk1977 );
1055ebaecc14Sdanielk1977 if( !zCreate ){
1056ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
1057ebaecc14Sdanielk1977 }else{
10586d683c5cSdrh nodeBlobReset(pRtree);
1059ebaecc14Sdanielk1977 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
1060ebaecc14Sdanielk1977 sqlite3_free(zCreate);
1061ebaecc14Sdanielk1977 }
1062ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
1063ebaecc14Sdanielk1977 rtreeRelease(pRtree);
1064ebaecc14Sdanielk1977 }
1065ebaecc14Sdanielk1977
1066ebaecc14Sdanielk1977 return rc;
1067ebaecc14Sdanielk1977 }
1068ebaecc14Sdanielk1977
1069ebaecc14Sdanielk1977 /*
1070ebaecc14Sdanielk1977 ** Rtree virtual table module xOpen method.
1071ebaecc14Sdanielk1977 */
rtreeOpen(sqlite3_vtab * pVTab,sqlite3_vtab_cursor ** ppCursor)1072ebaecc14Sdanielk1977 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
1073ebaecc14Sdanielk1977 int rc = SQLITE_NOMEM;
10742033d1c8Sdrh Rtree *pRtree = (Rtree *)pVTab;
1075ebaecc14Sdanielk1977 RtreeCursor *pCsr;
1076ebaecc14Sdanielk1977
10772d77d80aSdrh pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
1078ebaecc14Sdanielk1977 if( pCsr ){
1079ebaecc14Sdanielk1977 memset(pCsr, 0, sizeof(RtreeCursor));
1080ebaecc14Sdanielk1977 pCsr->base.pVtab = pVTab;
1081ebaecc14Sdanielk1977 rc = SQLITE_OK;
10822033d1c8Sdrh pRtree->nCursor++;
1083ebaecc14Sdanielk1977 }
1084ebaecc14Sdanielk1977 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
1085ebaecc14Sdanielk1977
1086ebaecc14Sdanielk1977 return rc;
1087ebaecc14Sdanielk1977 }
1088ebaecc14Sdanielk1977
10899508daa9Sdan
10909508daa9Sdan /*
10915f0dfc00Sdrh ** Reset a cursor back to its initial state.
10929508daa9Sdan */
resetCursor(RtreeCursor * pCsr)10935f0dfc00Sdrh static void resetCursor(RtreeCursor *pCsr){
10945f0dfc00Sdrh Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
10955f0dfc00Sdrh int ii;
10965f0dfc00Sdrh sqlite3_stmt *pStmt;
10979508daa9Sdan if( pCsr->aConstraint ){
10989508daa9Sdan int i; /* Used to iterate through constraint array */
10999508daa9Sdan for(i=0; i<pCsr->nConstraint; i++){
110065e6b0ddSdrh sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
110165e6b0ddSdrh if( pInfo ){
110265e6b0ddSdrh if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
110365e6b0ddSdrh sqlite3_free(pInfo);
11049508daa9Sdan }
11059508daa9Sdan }
11069508daa9Sdan sqlite3_free(pCsr->aConstraint);
11079508daa9Sdan pCsr->aConstraint = 0;
11089508daa9Sdan }
11095f0dfc00Sdrh for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
11105f0dfc00Sdrh sqlite3_free(pCsr->aPoint);
11115f0dfc00Sdrh pStmt = pCsr->pReadAux;
11125f0dfc00Sdrh memset(pCsr, 0, sizeof(RtreeCursor));
11135f0dfc00Sdrh pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
11145f0dfc00Sdrh pCsr->pReadAux = pStmt;
11155f0dfc00Sdrh
11169508daa9Sdan }
11179508daa9Sdan
1118ebaecc14Sdanielk1977 /*
1119ebaecc14Sdanielk1977 ** Rtree virtual table module xClose method.
1120ebaecc14Sdanielk1977 */
rtreeClose(sqlite3_vtab_cursor * cur)1121ebaecc14Sdanielk1977 static int rtreeClose(sqlite3_vtab_cursor *cur){
1122ebaecc14Sdanielk1977 Rtree *pRtree = (Rtree *)(cur->pVtab);
1123ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)cur;
11242033d1c8Sdrh assert( pRtree->nCursor>0 );
11255f0dfc00Sdrh resetCursor(pCsr);
1126e2971965Sdrh sqlite3_finalize(pCsr->pReadAux);
1127ebaecc14Sdanielk1977 sqlite3_free(pCsr);
11282033d1c8Sdrh pRtree->nCursor--;
11292033d1c8Sdrh nodeBlobReset(pRtree);
113065e6b0ddSdrh return SQLITE_OK;
1131ebaecc14Sdanielk1977 }
1132ebaecc14Sdanielk1977
1133ebaecc14Sdanielk1977 /*
1134ebaecc14Sdanielk1977 ** Rtree virtual table module xEof method.
1135ebaecc14Sdanielk1977 **
1136ebaecc14Sdanielk1977 ** Return non-zero if the cursor does not currently point to a valid
1137ebaecc14Sdanielk1977 ** record (i.e if the scan has finished), or zero otherwise.
1138ebaecc14Sdanielk1977 */
rtreeEof(sqlite3_vtab_cursor * cur)1139ebaecc14Sdanielk1977 static int rtreeEof(sqlite3_vtab_cursor *cur){
1140ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)cur;
114165e6b0ddSdrh return pCsr->atEOF;
1142ebaecc14Sdanielk1977 }
1143ebaecc14Sdanielk1977
1144ebaecc14Sdanielk1977 /*
114565e6b0ddSdrh ** Convert raw bits from the on-disk RTree record into a coordinate value.
114665e6b0ddSdrh ** The on-disk format is big-endian and needs to be converted for little-
114765e6b0ddSdrh ** endian platforms. The on-disk record stores integer coordinates if
114865e6b0ddSdrh ** eInt is true and it stores 32-bit floating point records if eInt is
114965e6b0ddSdrh ** false. a[] is the four bytes of the on-disk record to be decoded.
115065e6b0ddSdrh ** Store the results in "r".
115165e6b0ddSdrh **
115203626e38Sdrh ** There are five versions of this macro. The last one is generic. The
115303626e38Sdrh ** other four are various architectures-specific optimizations.
11549508daa9Sdan */
115503626e38Sdrh #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
115603626e38Sdrh #define RTREE_DECODE_COORD(eInt, a, r) { \
115703626e38Sdrh RtreeCoord c; /* Coordinate decoded */ \
115803626e38Sdrh c.u = _byteswap_ulong(*(u32*)a); \
115903626e38Sdrh r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
116003626e38Sdrh }
1161dc5ece86Sdrh #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
116203626e38Sdrh #define RTREE_DECODE_COORD(eInt, a, r) { \
116303626e38Sdrh RtreeCoord c; /* Coordinate decoded */ \
116403626e38Sdrh c.u = __builtin_bswap32(*(u32*)a); \
116503626e38Sdrh r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
116603626e38Sdrh }
116703626e38Sdrh #elif SQLITE_BYTEORDER==1234
116865e6b0ddSdrh #define RTREE_DECODE_COORD(eInt, a, r) { \
116965e6b0ddSdrh RtreeCoord c; /* Coordinate decoded */ \
117065e6b0ddSdrh memcpy(&c.u,a,4); \
117165e6b0ddSdrh c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
117265e6b0ddSdrh ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
117365e6b0ddSdrh r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
117465e6b0ddSdrh }
117503626e38Sdrh #elif SQLITE_BYTEORDER==4321
117665e6b0ddSdrh #define RTREE_DECODE_COORD(eInt, a, r) { \
117765e6b0ddSdrh RtreeCoord c; /* Coordinate decoded */ \
117865e6b0ddSdrh memcpy(&c.u,a,4); \
117965e6b0ddSdrh r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
118065e6b0ddSdrh }
118165e6b0ddSdrh #else
118265e6b0ddSdrh #define RTREE_DECODE_COORD(eInt, a, r) { \
118365e6b0ddSdrh RtreeCoord c; /* Coordinate decoded */ \
118465e6b0ddSdrh c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
118565e6b0ddSdrh +((u32)a[2]<<8) + a[3]; \
118665e6b0ddSdrh r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
118765e6b0ddSdrh }
118865e6b0ddSdrh #endif
118965e6b0ddSdrh
119065e6b0ddSdrh /*
119165e6b0ddSdrh ** Check the RTree node or entry given by pCellData and p against the MATCH
119265e6b0ddSdrh ** constraint pConstraint.
119365e6b0ddSdrh */
rtreeCallbackConstraint(RtreeConstraint * pConstraint,int eInt,u8 * pCellData,RtreeSearchPoint * pSearch,sqlite3_rtree_dbl * prScore,int * peWithin)119465e6b0ddSdrh static int rtreeCallbackConstraint(
119565e6b0ddSdrh RtreeConstraint *pConstraint, /* The constraint to test */
119665e6b0ddSdrh int eInt, /* True if RTree holding integer coordinates */
119765e6b0ddSdrh u8 *pCellData, /* Raw cell content */
119865e6b0ddSdrh RtreeSearchPoint *pSearch, /* Container of this cell */
119965e6b0ddSdrh sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
120065e6b0ddSdrh int *peWithin /* OUT: visibility of the cell */
12019508daa9Sdan ){
120265e6b0ddSdrh sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
120365e6b0ddSdrh int nCoord = pInfo->nCoord; /* No. of coordinates */
120465e6b0ddSdrh int rc; /* Callback return code */
120531a13495Sdrh RtreeCoord c; /* Translator union */
120665e6b0ddSdrh sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
12079508daa9Sdan
120865e6b0ddSdrh assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
120965e6b0ddSdrh assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
12109508daa9Sdan
121165e6b0ddSdrh if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
121265e6b0ddSdrh pInfo->iRowid = readInt64(pCellData);
12139508daa9Sdan }
121465e6b0ddSdrh pCellData += 8;
121531a13495Sdrh #ifndef SQLITE_RTREE_INT_ONLY
121631a13495Sdrh if( eInt==0 ){
121731a13495Sdrh switch( nCoord ){
121831a13495Sdrh case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
121931a13495Sdrh readCoord(pCellData+32, &c); aCoord[8] = c.f;
122031a13495Sdrh case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
122131a13495Sdrh readCoord(pCellData+24, &c); aCoord[6] = c.f;
122231a13495Sdrh case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
122331a13495Sdrh readCoord(pCellData+16, &c); aCoord[4] = c.f;
122431a13495Sdrh case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
122531a13495Sdrh readCoord(pCellData+8, &c); aCoord[2] = c.f;
122631a13495Sdrh default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
122731a13495Sdrh readCoord(pCellData, &c); aCoord[0] = c.f;
122831a13495Sdrh }
122931a13495Sdrh }else
123031a13495Sdrh #endif
123131a13495Sdrh {
123231a13495Sdrh switch( nCoord ){
123331a13495Sdrh case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
123431a13495Sdrh readCoord(pCellData+32, &c); aCoord[8] = c.i;
123531a13495Sdrh case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
123631a13495Sdrh readCoord(pCellData+24, &c); aCoord[6] = c.i;
123731a13495Sdrh case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
123831a13495Sdrh readCoord(pCellData+16, &c); aCoord[4] = c.i;
123931a13495Sdrh case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
124031a13495Sdrh readCoord(pCellData+8, &c); aCoord[2] = c.i;
124131a13495Sdrh default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
124231a13495Sdrh readCoord(pCellData, &c); aCoord[0] = c.i;
124331a13495Sdrh }
124431a13495Sdrh }
124565e6b0ddSdrh if( pConstraint->op==RTREE_MATCH ){
1246ce655a23Sdrh int eWithin = 0;
124765e6b0ddSdrh rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
1248ce655a23Sdrh nCoord, aCoord, &eWithin);
1249ce655a23Sdrh if( eWithin==0 ) *peWithin = NOT_WITHIN;
125065e6b0ddSdrh *prScore = RTREE_ZERO;
1251ebaecc14Sdanielk1977 }else{
125265e6b0ddSdrh pInfo->aCoord = aCoord;
125365e6b0ddSdrh pInfo->iLevel = pSearch->iLevel - 1;
125465e6b0ddSdrh pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
125565e6b0ddSdrh pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
125665e6b0ddSdrh rc = pConstraint->u.xQueryFunc(pInfo);
125765e6b0ddSdrh if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
125865e6b0ddSdrh if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
125965e6b0ddSdrh *prScore = pInfo->rScore;
1260ebaecc14Sdanielk1977 }
1261ebaecc14Sdanielk1977 }
1262c79b6a8cSdan return rc;
1263ebaecc14Sdanielk1977 }
1264ebaecc14Sdanielk1977
1265ebaecc14Sdanielk1977 /*
126665e6b0ddSdrh ** Check the internal RTree node given by pCellData against constraint p.
126765e6b0ddSdrh ** If this constraint cannot be satisfied by any child within the node,
126865e6b0ddSdrh ** set *peWithin to NOT_WITHIN.
126965e6b0ddSdrh */
rtreeNonleafConstraint(RtreeConstraint * p,int eInt,u8 * pCellData,int * peWithin)127065e6b0ddSdrh static void rtreeNonleafConstraint(
127165e6b0ddSdrh RtreeConstraint *p, /* The constraint to test */
127265e6b0ddSdrh int eInt, /* True if RTree holds integer coordinates */
127365e6b0ddSdrh u8 *pCellData, /* Raw cell content as appears on disk */
127465e6b0ddSdrh int *peWithin /* Adjust downward, as appropriate */
127565e6b0ddSdrh ){
127665e6b0ddSdrh sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
127765e6b0ddSdrh
127865e6b0ddSdrh /* p->iCoord might point to either a lower or upper bound coordinate
127965e6b0ddSdrh ** in a coordinate pair. But make pCellData point to the lower bound.
128065e6b0ddSdrh */
128165e6b0ddSdrh pCellData += 8 + 4*(p->iCoord&0xfe);
128265e6b0ddSdrh
128365e6b0ddSdrh assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1284674a9b34Sdrh || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1285674a9b34Sdrh || p->op==RTREE_FALSE );
128603626e38Sdrh assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
128765e6b0ddSdrh switch( p->op ){
1288826ec601Sdan case RTREE_TRUE: return; /* Always satisfied */
1289826ec601Sdan case RTREE_FALSE: break; /* Never satisfied */
129065e6b0ddSdrh case RTREE_EQ:
129165e6b0ddSdrh RTREE_DECODE_COORD(eInt, pCellData, val);
129265e6b0ddSdrh /* val now holds the lower bound of the coordinate pair */
1293826ec601Sdan if( p->u.rValue>=val ){
129465e6b0ddSdrh pCellData += 4;
129565e6b0ddSdrh RTREE_DECODE_COORD(eInt, pCellData, val);
129665e6b0ddSdrh /* val now holds the upper bound of the coordinate pair */
1297826ec601Sdan if( p->u.rValue<=val ) return;
129865e6b0ddSdrh }
1299895c807aSdan break;
1300826ec601Sdan case RTREE_LE:
1301826ec601Sdan case RTREE_LT:
1302826ec601Sdan RTREE_DECODE_COORD(eInt, pCellData, val);
1303826ec601Sdan /* val now holds the lower bound of the coordinate pair */
1304826ec601Sdan if( p->u.rValue>=val ) return;
1305826ec601Sdan break;
1306826ec601Sdan
1307826ec601Sdan default:
1308826ec601Sdan pCellData += 4;
1309826ec601Sdan RTREE_DECODE_COORD(eInt, pCellData, val);
1310826ec601Sdan /* val now holds the upper bound of the coordinate pair */
1311826ec601Sdan if( p->u.rValue<=val ) return;
1312826ec601Sdan break;
1313895c807aSdan }
1314826ec601Sdan *peWithin = NOT_WITHIN;
1315895c807aSdan }
131665e6b0ddSdrh
131765e6b0ddSdrh /*
131865e6b0ddSdrh ** Check the leaf RTree cell given by pCellData against constraint p.
131965e6b0ddSdrh ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
132065e6b0ddSdrh ** If the constraint is satisfied, leave *peWithin unchanged.
132165e6b0ddSdrh **
132265e6b0ddSdrh ** The constraint is of the form: xN op $val
132365e6b0ddSdrh **
132465e6b0ddSdrh ** The op is given by p->op. The xN is p->iCoord-th coordinate in
132565e6b0ddSdrh ** pCellData. $val is given by p->u.rValue.
132665e6b0ddSdrh */
rtreeLeafConstraint(RtreeConstraint * p,int eInt,u8 * pCellData,int * peWithin)132765e6b0ddSdrh static void rtreeLeafConstraint(
132865e6b0ddSdrh RtreeConstraint *p, /* The constraint to test */
132965e6b0ddSdrh int eInt, /* True if RTree holds integer coordinates */
133065e6b0ddSdrh u8 *pCellData, /* Raw cell content as appears on disk */
133165e6b0ddSdrh int *peWithin /* Adjust downward, as appropriate */
133265e6b0ddSdrh ){
133365e6b0ddSdrh RtreeDValue xN; /* Coordinate value converted to a double */
133465e6b0ddSdrh
133565e6b0ddSdrh assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
1336674a9b34Sdrh || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
1337674a9b34Sdrh || p->op==RTREE_FALSE );
133865e6b0ddSdrh pCellData += 8 + p->iCoord*4;
133903626e38Sdrh assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
134065e6b0ddSdrh RTREE_DECODE_COORD(eInt, pCellData, xN);
134165e6b0ddSdrh switch( p->op ){
1342674a9b34Sdrh case RTREE_TRUE: return; /* Always satisfied */
1343674a9b34Sdrh case RTREE_FALSE: break; /* Never satisfied */
134465e6b0ddSdrh case RTREE_LE: if( xN <= p->u.rValue ) return; break;
134565e6b0ddSdrh case RTREE_LT: if( xN < p->u.rValue ) return; break;
134665e6b0ddSdrh case RTREE_GE: if( xN >= p->u.rValue ) return; break;
134765e6b0ddSdrh case RTREE_GT: if( xN > p->u.rValue ) return; break;
134865e6b0ddSdrh default: if( xN == p->u.rValue ) return; break;
134965e6b0ddSdrh }
135065e6b0ddSdrh *peWithin = NOT_WITHIN;
135165e6b0ddSdrh }
135265e6b0ddSdrh
135365e6b0ddSdrh /*
1354ebaecc14Sdanielk1977 ** One of the cells in node pNode is guaranteed to have a 64-bit
1355ebaecc14Sdanielk1977 ** integer value equal to iRowid. Return the index of this cell.
1356ebaecc14Sdanielk1977 */
nodeRowidIndex(Rtree * pRtree,RtreeNode * pNode,i64 iRowid,int * piIndex)1357b51d2fa8Sdan static int nodeRowidIndex(
1358b51d2fa8Sdan Rtree *pRtree,
1359b51d2fa8Sdan RtreeNode *pNode,
1360b51d2fa8Sdan i64 iRowid,
1361b51d2fa8Sdan int *piIndex
1362b51d2fa8Sdan ){
1363ebaecc14Sdanielk1977 int ii;
1364b51d2fa8Sdan int nCell = NCELL(pNode);
136565e6b0ddSdrh assert( nCell<200 );
1366b51d2fa8Sdan for(ii=0; ii<nCell; ii++){
1367b51d2fa8Sdan if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
1368b51d2fa8Sdan *piIndex = ii;
1369b51d2fa8Sdan return SQLITE_OK;
1370ebaecc14Sdanielk1977 }
1371b51d2fa8Sdan }
1372fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
1373133d7dabSdan return SQLITE_CORRUPT_VTAB;
1374ebaecc14Sdanielk1977 }
1375ebaecc14Sdanielk1977
1376ebaecc14Sdanielk1977 /*
1377ebaecc14Sdanielk1977 ** Return the index of the cell containing a pointer to node pNode
1378ebaecc14Sdanielk1977 ** in its parent. If pNode is the root node, return -1.
1379ebaecc14Sdanielk1977 */
nodeParentIndex(Rtree * pRtree,RtreeNode * pNode,int * piIndex)1380b51d2fa8Sdan static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
1381ebaecc14Sdanielk1977 RtreeNode *pParent = pNode->pParent;
138204bd2c83Sdrh if( ALWAYS(pParent) ){
1383b51d2fa8Sdan return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
138404bd2c83Sdrh }else{
1385b51d2fa8Sdan *piIndex = -1;
1386b51d2fa8Sdan return SQLITE_OK;
1387ebaecc14Sdanielk1977 }
138804bd2c83Sdrh }
1389ebaecc14Sdanielk1977
1390ebaecc14Sdanielk1977 /*
139165e6b0ddSdrh ** Compare two search points. Return negative, zero, or positive if the first
139265e6b0ddSdrh ** is less than, equal to, or greater than the second.
139365e6b0ddSdrh **
139465e6b0ddSdrh ** The rScore is the primary key. Smaller rScore values come first.
139565e6b0ddSdrh ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
139665e6b0ddSdrh ** iLevel values coming first. In this way, if rScore is the same for all
139765e6b0ddSdrh ** SearchPoints, then iLevel becomes the deciding factor and the result
139865e6b0ddSdrh ** is a depth-first search, which is the desired default behavior.
139965e6b0ddSdrh */
rtreeSearchPointCompare(const RtreeSearchPoint * pA,const RtreeSearchPoint * pB)140065e6b0ddSdrh static int rtreeSearchPointCompare(
140165e6b0ddSdrh const RtreeSearchPoint *pA,
140265e6b0ddSdrh const RtreeSearchPoint *pB
140365e6b0ddSdrh ){
140465e6b0ddSdrh if( pA->rScore<pB->rScore ) return -1;
140565e6b0ddSdrh if( pA->rScore>pB->rScore ) return +1;
140665e6b0ddSdrh if( pA->iLevel<pB->iLevel ) return -1;
140765e6b0ddSdrh if( pA->iLevel>pB->iLevel ) return +1;
140865e6b0ddSdrh return 0;
140965e6b0ddSdrh }
141065e6b0ddSdrh
141165e6b0ddSdrh /*
1412b18bf843Sdrh ** Interchange two search points in a cursor.
141365e6b0ddSdrh */
rtreeSearchPointSwap(RtreeCursor * p,int i,int j)141465e6b0ddSdrh static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
141565e6b0ddSdrh RtreeSearchPoint t = p->aPoint[i];
141665e6b0ddSdrh assert( i<j );
141765e6b0ddSdrh p->aPoint[i] = p->aPoint[j];
141865e6b0ddSdrh p->aPoint[j] = t;
141965e6b0ddSdrh i++; j++;
142065e6b0ddSdrh if( i<RTREE_CACHE_SZ ){
142165e6b0ddSdrh if( j>=RTREE_CACHE_SZ ){
142265e6b0ddSdrh nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
142365e6b0ddSdrh p->aNode[i] = 0;
142465e6b0ddSdrh }else{
142565e6b0ddSdrh RtreeNode *pTemp = p->aNode[i];
142665e6b0ddSdrh p->aNode[i] = p->aNode[j];
142765e6b0ddSdrh p->aNode[j] = pTemp;
142865e6b0ddSdrh }
142965e6b0ddSdrh }
143065e6b0ddSdrh }
143165e6b0ddSdrh
143265e6b0ddSdrh /*
143365e6b0ddSdrh ** Return the search point with the lowest current score.
143465e6b0ddSdrh */
rtreeSearchPointFirst(RtreeCursor * pCur)143565e6b0ddSdrh static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
143665e6b0ddSdrh return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
143765e6b0ddSdrh }
143865e6b0ddSdrh
143965e6b0ddSdrh /*
144065e6b0ddSdrh ** Get the RtreeNode for the search point with the lowest score.
144165e6b0ddSdrh */
rtreeNodeOfFirstSearchPoint(RtreeCursor * pCur,int * pRC)144265e6b0ddSdrh static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
144365e6b0ddSdrh sqlite3_int64 id;
144465e6b0ddSdrh int ii = 1 - pCur->bPoint;
144565e6b0ddSdrh assert( ii==0 || ii==1 );
144665e6b0ddSdrh assert( pCur->bPoint || pCur->nPoint );
144765e6b0ddSdrh if( pCur->aNode[ii]==0 ){
144865e6b0ddSdrh assert( pRC!=0 );
144965e6b0ddSdrh id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
145065e6b0ddSdrh *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
145165e6b0ddSdrh }
145265e6b0ddSdrh return pCur->aNode[ii];
145365e6b0ddSdrh }
145465e6b0ddSdrh
145565e6b0ddSdrh /*
145665e6b0ddSdrh ** Push a new element onto the priority queue
145765e6b0ddSdrh */
rtreeEnqueue(RtreeCursor * pCur,RtreeDValue rScore,u8 iLevel)145865e6b0ddSdrh static RtreeSearchPoint *rtreeEnqueue(
145965e6b0ddSdrh RtreeCursor *pCur, /* The cursor */
146065e6b0ddSdrh RtreeDValue rScore, /* Score for the new search point */
146165e6b0ddSdrh u8 iLevel /* Level for the new search point */
146265e6b0ddSdrh ){
146365e6b0ddSdrh int i, j;
146465e6b0ddSdrh RtreeSearchPoint *pNew;
146565e6b0ddSdrh if( pCur->nPoint>=pCur->nPointAlloc ){
146665e6b0ddSdrh int nNew = pCur->nPointAlloc*2 + 8;
14672d77d80aSdrh pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
146865e6b0ddSdrh if( pNew==0 ) return 0;
146965e6b0ddSdrh pCur->aPoint = pNew;
147065e6b0ddSdrh pCur->nPointAlloc = nNew;
147165e6b0ddSdrh }
147265e6b0ddSdrh i = pCur->nPoint++;
147365e6b0ddSdrh pNew = pCur->aPoint + i;
147465e6b0ddSdrh pNew->rScore = rScore;
147565e6b0ddSdrh pNew->iLevel = iLevel;
1476f0a88279Sdrh assert( iLevel<=RTREE_MAX_DEPTH );
147765e6b0ddSdrh while( i>0 ){
147865e6b0ddSdrh RtreeSearchPoint *pParent;
147965e6b0ddSdrh j = (i-1)/2;
148065e6b0ddSdrh pParent = pCur->aPoint + j;
148165e6b0ddSdrh if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
148265e6b0ddSdrh rtreeSearchPointSwap(pCur, j, i);
148365e6b0ddSdrh i = j;
148465e6b0ddSdrh pNew = pParent;
148565e6b0ddSdrh }
148665e6b0ddSdrh return pNew;
148765e6b0ddSdrh }
148865e6b0ddSdrh
148965e6b0ddSdrh /*
149065e6b0ddSdrh ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
149165e6b0ddSdrh ** NULL if malloc fails.
149265e6b0ddSdrh */
rtreeSearchPointNew(RtreeCursor * pCur,RtreeDValue rScore,u8 iLevel)149365e6b0ddSdrh static RtreeSearchPoint *rtreeSearchPointNew(
149465e6b0ddSdrh RtreeCursor *pCur, /* The cursor */
149565e6b0ddSdrh RtreeDValue rScore, /* Score for the new search point */
149665e6b0ddSdrh u8 iLevel /* Level for the new search point */
149765e6b0ddSdrh ){
149865e6b0ddSdrh RtreeSearchPoint *pNew, *pFirst;
149965e6b0ddSdrh pFirst = rtreeSearchPointFirst(pCur);
150065e6b0ddSdrh pCur->anQueue[iLevel]++;
150165e6b0ddSdrh if( pFirst==0
150265e6b0ddSdrh || pFirst->rScore>rScore
150365e6b0ddSdrh || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
150465e6b0ddSdrh ){
150565e6b0ddSdrh if( pCur->bPoint ){
150665e6b0ddSdrh int ii;
150765e6b0ddSdrh pNew = rtreeEnqueue(pCur, rScore, iLevel);
150865e6b0ddSdrh if( pNew==0 ) return 0;
150965e6b0ddSdrh ii = (int)(pNew - pCur->aPoint) + 1;
151004bd2c83Sdrh assert( ii==1 );
151104bd2c83Sdrh if( ALWAYS(ii<RTREE_CACHE_SZ) ){
151265e6b0ddSdrh assert( pCur->aNode[ii]==0 );
151365e6b0ddSdrh pCur->aNode[ii] = pCur->aNode[0];
151465e6b0ddSdrh }else{
151565e6b0ddSdrh nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
151665e6b0ddSdrh }
151765e6b0ddSdrh pCur->aNode[0] = 0;
151865e6b0ddSdrh *pNew = pCur->sPoint;
151965e6b0ddSdrh }
152065e6b0ddSdrh pCur->sPoint.rScore = rScore;
152165e6b0ddSdrh pCur->sPoint.iLevel = iLevel;
152265e6b0ddSdrh pCur->bPoint = 1;
152365e6b0ddSdrh return &pCur->sPoint;
152465e6b0ddSdrh }else{
152565e6b0ddSdrh return rtreeEnqueue(pCur, rScore, iLevel);
152665e6b0ddSdrh }
152765e6b0ddSdrh }
152865e6b0ddSdrh
152965e6b0ddSdrh #if 0
153065e6b0ddSdrh /* Tracing routines for the RtreeSearchPoint queue */
153165e6b0ddSdrh static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
153265e6b0ddSdrh if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
153365e6b0ddSdrh printf(" %d.%05lld.%02d %g %d",
153465e6b0ddSdrh p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
153565e6b0ddSdrh );
153665e6b0ddSdrh idx++;
153765e6b0ddSdrh if( idx<RTREE_CACHE_SZ ){
153865e6b0ddSdrh printf(" %p\n", pCur->aNode[idx]);
153965e6b0ddSdrh }else{
154065e6b0ddSdrh printf("\n");
154165e6b0ddSdrh }
154265e6b0ddSdrh }
154365e6b0ddSdrh static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
154465e6b0ddSdrh int ii;
154565e6b0ddSdrh printf("=== %9s ", zPrefix);
154665e6b0ddSdrh if( pCur->bPoint ){
154765e6b0ddSdrh tracePoint(&pCur->sPoint, -1, pCur);
154865e6b0ddSdrh }
154965e6b0ddSdrh for(ii=0; ii<pCur->nPoint; ii++){
155065e6b0ddSdrh if( ii>0 || pCur->bPoint ) printf(" ");
155165e6b0ddSdrh tracePoint(&pCur->aPoint[ii], ii, pCur);
155265e6b0ddSdrh }
155365e6b0ddSdrh }
155465e6b0ddSdrh # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
155565e6b0ddSdrh #else
155665e6b0ddSdrh # define RTREE_QUEUE_TRACE(A,B) /* no-op */
155765e6b0ddSdrh #endif
155865e6b0ddSdrh
155965e6b0ddSdrh /* Remove the search point with the lowest current score.
156065e6b0ddSdrh */
rtreeSearchPointPop(RtreeCursor * p)156165e6b0ddSdrh static void rtreeSearchPointPop(RtreeCursor *p){
156265e6b0ddSdrh int i, j, k, n;
156365e6b0ddSdrh i = 1 - p->bPoint;
156465e6b0ddSdrh assert( i==0 || i==1 );
156565e6b0ddSdrh if( p->aNode[i] ){
156665e6b0ddSdrh nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
156765e6b0ddSdrh p->aNode[i] = 0;
156865e6b0ddSdrh }
156965e6b0ddSdrh if( p->bPoint ){
157065e6b0ddSdrh p->anQueue[p->sPoint.iLevel]--;
157165e6b0ddSdrh p->bPoint = 0;
157204bd2c83Sdrh }else if( ALWAYS(p->nPoint) ){
157365e6b0ddSdrh p->anQueue[p->aPoint[0].iLevel]--;
157465e6b0ddSdrh n = --p->nPoint;
157565e6b0ddSdrh p->aPoint[0] = p->aPoint[n];
157665e6b0ddSdrh if( n<RTREE_CACHE_SZ-1 ){
157765e6b0ddSdrh p->aNode[1] = p->aNode[n+1];
157865e6b0ddSdrh p->aNode[n+1] = 0;
157965e6b0ddSdrh }
158065e6b0ddSdrh i = 0;
158165e6b0ddSdrh while( (j = i*2+1)<n ){
158265e6b0ddSdrh k = j+1;
158365e6b0ddSdrh if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
158465e6b0ddSdrh if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
158565e6b0ddSdrh rtreeSearchPointSwap(p, i, k);
158665e6b0ddSdrh i = k;
158765e6b0ddSdrh }else{
158865e6b0ddSdrh break;
158965e6b0ddSdrh }
159065e6b0ddSdrh }else{
159165e6b0ddSdrh if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
159265e6b0ddSdrh rtreeSearchPointSwap(p, i, j);
159365e6b0ddSdrh i = j;
159465e6b0ddSdrh }else{
159565e6b0ddSdrh break;
159665e6b0ddSdrh }
159765e6b0ddSdrh }
159865e6b0ddSdrh }
159965e6b0ddSdrh }
160065e6b0ddSdrh }
160165e6b0ddSdrh
160265e6b0ddSdrh
160365e6b0ddSdrh /*
160465e6b0ddSdrh ** Continue the search on cursor pCur until the front of the queue
160565e6b0ddSdrh ** contains an entry suitable for returning as a result-set row,
160665e6b0ddSdrh ** or until the RtreeSearchPoint queue is empty, indicating that the
160765e6b0ddSdrh ** query has completed.
160865e6b0ddSdrh */
rtreeStepToLeaf(RtreeCursor * pCur)160965e6b0ddSdrh static int rtreeStepToLeaf(RtreeCursor *pCur){
161065e6b0ddSdrh RtreeSearchPoint *p;
161165e6b0ddSdrh Rtree *pRtree = RTREE_OF_CURSOR(pCur);
161265e6b0ddSdrh RtreeNode *pNode;
161365e6b0ddSdrh int eWithin;
161465e6b0ddSdrh int rc = SQLITE_OK;
161565e6b0ddSdrh int nCell;
161665e6b0ddSdrh int nConstraint = pCur->nConstraint;
161765e6b0ddSdrh int ii;
161865e6b0ddSdrh int eInt;
161965e6b0ddSdrh RtreeSearchPoint x;
162065e6b0ddSdrh
162165e6b0ddSdrh eInt = pRtree->eCoordType==RTREE_COORD_INT32;
162265e6b0ddSdrh while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
1623bcb0e64cSdrh u8 *pCellData;
162465e6b0ddSdrh pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
162565e6b0ddSdrh if( rc ) return rc;
162665e6b0ddSdrh nCell = NCELL(pNode);
162765e6b0ddSdrh assert( nCell<200 );
1628bcb0e64cSdrh pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
162965e6b0ddSdrh while( p->iCell<nCell ){
163065e6b0ddSdrh sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
163165e6b0ddSdrh eWithin = FULLY_WITHIN;
163265e6b0ddSdrh for(ii=0; ii<nConstraint; ii++){
163365e6b0ddSdrh RtreeConstraint *pConstraint = pCur->aConstraint + ii;
163465e6b0ddSdrh if( pConstraint->op>=RTREE_MATCH ){
163565e6b0ddSdrh rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
163665e6b0ddSdrh &rScore, &eWithin);
163765e6b0ddSdrh if( rc ) return rc;
163865e6b0ddSdrh }else if( p->iLevel==1 ){
163965e6b0ddSdrh rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
164065e6b0ddSdrh }else{
164165e6b0ddSdrh rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
164265e6b0ddSdrh }
1643bcb0e64cSdrh if( eWithin==NOT_WITHIN ){
164465e6b0ddSdrh p->iCell++;
1645bcb0e64cSdrh pCellData += pRtree->nBytesPerCell;
1646bcb0e64cSdrh break;
1647bcb0e64cSdrh }
1648bcb0e64cSdrh }
164965e6b0ddSdrh if( eWithin==NOT_WITHIN ) continue;
1650bcb0e64cSdrh p->iCell++;
165165e6b0ddSdrh x.iLevel = p->iLevel - 1;
165265e6b0ddSdrh if( x.iLevel ){
165365e6b0ddSdrh x.id = readInt64(pCellData);
16547fc296aaSdrh for(ii=0; ii<pCur->nPoint; ii++){
16557fc296aaSdrh if( pCur->aPoint[ii].id==x.id ){
16567fc296aaSdrh RTREE_IS_CORRUPT(pRtree);
16577fc296aaSdrh return SQLITE_CORRUPT_VTAB;
16587fc296aaSdrh }
16597fc296aaSdrh }
166065e6b0ddSdrh x.iCell = 0;
166165e6b0ddSdrh }else{
166265e6b0ddSdrh x.id = p->id;
166365e6b0ddSdrh x.iCell = p->iCell - 1;
166465e6b0ddSdrh }
166565e6b0ddSdrh if( p->iCell>=nCell ){
166665e6b0ddSdrh RTREE_QUEUE_TRACE(pCur, "POP-S:");
166765e6b0ddSdrh rtreeSearchPointPop(pCur);
166865e6b0ddSdrh }
166965e6b0ddSdrh if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
167065e6b0ddSdrh p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
167165e6b0ddSdrh if( p==0 ) return SQLITE_NOMEM;
16722e525322Smistachkin p->eWithin = (u8)eWithin;
167365e6b0ddSdrh p->id = x.id;
167465e6b0ddSdrh p->iCell = x.iCell;
167565e6b0ddSdrh RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
167665e6b0ddSdrh break;
167765e6b0ddSdrh }
167865e6b0ddSdrh if( p->iCell>=nCell ){
167965e6b0ddSdrh RTREE_QUEUE_TRACE(pCur, "POP-Se:");
168065e6b0ddSdrh rtreeSearchPointPop(pCur);
168165e6b0ddSdrh }
168265e6b0ddSdrh }
168365e6b0ddSdrh pCur->atEOF = p==0;
168465e6b0ddSdrh return SQLITE_OK;
168565e6b0ddSdrh }
168665e6b0ddSdrh
168765e6b0ddSdrh /*
1688ebaecc14Sdanielk1977 ** Rtree virtual table module xNext method.
1689ebaecc14Sdanielk1977 */
rtreeNext(sqlite3_vtab_cursor * pVtabCursor)1690ebaecc14Sdanielk1977 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
1691ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1692ebaecc14Sdanielk1977 int rc = SQLITE_OK;
1693ebaecc14Sdanielk1977
1694ebaecc14Sdanielk1977 /* Move to the next entry that matches the configured constraints. */
169565e6b0ddSdrh RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
1696e2971965Sdrh if( pCsr->bAuxValid ){
1697e2971965Sdrh pCsr->bAuxValid = 0;
1698e2971965Sdrh sqlite3_reset(pCsr->pReadAux);
1699e2971965Sdrh }
170065e6b0ddSdrh rtreeSearchPointPop(pCsr);
170165e6b0ddSdrh rc = rtreeStepToLeaf(pCsr);
1702ebaecc14Sdanielk1977 return rc;
1703ebaecc14Sdanielk1977 }
1704ebaecc14Sdanielk1977
1705ebaecc14Sdanielk1977 /*
1706ebaecc14Sdanielk1977 ** Rtree virtual table module xRowid method.
1707ebaecc14Sdanielk1977 */
rtreeRowid(sqlite3_vtab_cursor * pVtabCursor,sqlite_int64 * pRowid)1708ebaecc14Sdanielk1977 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
1709ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
171065e6b0ddSdrh RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
171165e6b0ddSdrh int rc = SQLITE_OK;
171265e6b0ddSdrh RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
17135f9c7ba9Sdrh if( rc==SQLITE_OK && ALWAYS(p) ){
171465e6b0ddSdrh *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
171565e6b0ddSdrh }
171665e6b0ddSdrh return rc;
1717ebaecc14Sdanielk1977 }
1718ebaecc14Sdanielk1977
1719ebaecc14Sdanielk1977 /*
1720ebaecc14Sdanielk1977 ** Rtree virtual table module xColumn method.
1721ebaecc14Sdanielk1977 */
rtreeColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)1722ebaecc14Sdanielk1977 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
1723ebaecc14Sdanielk1977 Rtree *pRtree = (Rtree *)cur->pVtab;
1724ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)cur;
172565e6b0ddSdrh RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
17263ddb5a51Sdanielk1977 RtreeCoord c;
172765e6b0ddSdrh int rc = SQLITE_OK;
172865e6b0ddSdrh RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
172965e6b0ddSdrh
17301e76c22bSdrh if( rc ) return rc;
17315f9c7ba9Sdrh if( NEVER(p==0) ) return SQLITE_OK;
173265e6b0ddSdrh if( i==0 ){
173365e6b0ddSdrh sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
1734e2971965Sdrh }else if( i<=pRtree->nDim2 ){
173565e6b0ddSdrh nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
1736f439fbdaSdrh #ifndef SQLITE_RTREE_INT_ONLY
17373ddb5a51Sdanielk1977 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
17383ddb5a51Sdanielk1977 sqlite3_result_double(ctx, c.f);
1739f439fbdaSdrh }else
1740f439fbdaSdrh #endif
1741f439fbdaSdrh {
17423ddb5a51Sdanielk1977 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
17433ddb5a51Sdanielk1977 sqlite3_result_int(ctx, c.i);
17443ddb5a51Sdanielk1977 }
1745e2971965Sdrh }else{
1746e2971965Sdrh if( !pCsr->bAuxValid ){
1747e2971965Sdrh if( pCsr->pReadAux==0 ){
1748e2971965Sdrh rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
1749e2971965Sdrh &pCsr->pReadAux, 0);
1750e2971965Sdrh if( rc ) return rc;
1751e2971965Sdrh }
1752e2971965Sdrh sqlite3_bind_int64(pCsr->pReadAux, 1,
1753e2971965Sdrh nodeGetRowid(pRtree, pNode, p->iCell));
1754e2971965Sdrh rc = sqlite3_step(pCsr->pReadAux);
1755e2971965Sdrh if( rc==SQLITE_ROW ){
1756e2971965Sdrh pCsr->bAuxValid = 1;
1757e2971965Sdrh }else{
1758e2971965Sdrh sqlite3_reset(pCsr->pReadAux);
1759e2971965Sdrh if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1760e2971965Sdrh return rc;
1761e2971965Sdrh }
1762e2971965Sdrh }
1763e2971965Sdrh sqlite3_result_value(ctx,
1764e2971965Sdrh sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
1765ebaecc14Sdanielk1977 }
1766ebaecc14Sdanielk1977 return SQLITE_OK;
1767ebaecc14Sdanielk1977 }
1768ebaecc14Sdanielk1977
1769ebaecc14Sdanielk1977 /*
1770ebaecc14Sdanielk1977 ** Use nodeAcquire() to obtain the leaf node containing the record with
1771ebaecc14Sdanielk1977 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
1772ebaecc14Sdanielk1977 ** return SQLITE_OK. If there is no such record in the table, set
1773ebaecc14Sdanielk1977 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
1774ebaecc14Sdanielk1977 ** to zero and return an SQLite error code.
1775ebaecc14Sdanielk1977 */
findLeafNode(Rtree * pRtree,i64 iRowid,RtreeNode ** ppLeaf,sqlite3_int64 * piNode)177665e6b0ddSdrh static int findLeafNode(
177765e6b0ddSdrh Rtree *pRtree, /* RTree to search */
177865e6b0ddSdrh i64 iRowid, /* The rowid searching for */
177965e6b0ddSdrh RtreeNode **ppLeaf, /* Write the node here */
178065e6b0ddSdrh sqlite3_int64 *piNode /* Write the node-id here */
178165e6b0ddSdrh ){
1782ebaecc14Sdanielk1977 int rc;
1783ebaecc14Sdanielk1977 *ppLeaf = 0;
1784ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
1785ebaecc14Sdanielk1977 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
1786ebaecc14Sdanielk1977 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
178765e6b0ddSdrh if( piNode ) *piNode = iNode;
1788ebaecc14Sdanielk1977 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
1789ebaecc14Sdanielk1977 sqlite3_reset(pRtree->pReadRowid);
1790ebaecc14Sdanielk1977 }else{
1791ebaecc14Sdanielk1977 rc = sqlite3_reset(pRtree->pReadRowid);
1792ebaecc14Sdanielk1977 }
1793ebaecc14Sdanielk1977 return rc;
1794ebaecc14Sdanielk1977 }
1795ebaecc14Sdanielk1977
17969508daa9Sdan /*
17979508daa9Sdan ** This function is called to configure the RtreeConstraint object passed
17989508daa9Sdan ** as the second argument for a MATCH constraint. The value passed as the
17999508daa9Sdan ** first argument to this function is the right-hand operand to the MATCH
18009508daa9Sdan ** operator.
18019508daa9Sdan */
deserializeGeometry(sqlite3_value * pValue,RtreeConstraint * pCons)18029508daa9Sdan static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
180322930062Sdrh RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
180465e6b0ddSdrh sqlite3_rtree_query_info *pInfo; /* Callback information */
18059508daa9Sdan
180622930062Sdrh pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
180722930062Sdrh if( pSrc==0 ) return SQLITE_ERROR;
180822930062Sdrh pInfo = (sqlite3_rtree_query_info*)
180922930062Sdrh sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
181065e6b0ddSdrh if( !pInfo ) return SQLITE_NOMEM;
181165e6b0ddSdrh memset(pInfo, 0, sizeof(*pInfo));
181265e6b0ddSdrh pBlob = (RtreeMatchArg*)&pInfo[1];
181322930062Sdrh memcpy(pBlob, pSrc, pSrc->iSize);
181465e6b0ddSdrh pInfo->pContext = pBlob->cb.pContext;
181565e6b0ddSdrh pInfo->nParam = pBlob->nParam;
181665e6b0ddSdrh pInfo->aParam = pBlob->aParam;
18174f03f413Sdrh pInfo->apSqlParam = pBlob->apSqlParam;
18189508daa9Sdan
181965e6b0ddSdrh if( pBlob->cb.xGeom ){
182065e6b0ddSdrh pCons->u.xGeom = pBlob->cb.xGeom;
182165e6b0ddSdrh }else{
182265e6b0ddSdrh pCons->op = RTREE_QUERY;
182365e6b0ddSdrh pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
182465e6b0ddSdrh }
182565e6b0ddSdrh pCons->pInfo = pInfo;
18269508daa9Sdan return SQLITE_OK;
18279508daa9Sdan }
1828ebaecc14Sdanielk1977
1829ebaecc14Sdanielk1977 /*
1830ebaecc14Sdanielk1977 ** Rtree virtual table module xFilter method.
1831ebaecc14Sdanielk1977 */
rtreeFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStr,int argc,sqlite3_value ** argv)1832ebaecc14Sdanielk1977 static int rtreeFilter(
1833ebaecc14Sdanielk1977 sqlite3_vtab_cursor *pVtabCursor,
1834ebaecc14Sdanielk1977 int idxNum, const char *idxStr,
1835ebaecc14Sdanielk1977 int argc, sqlite3_value **argv
1836ebaecc14Sdanielk1977 ){
1837ebaecc14Sdanielk1977 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
1838ebaecc14Sdanielk1977 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
1839ebaecc14Sdanielk1977 RtreeNode *pRoot = 0;
1840ebaecc14Sdanielk1977 int ii;
1841ebaecc14Sdanielk1977 int rc = SQLITE_OK;
184265e6b0ddSdrh int iCell = 0;
1843ebaecc14Sdanielk1977
1844ebaecc14Sdanielk1977 rtreeReference(pRtree);
1845ebaecc14Sdanielk1977
184657ff60b1Sdan /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
18475f0dfc00Sdrh resetCursor(pCsr);
1848ebaecc14Sdanielk1977
184957ff60b1Sdan pCsr->iStrategy = idxNum;
1850ebaecc14Sdanielk1977 if( idxNum==1 ){
1851ebaecc14Sdanielk1977 /* Special case - lookup by rowid. */
1852ebaecc14Sdanielk1977 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
18532e5c5052Sdrh RtreeSearchPoint *p; /* Search point for the leaf */
1854ebaecc14Sdanielk1977 i64 iRowid = sqlite3_value_int64(argv[0]);
185565e6b0ddSdrh i64 iNode = 0;
1856348d7f64Sdrh int eType = sqlite3_value_numeric_type(argv[0]);
1857348d7f64Sdrh if( eType==SQLITE_INTEGER
1858348d7f64Sdrh || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)
1859348d7f64Sdrh ){
186065e6b0ddSdrh rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
1861348d7f64Sdrh }else{
1862348d7f64Sdrh rc = SQLITE_OK;
1863348d7f64Sdrh pLeaf = 0;
1864348d7f64Sdrh }
186565e6b0ddSdrh if( rc==SQLITE_OK && pLeaf!=0 ){
186665e6b0ddSdrh p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
186765e6b0ddSdrh assert( p!=0 ); /* Always returns pCsr->sPoint */
186865e6b0ddSdrh pCsr->aNode[0] = pLeaf;
186965e6b0ddSdrh p->id = iNode;
187065e6b0ddSdrh p->eWithin = PARTLY_WITHIN;
187165e6b0ddSdrh rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
18722e525322Smistachkin p->iCell = (u8)iCell;
187365e6b0ddSdrh RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
187465e6b0ddSdrh }else{
187565e6b0ddSdrh pCsr->atEOF = 1;
1876ebaecc14Sdanielk1977 }
1877ebaecc14Sdanielk1977 }else{
1878ebaecc14Sdanielk1977 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
1879ebaecc14Sdanielk1977 ** with the configured constraints.
1880ebaecc14Sdanielk1977 */
188165e6b0ddSdrh rc = nodeAcquire(pRtree, 1, 0, &pRoot);
188265e6b0ddSdrh if( rc==SQLITE_OK && argc>0 ){
18832d77d80aSdrh pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
1884ebaecc14Sdanielk1977 pCsr->nConstraint = argc;
1885ebaecc14Sdanielk1977 if( !pCsr->aConstraint ){
1886ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
1887ebaecc14Sdanielk1977 }else{
18889508daa9Sdan memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
188965e6b0ddSdrh memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
1890086e4913Sdrh assert( (idxStr==0 && argc==0)
1891086e4913Sdrh || (idxStr && (int)strlen(idxStr)==argc*2) );
1892ebaecc14Sdanielk1977 for(ii=0; ii<argc; ii++){
1893ebaecc14Sdanielk1977 RtreeConstraint *p = &pCsr->aConstraint[ii];
1894e5748a55Sdrh int eType = sqlite3_value_numeric_type(argv[ii]);
1895ebaecc14Sdanielk1977 p->op = idxStr[ii*2];
189665e6b0ddSdrh p->iCoord = idxStr[ii*2+1]-'0';
189765e6b0ddSdrh if( p->op>=RTREE_MATCH ){
18989508daa9Sdan /* A MATCH operator. The right-hand-side must be a blob that
18999977edc7Sdan ** can be cast into an RtreeMatchArg object. One created using
19009508daa9Sdan ** an sqlite3_rtree_geometry_callback() SQL user function.
19019508daa9Sdan */
19029508daa9Sdan rc = deserializeGeometry(argv[ii], p);
19039508daa9Sdan if( rc!=SQLITE_OK ){
19049508daa9Sdan break;
19059508daa9Sdan }
19060e6f67b7Sdrh p->pInfo->nCoord = pRtree->nDim2;
190765e6b0ddSdrh p->pInfo->anQueue = pCsr->anQueue;
190865e6b0ddSdrh p->pInfo->mxLevel = pRtree->iDepth + 1;
1909674a9b34Sdrh }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
1910f439fbdaSdrh #ifdef SQLITE_RTREE_INT_ONLY
191165e6b0ddSdrh p->u.rValue = sqlite3_value_int64(argv[ii]);
1912f439fbdaSdrh #else
191365e6b0ddSdrh p->u.rValue = sqlite3_value_double(argv[ii]);
1914f439fbdaSdrh #endif
1915674a9b34Sdrh }else{
1916674a9b34Sdrh p->u.rValue = RTREE_ZERO;
1917674a9b34Sdrh if( eType==SQLITE_NULL ){
1918674a9b34Sdrh p->op = RTREE_FALSE;
1919674a9b34Sdrh }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
1920674a9b34Sdrh p->op = RTREE_TRUE;
1921674a9b34Sdrh }else{
1922674a9b34Sdrh p->op = RTREE_FALSE;
1923674a9b34Sdrh }
1924ebaecc14Sdanielk1977 }
1925ebaecc14Sdanielk1977 }
1926ebaecc14Sdanielk1977 }
19279508daa9Sdan }
192865e6b0ddSdrh if( rc==SQLITE_OK ){
192965e6b0ddSdrh RtreeSearchPoint *pNew;
1930eb56e290Sdrh assert( pCsr->bPoint==0 ); /* Due to the resetCursor() call above */
19312e525322Smistachkin pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
1932eb56e290Sdrh if( NEVER(pNew==0) ){ /* Because pCsr->bPoint was FALSE */
1933eb56e290Sdrh return SQLITE_NOMEM;
1934eb56e290Sdrh }
193565e6b0ddSdrh pNew->id = 1;
193665e6b0ddSdrh pNew->iCell = 0;
193765e6b0ddSdrh pNew->eWithin = PARTLY_WITHIN;
193865e6b0ddSdrh assert( pCsr->bPoint==1 );
193965e6b0ddSdrh pCsr->aNode[0] = pRoot;
194065e6b0ddSdrh pRoot = 0;
194165e6b0ddSdrh RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
194265e6b0ddSdrh rc = rtreeStepToLeaf(pCsr);
194365e6b0ddSdrh }
194465e6b0ddSdrh }
1945ebaecc14Sdanielk1977
1946ebaecc14Sdanielk1977 nodeRelease(pRtree, pRoot);
1947ebaecc14Sdanielk1977 rtreeRelease(pRtree);
1948ebaecc14Sdanielk1977 return rc;
1949ebaecc14Sdanielk1977 }
1950ebaecc14Sdanielk1977
1951ebaecc14Sdanielk1977 /*
1952ebaecc14Sdanielk1977 ** Rtree virtual table module xBestIndex method. There are three
1953ebaecc14Sdanielk1977 ** table scan strategies to choose from (in order from most to
1954ebaecc14Sdanielk1977 ** least desirable):
1955ebaecc14Sdanielk1977 **
1956ebaecc14Sdanielk1977 ** idxNum idxStr Strategy
1957ebaecc14Sdanielk1977 ** ------------------------------------------------
1958ebaecc14Sdanielk1977 ** 1 Unused Direct lookup by rowid.
1959036391f7Sdan ** 2 See below R-tree query or full-table scan.
1960ebaecc14Sdanielk1977 ** ------------------------------------------------
1961ebaecc14Sdanielk1977 **
1962036391f7Sdan ** If strategy 1 is used, then idxStr is not meaningful. If strategy
1963ebaecc14Sdanielk1977 ** 2 is used, idxStr is formatted to contain 2 bytes for each
1964ebaecc14Sdanielk1977 ** constraint used. The first two bytes of idxStr correspond to
1965ebaecc14Sdanielk1977 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
1966ebaecc14Sdanielk1977 ** (argvIndex==1) etc.
1967ebaecc14Sdanielk1977 **
1968ebaecc14Sdanielk1977 ** The first of each pair of bytes in idxStr identifies the constraint
1969ebaecc14Sdanielk1977 ** operator as follows:
1970ebaecc14Sdanielk1977 **
1971ebaecc14Sdanielk1977 ** Operator Byte Value
1972ebaecc14Sdanielk1977 ** ----------------------
1973ebaecc14Sdanielk1977 ** = 0x41 ('A')
1974ebaecc14Sdanielk1977 ** <= 0x42 ('B')
1975ebaecc14Sdanielk1977 ** < 0x43 ('C')
1976ebaecc14Sdanielk1977 ** >= 0x44 ('D')
1977ebaecc14Sdanielk1977 ** > 0x45 ('E')
19789508daa9Sdan ** MATCH 0x46 ('F')
1979ebaecc14Sdanielk1977 ** ----------------------
1980ebaecc14Sdanielk1977 **
1981ebaecc14Sdanielk1977 ** The second of each pair of bytes identifies the coordinate column
1982ebaecc14Sdanielk1977 ** to which the constraint applies. The leftmost coordinate column
1983ebaecc14Sdanielk1977 ** is 'a', the second from the left 'b' etc.
1984ebaecc14Sdanielk1977 */
rtreeBestIndex(sqlite3_vtab * tab,sqlite3_index_info * pIdxInfo)1985ebaecc14Sdanielk1977 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
1986a9f5815bSdan Rtree *pRtree = (Rtree*)tab;
1987ebaecc14Sdanielk1977 int rc = SQLITE_OK;
19888ad5c949Sdan int ii;
19896b76418eSdan int bMatch = 0; /* True if there exists a MATCH constraint */
1990a9f5815bSdan i64 nRow; /* Estimated rows returned by this scan */
1991ebaecc14Sdanielk1977
1992ebaecc14Sdanielk1977 int iIdx = 0;
19934b4f7801Sdrh char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
19944b4f7801Sdrh memset(zIdxStr, 0, sizeof(zIdxStr));
1995ebaecc14Sdanielk1977
19966b76418eSdan /* Check if there exists a MATCH constraint - even an unusable one. If there
19976b76418eSdan ** is, do not consider the lookup-by-rowid plan as using such a plan would
19986b76418eSdan ** require the VDBE to evaluate the MATCH constraint, which is not currently
19996b76418eSdan ** possible. */
20006b76418eSdan for(ii=0; ii<pIdxInfo->nConstraint; ii++){
20016b76418eSdan if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
20026b76418eSdan bMatch = 1;
20036b76418eSdan }
20046b76418eSdan }
20056b76418eSdan
2006ebaecc14Sdanielk1977 assert( pIdxInfo->idxStr==0 );
2007fcd71b60Sdrh for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
2008ebaecc14Sdanielk1977 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
2009ebaecc14Sdanielk1977
20106b76418eSdan if( bMatch==0 && p->usable
20118038cb99Sdrh && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
20126b76418eSdan ){
2013ebaecc14Sdanielk1977 /* We have an equality constraint on the rowid. Use strategy 1. */
2014ebaecc14Sdanielk1977 int jj;
2015ebaecc14Sdanielk1977 for(jj=0; jj<ii; jj++){
2016ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
2017ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[jj].omit = 0;
2018ebaecc14Sdanielk1977 }
2019ebaecc14Sdanielk1977 pIdxInfo->idxNum = 1;
2020ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
2021ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[jj].omit = 1;
2022865d4d42Sdanielk1977
2023865d4d42Sdanielk1977 /* This strategy involves a two rowid lookups on an B-Tree structures
2024865d4d42Sdanielk1977 ** and then a linear search of an R-Tree node. This should be
2025865d4d42Sdanielk1977 ** considered almost as quick as a direct rowid lookup (for which
2026a9f5815bSdan ** sqlite uses an internal cost of 0.0). It is expected to return
2027a9f5815bSdan ** a single row.
2028865d4d42Sdanielk1977 */
2029a9f5815bSdan pIdxInfo->estimatedCost = 30.0;
203004128aceSdrh pIdxInfo->estimatedRows = 1;
2031338e311aSdrh pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
2032ebaecc14Sdanielk1977 return SQLITE_OK;
2033ebaecc14Sdanielk1977 }
2034ebaecc14Sdanielk1977
20357578456cSdrh if( p->usable
20367578456cSdrh && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
20377578456cSdrh || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
20387578456cSdrh ){
20398ad5c949Sdan u8 op;
2040ebaecc14Sdanielk1977 switch( p->op ){
2041ebaecc14Sdanielk1977 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
2042ebaecc14Sdanielk1977 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
2043ebaecc14Sdanielk1977 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
2044ebaecc14Sdanielk1977 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
2045ebaecc14Sdanielk1977 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
20461429eca9Sdrh case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
20471429eca9Sdrh default: op = 0; break;
2048ebaecc14Sdanielk1977 }
20491429eca9Sdrh if( op ){
2050ebaecc14Sdanielk1977 zIdxStr[iIdx++] = op;
20512e525322Smistachkin zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
2052ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
2053ebaecc14Sdanielk1977 pIdxInfo->aConstraintUsage[ii].omit = 1;
2054ebaecc14Sdanielk1977 }
2055ebaecc14Sdanielk1977 }
20561429eca9Sdrh }
2057ebaecc14Sdanielk1977
2058ebaecc14Sdanielk1977 pIdxInfo->idxNum = 2;
2059ebaecc14Sdanielk1977 pIdxInfo->needToFreeIdxStr = 1;
2060ebaecc14Sdanielk1977 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
2061ebaecc14Sdanielk1977 return SQLITE_NOMEM;
2062ebaecc14Sdanielk1977 }
2063a9f5815bSdan
20642ea74dc8Sdrh nRow = pRtree->nRowEst >> (iIdx/2);
2065a9f5815bSdan pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
206604128aceSdrh pIdxInfo->estimatedRows = nRow;
2067a9f5815bSdan
2068ebaecc14Sdanielk1977 return rc;
2069ebaecc14Sdanielk1977 }
2070ebaecc14Sdanielk1977
2071ebaecc14Sdanielk1977 /*
2072ebaecc14Sdanielk1977 ** Return the N-dimensional volumn of the cell stored in *p.
2073ebaecc14Sdanielk1977 */
cellArea(Rtree * pRtree,RtreeCell * p)2074f439fbdaSdrh static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
20755db59b33Sdrh RtreeDValue area = (RtreeDValue)1;
20765db59b33Sdrh assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
20775db59b33Sdrh #ifndef SQLITE_RTREE_INT_ONLY
20785db59b33Sdrh if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
20795db59b33Sdrh switch( pRtree->nDim ){
20805db59b33Sdrh case 5: area = p->aCoord[9].f - p->aCoord[8].f;
20815db59b33Sdrh case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
20825db59b33Sdrh case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
20835db59b33Sdrh case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
20845db59b33Sdrh default: area *= p->aCoord[1].f - p->aCoord[0].f;
20855db59b33Sdrh }
20865db59b33Sdrh }else
20875db59b33Sdrh #endif
20885db59b33Sdrh {
20895db59b33Sdrh switch( pRtree->nDim ){
2090ed968fa4Sdrh case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
2091ed968fa4Sdrh case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
2092ed968fa4Sdrh case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
2093ed968fa4Sdrh case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
2094ed968fa4Sdrh default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
20955db59b33Sdrh }
2096ebaecc14Sdanielk1977 }
2097ebaecc14Sdanielk1977 return area;
2098ebaecc14Sdanielk1977 }
2099ebaecc14Sdanielk1977
2100ebaecc14Sdanielk1977 /*
2101ebaecc14Sdanielk1977 ** Return the margin length of cell p. The margin length is the sum
2102ebaecc14Sdanielk1977 ** of the objects size in each dimension.
2103ebaecc14Sdanielk1977 */
cellMargin(Rtree * pRtree,RtreeCell * p)2104f439fbdaSdrh static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
2105edd9bcb3Sdrh RtreeDValue margin = 0;
2106edd9bcb3Sdrh int ii = pRtree->nDim2 - 2;
2107edd9bcb3Sdrh do{
2108f439fbdaSdrh margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
2109edd9bcb3Sdrh ii -= 2;
2110edd9bcb3Sdrh }while( ii>=0 );
2111ebaecc14Sdanielk1977 return margin;
2112ebaecc14Sdanielk1977 }
2113ebaecc14Sdanielk1977
2114ebaecc14Sdanielk1977 /*
2115ebaecc14Sdanielk1977 ** Store the union of cells p1 and p2 in p1.
2116ebaecc14Sdanielk1977 */
cellUnion(Rtree * pRtree,RtreeCell * p1,RtreeCell * p2)2117ebaecc14Sdanielk1977 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
21180e6f67b7Sdrh int ii = 0;
21193ddb5a51Sdanielk1977 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
21200e6f67b7Sdrh do{
21213ddb5a51Sdanielk1977 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
21223ddb5a51Sdanielk1977 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
21230e6f67b7Sdrh ii += 2;
21240e6f67b7Sdrh }while( ii<pRtree->nDim2 );
21253ddb5a51Sdanielk1977 }else{
21260e6f67b7Sdrh do{
21273ddb5a51Sdanielk1977 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
21283ddb5a51Sdanielk1977 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
21290e6f67b7Sdrh ii += 2;
21300e6f67b7Sdrh }while( ii<pRtree->nDim2 );
2131ebaecc14Sdanielk1977 }
2132ebaecc14Sdanielk1977 }
2133ebaecc14Sdanielk1977
2134ebaecc14Sdanielk1977 /*
2135b9134e3eSdanielk1977 ** Return true if the area covered by p2 is a subset of the area covered
2136b9134e3eSdanielk1977 ** by p1. False otherwise.
2137b9134e3eSdanielk1977 */
cellContains(Rtree * pRtree,RtreeCell * p1,RtreeCell * p2)2138b9134e3eSdanielk1977 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
2139b9134e3eSdanielk1977 int ii;
2140b9134e3eSdanielk1977 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
21410e6f67b7Sdrh for(ii=0; ii<pRtree->nDim2; ii+=2){
2142b9134e3eSdanielk1977 RtreeCoord *a1 = &p1->aCoord[ii];
2143b9134e3eSdanielk1977 RtreeCoord *a2 = &p2->aCoord[ii];
2144b9134e3eSdanielk1977 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
2145b9134e3eSdanielk1977 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
2146b9134e3eSdanielk1977 ){
2147b9134e3eSdanielk1977 return 0;
2148b9134e3eSdanielk1977 }
2149b9134e3eSdanielk1977 }
2150b9134e3eSdanielk1977 return 1;
2151b9134e3eSdanielk1977 }
2152b9134e3eSdanielk1977
2153b9134e3eSdanielk1977 /*
2154ebaecc14Sdanielk1977 ** Return the amount cell p would grow by if it were unioned with pCell.
2155ebaecc14Sdanielk1977 */
cellGrowth(Rtree * pRtree,RtreeCell * p,RtreeCell * pCell)2156f439fbdaSdrh static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
2157f439fbdaSdrh RtreeDValue area;
2158ebaecc14Sdanielk1977 RtreeCell cell;
2159ebaecc14Sdanielk1977 memcpy(&cell, p, sizeof(RtreeCell));
2160ebaecc14Sdanielk1977 area = cellArea(pRtree, &cell);
2161ebaecc14Sdanielk1977 cellUnion(pRtree, &cell, pCell);
2162ebaecc14Sdanielk1977 return (cellArea(pRtree, &cell)-area);
2163ebaecc14Sdanielk1977 }
2164ebaecc14Sdanielk1977
cellOverlap(Rtree * pRtree,RtreeCell * p,RtreeCell * aCell,int nCell)2165f439fbdaSdrh static RtreeDValue cellOverlap(
2166ebaecc14Sdanielk1977 Rtree *pRtree,
2167ebaecc14Sdanielk1977 RtreeCell *p,
2168ebaecc14Sdanielk1977 RtreeCell *aCell,
216965e6b0ddSdrh int nCell
2170ebaecc14Sdanielk1977 ){
2171ebaecc14Sdanielk1977 int ii;
217265e6b0ddSdrh RtreeDValue overlap = RTREE_ZERO;
2173ebaecc14Sdanielk1977 for(ii=0; ii<nCell; ii++){
2174ebaecc14Sdanielk1977 int jj;
2175f439fbdaSdrh RtreeDValue o = (RtreeDValue)1;
21760e6f67b7Sdrh for(jj=0; jj<pRtree->nDim2; jj+=2){
2177f439fbdaSdrh RtreeDValue x1, x2;
21783ddb5a51Sdanielk1977 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
21793ddb5a51Sdanielk1977 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
2180ebaecc14Sdanielk1977 if( x2<x1 ){
218165e6b0ddSdrh o = (RtreeDValue)0;
2182ebaecc14Sdanielk1977 break;
2183ebaecc14Sdanielk1977 }else{
2184f439fbdaSdrh o = o * (x2-x1);
2185ebaecc14Sdanielk1977 }
2186ebaecc14Sdanielk1977 }
2187ebaecc14Sdanielk1977 overlap += o;
2188ebaecc14Sdanielk1977 }
2189ebaecc14Sdanielk1977 return overlap;
2190ebaecc14Sdanielk1977 }
2191ebaecc14Sdanielk1977
2192ebaecc14Sdanielk1977
2193ebaecc14Sdanielk1977 /*
2194ebaecc14Sdanielk1977 ** This function implements the ChooseLeaf algorithm from Gutman[84].
2195ebaecc14Sdanielk1977 ** ChooseSubTree in r*tree terminology.
2196ebaecc14Sdanielk1977 */
ChooseLeaf(Rtree * pRtree,RtreeCell * pCell,int iHeight,RtreeNode ** ppLeaf)2197ebaecc14Sdanielk1977 static int ChooseLeaf(
2198ebaecc14Sdanielk1977 Rtree *pRtree, /* Rtree table */
2199ebaecc14Sdanielk1977 RtreeCell *pCell, /* Cell to insert into rtree */
2200ebaecc14Sdanielk1977 int iHeight, /* Height of sub-tree rooted at pCell */
2201ebaecc14Sdanielk1977 RtreeNode **ppLeaf /* OUT: Selected leaf page */
2202ebaecc14Sdanielk1977 ){
2203ebaecc14Sdanielk1977 int rc;
2204ebaecc14Sdanielk1977 int ii;
2205468c6493Sdrh RtreeNode *pNode = 0;
2206ebaecc14Sdanielk1977 rc = nodeAcquire(pRtree, 1, 0, &pNode);
2207ebaecc14Sdanielk1977
2208ebaecc14Sdanielk1977 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
2209ebaecc14Sdanielk1977 int iCell;
2210051eb38aSdrh sqlite3_int64 iBest = 0;
2211ebaecc14Sdanielk1977
221265e6b0ddSdrh RtreeDValue fMinGrowth = RTREE_ZERO;
221365e6b0ddSdrh RtreeDValue fMinArea = RTREE_ZERO;
2214ebaecc14Sdanielk1977
2215ebaecc14Sdanielk1977 int nCell = NCELL(pNode);
2216ebaecc14Sdanielk1977 RtreeCell cell;
22177d4c94bcSdrh RtreeNode *pChild = 0;
2218ebaecc14Sdanielk1977
2219ebaecc14Sdanielk1977 RtreeCell *aCell = 0;
2220ebaecc14Sdanielk1977
2221ebaecc14Sdanielk1977 /* Select the child node which will be enlarged the least if pCell
2222ebaecc14Sdanielk1977 ** is inserted into it. Resolve ties by choosing the entry with
2223ebaecc14Sdanielk1977 ** the smallest area.
2224ebaecc14Sdanielk1977 */
2225ebaecc14Sdanielk1977 for(iCell=0; iCell<nCell; iCell++){
222692e01aafSdan int bBest = 0;
2227f439fbdaSdrh RtreeDValue growth;
2228f439fbdaSdrh RtreeDValue area;
2229ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, iCell, &cell);
2230ebaecc14Sdanielk1977 growth = cellGrowth(pRtree, &cell, pCell);
2231ebaecc14Sdanielk1977 area = cellArea(pRtree, &cell);
223292e01aafSdan if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
223392e01aafSdan bBest = 1;
223492e01aafSdan }
223592e01aafSdan if( bBest ){
2236ebaecc14Sdanielk1977 fMinGrowth = growth;
2237ebaecc14Sdanielk1977 fMinArea = area;
2238ebaecc14Sdanielk1977 iBest = cell.iRowid;
2239ebaecc14Sdanielk1977 }
2240ebaecc14Sdanielk1977 }
2241ebaecc14Sdanielk1977
2242ebaecc14Sdanielk1977 sqlite3_free(aCell);
2243ebaecc14Sdanielk1977 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
2244ebaecc14Sdanielk1977 nodeRelease(pRtree, pNode);
2245ebaecc14Sdanielk1977 pNode = pChild;
2246ebaecc14Sdanielk1977 }
2247ebaecc14Sdanielk1977
2248ebaecc14Sdanielk1977 *ppLeaf = pNode;
2249ebaecc14Sdanielk1977 return rc;
2250ebaecc14Sdanielk1977 }
2251ebaecc14Sdanielk1977
2252ebaecc14Sdanielk1977 /*
2253ebaecc14Sdanielk1977 ** A cell with the same content as pCell has just been inserted into
2254ebaecc14Sdanielk1977 ** the node pNode. This function updates the bounding box cells in
2255ebaecc14Sdanielk1977 ** all ancestor elements.
2256ebaecc14Sdanielk1977 */
AdjustTree(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell)2257b51d2fa8Sdan static int AdjustTree(
2258ebaecc14Sdanielk1977 Rtree *pRtree, /* Rtree table */
2259ebaecc14Sdanielk1977 RtreeNode *pNode, /* Adjust ancestry of this node. */
2260ebaecc14Sdanielk1977 RtreeCell *pCell /* This cell was just inserted */
2261ebaecc14Sdanielk1977 ){
2262ebaecc14Sdanielk1977 RtreeNode *p = pNode;
2263fb077f3cSdrh int cnt = 0;
2264750f2331Sdrh int rc;
2265ebaecc14Sdanielk1977 while( p->pParent ){
2266ebaecc14Sdanielk1977 RtreeNode *pParent = p->pParent;
2267b51d2fa8Sdan RtreeCell cell;
2268b51d2fa8Sdan int iCell;
2269b51d2fa8Sdan
2270750f2331Sdrh cnt++;
2271750f2331Sdrh if( NEVER(cnt>100) ){
2272750f2331Sdrh RTREE_IS_CORRUPT(pRtree);
2273750f2331Sdrh return SQLITE_CORRUPT_VTAB;
2274750f2331Sdrh }
2275750f2331Sdrh rc = nodeParentIndex(pRtree, p, &iCell);
2276750f2331Sdrh if( NEVER(rc!=SQLITE_OK) ){
2277fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
2278133d7dabSdan return SQLITE_CORRUPT_VTAB;
2279b51d2fa8Sdan }
2280ebaecc14Sdanielk1977
2281ebaecc14Sdanielk1977 nodeGetCell(pRtree, pParent, iCell, &cell);
2282b9134e3eSdanielk1977 if( !cellContains(pRtree, &cell, pCell) ){
2283ebaecc14Sdanielk1977 cellUnion(pRtree, &cell, pCell);
2284ebaecc14Sdanielk1977 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
2285ebaecc14Sdanielk1977 }
2286ebaecc14Sdanielk1977
2287ebaecc14Sdanielk1977 p = pParent;
2288ebaecc14Sdanielk1977 }
2289b51d2fa8Sdan return SQLITE_OK;
2290ebaecc14Sdanielk1977 }
2291ebaecc14Sdanielk1977
2292ebaecc14Sdanielk1977 /*
2293ebaecc14Sdanielk1977 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
2294ebaecc14Sdanielk1977 */
rowidWrite(Rtree * pRtree,sqlite3_int64 iRowid,sqlite3_int64 iNode)2295ebaecc14Sdanielk1977 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
2296ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
2297ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
2298ebaecc14Sdanielk1977 sqlite3_step(pRtree->pWriteRowid);
2299ebaecc14Sdanielk1977 return sqlite3_reset(pRtree->pWriteRowid);
2300ebaecc14Sdanielk1977 }
2301ebaecc14Sdanielk1977
2302ebaecc14Sdanielk1977 /*
2303ebaecc14Sdanielk1977 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
2304ebaecc14Sdanielk1977 */
parentWrite(Rtree * pRtree,sqlite3_int64 iNode,sqlite3_int64 iPar)2305ebaecc14Sdanielk1977 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
2306ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
2307ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
2308ebaecc14Sdanielk1977 sqlite3_step(pRtree->pWriteParent);
2309ebaecc14Sdanielk1977 return sqlite3_reset(pRtree->pWriteParent);
2310ebaecc14Sdanielk1977 }
2311ebaecc14Sdanielk1977
231258f1c8b7Sdrh static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
2313ebaecc14Sdanielk1977
2314ebaecc14Sdanielk1977
2315ebaecc14Sdanielk1977 /*
2316ebaecc14Sdanielk1977 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
2317ebaecc14Sdanielk1977 ** nIdx. The aIdx array contains the set of integers from 0 to
2318ebaecc14Sdanielk1977 ** (nIdx-1) in no particular order. This function sorts the values
2319ebaecc14Sdanielk1977 ** in aIdx according to the indexed values in aDistance. For
2320ebaecc14Sdanielk1977 ** example, assuming the inputs:
2321ebaecc14Sdanielk1977 **
2322ebaecc14Sdanielk1977 ** aIdx = { 0, 1, 2, 3 }
2323ebaecc14Sdanielk1977 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
2324ebaecc14Sdanielk1977 **
2325ebaecc14Sdanielk1977 ** this function sets the aIdx array to contain:
2326ebaecc14Sdanielk1977 **
2327ebaecc14Sdanielk1977 ** aIdx = { 0, 1, 2, 3 }
2328ebaecc14Sdanielk1977 **
2329ebaecc14Sdanielk1977 ** The aSpare array is used as temporary working space by the
2330ebaecc14Sdanielk1977 ** sorting algorithm.
2331ebaecc14Sdanielk1977 */
SortByDistance(int * aIdx,int nIdx,RtreeDValue * aDistance,int * aSpare)2332ebaecc14Sdanielk1977 static void SortByDistance(
2333ebaecc14Sdanielk1977 int *aIdx,
2334ebaecc14Sdanielk1977 int nIdx,
2335f439fbdaSdrh RtreeDValue *aDistance,
2336ebaecc14Sdanielk1977 int *aSpare
2337ebaecc14Sdanielk1977 ){
2338ebaecc14Sdanielk1977 if( nIdx>1 ){
2339ebaecc14Sdanielk1977 int iLeft = 0;
2340ebaecc14Sdanielk1977 int iRight = 0;
2341ebaecc14Sdanielk1977
2342ebaecc14Sdanielk1977 int nLeft = nIdx/2;
2343ebaecc14Sdanielk1977 int nRight = nIdx-nLeft;
2344ebaecc14Sdanielk1977 int *aLeft = aIdx;
2345ebaecc14Sdanielk1977 int *aRight = &aIdx[nLeft];
2346ebaecc14Sdanielk1977
2347ebaecc14Sdanielk1977 SortByDistance(aLeft, nLeft, aDistance, aSpare);
2348ebaecc14Sdanielk1977 SortByDistance(aRight, nRight, aDistance, aSpare);
2349ebaecc14Sdanielk1977
2350ebaecc14Sdanielk1977 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2351ebaecc14Sdanielk1977 aLeft = aSpare;
2352ebaecc14Sdanielk1977
2353ebaecc14Sdanielk1977 while( iLeft<nLeft || iRight<nRight ){
2354ebaecc14Sdanielk1977 if( iLeft==nLeft ){
2355ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aRight[iRight];
2356ebaecc14Sdanielk1977 iRight++;
2357ebaecc14Sdanielk1977 }else if( iRight==nRight ){
2358ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aLeft[iLeft];
2359ebaecc14Sdanielk1977 iLeft++;
2360ebaecc14Sdanielk1977 }else{
2361f439fbdaSdrh RtreeDValue fLeft = aDistance[aLeft[iLeft]];
2362f439fbdaSdrh RtreeDValue fRight = aDistance[aRight[iRight]];
2363ebaecc14Sdanielk1977 if( fLeft<fRight ){
2364ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aLeft[iLeft];
2365ebaecc14Sdanielk1977 iLeft++;
2366ebaecc14Sdanielk1977 }else{
2367ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aRight[iRight];
2368ebaecc14Sdanielk1977 iRight++;
2369ebaecc14Sdanielk1977 }
2370ebaecc14Sdanielk1977 }
2371ebaecc14Sdanielk1977 }
2372ebaecc14Sdanielk1977
2373ebaecc14Sdanielk1977 #if 0
2374ebaecc14Sdanielk1977 /* Check that the sort worked */
2375ebaecc14Sdanielk1977 {
2376ebaecc14Sdanielk1977 int jj;
2377ebaecc14Sdanielk1977 for(jj=1; jj<nIdx; jj++){
2378f439fbdaSdrh RtreeDValue left = aDistance[aIdx[jj-1]];
2379f439fbdaSdrh RtreeDValue right = aDistance[aIdx[jj]];
2380ebaecc14Sdanielk1977 assert( left<=right );
2381ebaecc14Sdanielk1977 }
2382ebaecc14Sdanielk1977 }
2383ebaecc14Sdanielk1977 #endif
2384ebaecc14Sdanielk1977 }
2385ebaecc14Sdanielk1977 }
2386ebaecc14Sdanielk1977
2387ebaecc14Sdanielk1977 /*
2388ebaecc14Sdanielk1977 ** Arguments aIdx, aCell and aSpare all point to arrays of size
2389ebaecc14Sdanielk1977 ** nIdx. The aIdx array contains the set of integers from 0 to
2390ebaecc14Sdanielk1977 ** (nIdx-1) in no particular order. This function sorts the values
2391ebaecc14Sdanielk1977 ** in aIdx according to dimension iDim of the cells in aCell. The
2392ebaecc14Sdanielk1977 ** minimum value of dimension iDim is considered first, the
2393ebaecc14Sdanielk1977 ** maximum used to break ties.
2394ebaecc14Sdanielk1977 **
2395ebaecc14Sdanielk1977 ** The aSpare array is used as temporary working space by the
2396ebaecc14Sdanielk1977 ** sorting algorithm.
2397ebaecc14Sdanielk1977 */
SortByDimension(Rtree * pRtree,int * aIdx,int nIdx,int iDim,RtreeCell * aCell,int * aSpare)2398ebaecc14Sdanielk1977 static void SortByDimension(
23993ddb5a51Sdanielk1977 Rtree *pRtree,
2400ebaecc14Sdanielk1977 int *aIdx,
2401ebaecc14Sdanielk1977 int nIdx,
2402ebaecc14Sdanielk1977 int iDim,
2403ebaecc14Sdanielk1977 RtreeCell *aCell,
2404ebaecc14Sdanielk1977 int *aSpare
2405ebaecc14Sdanielk1977 ){
2406ebaecc14Sdanielk1977 if( nIdx>1 ){
2407ebaecc14Sdanielk1977
2408ebaecc14Sdanielk1977 int iLeft = 0;
2409ebaecc14Sdanielk1977 int iRight = 0;
2410ebaecc14Sdanielk1977
2411ebaecc14Sdanielk1977 int nLeft = nIdx/2;
2412ebaecc14Sdanielk1977 int nRight = nIdx-nLeft;
2413ebaecc14Sdanielk1977 int *aLeft = aIdx;
2414ebaecc14Sdanielk1977 int *aRight = &aIdx[nLeft];
2415ebaecc14Sdanielk1977
24163ddb5a51Sdanielk1977 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
24173ddb5a51Sdanielk1977 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
2418ebaecc14Sdanielk1977
2419ebaecc14Sdanielk1977 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
2420ebaecc14Sdanielk1977 aLeft = aSpare;
2421ebaecc14Sdanielk1977 while( iLeft<nLeft || iRight<nRight ){
2422f439fbdaSdrh RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
2423f439fbdaSdrh RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
2424f439fbdaSdrh RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
2425f439fbdaSdrh RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
2426ebaecc14Sdanielk1977 if( (iLeft!=nLeft) && ((iRight==nRight)
2427ebaecc14Sdanielk1977 || (xleft1<xright1)
2428ebaecc14Sdanielk1977 || (xleft1==xright1 && xleft2<xright2)
2429ebaecc14Sdanielk1977 )){
2430ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aLeft[iLeft];
2431ebaecc14Sdanielk1977 iLeft++;
2432ebaecc14Sdanielk1977 }else{
2433ebaecc14Sdanielk1977 aIdx[iLeft+iRight] = aRight[iRight];
2434ebaecc14Sdanielk1977 iRight++;
2435ebaecc14Sdanielk1977 }
2436ebaecc14Sdanielk1977 }
2437ebaecc14Sdanielk1977
2438ebaecc14Sdanielk1977 #if 0
2439ebaecc14Sdanielk1977 /* Check that the sort worked */
2440ebaecc14Sdanielk1977 {
2441ebaecc14Sdanielk1977 int jj;
2442ebaecc14Sdanielk1977 for(jj=1; jj<nIdx; jj++){
2443f439fbdaSdrh RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
2444f439fbdaSdrh RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
2445f439fbdaSdrh RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
2446f439fbdaSdrh RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
2447ebaecc14Sdanielk1977 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
2448ebaecc14Sdanielk1977 }
2449ebaecc14Sdanielk1977 }
2450ebaecc14Sdanielk1977 #endif
2451ebaecc14Sdanielk1977 }
2452ebaecc14Sdanielk1977 }
2453ebaecc14Sdanielk1977
2454ebaecc14Sdanielk1977 /*
2455ebaecc14Sdanielk1977 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
2456ebaecc14Sdanielk1977 */
splitNodeStartree(Rtree * pRtree,RtreeCell * aCell,int nCell,RtreeNode * pLeft,RtreeNode * pRight,RtreeCell * pBboxLeft,RtreeCell * pBboxRight)2457ebaecc14Sdanielk1977 static int splitNodeStartree(
2458ebaecc14Sdanielk1977 Rtree *pRtree,
2459ebaecc14Sdanielk1977 RtreeCell *aCell,
2460ebaecc14Sdanielk1977 int nCell,
2461ebaecc14Sdanielk1977 RtreeNode *pLeft,
2462ebaecc14Sdanielk1977 RtreeNode *pRight,
2463ebaecc14Sdanielk1977 RtreeCell *pBboxLeft,
2464ebaecc14Sdanielk1977 RtreeCell *pBboxRight
2465ebaecc14Sdanielk1977 ){
2466ebaecc14Sdanielk1977 int **aaSorted;
2467ebaecc14Sdanielk1977 int *aSpare;
2468ebaecc14Sdanielk1977 int ii;
2469ebaecc14Sdanielk1977
2470051eb38aSdrh int iBestDim = 0;
2471051eb38aSdrh int iBestSplit = 0;
247265e6b0ddSdrh RtreeDValue fBestMargin = RTREE_ZERO;
2473ebaecc14Sdanielk1977
24742d77d80aSdrh sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
2475ebaecc14Sdanielk1977
24762d77d80aSdrh aaSorted = (int **)sqlite3_malloc64(nByte);
2477ebaecc14Sdanielk1977 if( !aaSorted ){
2478ebaecc14Sdanielk1977 return SQLITE_NOMEM;
2479ebaecc14Sdanielk1977 }
2480ebaecc14Sdanielk1977
2481ebaecc14Sdanielk1977 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
2482ebaecc14Sdanielk1977 memset(aaSorted, 0, nByte);
2483ebaecc14Sdanielk1977 for(ii=0; ii<pRtree->nDim; ii++){
2484ebaecc14Sdanielk1977 int jj;
2485ebaecc14Sdanielk1977 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
2486ebaecc14Sdanielk1977 for(jj=0; jj<nCell; jj++){
2487ebaecc14Sdanielk1977 aaSorted[ii][jj] = jj;
2488ebaecc14Sdanielk1977 }
24893ddb5a51Sdanielk1977 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
2490ebaecc14Sdanielk1977 }
2491ebaecc14Sdanielk1977
2492ebaecc14Sdanielk1977 for(ii=0; ii<pRtree->nDim; ii++){
249365e6b0ddSdrh RtreeDValue margin = RTREE_ZERO;
249465e6b0ddSdrh RtreeDValue fBestOverlap = RTREE_ZERO;
249565e6b0ddSdrh RtreeDValue fBestArea = RTREE_ZERO;
2496051eb38aSdrh int iBestLeft = 0;
2497ebaecc14Sdanielk1977 int nLeft;
2498ebaecc14Sdanielk1977
2499ebaecc14Sdanielk1977 for(
2500ebaecc14Sdanielk1977 nLeft=RTREE_MINCELLS(pRtree);
2501ebaecc14Sdanielk1977 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
2502ebaecc14Sdanielk1977 nLeft++
2503ebaecc14Sdanielk1977 ){
2504ebaecc14Sdanielk1977 RtreeCell left;
2505ebaecc14Sdanielk1977 RtreeCell right;
2506ebaecc14Sdanielk1977 int kk;
2507f439fbdaSdrh RtreeDValue overlap;
2508f439fbdaSdrh RtreeDValue area;
2509ebaecc14Sdanielk1977
2510ebaecc14Sdanielk1977 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
2511ebaecc14Sdanielk1977 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
2512ebaecc14Sdanielk1977 for(kk=1; kk<(nCell-1); kk++){
2513ebaecc14Sdanielk1977 if( kk<nLeft ){
2514ebaecc14Sdanielk1977 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
2515ebaecc14Sdanielk1977 }else{
2516ebaecc14Sdanielk1977 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
2517ebaecc14Sdanielk1977 }
2518ebaecc14Sdanielk1977 }
2519ebaecc14Sdanielk1977 margin += cellMargin(pRtree, &left);
2520ebaecc14Sdanielk1977 margin += cellMargin(pRtree, &right);
252165e6b0ddSdrh overlap = cellOverlap(pRtree, &left, &right, 1);
2522ebaecc14Sdanielk1977 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
2523ebaecc14Sdanielk1977 if( (nLeft==RTREE_MINCELLS(pRtree))
2524ebaecc14Sdanielk1977 || (overlap<fBestOverlap)
2525ebaecc14Sdanielk1977 || (overlap==fBestOverlap && area<fBestArea)
2526ebaecc14Sdanielk1977 ){
2527ebaecc14Sdanielk1977 iBestLeft = nLeft;
2528ebaecc14Sdanielk1977 fBestOverlap = overlap;
2529ebaecc14Sdanielk1977 fBestArea = area;
2530ebaecc14Sdanielk1977 }
2531ebaecc14Sdanielk1977 }
2532ebaecc14Sdanielk1977
2533ebaecc14Sdanielk1977 if( ii==0 || margin<fBestMargin ){
2534ebaecc14Sdanielk1977 iBestDim = ii;
2535ebaecc14Sdanielk1977 fBestMargin = margin;
2536ebaecc14Sdanielk1977 iBestSplit = iBestLeft;
2537ebaecc14Sdanielk1977 }
2538ebaecc14Sdanielk1977 }
2539ebaecc14Sdanielk1977
2540ebaecc14Sdanielk1977 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
2541ebaecc14Sdanielk1977 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
2542ebaecc14Sdanielk1977 for(ii=0; ii<nCell; ii++){
2543ebaecc14Sdanielk1977 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
2544ebaecc14Sdanielk1977 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
2545ebaecc14Sdanielk1977 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
2546ebaecc14Sdanielk1977 nodeInsertCell(pRtree, pTarget, pCell);
2547ebaecc14Sdanielk1977 cellUnion(pRtree, pBbox, pCell);
2548ebaecc14Sdanielk1977 }
2549ebaecc14Sdanielk1977
2550ebaecc14Sdanielk1977 sqlite3_free(aaSorted);
2551ebaecc14Sdanielk1977 return SQLITE_OK;
2552ebaecc14Sdanielk1977 }
2553ebaecc14Sdanielk1977
2554ebaecc14Sdanielk1977
updateMapping(Rtree * pRtree,i64 iRowid,RtreeNode * pNode,int iHeight)2555ebaecc14Sdanielk1977 static int updateMapping(
2556ebaecc14Sdanielk1977 Rtree *pRtree,
2557ebaecc14Sdanielk1977 i64 iRowid,
2558ebaecc14Sdanielk1977 RtreeNode *pNode,
2559ebaecc14Sdanielk1977 int iHeight
2560ebaecc14Sdanielk1977 ){
2561ebaecc14Sdanielk1977 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
2562ebaecc14Sdanielk1977 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
2563ebaecc14Sdanielk1977 if( iHeight>0 ){
2564ebaecc14Sdanielk1977 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
25654b67c655Sdan RtreeNode *p;
25664b67c655Sdan for(p=pNode; p; p=p->pParent){
25674b67c655Sdan if( p==pChild ) return SQLITE_CORRUPT_VTAB;
25684b67c655Sdan }
2569ebaecc14Sdanielk1977 if( pChild ){
2570ebaecc14Sdanielk1977 nodeRelease(pRtree, pChild->pParent);
2571ebaecc14Sdanielk1977 nodeReference(pNode);
2572ebaecc14Sdanielk1977 pChild->pParent = pNode;
2573ebaecc14Sdanielk1977 }
2574ebaecc14Sdanielk1977 }
25757d4c94bcSdrh if( NEVER(pNode==0) ) return SQLITE_ERROR;
2576ebaecc14Sdanielk1977 return xSetMapping(pRtree, iRowid, pNode->iNode);
2577ebaecc14Sdanielk1977 }
2578ebaecc14Sdanielk1977
SplitNode(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell,int iHeight)2579ebaecc14Sdanielk1977 static int SplitNode(
2580ebaecc14Sdanielk1977 Rtree *pRtree,
2581ebaecc14Sdanielk1977 RtreeNode *pNode,
2582ebaecc14Sdanielk1977 RtreeCell *pCell,
2583ebaecc14Sdanielk1977 int iHeight
2584ebaecc14Sdanielk1977 ){
2585ebaecc14Sdanielk1977 int i;
2586ebaecc14Sdanielk1977 int newCellIsRight = 0;
2587ebaecc14Sdanielk1977
2588ebaecc14Sdanielk1977 int rc = SQLITE_OK;
2589ebaecc14Sdanielk1977 int nCell = NCELL(pNode);
2590ebaecc14Sdanielk1977 RtreeCell *aCell;
2591ebaecc14Sdanielk1977 int *aiUsed;
2592ebaecc14Sdanielk1977
2593ebaecc14Sdanielk1977 RtreeNode *pLeft = 0;
2594ebaecc14Sdanielk1977 RtreeNode *pRight = 0;
2595ebaecc14Sdanielk1977
2596ebaecc14Sdanielk1977 RtreeCell leftbbox;
2597ebaecc14Sdanielk1977 RtreeCell rightbbox;
2598ebaecc14Sdanielk1977
2599ebaecc14Sdanielk1977 /* Allocate an array and populate it with a copy of pCell and
2600ebaecc14Sdanielk1977 ** all cells from node pLeft. Then zero the original node.
2601ebaecc14Sdanielk1977 */
26022d77d80aSdrh aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
2603ebaecc14Sdanielk1977 if( !aCell ){
2604ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
2605ebaecc14Sdanielk1977 goto splitnode_out;
2606ebaecc14Sdanielk1977 }
2607ebaecc14Sdanielk1977 aiUsed = (int *)&aCell[nCell+1];
2608ebaecc14Sdanielk1977 memset(aiUsed, 0, sizeof(int)*(nCell+1));
2609ebaecc14Sdanielk1977 for(i=0; i<nCell; i++){
2610ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, i, &aCell[i]);
2611ebaecc14Sdanielk1977 }
2612ebaecc14Sdanielk1977 nodeZero(pRtree, pNode);
2613ebaecc14Sdanielk1977 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
2614ebaecc14Sdanielk1977 nCell++;
2615ebaecc14Sdanielk1977
2616ebaecc14Sdanielk1977 if( pNode->iNode==1 ){
261792e01aafSdan pRight = nodeNew(pRtree, pNode);
261892e01aafSdan pLeft = nodeNew(pRtree, pNode);
2619ebaecc14Sdanielk1977 pRtree->iDepth++;
2620ebaecc14Sdanielk1977 pNode->isDirty = 1;
2621ebaecc14Sdanielk1977 writeInt16(pNode->zData, pRtree->iDepth);
2622ebaecc14Sdanielk1977 }else{
2623ebaecc14Sdanielk1977 pLeft = pNode;
262492e01aafSdan pRight = nodeNew(pRtree, pLeft->pParent);
2625c8c9cdd9Sdrh pLeft->nRef++;
2626ebaecc14Sdanielk1977 }
2627ebaecc14Sdanielk1977
2628ebaecc14Sdanielk1977 if( !pLeft || !pRight ){
2629ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
2630ebaecc14Sdanielk1977 goto splitnode_out;
2631ebaecc14Sdanielk1977 }
2632ebaecc14Sdanielk1977
2633ebaecc14Sdanielk1977 memset(pLeft->zData, 0, pRtree->iNodeSize);
2634ebaecc14Sdanielk1977 memset(pRight->zData, 0, pRtree->iNodeSize);
2635ebaecc14Sdanielk1977
263665e6b0ddSdrh rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
263765e6b0ddSdrh &leftbbox, &rightbbox);
2638ebaecc14Sdanielk1977 if( rc!=SQLITE_OK ){
2639ebaecc14Sdanielk1977 goto splitnode_out;
2640ebaecc14Sdanielk1977 }
2641ebaecc14Sdanielk1977
2642f836afd4Sdan /* Ensure both child nodes have node numbers assigned to them by calling
2643f836afd4Sdan ** nodeWrite(). Node pRight always needs a node number, as it was created
2644f836afd4Sdan ** by nodeNew() above. But node pLeft sometimes already has a node number.
2645f836afd4Sdan ** In this case avoid the all to nodeWrite().
2646f836afd4Sdan */
2647f836afd4Sdan if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
2648ebaecc14Sdanielk1977 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
2649ebaecc14Sdanielk1977 ){
2650ebaecc14Sdanielk1977 goto splitnode_out;
2651ebaecc14Sdanielk1977 }
2652ebaecc14Sdanielk1977
2653ebaecc14Sdanielk1977 rightbbox.iRowid = pRight->iNode;
2654ebaecc14Sdanielk1977 leftbbox.iRowid = pLeft->iNode;
2655ebaecc14Sdanielk1977
2656ebaecc14Sdanielk1977 if( pNode->iNode==1 ){
265758f1c8b7Sdrh rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
2658ebaecc14Sdanielk1977 if( rc!=SQLITE_OK ){
2659ebaecc14Sdanielk1977 goto splitnode_out;
2660ebaecc14Sdanielk1977 }
2661ebaecc14Sdanielk1977 }else{
2662ebaecc14Sdanielk1977 RtreeNode *pParent = pLeft->pParent;
2663b51d2fa8Sdan int iCell;
2664b51d2fa8Sdan rc = nodeParentIndex(pRtree, pLeft, &iCell);
2665750f2331Sdrh if( ALWAYS(rc==SQLITE_OK) ){
2666ebaecc14Sdanielk1977 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
2667b51d2fa8Sdan rc = AdjustTree(pRtree, pParent, &leftbbox);
2668750f2331Sdrh assert( rc==SQLITE_OK );
2669b51d2fa8Sdan }
2670750f2331Sdrh if( NEVER(rc!=SQLITE_OK) ){
2671b51d2fa8Sdan goto splitnode_out;
2672b51d2fa8Sdan }
2673ebaecc14Sdanielk1977 }
267458f1c8b7Sdrh if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
2675ebaecc14Sdanielk1977 goto splitnode_out;
2676ebaecc14Sdanielk1977 }
2677ebaecc14Sdanielk1977
2678ebaecc14Sdanielk1977 for(i=0; i<NCELL(pRight); i++){
2679ebaecc14Sdanielk1977 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
2680ebaecc14Sdanielk1977 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
2681ebaecc14Sdanielk1977 if( iRowid==pCell->iRowid ){
2682ebaecc14Sdanielk1977 newCellIsRight = 1;
2683ebaecc14Sdanielk1977 }
2684ebaecc14Sdanielk1977 if( rc!=SQLITE_OK ){
2685ebaecc14Sdanielk1977 goto splitnode_out;
2686ebaecc14Sdanielk1977 }
2687ebaecc14Sdanielk1977 }
2688ebaecc14Sdanielk1977 if( pNode->iNode==1 ){
2689ebaecc14Sdanielk1977 for(i=0; i<NCELL(pLeft); i++){
2690ebaecc14Sdanielk1977 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
2691ebaecc14Sdanielk1977 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
2692ebaecc14Sdanielk1977 if( rc!=SQLITE_OK ){
2693ebaecc14Sdanielk1977 goto splitnode_out;
2694ebaecc14Sdanielk1977 }
2695ebaecc14Sdanielk1977 }
2696ebaecc14Sdanielk1977 }else if( newCellIsRight==0 ){
2697ebaecc14Sdanielk1977 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
2698ebaecc14Sdanielk1977 }
2699ebaecc14Sdanielk1977
2700ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
2701ebaecc14Sdanielk1977 rc = nodeRelease(pRtree, pRight);
2702ebaecc14Sdanielk1977 pRight = 0;
2703ebaecc14Sdanielk1977 }
2704ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
2705ebaecc14Sdanielk1977 rc = nodeRelease(pRtree, pLeft);
2706ebaecc14Sdanielk1977 pLeft = 0;
2707ebaecc14Sdanielk1977 }
2708ebaecc14Sdanielk1977
2709ebaecc14Sdanielk1977 splitnode_out:
2710ebaecc14Sdanielk1977 nodeRelease(pRtree, pRight);
2711ebaecc14Sdanielk1977 nodeRelease(pRtree, pLeft);
2712ebaecc14Sdanielk1977 sqlite3_free(aCell);
2713ebaecc14Sdanielk1977 return rc;
2714ebaecc14Sdanielk1977 }
2715ebaecc14Sdanielk1977
27162bf19178Sdan /*
2717b51d2fa8Sdan ** If node pLeaf is not the root of the r-tree and its pParent pointer is
2718b51d2fa8Sdan ** still NULL, load all ancestor nodes of pLeaf into memory and populate
2719b51d2fa8Sdan ** the pLeaf->pParent chain all the way up to the root node.
2720af7626f5Sdan **
2721af7626f5Sdan ** This operation is required when a row is deleted (or updated - an update
2722af7626f5Sdan ** is implemented as a delete followed by an insert). SQLite provides the
2723af7626f5Sdan ** rowid of the row to delete, which can be used to find the leaf on which
2724af7626f5Sdan ** the entry resides (argument pLeaf). Once the leaf is located, this
2725af7626f5Sdan ** function is called to determine its ancestry.
27262bf19178Sdan */
fixLeafParent(Rtree * pRtree,RtreeNode * pLeaf)2727ebaecc14Sdanielk1977 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
2728ebaecc14Sdanielk1977 int rc = SQLITE_OK;
2729b51d2fa8Sdan RtreeNode *pChild = pLeaf;
2730b51d2fa8Sdan while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
2731b51d2fa8Sdan int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
2732b51d2fa8Sdan sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
2733f836afd4Sdan rc = sqlite3_step(pRtree->pReadParent);
2734f836afd4Sdan if( rc==SQLITE_ROW ){
2735af7626f5Sdan RtreeNode *pTest; /* Used to test for reference loops */
2736af7626f5Sdan i64 iNode; /* Node number of parent node */
2737af7626f5Sdan
2738af7626f5Sdan /* Before setting pChild->pParent, test that we are not creating a
2739af7626f5Sdan ** loop of references (as we would if, say, pChild==pParent). We don't
2740af7626f5Sdan ** want to do this as it leads to a memory leak when trying to delete
2741af7626f5Sdan ** the referenced counted node structures.
2742af7626f5Sdan */
2743af7626f5Sdan iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
2744b51d2fa8Sdan for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
27455f9c7ba9Sdrh if( pTest==0 ){
2746b51d2fa8Sdan rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
2747ebaecc14Sdanielk1977 }
2748f836afd4Sdan }
2749b51d2fa8Sdan rc = sqlite3_reset(pRtree->pReadParent);
2750b51d2fa8Sdan if( rc==SQLITE_OK ) rc = rc2;
2751fb077f3cSdrh if( rc==SQLITE_OK && !pChild->pParent ){
2752fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
2753fb077f3cSdrh rc = SQLITE_CORRUPT_VTAB;
2754fb077f3cSdrh }
2755b51d2fa8Sdan pChild = pChild->pParent;
2756ebaecc14Sdanielk1977 }
2757ebaecc14Sdanielk1977 return rc;
2758ebaecc14Sdanielk1977 }
2759ebaecc14Sdanielk1977
2760ebaecc14Sdanielk1977 static int deleteCell(Rtree *, RtreeNode *, int, int);
2761ebaecc14Sdanielk1977
removeNode(Rtree * pRtree,RtreeNode * pNode,int iHeight)2762ebaecc14Sdanielk1977 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
2763ebaecc14Sdanielk1977 int rc;
2764897230ebSdan int rc2;
2765051eb38aSdrh RtreeNode *pParent = 0;
2766ebaecc14Sdanielk1977 int iCell;
2767ebaecc14Sdanielk1977
2768ebaecc14Sdanielk1977 assert( pNode->nRef==1 );
2769ebaecc14Sdanielk1977
2770ebaecc14Sdanielk1977 /* Remove the entry in the parent cell. */
2771b51d2fa8Sdan rc = nodeParentIndex(pRtree, pNode, &iCell);
277286b262ecSdrh if( rc==SQLITE_OK ){
2773ebaecc14Sdanielk1977 pParent = pNode->pParent;
2774ebaecc14Sdanielk1977 pNode->pParent = 0;
2775897230ebSdan rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
2776c2f61c18Sdrh testcase( rc!=SQLITE_OK );
2777b51d2fa8Sdan }
2778897230ebSdan rc2 = nodeRelease(pRtree, pParent);
277986b262ecSdrh if( rc==SQLITE_OK ){
2780897230ebSdan rc = rc2;
2781897230ebSdan }
2782897230ebSdan if( rc!=SQLITE_OK ){
2783ebaecc14Sdanielk1977 return rc;
2784ebaecc14Sdanielk1977 }
2785ebaecc14Sdanielk1977
2786ebaecc14Sdanielk1977 /* Remove the xxx_node entry. */
2787ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
2788ebaecc14Sdanielk1977 sqlite3_step(pRtree->pDeleteNode);
2789ebaecc14Sdanielk1977 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
2790ebaecc14Sdanielk1977 return rc;
2791ebaecc14Sdanielk1977 }
2792ebaecc14Sdanielk1977
2793ebaecc14Sdanielk1977 /* Remove the xxx_parent entry. */
2794ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
2795ebaecc14Sdanielk1977 sqlite3_step(pRtree->pDeleteParent);
2796ebaecc14Sdanielk1977 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
2797ebaecc14Sdanielk1977 return rc;
2798ebaecc14Sdanielk1977 }
2799ebaecc14Sdanielk1977
2800ebaecc14Sdanielk1977 /* Remove the node from the in-memory hash table and link it into
2801ebaecc14Sdanielk1977 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
2802ebaecc14Sdanielk1977 */
2803ebaecc14Sdanielk1977 nodeHashDelete(pRtree, pNode);
2804ebaecc14Sdanielk1977 pNode->iNode = iHeight;
2805ebaecc14Sdanielk1977 pNode->pNext = pRtree->pDeleted;
2806ebaecc14Sdanielk1977 pNode->nRef++;
2807ebaecc14Sdanielk1977 pRtree->pDeleted = pNode;
2808ebaecc14Sdanielk1977
2809ebaecc14Sdanielk1977 return SQLITE_OK;
2810ebaecc14Sdanielk1977 }
2811ebaecc14Sdanielk1977
fixBoundingBox(Rtree * pRtree,RtreeNode * pNode)2812b51d2fa8Sdan static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
2813ebaecc14Sdanielk1977 RtreeNode *pParent = pNode->pParent;
2814b51d2fa8Sdan int rc = SQLITE_OK;
2815ebaecc14Sdanielk1977 if( pParent ){
2816ebaecc14Sdanielk1977 int ii;
2817ebaecc14Sdanielk1977 int nCell = NCELL(pNode);
2818ebaecc14Sdanielk1977 RtreeCell box; /* Bounding box for pNode */
2819ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, 0, &box);
2820ebaecc14Sdanielk1977 for(ii=1; ii<nCell; ii++){
2821ebaecc14Sdanielk1977 RtreeCell cell;
2822ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, ii, &cell);
2823ebaecc14Sdanielk1977 cellUnion(pRtree, &box, &cell);
2824ebaecc14Sdanielk1977 }
2825ebaecc14Sdanielk1977 box.iRowid = pNode->iNode;
2826b51d2fa8Sdan rc = nodeParentIndex(pRtree, pNode, &ii);
282789b17154Sdrh if( rc==SQLITE_OK ){
2828ebaecc14Sdanielk1977 nodeOverwriteCell(pRtree, pParent, &box, ii);
2829b51d2fa8Sdan rc = fixBoundingBox(pRtree, pParent);
2830ebaecc14Sdanielk1977 }
2831ebaecc14Sdanielk1977 }
2832b51d2fa8Sdan return rc;
2833b51d2fa8Sdan }
2834ebaecc14Sdanielk1977
2835ebaecc14Sdanielk1977 /*
2836ebaecc14Sdanielk1977 ** Delete the cell at index iCell of node pNode. After removing the
2837ebaecc14Sdanielk1977 ** cell, adjust the r-tree data structure if required.
2838ebaecc14Sdanielk1977 */
deleteCell(Rtree * pRtree,RtreeNode * pNode,int iCell,int iHeight)2839ebaecc14Sdanielk1977 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
2840c2345402Sdan RtreeNode *pParent;
2841ebaecc14Sdanielk1977 int rc;
2842ebaecc14Sdanielk1977
2843ebaecc14Sdanielk1977 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
2844ebaecc14Sdanielk1977 return rc;
2845ebaecc14Sdanielk1977 }
2846ebaecc14Sdanielk1977
2847ebaecc14Sdanielk1977 /* Remove the cell from the node. This call just moves bytes around
2848ebaecc14Sdanielk1977 ** the in-memory node image, so it cannot fail.
2849ebaecc14Sdanielk1977 */
2850ebaecc14Sdanielk1977 nodeDeleteCell(pRtree, pNode, iCell);
2851ebaecc14Sdanielk1977
2852ebaecc14Sdanielk1977 /* If the node is not the tree root and now has less than the minimum
2853ebaecc14Sdanielk1977 ** number of cells, remove it from the tree. Otherwise, update the
2854ebaecc14Sdanielk1977 ** cell in the parent node so that it tightly contains the updated
2855ebaecc14Sdanielk1977 ** node.
2856ebaecc14Sdanielk1977 */
2857c2345402Sdan pParent = pNode->pParent;
2858c2345402Sdan assert( pParent || pNode->iNode==1 );
2859c2345402Sdan if( pParent ){
2860c2345402Sdan if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
2861ebaecc14Sdanielk1977 rc = removeNode(pRtree, pNode, iHeight);
2862ebaecc14Sdanielk1977 }else{
2863b51d2fa8Sdan rc = fixBoundingBox(pRtree, pNode);
2864ebaecc14Sdanielk1977 }
2865ebaecc14Sdanielk1977 }
2866ebaecc14Sdanielk1977
2867ebaecc14Sdanielk1977 return rc;
2868ebaecc14Sdanielk1977 }
2869ebaecc14Sdanielk1977
Reinsert(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell,int iHeight)2870ebaecc14Sdanielk1977 static int Reinsert(
2871ebaecc14Sdanielk1977 Rtree *pRtree,
2872ebaecc14Sdanielk1977 RtreeNode *pNode,
2873ebaecc14Sdanielk1977 RtreeCell *pCell,
2874ebaecc14Sdanielk1977 int iHeight
2875ebaecc14Sdanielk1977 ){
2876ebaecc14Sdanielk1977 int *aOrder;
2877ebaecc14Sdanielk1977 int *aSpare;
2878ebaecc14Sdanielk1977 RtreeCell *aCell;
2879f439fbdaSdrh RtreeDValue *aDistance;
2880ebaecc14Sdanielk1977 int nCell;
2881f439fbdaSdrh RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
2882ebaecc14Sdanielk1977 int iDim;
2883ebaecc14Sdanielk1977 int ii;
2884ebaecc14Sdanielk1977 int rc = SQLITE_OK;
2885f439fbdaSdrh int n;
2886ebaecc14Sdanielk1977
2887f439fbdaSdrh memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
2888ebaecc14Sdanielk1977
2889ebaecc14Sdanielk1977 nCell = NCELL(pNode)+1;
2890f439fbdaSdrh n = (nCell+1)&(~1);
2891ebaecc14Sdanielk1977
2892ebaecc14Sdanielk1977 /* Allocate the buffers used by this operation. The allocation is
2893ebaecc14Sdanielk1977 ** relinquished before this function returns.
2894ebaecc14Sdanielk1977 */
28952d77d80aSdrh aCell = (RtreeCell *)sqlite3_malloc64(n * (
2896ebaecc14Sdanielk1977 sizeof(RtreeCell) + /* aCell array */
2897ebaecc14Sdanielk1977 sizeof(int) + /* aOrder array */
2898ebaecc14Sdanielk1977 sizeof(int) + /* aSpare array */
2899f439fbdaSdrh sizeof(RtreeDValue) /* aDistance array */
2900ebaecc14Sdanielk1977 ));
2901ebaecc14Sdanielk1977 if( !aCell ){
2902ebaecc14Sdanielk1977 return SQLITE_NOMEM;
2903ebaecc14Sdanielk1977 }
2904f439fbdaSdrh aOrder = (int *)&aCell[n];
2905f439fbdaSdrh aSpare = (int *)&aOrder[n];
2906f439fbdaSdrh aDistance = (RtreeDValue *)&aSpare[n];
2907ebaecc14Sdanielk1977
2908ebaecc14Sdanielk1977 for(ii=0; ii<nCell; ii++){
2909ebaecc14Sdanielk1977 if( ii==(nCell-1) ){
2910ebaecc14Sdanielk1977 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
2911ebaecc14Sdanielk1977 }else{
2912ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
2913ebaecc14Sdanielk1977 }
2914ebaecc14Sdanielk1977 aOrder[ii] = ii;
2915ebaecc14Sdanielk1977 for(iDim=0; iDim<pRtree->nDim; iDim++){
2916f439fbdaSdrh aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
2917f439fbdaSdrh aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
2918ebaecc14Sdanielk1977 }
2919ebaecc14Sdanielk1977 }
2920ebaecc14Sdanielk1977 for(iDim=0; iDim<pRtree->nDim; iDim++){
2921f439fbdaSdrh aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
2922ebaecc14Sdanielk1977 }
2923ebaecc14Sdanielk1977
2924ebaecc14Sdanielk1977 for(ii=0; ii<nCell; ii++){
292565e6b0ddSdrh aDistance[ii] = RTREE_ZERO;
2926ebaecc14Sdanielk1977 for(iDim=0; iDim<pRtree->nDim; iDim++){
2927f439fbdaSdrh RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
29287fd33929Sdrh DCOORD(aCell[ii].aCoord[iDim*2]));
2929ebaecc14Sdanielk1977 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
2930ebaecc14Sdanielk1977 }
2931ebaecc14Sdanielk1977 }
2932ebaecc14Sdanielk1977
2933ebaecc14Sdanielk1977 SortByDistance(aOrder, nCell, aDistance, aSpare);
2934ebaecc14Sdanielk1977 nodeZero(pRtree, pNode);
2935ebaecc14Sdanielk1977
2936ebaecc14Sdanielk1977 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
2937ebaecc14Sdanielk1977 RtreeCell *p = &aCell[aOrder[ii]];
2938ebaecc14Sdanielk1977 nodeInsertCell(pRtree, pNode, p);
2939ebaecc14Sdanielk1977 if( p->iRowid==pCell->iRowid ){
2940ebaecc14Sdanielk1977 if( iHeight==0 ){
2941ebaecc14Sdanielk1977 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
2942ebaecc14Sdanielk1977 }else{
2943ebaecc14Sdanielk1977 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
2944ebaecc14Sdanielk1977 }
2945ebaecc14Sdanielk1977 }
2946ebaecc14Sdanielk1977 }
2947ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
2948b51d2fa8Sdan rc = fixBoundingBox(pRtree, pNode);
2949ebaecc14Sdanielk1977 }
2950ebaecc14Sdanielk1977 for(; rc==SQLITE_OK && ii<nCell; ii++){
2951ebaecc14Sdanielk1977 /* Find a node to store this cell in. pNode->iNode currently contains
2952ebaecc14Sdanielk1977 ** the height of the sub-tree headed by the cell.
2953ebaecc14Sdanielk1977 */
2954ebaecc14Sdanielk1977 RtreeNode *pInsert;
2955ebaecc14Sdanielk1977 RtreeCell *p = &aCell[aOrder[ii]];
2956ebaecc14Sdanielk1977 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
2957ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
2958ebaecc14Sdanielk1977 int rc2;
295958f1c8b7Sdrh rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
2960ebaecc14Sdanielk1977 rc2 = nodeRelease(pRtree, pInsert);
2961ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
2962ebaecc14Sdanielk1977 rc = rc2;
2963ebaecc14Sdanielk1977 }
2964ebaecc14Sdanielk1977 }
2965ebaecc14Sdanielk1977 }
2966ebaecc14Sdanielk1977
2967ebaecc14Sdanielk1977 sqlite3_free(aCell);
2968ebaecc14Sdanielk1977 return rc;
2969ebaecc14Sdanielk1977 }
2970ebaecc14Sdanielk1977
2971ebaecc14Sdanielk1977 /*
2972ebaecc14Sdanielk1977 ** Insert cell pCell into node pNode. Node pNode is the head of a
2973ebaecc14Sdanielk1977 ** subtree iHeight high (leaf nodes have iHeight==0).
2974ebaecc14Sdanielk1977 */
rtreeInsertCell(Rtree * pRtree,RtreeNode * pNode,RtreeCell * pCell,int iHeight)297558f1c8b7Sdrh static int rtreeInsertCell(
2976ebaecc14Sdanielk1977 Rtree *pRtree,
2977ebaecc14Sdanielk1977 RtreeNode *pNode,
2978ebaecc14Sdanielk1977 RtreeCell *pCell,
2979ebaecc14Sdanielk1977 int iHeight
2980ebaecc14Sdanielk1977 ){
2981ebaecc14Sdanielk1977 int rc = SQLITE_OK;
2982ebaecc14Sdanielk1977 if( iHeight>0 ){
2983ebaecc14Sdanielk1977 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
2984ebaecc14Sdanielk1977 if( pChild ){
2985ebaecc14Sdanielk1977 nodeRelease(pRtree, pChild->pParent);
2986ebaecc14Sdanielk1977 nodeReference(pNode);
2987ebaecc14Sdanielk1977 pChild->pParent = pNode;
2988ebaecc14Sdanielk1977 }
2989ebaecc14Sdanielk1977 }
2990ebaecc14Sdanielk1977 if( nodeInsertCell(pRtree, pNode, pCell) ){
2991ebaecc14Sdanielk1977 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
2992ebaecc14Sdanielk1977 rc = SplitNode(pRtree, pNode, pCell, iHeight);
2993ebaecc14Sdanielk1977 }else{
2994ebaecc14Sdanielk1977 pRtree->iReinsertHeight = iHeight;
2995ebaecc14Sdanielk1977 rc = Reinsert(pRtree, pNode, pCell, iHeight);
2996ebaecc14Sdanielk1977 }
2997ebaecc14Sdanielk1977 }else{
2998b51d2fa8Sdan rc = AdjustTree(pRtree, pNode, pCell);
2999c464ec67Sdrh if( ALWAYS(rc==SQLITE_OK) ){
3000ebaecc14Sdanielk1977 if( iHeight==0 ){
3001ebaecc14Sdanielk1977 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
3002ebaecc14Sdanielk1977 }else{
3003ebaecc14Sdanielk1977 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
3004ebaecc14Sdanielk1977 }
3005ebaecc14Sdanielk1977 }
3006b51d2fa8Sdan }
3007ebaecc14Sdanielk1977 return rc;
3008ebaecc14Sdanielk1977 }
3009ebaecc14Sdanielk1977
reinsertNodeContent(Rtree * pRtree,RtreeNode * pNode)3010ebaecc14Sdanielk1977 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
3011ebaecc14Sdanielk1977 int ii;
3012ebaecc14Sdanielk1977 int rc = SQLITE_OK;
3013ebaecc14Sdanielk1977 int nCell = NCELL(pNode);
3014ebaecc14Sdanielk1977
3015ebaecc14Sdanielk1977 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
3016ebaecc14Sdanielk1977 RtreeNode *pInsert;
3017ebaecc14Sdanielk1977 RtreeCell cell;
3018ebaecc14Sdanielk1977 nodeGetCell(pRtree, pNode, ii, &cell);
3019ebaecc14Sdanielk1977
3020ebaecc14Sdanielk1977 /* Find a node to store this cell in. pNode->iNode currently contains
3021ebaecc14Sdanielk1977 ** the height of the sub-tree headed by the cell.
3022ebaecc14Sdanielk1977 */
30237fd33929Sdrh rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
3024ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3025ebaecc14Sdanielk1977 int rc2;
30267fd33929Sdrh rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
3027ebaecc14Sdanielk1977 rc2 = nodeRelease(pRtree, pInsert);
3028ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3029ebaecc14Sdanielk1977 rc = rc2;
3030ebaecc14Sdanielk1977 }
3031ebaecc14Sdanielk1977 }
3032ebaecc14Sdanielk1977 }
3033ebaecc14Sdanielk1977 return rc;
3034ebaecc14Sdanielk1977 }
3035ebaecc14Sdanielk1977
3036ebaecc14Sdanielk1977 /*
3037ebaecc14Sdanielk1977 ** Select a currently unused rowid for a new r-tree record.
3038ebaecc14Sdanielk1977 */
rtreeNewRowid(Rtree * pRtree,i64 * piRowid)3039b0af3d1fSdrh static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
3040ebaecc14Sdanielk1977 int rc;
3041ebaecc14Sdanielk1977 sqlite3_bind_null(pRtree->pWriteRowid, 1);
3042ebaecc14Sdanielk1977 sqlite3_bind_null(pRtree->pWriteRowid, 2);
3043ebaecc14Sdanielk1977 sqlite3_step(pRtree->pWriteRowid);
3044ebaecc14Sdanielk1977 rc = sqlite3_reset(pRtree->pWriteRowid);
3045ebaecc14Sdanielk1977 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
3046ebaecc14Sdanielk1977 return rc;
3047ebaecc14Sdanielk1977 }
3048ebaecc14Sdanielk1977
3049ebaecc14Sdanielk1977 /*
3050c6055c73Sdan ** Remove the entry with rowid=iDelete from the r-tree structure.
3051ebaecc14Sdanielk1977 */
rtreeDeleteRowid(Rtree * pRtree,sqlite3_int64 iDelete)3052c6055c73Sdan static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
3053c6055c73Sdan int rc; /* Return code */
3054c197eedbSmistachkin RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
3055ebaecc14Sdanielk1977 int iCell; /* Index of iDelete cell in pLeaf */
305696168057Sdrh RtreeNode *pRoot = 0; /* Root node of rtree structure */
3057c6055c73Sdan
3058ebaecc14Sdanielk1977
305948864df9Smistachkin /* Obtain a reference to the root node to initialize Rtree.iDepth */
3060ebaecc14Sdanielk1977 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
3061ebaecc14Sdanielk1977
3062ebaecc14Sdanielk1977 /* Obtain a reference to the leaf node that contains the entry
3063ebaecc14Sdanielk1977 ** about to be deleted.
3064ebaecc14Sdanielk1977 */
3065ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
306665e6b0ddSdrh rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
3067ebaecc14Sdanielk1977 }
3068ebaecc14Sdanielk1977
3069273e01b4Sdrh #ifdef CORRUPT_DB
3070273e01b4Sdrh assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
3071273e01b4Sdrh #endif
3072273e01b4Sdrh
3073ebaecc14Sdanielk1977 /* Delete the cell in question from the leaf node. */
3074273e01b4Sdrh if( rc==SQLITE_OK && pLeaf ){
3075ebaecc14Sdanielk1977 int rc2;
3076b51d2fa8Sdan rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
3077b51d2fa8Sdan if( rc==SQLITE_OK ){
3078ebaecc14Sdanielk1977 rc = deleteCell(pRtree, pLeaf, iCell, 0);
3079b51d2fa8Sdan }
3080ebaecc14Sdanielk1977 rc2 = nodeRelease(pRtree, pLeaf);
3081ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3082ebaecc14Sdanielk1977 rc = rc2;
3083ebaecc14Sdanielk1977 }
3084ebaecc14Sdanielk1977 }
3085ebaecc14Sdanielk1977
3086ebaecc14Sdanielk1977 /* Delete the corresponding entry in the <rtree>_rowid table. */
3087ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3088ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
3089ebaecc14Sdanielk1977 sqlite3_step(pRtree->pDeleteRowid);
3090ebaecc14Sdanielk1977 rc = sqlite3_reset(pRtree->pDeleteRowid);
3091ebaecc14Sdanielk1977 }
3092ebaecc14Sdanielk1977
3093ebaecc14Sdanielk1977 /* Check if the root node now has exactly one child. If so, remove
3094ebaecc14Sdanielk1977 ** it, schedule the contents of the child for reinsertion and
3095ebaecc14Sdanielk1977 ** reduce the tree height by one.
3096ebaecc14Sdanielk1977 **
3097ebaecc14Sdanielk1977 ** This is equivalent to copying the contents of the child into
3098ebaecc14Sdanielk1977 ** the root node (the operation that Gutman's paper says to perform
3099ebaecc14Sdanielk1977 ** in this scenario).
3100ebaecc14Sdanielk1977 */
31012bf19178Sdan if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
3102897230ebSdan int rc2;
3103468c6493Sdrh RtreeNode *pChild = 0;
3104ebaecc14Sdanielk1977 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
3105495f78d8Sdrh rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); /* tag-20210916a */
3106ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3107ebaecc14Sdanielk1977 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
3108ebaecc14Sdanielk1977 }
3109897230ebSdan rc2 = nodeRelease(pRtree, pChild);
3110897230ebSdan if( rc==SQLITE_OK ) rc = rc2;
3111ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3112ebaecc14Sdanielk1977 pRtree->iDepth--;
3113ebaecc14Sdanielk1977 writeInt16(pRoot->zData, pRtree->iDepth);
3114ebaecc14Sdanielk1977 pRoot->isDirty = 1;
3115ebaecc14Sdanielk1977 }
3116ebaecc14Sdanielk1977 }
3117ebaecc14Sdanielk1977
3118ebaecc14Sdanielk1977 /* Re-insert the contents of any underfull nodes removed from the tree. */
3119ebaecc14Sdanielk1977 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
3120ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3121ebaecc14Sdanielk1977 rc = reinsertNodeContent(pRtree, pLeaf);
3122ebaecc14Sdanielk1977 }
3123ebaecc14Sdanielk1977 pRtree->pDeleted = pLeaf->pNext;
3124c8c9cdd9Sdrh pRtree->nNodeRef--;
3125ebaecc14Sdanielk1977 sqlite3_free(pLeaf);
3126ebaecc14Sdanielk1977 }
3127ebaecc14Sdanielk1977
3128ebaecc14Sdanielk1977 /* Release the reference to the root node. */
3129ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3130ebaecc14Sdanielk1977 rc = nodeRelease(pRtree, pRoot);
3131ebaecc14Sdanielk1977 }else{
3132ebaecc14Sdanielk1977 nodeRelease(pRtree, pRoot);
3133ebaecc14Sdanielk1977 }
3134c6055c73Sdan
3135c6055c73Sdan return rc;
3136ebaecc14Sdanielk1977 }
3137ebaecc14Sdanielk1977
31380e3037acSdrh /*
31390e3037acSdrh ** Rounding constants for float->double conversion.
31400e3037acSdrh */
31410e3037acSdrh #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
31420e3037acSdrh #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
31430e3037acSdrh
3144c6bff382Sdrh #if !defined(SQLITE_RTREE_INT_ONLY)
3145c6055c73Sdan /*
314679238636Sdrh ** Convert an sqlite3_value into an RtreeValue (presumably a float)
314779238636Sdrh ** while taking care to round toward negative or positive, respectively.
314879238636Sdrh */
rtreeValueDown(sqlite3_value * v)314979238636Sdrh static RtreeValue rtreeValueDown(sqlite3_value *v){
315079238636Sdrh double d = sqlite3_value_double(v);
315179238636Sdrh float f = (float)d;
315279238636Sdrh if( f>d ){
31530e3037acSdrh f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
315479238636Sdrh }
315579238636Sdrh return f;
315679238636Sdrh }
rtreeValueUp(sqlite3_value * v)315779238636Sdrh static RtreeValue rtreeValueUp(sqlite3_value *v){
315879238636Sdrh double d = sqlite3_value_double(v);
315979238636Sdrh float f = (float)d;
316079238636Sdrh if( f<d ){
31610e3037acSdrh f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
316279238636Sdrh }
316379238636Sdrh return f;
316479238636Sdrh }
3165c6bff382Sdrh #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
3166c6bff382Sdrh
31675782bc27Sdan /*
31685782bc27Sdan ** A constraint has failed while inserting a row into an rtree table.
31695782bc27Sdan ** Assuming no OOM error occurs, this function sets the error message
31705782bc27Sdan ** (at pRtree->base.zErrMsg) to an appropriate value and returns
31715782bc27Sdan ** SQLITE_CONSTRAINT.
31725782bc27Sdan **
31735782bc27Sdan ** Parameter iCol is the index of the leftmost column involved in the
31745782bc27Sdan ** constraint failure. If it is 0, then the constraint that failed is
31755782bc27Sdan ** the unique constraint on the id column. Otherwise, it is the rtree
31765782bc27Sdan ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
31775782bc27Sdan **
31785782bc27Sdan ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
31795782bc27Sdan */
rtreeConstraintError(Rtree * pRtree,int iCol)31805782bc27Sdan static int rtreeConstraintError(Rtree *pRtree, int iCol){
31815782bc27Sdan sqlite3_stmt *pStmt = 0;
31825782bc27Sdan char *zSql;
31835782bc27Sdan int rc;
31845782bc27Sdan
31855782bc27Sdan assert( iCol==0 || iCol%2 );
31865782bc27Sdan zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
31875782bc27Sdan if( zSql ){
31885782bc27Sdan rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
31895782bc27Sdan }else{
31905782bc27Sdan rc = SQLITE_NOMEM;
31915782bc27Sdan }
31925782bc27Sdan sqlite3_free(zSql);
31935782bc27Sdan
31945782bc27Sdan if( rc==SQLITE_OK ){
31955782bc27Sdan if( iCol==0 ){
31965782bc27Sdan const char *zCol = sqlite3_column_name(pStmt, 0);
31975782bc27Sdan pRtree->base.zErrMsg = sqlite3_mprintf(
31985782bc27Sdan "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
31995782bc27Sdan );
32005782bc27Sdan }else{
32015782bc27Sdan const char *zCol1 = sqlite3_column_name(pStmt, iCol);
32025782bc27Sdan const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
32035782bc27Sdan pRtree->base.zErrMsg = sqlite3_mprintf(
32045782bc27Sdan "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
32055782bc27Sdan );
32065782bc27Sdan }
32075782bc27Sdan }
32085782bc27Sdan
32095782bc27Sdan sqlite3_finalize(pStmt);
32105782bc27Sdan return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
32115782bc27Sdan }
32125782bc27Sdan
32135782bc27Sdan
321479238636Sdrh
321579238636Sdrh /*
3216c6055c73Sdan ** The xUpdate method for rtree module virtual tables.
3217ebaecc14Sdanielk1977 */
rtreeUpdate(sqlite3_vtab * pVtab,int nData,sqlite3_value ** aData,sqlite_int64 * pRowid)3218c6055c73Sdan static int rtreeUpdate(
3219c6055c73Sdan sqlite3_vtab *pVtab,
3220c6055c73Sdan int nData,
3221e2971965Sdrh sqlite3_value **aData,
3222c6055c73Sdan sqlite_int64 *pRowid
3223c6055c73Sdan ){
3224c6055c73Sdan Rtree *pRtree = (Rtree *)pVtab;
3225c6055c73Sdan int rc = SQLITE_OK;
3226c6055c73Sdan RtreeCell cell; /* New cell to insert if nData>1 */
3227c6055c73Sdan int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
3228c6055c73Sdan
3229c8c9cdd9Sdrh if( pRtree->nNodeRef ){
3230c8c9cdd9Sdrh /* Unable to write to the btree while another cursor is reading from it,
3231c8c9cdd9Sdrh ** since the write might do a rebalance which would disrupt the read
3232c8c9cdd9Sdrh ** cursor. */
3233c8c9cdd9Sdrh return SQLITE_LOCKED_VTAB;
3234c8c9cdd9Sdrh }
3235c6055c73Sdan rtreeReference(pRtree);
3236c6055c73Sdan assert(nData>=1);
3237c6055c73Sdan
3238*de033d07Sdrh memset(&cell, 0, sizeof(cell));
32397bb6e8e1Smistachkin
3240c6055c73Sdan /* Constraint handling. A write operation on an r-tree table may return
3241c6055c73Sdan ** SQLITE_CONSTRAINT for two reasons:
3242c6055c73Sdan **
3243c6055c73Sdan ** 1. A duplicate rowid value, or
3244c6055c73Sdan ** 2. The supplied data violates the "x2>=x1" constraint.
3245c6055c73Sdan **
3246c6055c73Sdan ** In the first case, if the conflict-handling mode is REPLACE, then
3247c6055c73Sdan ** the conflicting row can be removed before proceeding. In the second
3248c6055c73Sdan ** case, SQLITE_CONSTRAINT must be returned regardless of the
3249c6055c73Sdan ** conflict-handling mode specified by the user.
3250c6055c73Sdan */
3251c6055c73Sdan if( nData>1 ){
3252ebaecc14Sdanielk1977 int ii;
3253e2971965Sdrh int nn = nData - 4;
3254ebaecc14Sdanielk1977
3255e2971965Sdrh if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
3256e2971965Sdrh /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
3257e9c5f976Sdrh **
3258e9c5f976Sdrh ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
3259e9c5f976Sdrh ** with "column" that are interpreted as table constraints.
3260e9c5f976Sdrh ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
3261e9c5f976Sdrh ** This problem was discovered after years of use, so we silently ignore
3262e9c5f976Sdrh ** these kinds of misdeclared tables to avoid breaking any legacy.
3263e9c5f976Sdrh */
3264e9c5f976Sdrh
3265f439fbdaSdrh #ifndef SQLITE_RTREE_INT_ONLY
32663ddb5a51Sdanielk1977 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
3267e2971965Sdrh for(ii=0; ii<nn; ii+=2){
3268e2971965Sdrh cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
3269e2971965Sdrh cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
32703ddb5a51Sdanielk1977 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
32715782bc27Sdan rc = rtreeConstraintError(pRtree, ii+1);
3272ebaecc14Sdanielk1977 goto constraint;
3273ebaecc14Sdanielk1977 }
3274ebaecc14Sdanielk1977 }
3275f439fbdaSdrh }else
3276f439fbdaSdrh #endif
3277f439fbdaSdrh {
3278e2971965Sdrh for(ii=0; ii<nn; ii+=2){
3279e2971965Sdrh cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
3280e2971965Sdrh cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
32813ddb5a51Sdanielk1977 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
32825782bc27Sdan rc = rtreeConstraintError(pRtree, ii+1);
32833ddb5a51Sdanielk1977 goto constraint;
32843ddb5a51Sdanielk1977 }
32853ddb5a51Sdanielk1977 }
32863ddb5a51Sdanielk1977 }
3287ebaecc14Sdanielk1977
3288c6055c73Sdan /* If a rowid value was supplied, check if it is already present in
3289c6055c73Sdan ** the table. If so, the constraint has failed. */
3290e2971965Sdrh if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
3291e2971965Sdrh cell.iRowid = sqlite3_value_int64(aData[2]);
3292e2971965Sdrh if( sqlite3_value_type(aData[0])==SQLITE_NULL
3293e2971965Sdrh || sqlite3_value_int64(aData[0])!=cell.iRowid
3294c6055c73Sdan ){
3295c6055c73Sdan int steprc;
3296ebaecc14Sdanielk1977 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
3297c6055c73Sdan steprc = sqlite3_step(pRtree->pReadRowid);
3298c6055c73Sdan rc = sqlite3_reset(pRtree->pReadRowid);
3299c6055c73Sdan if( SQLITE_ROW==steprc ){
3300c6055c73Sdan if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
3301c6055c73Sdan rc = rtreeDeleteRowid(pRtree, cell.iRowid);
3302c6055c73Sdan }else{
33035782bc27Sdan rc = rtreeConstraintError(pRtree, 0);
3304ebaecc14Sdanielk1977 goto constraint;
3305ebaecc14Sdanielk1977 }
3306c6055c73Sdan }
3307c6055c73Sdan }
3308c6055c73Sdan bHaveRowid = 1;
3309c6055c73Sdan }
3310c6055c73Sdan }
3311c6055c73Sdan
3312e2971965Sdrh /* If aData[0] is not an SQL NULL value, it is the rowid of a
3313c6055c73Sdan ** record to delete from the r-tree table. The following block does
3314c6055c73Sdan ** just that.
3315c6055c73Sdan */
3316e2971965Sdrh if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
3317e2971965Sdrh rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
3318c6055c73Sdan }
3319c6055c73Sdan
3320e2971965Sdrh /* If the aData[] array contains more than one element, elements
3321e2971965Sdrh ** (aData[2]..aData[argc-1]) contain a new record to insert into
3322c6055c73Sdan ** the r-tree structure.
3323c6055c73Sdan */
3324c6055c73Sdan if( rc==SQLITE_OK && nData>1 ){
3325c6055c73Sdan /* Insert the new record into the r-tree */
3326c197eedbSmistachkin RtreeNode *pLeaf = 0;
3327c6055c73Sdan
3328c6055c73Sdan /* Figure out the rowid of the new row. */
3329c6055c73Sdan if( bHaveRowid==0 ){
3330b0af3d1fSdrh rc = rtreeNewRowid(pRtree, &cell.iRowid);
3331ebaecc14Sdanielk1977 }
33323f0d9d38Sdan *pRowid = cell.iRowid;
3333ebaecc14Sdanielk1977
3334ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3335ebaecc14Sdanielk1977 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
3336ebaecc14Sdanielk1977 }
3337ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3338ebaecc14Sdanielk1977 int rc2;
3339ebaecc14Sdanielk1977 pRtree->iReinsertHeight = -1;
334058f1c8b7Sdrh rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
3341ebaecc14Sdanielk1977 rc2 = nodeRelease(pRtree, pLeaf);
3342ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
3343ebaecc14Sdanielk1977 rc = rc2;
3344ebaecc14Sdanielk1977 }
3345ebaecc14Sdanielk1977 }
3346cde4bf8bSdrh if( rc==SQLITE_OK && pRtree->nAux ){
3347e2971965Sdrh sqlite3_stmt *pUp = pRtree->pWriteAux;
3348e2971965Sdrh int jj;
3349e2971965Sdrh sqlite3_bind_int64(pUp, 1, *pRowid);
3350e2971965Sdrh for(jj=0; jj<pRtree->nAux; jj++){
3351e2971965Sdrh sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
3352e2971965Sdrh }
3353e2971965Sdrh sqlite3_step(pUp);
3354e2971965Sdrh rc = sqlite3_reset(pUp);
3355e2971965Sdrh }
3356ebaecc14Sdanielk1977 }
3357ebaecc14Sdanielk1977
3358ebaecc14Sdanielk1977 constraint:
3359ebaecc14Sdanielk1977 rtreeRelease(pRtree);
3360ebaecc14Sdanielk1977 return rc;
3361ebaecc14Sdanielk1977 }
3362ebaecc14Sdanielk1977
3363ebaecc14Sdanielk1977 /*
33646d683c5cSdrh ** Called when a transaction starts.
33656d683c5cSdrh */
rtreeBeginTransaction(sqlite3_vtab * pVtab)33666d683c5cSdrh static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
33672033d1c8Sdrh Rtree *pRtree = (Rtree *)pVtab;
33682033d1c8Sdrh assert( pRtree->inWrTrans==0 );
33692033d1c8Sdrh pRtree->inWrTrans++;
33706d683c5cSdrh return SQLITE_OK;
33716d683c5cSdrh }
33726d683c5cSdrh
33736d683c5cSdrh /*
33746d683c5cSdrh ** Called when a transaction completes (either by COMMIT or ROLLBACK).
33756d683c5cSdrh ** The sqlite3_blob object should be released at this point.
33766d683c5cSdrh */
rtreeEndTransaction(sqlite3_vtab * pVtab)33776d683c5cSdrh static int rtreeEndTransaction(sqlite3_vtab *pVtab){
33786d683c5cSdrh Rtree *pRtree = (Rtree *)pVtab;
33792033d1c8Sdrh pRtree->inWrTrans = 0;
33806d683c5cSdrh nodeBlobReset(pRtree);
33816d683c5cSdrh return SQLITE_OK;
33826d683c5cSdrh }
33836d683c5cSdrh
33846d683c5cSdrh /*
3385ebaecc14Sdanielk1977 ** The xRename method for rtree module virtual tables.
3386ebaecc14Sdanielk1977 */
rtreeRename(sqlite3_vtab * pVtab,const char * zNewName)3387ebaecc14Sdanielk1977 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
3388ebaecc14Sdanielk1977 Rtree *pRtree = (Rtree *)pVtab;
3389ebaecc14Sdanielk1977 int rc = SQLITE_NOMEM;
3390ebaecc14Sdanielk1977 char *zSql = sqlite3_mprintf(
33919f86ad23Sdrh "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
33929f86ad23Sdrh "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
33939f86ad23Sdrh "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
3394ebaecc14Sdanielk1977 , pRtree->zDb, pRtree->zName, zNewName
3395ebaecc14Sdanielk1977 , pRtree->zDb, pRtree->zName, zNewName
3396ebaecc14Sdanielk1977 , pRtree->zDb, pRtree->zName, zNewName
3397ebaecc14Sdanielk1977 );
3398ebaecc14Sdanielk1977 if( zSql ){
3399297e2bdbSdrh nodeBlobReset(pRtree);
3400ebaecc14Sdanielk1977 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
3401ebaecc14Sdanielk1977 sqlite3_free(zSql);
3402ebaecc14Sdanielk1977 }
3403ebaecc14Sdanielk1977 return rc;
3404ebaecc14Sdanielk1977 }
3405ebaecc14Sdanielk1977
34065b09d13aSdan /*
34075b09d13aSdan ** The xSavepoint method.
34085b09d13aSdan **
34095b09d13aSdan ** This module does not need to do anything to support savepoints. However,
34105b09d13aSdan ** it uses this hook to close any open blob handle. This is done because a
34115b09d13aSdan ** DROP TABLE command - which fortunately always opens a savepoint - cannot
34125b09d13aSdan ** succeed if there are any open blob handles. i.e. if the blob handle were
34135b09d13aSdan ** not closed here, the following would fail:
34145b09d13aSdan **
34155b09d13aSdan ** BEGIN;
34165b09d13aSdan ** INSERT INTO rtree...
34175b09d13aSdan ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
34185b09d13aSdan ** COMMIT;
34195b09d13aSdan */
rtreeSavepoint(sqlite3_vtab * pVtab,int iSavepoint)34205b09d13aSdan static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
34215b09d13aSdan Rtree *pRtree = (Rtree *)pVtab;
3422ed008eceSmistachkin u8 iwt = pRtree->inWrTrans;
3423f8a2e8c2Sdrh UNUSED_PARAMETER(iSavepoint);
34245b09d13aSdan pRtree->inWrTrans = 0;
34255b09d13aSdan nodeBlobReset(pRtree);
34265b09d13aSdan pRtree->inWrTrans = iwt;
34275b09d13aSdan return SQLITE_OK;
34285b09d13aSdan }
34296d683c5cSdrh
3430a9f5815bSdan /*
3431a9f5815bSdan ** This function populates the pRtree->nRowEst variable with an estimate
3432a9f5815bSdan ** of the number of rows in the virtual table. If possible, this is based
3433a9f5815bSdan ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
3434a9f5815bSdan */
rtreeQueryStat1(sqlite3 * db,Rtree * pRtree)3435a9f5815bSdan static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
343687af14a6Sdan const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
343787af14a6Sdan char *zSql;
3438a9f5815bSdan sqlite3_stmt *p;
3439a9f5815bSdan int rc;
3440162f1535Sdrh i64 nRow = RTREE_MIN_ROWEST;
3441a9f5815bSdan
3442ea5e5f0bSdan rc = sqlite3_table_column_metadata(
3443ea5e5f0bSdan db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
3444ea5e5f0bSdan );
3445ea5e5f0bSdan if( rc!=SQLITE_OK ){
3446e62c2fe1Sdrh pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
3447ea5e5f0bSdan return rc==SQLITE_ERROR ? SQLITE_OK : rc;
3448e62c2fe1Sdrh }
344987af14a6Sdan zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
345087af14a6Sdan if( zSql==0 ){
345187af14a6Sdan rc = SQLITE_NOMEM;
345287af14a6Sdan }else{
3453a9f5815bSdan rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
3454a9f5815bSdan if( rc==SQLITE_OK ){
3455a9f5815bSdan if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
3456a9f5815bSdan rc = sqlite3_finalize(p);
3457a9f5815bSdan }
345887af14a6Sdan sqlite3_free(zSql);
345987af14a6Sdan }
3460162f1535Sdrh pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
3461a9f5815bSdan return rc;
3462a9f5815bSdan }
3463a9f5815bSdan
346484c501baSdrh
346584c501baSdrh /*
346684c501baSdrh ** Return true if zName is the extension on one of the shadow tables used
346784c501baSdrh ** by this module.
346884c501baSdrh */
rtreeShadowName(const char * zName)346984c501baSdrh static int rtreeShadowName(const char *zName){
347084c501baSdrh static const char *azName[] = {
347184c501baSdrh "node", "parent", "rowid"
347284c501baSdrh };
347384c501baSdrh unsigned int i;
347484c501baSdrh for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
347584c501baSdrh if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
347684c501baSdrh }
347784c501baSdrh return 0;
347884c501baSdrh }
347984c501baSdrh
3480ebaecc14Sdanielk1977 static sqlite3_module rtreeModule = {
348184c501baSdrh 3, /* iVersion */
3482ebaecc14Sdanielk1977 rtreeCreate, /* xCreate - create a table */
3483ebaecc14Sdanielk1977 rtreeConnect, /* xConnect - connect to an existing table */
3484ebaecc14Sdanielk1977 rtreeBestIndex, /* xBestIndex - Determine search strategy */
3485ebaecc14Sdanielk1977 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
3486ebaecc14Sdanielk1977 rtreeDestroy, /* xDestroy - Drop a table */
3487ebaecc14Sdanielk1977 rtreeOpen, /* xOpen - open a cursor */
3488ebaecc14Sdanielk1977 rtreeClose, /* xClose - close a cursor */
3489ebaecc14Sdanielk1977 rtreeFilter, /* xFilter - configure scan constraints */
3490ebaecc14Sdanielk1977 rtreeNext, /* xNext - advance a cursor */
3491ebaecc14Sdanielk1977 rtreeEof, /* xEof */
3492ebaecc14Sdanielk1977 rtreeColumn, /* xColumn - read data */
3493ebaecc14Sdanielk1977 rtreeRowid, /* xRowid - read data */
3494ebaecc14Sdanielk1977 rtreeUpdate, /* xUpdate - write data */
34956d683c5cSdrh rtreeBeginTransaction, /* xBegin - begin transaction */
3496010e312fSdrh rtreeEndTransaction, /* xSync - sync transaction */
34976d683c5cSdrh rtreeEndTransaction, /* xCommit - commit transaction */
34986d683c5cSdrh rtreeEndTransaction, /* xRollback - rollback transaction */
3499ebaecc14Sdanielk1977 0, /* xFindFunction - function overloading */
35007ee4fdd7Sdrh rtreeRename, /* xRename - rename the table */
35015b09d13aSdan rtreeSavepoint, /* xSavepoint */
35027ee4fdd7Sdrh 0, /* xRelease */
35036d683c5cSdrh 0, /* xRollbackTo */
350484c501baSdrh rtreeShadowName /* xShadowName */
3505ebaecc14Sdanielk1977 };
3506ebaecc14Sdanielk1977
rtreeSqlInit(Rtree * pRtree,sqlite3 * db,const char * zDb,const char * zPrefix,int isCreate)3507ebaecc14Sdanielk1977 static int rtreeSqlInit(
3508ebaecc14Sdanielk1977 Rtree *pRtree,
3509ebaecc14Sdanielk1977 sqlite3 *db,
3510ebaecc14Sdanielk1977 const char *zDb,
3511ebaecc14Sdanielk1977 const char *zPrefix,
3512ebaecc14Sdanielk1977 int isCreate
3513ebaecc14Sdanielk1977 ){
3514ebaecc14Sdanielk1977 int rc = SQLITE_OK;
3515ebaecc14Sdanielk1977
35163accc7e1Sdrh #define N_STATEMENT 8
3517ebaecc14Sdanielk1977 static const char *azSql[N_STATEMENT] = {
35183accc7e1Sdrh /* Write the xxx_node table */
3519e2971965Sdrh "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
3520e2971965Sdrh "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
3521ebaecc14Sdanielk1977
3522ebaecc14Sdanielk1977 /* Read and write the xxx_rowid table */
3523e2971965Sdrh "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3524e2971965Sdrh "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
3525e2971965Sdrh "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
3526ebaecc14Sdanielk1977
3527ebaecc14Sdanielk1977 /* Read and write the xxx_parent table */
3528e2971965Sdrh "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
3529e2971965Sdrh "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
3530e2971965Sdrh "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
3531ebaecc14Sdanielk1977 };
3532ebaecc14Sdanielk1977 sqlite3_stmt **appStmt[N_STATEMENT];
3533ebaecc14Sdanielk1977 int i;
3534deb201b8Sdan const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
3535ebaecc14Sdanielk1977
3536ebaecc14Sdanielk1977 pRtree->db = db;
3537ebaecc14Sdanielk1977
3538ebaecc14Sdanielk1977 if( isCreate ){
3539e2971965Sdrh char *zCreate;
3540e2971965Sdrh sqlite3_str *p = sqlite3_str_new(db);
3541e2971965Sdrh int ii;
3542e2971965Sdrh sqlite3_str_appendf(p,
3543e2971965Sdrh "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
3544e2971965Sdrh zDb, zPrefix);
3545e2971965Sdrh for(ii=0; ii<pRtree->nAux; ii++){
3546e2971965Sdrh sqlite3_str_appendf(p,",a%d",ii);
3547e2971965Sdrh }
3548e2971965Sdrh sqlite3_str_appendf(p,
3549e2971965Sdrh ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
3550e2971965Sdrh zDb, zPrefix);
3551e2971965Sdrh sqlite3_str_appendf(p,
3552e2971965Sdrh "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
3553e2971965Sdrh zDb, zPrefix);
3554e2971965Sdrh sqlite3_str_appendf(p,
3555e2971965Sdrh "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
3556e2971965Sdrh zDb, zPrefix, pRtree->iNodeSize);
3557e2971965Sdrh zCreate = sqlite3_str_finish(p);
3558ebaecc14Sdanielk1977 if( !zCreate ){
3559ebaecc14Sdanielk1977 return SQLITE_NOMEM;
3560ebaecc14Sdanielk1977 }
3561ebaecc14Sdanielk1977 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
3562ebaecc14Sdanielk1977 sqlite3_free(zCreate);
3563ebaecc14Sdanielk1977 if( rc!=SQLITE_OK ){
3564ebaecc14Sdanielk1977 return rc;
3565ebaecc14Sdanielk1977 }
3566ebaecc14Sdanielk1977 }
3567ebaecc14Sdanielk1977
35683accc7e1Sdrh appStmt[0] = &pRtree->pWriteNode;
35693accc7e1Sdrh appStmt[1] = &pRtree->pDeleteNode;
35703accc7e1Sdrh appStmt[2] = &pRtree->pReadRowid;
35713accc7e1Sdrh appStmt[3] = &pRtree->pWriteRowid;
35723accc7e1Sdrh appStmt[4] = &pRtree->pDeleteRowid;
35733accc7e1Sdrh appStmt[5] = &pRtree->pReadParent;
35743accc7e1Sdrh appStmt[6] = &pRtree->pWriteParent;
35753accc7e1Sdrh appStmt[7] = &pRtree->pDeleteParent;
3576ebaecc14Sdanielk1977
3577a9f5815bSdan rc = rtreeQueryStat1(db, pRtree);
3578ebaecc14Sdanielk1977 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
3579e2971965Sdrh char *zSql;
3580e2971965Sdrh const char *zFormat;
3581e2971965Sdrh if( i!=3 || pRtree->nAux==0 ){
3582e2971965Sdrh zFormat = azSql[i];
3583e2971965Sdrh }else {
3584e2971965Sdrh /* An UPSERT is very slightly slower than REPLACE, but it is needed
3585e2971965Sdrh ** if there are auxiliary columns */
3586e2971965Sdrh zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
3587e2971965Sdrh "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
3588e2971965Sdrh }
3589e2971965Sdrh zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
3590ebaecc14Sdanielk1977 if( zSql ){
3591deb201b8Sdan rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
3592ebaecc14Sdanielk1977 }else{
3593ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
3594ebaecc14Sdanielk1977 }
3595ebaecc14Sdanielk1977 sqlite3_free(zSql);
3596ebaecc14Sdanielk1977 }
3597e2971965Sdrh if( pRtree->nAux ){
3598e2971965Sdrh pRtree->zReadAuxSql = sqlite3_mprintf(
3599e2971965Sdrh "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
3600e2971965Sdrh zDb, zPrefix);
3601e2971965Sdrh if( pRtree->zReadAuxSql==0 ){
3602e2971965Sdrh rc = SQLITE_NOMEM;
3603e2971965Sdrh }else{
3604e2971965Sdrh sqlite3_str *p = sqlite3_str_new(db);
3605e2971965Sdrh int ii;
3606e2971965Sdrh char *zSql;
3607e2971965Sdrh sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
3608e2971965Sdrh for(ii=0; ii<pRtree->nAux; ii++){
3609e2971965Sdrh if( ii ) sqlite3_str_append(p, ",", 1);
36108e4616c2Sdrh #ifdef SQLITE_ENABLE_GEOPOLY
361117f19eadSdrh if( ii<pRtree->nAuxNotNull ){
361217f19eadSdrh sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
36138e4616c2Sdrh }else
36148e4616c2Sdrh #endif
36158e4616c2Sdrh {
3616e2971965Sdrh sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
3617e2971965Sdrh }
361817f19eadSdrh }
3619e2971965Sdrh sqlite3_str_appendf(p, " WHERE rowid=?1");
3620e2971965Sdrh zSql = sqlite3_str_finish(p);
3621e2971965Sdrh if( zSql==0 ){
3622e2971965Sdrh rc = SQLITE_NOMEM;
3623e2971965Sdrh }else{
3624deb201b8Sdan rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
3625e2971965Sdrh sqlite3_free(zSql);
3626e2971965Sdrh }
3627e2971965Sdrh }
3628e2971965Sdrh }
3629ebaecc14Sdanielk1977
3630ebaecc14Sdanielk1977 return rc;
3631ebaecc14Sdanielk1977 }
3632ebaecc14Sdanielk1977
3633ebaecc14Sdanielk1977 /*
36345dcb3937Sdan ** The second argument to this function contains the text of an SQL statement
36355dcb3937Sdan ** that returns a single integer value. The statement is compiled and executed
36365dcb3937Sdan ** using database connection db. If successful, the integer value returned
36375dcb3937Sdan ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
36385dcb3937Sdan ** code is returned and the value of *piVal after returning is not defined.
3639ebaecc14Sdanielk1977 */
getIntFromStmt(sqlite3 * db,const char * zSql,int * piVal)36405dcb3937Sdan static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
3641ebaecc14Sdanielk1977 int rc = SQLITE_NOMEM;
36425dcb3937Sdan if( zSql ){
3643ebaecc14Sdanielk1977 sqlite3_stmt *pStmt = 0;
3644ebaecc14Sdanielk1977 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
36455dcb3937Sdan if( rc==SQLITE_OK ){
36465dcb3937Sdan if( SQLITE_ROW==sqlite3_step(pStmt) ){
36475dcb3937Sdan *piVal = sqlite3_column_int(pStmt, 0);
36485dcb3937Sdan }
36495dcb3937Sdan rc = sqlite3_finalize(pStmt);
36505dcb3937Sdan }
36515dcb3937Sdan }
3652ebaecc14Sdanielk1977 return rc;
3653ebaecc14Sdanielk1977 }
3654ebaecc14Sdanielk1977
36555dcb3937Sdan /*
36565dcb3937Sdan ** This function is called from within the xConnect() or xCreate() method to
36575dcb3937Sdan ** determine the node-size used by the rtree table being created or connected
36585dcb3937Sdan ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
36595dcb3937Sdan ** Otherwise, an SQLite error code is returned.
36605dcb3937Sdan **
36615dcb3937Sdan ** If this function is being called as part of an xConnect(), then the rtree
36625dcb3937Sdan ** table already exists. In this case the node-size is determined by inspecting
36635dcb3937Sdan ** the root node of the tree.
36645dcb3937Sdan **
36655dcb3937Sdan ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
36665dcb3937Sdan ** This ensures that each node is stored on a single database page. If the
36675dcb3937Sdan ** database page-size is so large that more than RTREE_MAXCELLS entries
36685dcb3937Sdan ** would fit in a single node, use a smaller node-size.
36695dcb3937Sdan */
getNodeSize(sqlite3 * db,Rtree * pRtree,int isCreate,char ** pzErr)36705dcb3937Sdan static int getNodeSize(
36715dcb3937Sdan sqlite3 *db, /* Database handle */
36725dcb3937Sdan Rtree *pRtree, /* Rtree handle */
3673806c0066Smistachkin int isCreate, /* True for xCreate, false for xConnect */
3674806c0066Smistachkin char **pzErr /* OUT: Error message, if any */
36755dcb3937Sdan ){
36765dcb3937Sdan int rc;
36775dcb3937Sdan char *zSql;
36785dcb3937Sdan if( isCreate ){
3679051eb38aSdrh int iPageSize = 0;
36805dcb3937Sdan zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
36815dcb3937Sdan rc = getIntFromStmt(db, zSql, &iPageSize);
36825dcb3937Sdan if( rc==SQLITE_OK ){
36835dcb3937Sdan pRtree->iNodeSize = iPageSize-64;
36845dcb3937Sdan if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
36855dcb3937Sdan pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
3686ebaecc14Sdanielk1977 }
3687806c0066Smistachkin }else{
3688806c0066Smistachkin *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
36895dcb3937Sdan }
36905dcb3937Sdan }else{
36915dcb3937Sdan zSql = sqlite3_mprintf(
36925dcb3937Sdan "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
36935dcb3937Sdan pRtree->zDb, pRtree->zName
36945dcb3937Sdan );
36955dcb3937Sdan rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
3696806c0066Smistachkin if( rc!=SQLITE_OK ){
3697806c0066Smistachkin *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3698c7b1ee5fSdrh }else if( pRtree->iNodeSize<(512-64) ){
36996362bbe6Sdrh rc = SQLITE_CORRUPT_VTAB;
3700fb077f3cSdrh RTREE_IS_CORRUPT(pRtree);
3701c7b1ee5fSdrh *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
3702c7b1ee5fSdrh pRtree->zName);
3703806c0066Smistachkin }
37045dcb3937Sdan }
37055dcb3937Sdan
37065dcb3937Sdan sqlite3_free(zSql);
37075dcb3937Sdan return rc;
3708ebaecc14Sdanielk1977 }
3709ebaecc14Sdanielk1977
3710ebaecc14Sdanielk1977 /*
37110a64ddbeSdrh ** Return the length of a token
37120a64ddbeSdrh */
rtreeTokenLength(const char * z)37130a64ddbeSdrh static int rtreeTokenLength(const char *z){
37140a64ddbeSdrh int dummy = 0;
37150a64ddbeSdrh return sqlite3GetToken((const unsigned char*)z,&dummy);
37160a64ddbeSdrh }
37170a64ddbeSdrh
37180a64ddbeSdrh /*
3719ebaecc14Sdanielk1977 ** This function is the implementation of both the xConnect and xCreate
3720ebaecc14Sdanielk1977 ** methods of the r-tree virtual table.
3721ebaecc14Sdanielk1977 **
3722ebaecc14Sdanielk1977 ** argv[0] -> module name
3723ebaecc14Sdanielk1977 ** argv[1] -> database name
3724ebaecc14Sdanielk1977 ** argv[2] -> table name
3725ebaecc14Sdanielk1977 ** argv[...] -> column names...
3726ebaecc14Sdanielk1977 */
rtreeInit(sqlite3 * db,void * pAux,int argc,const char * const * argv,sqlite3_vtab ** ppVtab,char ** pzErr,int isCreate)3727ebaecc14Sdanielk1977 static int rtreeInit(
3728ebaecc14Sdanielk1977 sqlite3 *db, /* Database connection */
3729a7435e31Sdanielk1977 void *pAux, /* One of the RTREE_COORD_* constants */
3730ebaecc14Sdanielk1977 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
3731ebaecc14Sdanielk1977 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
3732ebaecc14Sdanielk1977 char **pzErr, /* OUT: Error message, if any */
3733a7435e31Sdanielk1977 int isCreate /* True for xCreate, false for xConnect */
3734ebaecc14Sdanielk1977 ){
3735ebaecc14Sdanielk1977 int rc = SQLITE_OK;
3736ebaecc14Sdanielk1977 Rtree *pRtree;
3737ebaecc14Sdanielk1977 int nDb; /* Length of string argv[1] */
3738ebaecc14Sdanielk1977 int nName; /* Length of string argv[2] */
37399508daa9Sdan int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
3740e2971965Sdrh sqlite3_str *pSql;
3741e2971965Sdrh char *zSql;
3742e2971965Sdrh int ii = 4;
3743e2971965Sdrh int iErr;
3744ebaecc14Sdanielk1977
3745ebaecc14Sdanielk1977 const char *aErrMsg[] = {
3746ebaecc14Sdanielk1977 0, /* 0 */
3747ebaecc14Sdanielk1977 "Wrong number of columns for an rtree table", /* 1 */
3748ebaecc14Sdanielk1977 "Too few columns for an rtree table", /* 2 */
3749e2971965Sdrh "Too many columns for an rtree table", /* 3 */
3750252f3961Sdrh "Auxiliary rtree columns must be last" /* 4 */
3751ebaecc14Sdanielk1977 };
3752ebaecc14Sdanielk1977
3753252f3961Sdrh assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
37545102cf8dSdrh if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
37555102cf8dSdrh *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
3756ebaecc14Sdanielk1977 return SQLITE_ERROR;
3757ebaecc14Sdanielk1977 }
3758ebaecc14Sdanielk1977
3759c6055c73Sdan sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
3760c6055c73Sdan
3761ebaecc14Sdanielk1977 /* Allocate the sqlite3_vtab structure */
376201ea399aSdrh nDb = (int)strlen(argv[1]);
376301ea399aSdrh nName = (int)strlen(argv[2]);
37642d77d80aSdrh pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
3765ebaecc14Sdanielk1977 if( !pRtree ){
3766ebaecc14Sdanielk1977 return SQLITE_NOMEM;
3767ebaecc14Sdanielk1977 }
3768ebaecc14Sdanielk1977 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
3769ebaecc14Sdanielk1977 pRtree->nBusy = 1;
3770ebaecc14Sdanielk1977 pRtree->base.pModule = &rtreeModule;
3771ebaecc14Sdanielk1977 pRtree->zDb = (char *)&pRtree[1];
3772ebaecc14Sdanielk1977 pRtree->zName = &pRtree->zDb[nDb+1];
37732e525322Smistachkin pRtree->eCoordType = (u8)eCoordType;
3774ebaecc14Sdanielk1977 memcpy(pRtree->zDb, argv[1], nDb);
3775ebaecc14Sdanielk1977 memcpy(pRtree->zName, argv[2], nName);
3776ebaecc14Sdanielk1977
3777ebaecc14Sdanielk1977
3778ebaecc14Sdanielk1977 /* Create/Connect to the underlying relational database schema. If
3779ebaecc14Sdanielk1977 ** that is successful, call sqlite3_declare_vtab() to configure
3780ebaecc14Sdanielk1977 ** the r-tree table schema.
3781ebaecc14Sdanielk1977 */
3782e2971965Sdrh pSql = sqlite3_str_new(db);
37830a64ddbeSdrh sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
37840a64ddbeSdrh rtreeTokenLength(argv[3]), argv[3]);
3785a090ab90Sdrh for(ii=4; ii<argc; ii++){
37860a64ddbeSdrh const char *zArg = argv[ii];
37870a64ddbeSdrh if( zArg[0]=='+' ){
3788e2971965Sdrh pRtree->nAux++;
3789c7a046e2Sdrh sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
3790e2971965Sdrh }else if( pRtree->nAux>0 ){
3791e2971965Sdrh break;
3792e2971965Sdrh }else{
37932826918dSdrh static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
3794e2971965Sdrh pRtree->nDim2++;
37952826918dSdrh sqlite3_str_appendf(pSql, azFormat[eCoordType],
37962826918dSdrh rtreeTokenLength(zArg), zArg);
3797ebaecc14Sdanielk1977 }
3798e2971965Sdrh }
3799a090ab90Sdrh sqlite3_str_appendf(pSql, ");");
3800a090ab90Sdrh zSql = sqlite3_str_finish(pSql);
380133c54a98Sdanielk1977 if( !zSql ){
3802ebaecc14Sdanielk1977 rc = SQLITE_NOMEM;
3803e2971965Sdrh }else if( ii<argc ){
3804e2971965Sdrh *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
3805e2971965Sdrh rc = SQLITE_ERROR;
380633c54a98Sdanielk1977 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
380733c54a98Sdanielk1977 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3808ebaecc14Sdanielk1977 }
3809ebaecc14Sdanielk1977 sqlite3_free(zSql);
3810e2971965Sdrh if( rc ) goto rtreeInit_fail;
3811e2971965Sdrh pRtree->nDim = pRtree->nDim2/2;
3812e2971965Sdrh if( pRtree->nDim<1 ){
3813e2971965Sdrh iErr = 2;
3814e2971965Sdrh }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
3815e2971965Sdrh iErr = 3;
3816e2971965Sdrh }else if( pRtree->nDim2 % 2 ){
3817e2971965Sdrh iErr = 1;
3818e2971965Sdrh }else{
3819e2971965Sdrh iErr = 0;
3820ebaecc14Sdanielk1977 }
3821e2971965Sdrh if( iErr ){
3822e2971965Sdrh *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
3823e2971965Sdrh goto rtreeInit_fail;
3824e2971965Sdrh }
3825e2971965Sdrh pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
3826e2971965Sdrh
3827e2971965Sdrh /* Figure out the node size to use. */
3828e2971965Sdrh rc = getNodeSize(db, pRtree, isCreate, pzErr);
3829e2971965Sdrh if( rc ) goto rtreeInit_fail;
3830e2971965Sdrh rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
3831e2971965Sdrh if( rc ){
3832e2971965Sdrh *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
3833e2971965Sdrh goto rtreeInit_fail;
38345dcb3937Sdan }
3835ebaecc14Sdanielk1977
3836ebaecc14Sdanielk1977 *ppVtab = (sqlite3_vtab *)pRtree;
3837e2971965Sdrh return SQLITE_OK;
3838e2971965Sdrh
3839e2971965Sdrh rtreeInit_fail:
3840e2971965Sdrh if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
3841d88e521fSdan assert( *ppVtab==0 );
3842d88e521fSdan assert( pRtree->nBusy==1 );
3843ebaecc14Sdanielk1977 rtreeRelease(pRtree);
3844ebaecc14Sdanielk1977 return rc;
3845ebaecc14Sdanielk1977 }
3846ebaecc14Sdanielk1977
3847ebaecc14Sdanielk1977
3848ebaecc14Sdanielk1977 /*
3849ebaecc14Sdanielk1977 ** Implementation of a scalar function that decodes r-tree nodes to
3850ebaecc14Sdanielk1977 ** human readable strings. This can be used for debugging and analysis.
3851ebaecc14Sdanielk1977 **
385265e6b0ddSdrh ** The scalar function takes two arguments: (1) the number of dimensions
385365e6b0ddSdrh ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
385465e6b0ddSdrh ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
385565e6b0ddSdrh ** deserialize all nodes, a statement like:
3856ebaecc14Sdanielk1977 **
3857ebaecc14Sdanielk1977 ** SELECT rtreenode(2, data) FROM rt_node;
3858ebaecc14Sdanielk1977 **
3859ebaecc14Sdanielk1977 ** The human readable string takes the form of a Tcl list with one
3860ebaecc14Sdanielk1977 ** entry for each cell in the r-tree node. Each entry is itself a
3861ebaecc14Sdanielk1977 ** list, containing the 8-byte rowid/pageno followed by the
3862ebaecc14Sdanielk1977 ** <num-dimension>*2 coordinates.
3863ebaecc14Sdanielk1977 */
rtreenode(sqlite3_context * ctx,int nArg,sqlite3_value ** apArg)3864ebaecc14Sdanielk1977 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
3865ebaecc14Sdanielk1977 RtreeNode node;
3866ebaecc14Sdanielk1977 Rtree tree;
3867ebaecc14Sdanielk1977 int ii;
3868e41fd72aSdrh int nData;
3869e41fd72aSdrh int errCode;
3870e41fd72aSdrh sqlite3_str *pOut;
3871ebaecc14Sdanielk1977
38726ea28d6dSdrh UNUSED_PARAMETER(nArg);
3873ebaecc14Sdanielk1977 memset(&node, 0, sizeof(RtreeNode));
3874ebaecc14Sdanielk1977 memset(&tree, 0, sizeof(Rtree));
38752e525322Smistachkin tree.nDim = (u8)sqlite3_value_int(apArg[0]);
3876e41fd72aSdrh if( tree.nDim<1 || tree.nDim>5 ) return;
38770e6f67b7Sdrh tree.nDim2 = tree.nDim*2;
3878ebaecc14Sdanielk1977 tree.nBytesPerCell = 8 + 8 * tree.nDim;
3879ebaecc14Sdanielk1977 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
388011a9ad56Sdrh if( node.zData==0 ) return;
3881e41fd72aSdrh nData = sqlite3_value_bytes(apArg[1]);
3882e41fd72aSdrh if( nData<4 ) return;
3883e41fd72aSdrh if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
3884ebaecc14Sdanielk1977
3885e41fd72aSdrh pOut = sqlite3_str_new(0);
3886ebaecc14Sdanielk1977 for(ii=0; ii<NCELL(&node); ii++){
3887ebaecc14Sdanielk1977 RtreeCell cell;
3888ebaecc14Sdanielk1977 int jj;
3889ebaecc14Sdanielk1977
3890ebaecc14Sdanielk1977 nodeGetCell(&tree, &node, ii, &cell);
3891e41fd72aSdrh if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
3892e41fd72aSdrh sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
38930e6f67b7Sdrh for(jj=0; jj<tree.nDim2; jj++){
3894f439fbdaSdrh #ifndef SQLITE_RTREE_INT_ONLY
3895e41fd72aSdrh sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
3896f439fbdaSdrh #else
3897e41fd72aSdrh sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
3898f439fbdaSdrh #endif
3899ebaecc14Sdanielk1977 }
3900e41fd72aSdrh sqlite3_str_append(pOut, "}", 1);
3901ebaecc14Sdanielk1977 }
3902e41fd72aSdrh errCode = sqlite3_str_errcode(pOut);
3903e41fd72aSdrh sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
3904e41fd72aSdrh sqlite3_result_error_code(ctx, errCode);
3905ebaecc14Sdanielk1977 }
3906ebaecc14Sdanielk1977
390765e6b0ddSdrh /* This routine implements an SQL function that returns the "depth" parameter
390865e6b0ddSdrh ** from the front of a blob that is an r-tree node. For example:
390965e6b0ddSdrh **
391065e6b0ddSdrh ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
391165e6b0ddSdrh **
391265e6b0ddSdrh ** The depth value is 0 for all nodes other than the root node, and the root
391365e6b0ddSdrh ** node always has nodeno=1, so the example above is the primary use for this
391465e6b0ddSdrh ** routine. This routine is intended for testing and analysis only.
391565e6b0ddSdrh */
rtreedepth(sqlite3_context * ctx,int nArg,sqlite3_value ** apArg)3916ebaecc14Sdanielk1977 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
39176ea28d6dSdrh UNUSED_PARAMETER(nArg);
3918ebaecc14Sdanielk1977 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
3919ebaecc14Sdanielk1977 || sqlite3_value_bytes(apArg[0])<2
3920b3d2ba7cSdrh
3921ebaecc14Sdanielk1977 ){
3922ebaecc14Sdanielk1977 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
3923ebaecc14Sdanielk1977 }else{
3924ebaecc14Sdanielk1977 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
3925b3d2ba7cSdrh if( zBlob ){
3926ebaecc14Sdanielk1977 sqlite3_result_int(ctx, readInt16(zBlob));
3927b3d2ba7cSdrh }else{
3928b3d2ba7cSdrh sqlite3_result_error_nomem(ctx);
3929b3d2ba7cSdrh }
3930ebaecc14Sdanielk1977 }
3931ebaecc14Sdanielk1977 }
3932ebaecc14Sdanielk1977
3933ebaecc14Sdanielk1977 /*
39341917e92fSdan ** Context object passed between the various routines that make up the
39351917e92fSdan ** implementation of integrity-check function rtreecheck().
39361917e92fSdan */
39371917e92fSdan typedef struct RtreeCheck RtreeCheck;
39381917e92fSdan struct RtreeCheck {
39391917e92fSdan sqlite3 *db; /* Database handle */
39401917e92fSdan const char *zDb; /* Database containing rtree table */
39411917e92fSdan const char *zTab; /* Name of rtree table */
39421917e92fSdan int bInt; /* True for rtree_i32 table */
39431917e92fSdan int nDim; /* Number of dimensions for this rtree tbl */
39441917e92fSdan sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
39451917e92fSdan sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
39461917e92fSdan int nLeaf; /* Number of leaf cells in table */
39471917e92fSdan int nNonLeaf; /* Number of non-leaf cells in table */
39481917e92fSdan int rc; /* Return code */
39491917e92fSdan char *zReport; /* Message to report */
39501917e92fSdan int nErr; /* Number of lines in zReport */
39511917e92fSdan };
39521917e92fSdan
39531917e92fSdan #define RTREE_CHECK_MAX_ERROR 100
39541917e92fSdan
39551917e92fSdan /*
39561917e92fSdan ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
39571917e92fSdan ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
39581917e92fSdan */
rtreeCheckReset(RtreeCheck * pCheck,sqlite3_stmt * pStmt)39591917e92fSdan static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
39601917e92fSdan int rc = sqlite3_reset(pStmt);
39611917e92fSdan if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
39621917e92fSdan }
39631917e92fSdan
39641917e92fSdan /*
39651917e92fSdan ** The second and subsequent arguments to this function are a format string
39661917e92fSdan ** and printf style arguments. This function formats the string and attempts
39671917e92fSdan ** to compile it as an SQL statement.
39681917e92fSdan **
39691917e92fSdan ** If successful, a pointer to the new SQL statement is returned. Otherwise,
39701917e92fSdan ** NULL is returned and an error code left in RtreeCheck.rc.
39711917e92fSdan */
rtreeCheckPrepare(RtreeCheck * pCheck,const char * zFmt,...)39721917e92fSdan static sqlite3_stmt *rtreeCheckPrepare(
39731917e92fSdan RtreeCheck *pCheck, /* RtreeCheck object */
39741917e92fSdan const char *zFmt, ... /* Format string and trailing args */
39751917e92fSdan ){
39761917e92fSdan va_list ap;
39778c66e5b7Smistachkin char *z;
39781917e92fSdan sqlite3_stmt *pRet = 0;
39791917e92fSdan
39808c66e5b7Smistachkin va_start(ap, zFmt);
39818c66e5b7Smistachkin z = sqlite3_vmprintf(zFmt, ap);
39828c66e5b7Smistachkin
39831917e92fSdan if( pCheck->rc==SQLITE_OK ){
39847e2b38c5Sdan if( z==0 ){
39857e2b38c5Sdan pCheck->rc = SQLITE_NOMEM;
39867e2b38c5Sdan }else{
39871917e92fSdan pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
39881917e92fSdan }
39897e2b38c5Sdan }
39901917e92fSdan
39911917e92fSdan sqlite3_free(z);
39921917e92fSdan va_end(ap);
39931917e92fSdan return pRet;
39941917e92fSdan }
39951917e92fSdan
39961917e92fSdan /*
39971917e92fSdan ** The second and subsequent arguments to this function are a printf()
39981917e92fSdan ** style format string and arguments. This function formats the string and
39991917e92fSdan ** appends it to the report being accumuated in pCheck.
40001917e92fSdan */
rtreeCheckAppendMsg(RtreeCheck * pCheck,const char * zFmt,...)40011917e92fSdan static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
40021917e92fSdan va_list ap;
40031917e92fSdan va_start(ap, zFmt);
40041917e92fSdan if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
40051917e92fSdan char *z = sqlite3_vmprintf(zFmt, ap);
40061917e92fSdan if( z==0 ){
40071917e92fSdan pCheck->rc = SQLITE_NOMEM;
40081917e92fSdan }else{
40091917e92fSdan pCheck->zReport = sqlite3_mprintf("%z%s%z",
40101917e92fSdan pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
40111917e92fSdan );
40121917e92fSdan if( pCheck->zReport==0 ){
40131917e92fSdan pCheck->rc = SQLITE_NOMEM;
40141917e92fSdan }
40151917e92fSdan }
40161917e92fSdan pCheck->nErr++;
40171917e92fSdan }
40181917e92fSdan va_end(ap);
40191917e92fSdan }
40201917e92fSdan
40211917e92fSdan /*
40221917e92fSdan ** This function is a no-op if there is already an error code stored
40231917e92fSdan ** in the RtreeCheck object indicated by the first argument. NULL is
40241917e92fSdan ** returned in this case.
40251917e92fSdan **
40261917e92fSdan ** Otherwise, the contents of rtree table node iNode are loaded from
40271917e92fSdan ** the database and copied into a buffer obtained from sqlite3_malloc().
40281917e92fSdan ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
40291917e92fSdan ** is set to the size of the buffer in bytes.
40301917e92fSdan **
40311917e92fSdan ** Or, if an error does occur, NULL is returned and an error code left
40321917e92fSdan ** in the RtreeCheck object. The final value of *pnNode is undefined in
40331917e92fSdan ** this case.
40341917e92fSdan */
rtreeCheckGetNode(RtreeCheck * pCheck,i64 iNode,int * pnNode)40351917e92fSdan static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
40361917e92fSdan u8 *pRet = 0; /* Return value */
40371917e92fSdan
4038558ef11aSdrh if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
40391917e92fSdan pCheck->pGetNode = rtreeCheckPrepare(pCheck,
40401917e92fSdan "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
40411917e92fSdan pCheck->zDb, pCheck->zTab
40421917e92fSdan );
40431917e92fSdan }
40441917e92fSdan
40451917e92fSdan if( pCheck->rc==SQLITE_OK ){
40461917e92fSdan sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
40471917e92fSdan if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
40481917e92fSdan int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
40491917e92fSdan const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
40502d77d80aSdrh pRet = sqlite3_malloc64(nNode);
40511917e92fSdan if( pRet==0 ){
40521917e92fSdan pCheck->rc = SQLITE_NOMEM;
40531917e92fSdan }else{
40541917e92fSdan memcpy(pRet, pNode, nNode);
40551917e92fSdan *pnNode = nNode;
40561917e92fSdan }
40571917e92fSdan }
40581917e92fSdan rtreeCheckReset(pCheck, pCheck->pGetNode);
40591917e92fSdan if( pCheck->rc==SQLITE_OK && pRet==0 ){
40601917e92fSdan rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
40611917e92fSdan }
40621917e92fSdan }
40631917e92fSdan
40641917e92fSdan return pRet;
40651917e92fSdan }
40661917e92fSdan
40671917e92fSdan /*
40681917e92fSdan ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
40691917e92fSdan ** (if bLeaf==1) table contains a specified entry. The schemas of the
40701917e92fSdan ** two tables are:
40711917e92fSdan **
40721917e92fSdan ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
40737578456cSdrh ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
40741917e92fSdan **
40751917e92fSdan ** In both cases, this function checks that there exists an entry with
40761917e92fSdan ** IPK value iKey and the second column set to iVal.
40771917e92fSdan **
40781917e92fSdan */
rtreeCheckMapping(RtreeCheck * pCheck,int bLeaf,i64 iKey,i64 iVal)40791917e92fSdan static void rtreeCheckMapping(
40801917e92fSdan RtreeCheck *pCheck, /* RtreeCheck object */
40811917e92fSdan int bLeaf, /* True for a leaf cell, false for interior */
40821917e92fSdan i64 iKey, /* Key for mapping */
40831917e92fSdan i64 iVal /* Expected value for mapping */
40841917e92fSdan ){
40851917e92fSdan int rc;
40861917e92fSdan sqlite3_stmt *pStmt;
40871917e92fSdan const char *azSql[2] = {
40887578456cSdrh "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
40897578456cSdrh "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
40901917e92fSdan };
40911917e92fSdan
40921917e92fSdan assert( bLeaf==0 || bLeaf==1 );
40931917e92fSdan if( pCheck->aCheckMapping[bLeaf]==0 ){
40941917e92fSdan pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
40951917e92fSdan azSql[bLeaf], pCheck->zDb, pCheck->zTab
40961917e92fSdan );
40971917e92fSdan }
40981917e92fSdan if( pCheck->rc!=SQLITE_OK ) return;
40991917e92fSdan
41001917e92fSdan pStmt = pCheck->aCheckMapping[bLeaf];
41011917e92fSdan sqlite3_bind_int64(pStmt, 1, iKey);
41021917e92fSdan rc = sqlite3_step(pStmt);
41031917e92fSdan if( rc==SQLITE_DONE ){
41041917e92fSdan rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
41051917e92fSdan iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
41061917e92fSdan );
41071917e92fSdan }else if( rc==SQLITE_ROW ){
41081917e92fSdan i64 ii = sqlite3_column_int64(pStmt, 0);
41091917e92fSdan if( ii!=iVal ){
41101917e92fSdan rtreeCheckAppendMsg(pCheck,
41111917e92fSdan "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
41121917e92fSdan iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
41131917e92fSdan );
41141917e92fSdan }
41151917e92fSdan }
41161917e92fSdan rtreeCheckReset(pCheck, pStmt);
41171917e92fSdan }
41181917e92fSdan
41197e2b38c5Sdan /*
41207e2b38c5Sdan ** Argument pCell points to an array of coordinates stored on an rtree page.
41217e2b38c5Sdan ** This function checks that the coordinates are internally consistent (no
41227e2b38c5Sdan ** x1>x2 conditions) and adds an error message to the RtreeCheck object
41237e2b38c5Sdan ** if they are not.
41247e2b38c5Sdan **
41257e2b38c5Sdan ** Additionally, if pParent is not NULL, then it is assumed to point to
41267e2b38c5Sdan ** the array of coordinates on the parent page that bound the page
41277e2b38c5Sdan ** containing pCell. In this case it is also verified that the two
41287e2b38c5Sdan ** sets of coordinates are mutually consistent and an error message added
41297e2b38c5Sdan ** to the RtreeCheck object if they are not.
41307e2b38c5Sdan */
rtreeCheckCellCoord(RtreeCheck * pCheck,i64 iNode,int iCell,u8 * pCell,u8 * pParent)41311917e92fSdan static void rtreeCheckCellCoord(
41321917e92fSdan RtreeCheck *pCheck,
41337e2b38c5Sdan i64 iNode, /* Node id to use in error messages */
41347e2b38c5Sdan int iCell, /* Cell number to use in error messages */
41351917e92fSdan u8 *pCell, /* Pointer to cell coordinates */
41361917e92fSdan u8 *pParent /* Pointer to parent coordinates */
41371917e92fSdan ){
41381917e92fSdan RtreeCoord c1, c2;
41391917e92fSdan RtreeCoord p1, p2;
41401917e92fSdan int i;
41411917e92fSdan
41421917e92fSdan for(i=0; i<pCheck->nDim; i++){
41431917e92fSdan readCoord(&pCell[4*2*i], &c1);
41441917e92fSdan readCoord(&pCell[4*(2*i + 1)], &c2);
41451917e92fSdan
41461917e92fSdan /* printf("%e, %e\n", c1.u.f, c2.u.f); */
41471917e92fSdan if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
41481917e92fSdan rtreeCheckAppendMsg(pCheck,
41491917e92fSdan "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
41501917e92fSdan );
41511917e92fSdan }
41521917e92fSdan
41531917e92fSdan if( pParent ){
41541917e92fSdan readCoord(&pParent[4*2*i], &p1);
41551917e92fSdan readCoord(&pParent[4*(2*i + 1)], &p2);
41561917e92fSdan
41571917e92fSdan if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
41581917e92fSdan || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
41591917e92fSdan ){
41601917e92fSdan rtreeCheckAppendMsg(pCheck,
41611917e92fSdan "Dimension %d of cell %d on node %lld is corrupt relative to parent"
41621917e92fSdan , i, iCell, iNode
41631917e92fSdan );
41641917e92fSdan }
41651917e92fSdan }
41661917e92fSdan }
41671917e92fSdan }
41681917e92fSdan
41697e2b38c5Sdan /*
41707e2b38c5Sdan ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
41717e2b38c5Sdan ** the r-tree structure. Argument aParent points to the array of coordinates
41727e2b38c5Sdan ** that bound node iNode on the parent node.
41737e2b38c5Sdan **
41747e2b38c5Sdan ** If any problems are discovered, an error message is appended to the
41757e2b38c5Sdan ** report accumulated in the RtreeCheck object.
41767e2b38c5Sdan */
rtreeCheckNode(RtreeCheck * pCheck,int iDepth,u8 * aParent,i64 iNode)41771917e92fSdan static void rtreeCheckNode(
41781917e92fSdan RtreeCheck *pCheck,
41791917e92fSdan int iDepth, /* Depth of iNode (0==leaf) */
41801917e92fSdan u8 *aParent, /* Buffer containing parent coords */
41811917e92fSdan i64 iNode /* Node to check */
41821917e92fSdan ){
41831917e92fSdan u8 *aNode = 0;
41841917e92fSdan int nNode = 0;
41851917e92fSdan
41861917e92fSdan assert( iNode==1 || aParent!=0 );
41871917e92fSdan assert( pCheck->nDim>0 );
41881917e92fSdan
41891917e92fSdan aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
41901917e92fSdan if( aNode ){
41911917e92fSdan if( nNode<4 ){
41921917e92fSdan rtreeCheckAppendMsg(pCheck,
41931917e92fSdan "Node %lld is too small (%d bytes)", iNode, nNode
41941917e92fSdan );
41951917e92fSdan }else{
41961917e92fSdan int nCell; /* Number of cells on page */
41971917e92fSdan int i; /* Used to iterate through cells */
41981917e92fSdan if( aParent==0 ){
41991917e92fSdan iDepth = readInt16(aNode);
42001917e92fSdan if( iDepth>RTREE_MAX_DEPTH ){
42011917e92fSdan rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
42021917e92fSdan sqlite3_free(aNode);
42031917e92fSdan return;
42041917e92fSdan }
42051917e92fSdan }
42061917e92fSdan nCell = readInt16(&aNode[2]);
42071917e92fSdan if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
42081917e92fSdan rtreeCheckAppendMsg(pCheck,
42091917e92fSdan "Node %lld is too small for cell count of %d (%d bytes)",
42101917e92fSdan iNode, nCell, nNode
42111917e92fSdan );
42127e2b38c5Sdan }else{
42131917e92fSdan for(i=0; i<nCell; i++){
42141917e92fSdan u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
42151917e92fSdan i64 iVal = readInt64(pCell);
42161917e92fSdan rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
42171917e92fSdan
42181917e92fSdan if( iDepth>0 ){
42191917e92fSdan rtreeCheckMapping(pCheck, 0, iVal, iNode);
42201917e92fSdan rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
42211917e92fSdan pCheck->nNonLeaf++;
42221917e92fSdan }else{
42231917e92fSdan rtreeCheckMapping(pCheck, 1, iVal, iNode);
42241917e92fSdan pCheck->nLeaf++;
42251917e92fSdan }
42261917e92fSdan }
42271917e92fSdan }
42287e2b38c5Sdan }
42291917e92fSdan sqlite3_free(aNode);
42301917e92fSdan }
42311917e92fSdan }
42321917e92fSdan
42337e2b38c5Sdan /*
42347e2b38c5Sdan ** The second argument to this function must be either "_rowid" or
42357e2b38c5Sdan ** "_parent". This function checks that the number of entries in the
42367e2b38c5Sdan ** %_rowid or %_parent table is exactly nExpect. If not, it adds
42377e2b38c5Sdan ** an error message to the report in the RtreeCheck object indicated
42387e2b38c5Sdan ** by the first argument.
42397e2b38c5Sdan */
rtreeCheckCount(RtreeCheck * pCheck,const char * zTbl,i64 nExpect)42407e2b38c5Sdan static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
42411917e92fSdan if( pCheck->rc==SQLITE_OK ){
42421917e92fSdan sqlite3_stmt *pCount;
42431917e92fSdan pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
42441917e92fSdan pCheck->zDb, pCheck->zTab, zTbl
42451917e92fSdan );
42461917e92fSdan if( pCount ){
42471917e92fSdan if( sqlite3_step(pCount)==SQLITE_ROW ){
42481917e92fSdan i64 nActual = sqlite3_column_int64(pCount, 0);
42497e2b38c5Sdan if( nActual!=nExpect ){
42501917e92fSdan rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
42517e2b38c5Sdan " - expected %lld, actual %lld" , zTbl, nExpect, nActual
42521917e92fSdan );
42531917e92fSdan }
42541917e92fSdan }
42551917e92fSdan pCheck->rc = sqlite3_finalize(pCount);
42561917e92fSdan }
42571917e92fSdan }
42581917e92fSdan }
42591917e92fSdan
42607e2b38c5Sdan /*
42617e2b38c5Sdan ** This function does the bulk of the work for the rtree integrity-check.
42627e2b38c5Sdan ** It is called by rtreecheck(), which is the SQL function implementation.
42637e2b38c5Sdan */
rtreeCheckTable(sqlite3 * db,const char * zDb,const char * zTab,char ** pzReport)42647e2b38c5Sdan static int rtreeCheckTable(
42651917e92fSdan sqlite3 *db, /* Database handle to access db through */
42661917e92fSdan const char *zDb, /* Name of db ("main", "temp" etc.) */
42671917e92fSdan const char *zTab, /* Name of rtree table to check */
42681917e92fSdan char **pzReport /* OUT: sqlite3_malloc'd report text */
42691917e92fSdan ){
42701917e92fSdan RtreeCheck check; /* Common context for various routines */
42711917e92fSdan sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
42721917e92fSdan int bEnd = 0; /* True if transaction should be closed */
427326fb1266Sdrh int nAux = 0; /* Number of extra columns. */
42741917e92fSdan
42751917e92fSdan /* Initialize the context object */
42761917e92fSdan memset(&check, 0, sizeof(check));
42771917e92fSdan check.db = db;
42781917e92fSdan check.zDb = zDb;
42791917e92fSdan check.zTab = zTab;
42801917e92fSdan
42811917e92fSdan /* If there is not already an open transaction, open one now. This is
42821917e92fSdan ** to ensure that the queries run as part of this integrity-check operate
42831917e92fSdan ** on a consistent snapshot. */
42841917e92fSdan if( sqlite3_get_autocommit(db) ){
42851917e92fSdan check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
42861917e92fSdan bEnd = 1;
42871917e92fSdan }
42881917e92fSdan
428926fb1266Sdrh /* Find the number of auxiliary columns */
429026fb1266Sdrh if( check.rc==SQLITE_OK ){
429126fb1266Sdrh pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
429226fb1266Sdrh if( pStmt ){
429326fb1266Sdrh nAux = sqlite3_column_count(pStmt) - 2;
429426fb1266Sdrh sqlite3_finalize(pStmt);
42954c5b7b92Sdrh }else
42964c5b7b92Sdrh if( check.rc!=SQLITE_NOMEM ){
429726fb1266Sdrh check.rc = SQLITE_OK;
429826fb1266Sdrh }
42994c5b7b92Sdrh }
430026fb1266Sdrh
43011917e92fSdan /* Find number of dimensions in the rtree table. */
43021917e92fSdan pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
43031917e92fSdan if( pStmt ){
43041917e92fSdan int rc;
430526fb1266Sdrh check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
43061917e92fSdan if( check.nDim<1 ){
43071917e92fSdan rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
43081917e92fSdan }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
43091917e92fSdan check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
43101917e92fSdan }
43111917e92fSdan rc = sqlite3_finalize(pStmt);
43121917e92fSdan if( rc!=SQLITE_CORRUPT ) check.rc = rc;
43131917e92fSdan }
43141917e92fSdan
43151917e92fSdan /* Do the actual integrity-check */
43167e2b38c5Sdan if( check.nDim>=1 ){
43171917e92fSdan if( check.rc==SQLITE_OK ){
43181917e92fSdan rtreeCheckNode(&check, 0, 0, 1);
43191917e92fSdan }
43201917e92fSdan rtreeCheckCount(&check, "_rowid", check.nLeaf);
43211917e92fSdan rtreeCheckCount(&check, "_parent", check.nNonLeaf);
43227e2b38c5Sdan }
43231917e92fSdan
43241917e92fSdan /* Finalize SQL statements used by the integrity-check */
43251917e92fSdan sqlite3_finalize(check.pGetNode);
43261917e92fSdan sqlite3_finalize(check.aCheckMapping[0]);
43271917e92fSdan sqlite3_finalize(check.aCheckMapping[1]);
43281917e92fSdan
43291917e92fSdan /* If one was opened, close the transaction */
43301917e92fSdan if( bEnd ){
43311917e92fSdan int rc = sqlite3_exec(db, "END", 0, 0, 0);
43321917e92fSdan if( check.rc==SQLITE_OK ) check.rc = rc;
43331917e92fSdan }
43341917e92fSdan *pzReport = check.zReport;
43351917e92fSdan return check.rc;
43361917e92fSdan }
43371917e92fSdan
43381917e92fSdan /*
43391917e92fSdan ** Usage:
43401917e92fSdan **
43411917e92fSdan ** rtreecheck(<rtree-table>);
43421917e92fSdan ** rtreecheck(<database>, <rtree-table>);
43431917e92fSdan **
43441917e92fSdan ** Invoking this SQL function runs an integrity-check on the named rtree
43451917e92fSdan ** table. The integrity-check verifies the following:
43461917e92fSdan **
43471917e92fSdan ** 1. For each cell in the r-tree structure (%_node table), that:
43481917e92fSdan **
43491917e92fSdan ** a) for each dimension, (coord1 <= coord2).
43501917e92fSdan **
43511917e92fSdan ** b) unless the cell is on the root node, that the cell is bounded
43521917e92fSdan ** by the parent cell on the parent node.
43531917e92fSdan **
43541917e92fSdan ** c) for leaf nodes, that there is an entry in the %_rowid
43551917e92fSdan ** table corresponding to the cell's rowid value that
43561917e92fSdan ** points to the correct node.
43571917e92fSdan **
43581917e92fSdan ** d) for cells on non-leaf nodes, that there is an entry in the
43591917e92fSdan ** %_parent table mapping from the cell's child node to the
43601917e92fSdan ** node that it resides on.
43611917e92fSdan **
43621917e92fSdan ** 2. That there are the same number of entries in the %_rowid table
43631917e92fSdan ** as there are leaf cells in the r-tree structure, and that there
43641917e92fSdan ** is a leaf cell that corresponds to each entry in the %_rowid table.
43651917e92fSdan **
43661917e92fSdan ** 3. That there are the same number of entries in the %_parent table
43671917e92fSdan ** as there are non-leaf cells in the r-tree structure, and that
43681917e92fSdan ** there is a non-leaf cell that corresponds to each entry in the
43691917e92fSdan ** %_parent table.
43701917e92fSdan */
rtreecheck(sqlite3_context * ctx,int nArg,sqlite3_value ** apArg)43711917e92fSdan static void rtreecheck(
43721917e92fSdan sqlite3_context *ctx,
43731917e92fSdan int nArg,
43741917e92fSdan sqlite3_value **apArg
43751917e92fSdan ){
43761917e92fSdan if( nArg!=1 && nArg!=2 ){
43771917e92fSdan sqlite3_result_error(ctx,
43781917e92fSdan "wrong number of arguments to function rtreecheck()", -1
43791917e92fSdan );
43801917e92fSdan }else{
43811917e92fSdan int rc;
43821917e92fSdan char *zReport = 0;
43831917e92fSdan const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
43841917e92fSdan const char *zTab;
43851917e92fSdan if( nArg==1 ){
43861917e92fSdan zTab = zDb;
43871917e92fSdan zDb = "main";
43881917e92fSdan }else{
43891917e92fSdan zTab = (const char*)sqlite3_value_text(apArg[1]);
43901917e92fSdan }
43917e2b38c5Sdan rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
43921917e92fSdan if( rc==SQLITE_OK ){
43931917e92fSdan sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
43941917e92fSdan }else{
43951917e92fSdan sqlite3_result_error_code(ctx, rc);
43961917e92fSdan }
43971917e92fSdan sqlite3_free(zReport);
43981917e92fSdan }
43991917e92fSdan }
44001917e92fSdan
4401748b8fdaSdrh /* Conditionally include the geopoly code */
4402748b8fdaSdrh #ifdef SQLITE_ENABLE_GEOPOLY
4403748b8fdaSdrh # include "geopoly.c"
4404748b8fdaSdrh #endif
44051917e92fSdan
44061917e92fSdan /*
4407ebaecc14Sdanielk1977 ** Register the r-tree module with database handle db. This creates the
4408ebaecc14Sdanielk1977 ** virtual table module "rtree" and the debugging/analysis scalar
4409ebaecc14Sdanielk1977 ** function "rtreenode".
4410ebaecc14Sdanielk1977 */
sqlite3RtreeInit(sqlite3 * db)4411ebaecc14Sdanielk1977 int sqlite3RtreeInit(sqlite3 *db){
4412f836afd4Sdan const int utf8 = SQLITE_UTF8;
4413f836afd4Sdan int rc;
4414ebaecc14Sdanielk1977
4415ebaecc14Sdanielk1977 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
4416ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
4417ebaecc14Sdanielk1977 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
4418ebaecc14Sdanielk1977 }
4419ebaecc14Sdanielk1977 if( rc==SQLITE_OK ){
44201917e92fSdan rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
44211917e92fSdan }
44221917e92fSdan if( rc==SQLITE_OK ){
4423f439fbdaSdrh #ifdef SQLITE_RTREE_INT_ONLY
4424f439fbdaSdrh void *c = (void *)RTREE_COORD_INT32;
4425f439fbdaSdrh #else
44263ddb5a51Sdanielk1977 void *c = (void *)RTREE_COORD_REAL32;
4427f439fbdaSdrh #endif
44283ddb5a51Sdanielk1977 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
44293ddb5a51Sdanielk1977 }
44303ddb5a51Sdanielk1977 if( rc==SQLITE_OK ){
44313ddb5a51Sdanielk1977 void *c = (void *)RTREE_COORD_INT32;
44323ddb5a51Sdanielk1977 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
4433ebaecc14Sdanielk1977 }
4434748b8fdaSdrh #ifdef SQLITE_ENABLE_GEOPOLY
4435748b8fdaSdrh if( rc==SQLITE_OK ){
4436748b8fdaSdrh rc = sqlite3_geopoly_init(db);
4437748b8fdaSdrh }
4438748b8fdaSdrh #endif
4439ebaecc14Sdanielk1977
4440ebaecc14Sdanielk1977 return rc;
4441ebaecc14Sdanielk1977 }
4442ebaecc14Sdanielk1977
4443c223b8f1Sdan /*
444465e6b0ddSdrh ** This routine deletes the RtreeGeomCallback object that was attached
444565e6b0ddSdrh ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
444665e6b0ddSdrh ** or sqlite3_rtree_query_callback(). In other words, this routine is the
444765e6b0ddSdrh ** destructor for an RtreeGeomCallback objecct. This routine is called when
444865e6b0ddSdrh ** the corresponding SQL function is deleted.
4449c223b8f1Sdan */
rtreeFreeCallback(void * p)445065e6b0ddSdrh static void rtreeFreeCallback(void *p){
445165e6b0ddSdrh RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
445265e6b0ddSdrh if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
44539508daa9Sdan sqlite3_free(p);
44549508daa9Sdan }
44559508daa9Sdan
4456c223b8f1Sdan /*
44574f03f413Sdrh ** This routine frees the BLOB that is returned by geomCallback().
44584f03f413Sdrh */
rtreeMatchArgFree(void * pArg)44594f03f413Sdrh static void rtreeMatchArgFree(void *pArg){
44604f03f413Sdrh int i;
44614f03f413Sdrh RtreeMatchArg *p = (RtreeMatchArg*)pArg;
44624f03f413Sdrh for(i=0; i<p->nParam; i++){
44634f03f413Sdrh sqlite3_value_free(p->apSqlParam[i]);
44644f03f413Sdrh }
44654f03f413Sdrh sqlite3_free(p);
44664f03f413Sdrh }
44674f03f413Sdrh
44684f03f413Sdrh /*
446965e6b0ddSdrh ** Each call to sqlite3_rtree_geometry_callback() or
447065e6b0ddSdrh ** sqlite3_rtree_query_callback() creates an ordinary SQLite
447165e6b0ddSdrh ** scalar function that is implemented by this routine.
4472c223b8f1Sdan **
447365e6b0ddSdrh ** All this function does is construct an RtreeMatchArg object that
447465e6b0ddSdrh ** contains the geometry-checking callback routines and a list of
447565e6b0ddSdrh ** parameters to this function, then return that RtreeMatchArg object
447665e6b0ddSdrh ** as a BLOB.
447765e6b0ddSdrh **
447865e6b0ddSdrh ** The R-Tree MATCH operator will read the returned BLOB, deserialize
447965e6b0ddSdrh ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
448065e6b0ddSdrh ** out which elements of the R-Tree should be returned by the query.
4481c223b8f1Sdan */
geomCallback(sqlite3_context * ctx,int nArg,sqlite3_value ** aArg)44829508daa9Sdan static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
44839977edc7Sdan RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
44849977edc7Sdan RtreeMatchArg *pBlob;
44852d77d80aSdrh sqlite3_int64 nBlob;
44864f03f413Sdrh int memErr = 0;
44879508daa9Sdan
44884f03f413Sdrh nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
44894f03f413Sdrh + nArg*sizeof(sqlite3_value*);
44902d77d80aSdrh pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
44919508daa9Sdan if( !pBlob ){
44929508daa9Sdan sqlite3_result_error_nomem(ctx);
44939508daa9Sdan }else{
44949508daa9Sdan int i;
449522930062Sdrh pBlob->iSize = nBlob;
449665e6b0ddSdrh pBlob->cb = pGeomCtx[0];
44974f03f413Sdrh pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
44989508daa9Sdan pBlob->nParam = nArg;
44999508daa9Sdan for(i=0; i<nArg; i++){
45004f03f413Sdrh pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
45014f03f413Sdrh if( pBlob->apSqlParam[i]==0 ) memErr = 1;
4502f439fbdaSdrh #ifdef SQLITE_RTREE_INT_ONLY
4503f439fbdaSdrh pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
4504f439fbdaSdrh #else
45059508daa9Sdan pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
4506f439fbdaSdrh #endif
45079508daa9Sdan }
45084f03f413Sdrh if( memErr ){
45094f03f413Sdrh sqlite3_result_error_nomem(ctx);
45104f03f413Sdrh rtreeMatchArgFree(pBlob);
45114f03f413Sdrh }else{
451222930062Sdrh sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
4513856d446eSdrh }
45149508daa9Sdan }
45159508daa9Sdan }
45169508daa9Sdan
4517c223b8f1Sdan /*
4518c223b8f1Sdan ** Register a new geometry function for use with the r-tree MATCH operator.
4519c223b8f1Sdan */
sqlite3_rtree_geometry_callback(sqlite3 * db,const char * zGeom,int (* xGeom)(sqlite3_rtree_geometry *,int,RtreeDValue *,int *),void * pContext)45209508daa9Sdan int sqlite3_rtree_geometry_callback(
452165e6b0ddSdrh sqlite3 *db, /* Register SQL function on this connection */
452265e6b0ddSdrh const char *zGeom, /* Name of the new SQL function */
452365e6b0ddSdrh int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
452465e6b0ddSdrh void *pContext /* Extra data associated with the callback */
45259508daa9Sdan ){
45269977edc7Sdan RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
45279508daa9Sdan
45289508daa9Sdan /* Allocate and populate the context object. */
45299977edc7Sdan pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
45309508daa9Sdan if( !pGeomCtx ) return SQLITE_NOMEM;
45319508daa9Sdan pGeomCtx->xGeom = xGeom;
453265e6b0ddSdrh pGeomCtx->xQueryFunc = 0;
453365e6b0ddSdrh pGeomCtx->xDestructor = 0;
45349508daa9Sdan pGeomCtx->pContext = pContext;
45359508daa9Sdan return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
453665e6b0ddSdrh (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
453765e6b0ddSdrh );
453865e6b0ddSdrh }
453965e6b0ddSdrh
454065e6b0ddSdrh /*
454165e6b0ddSdrh ** Register a new 2nd-generation geometry function for use with the
454265e6b0ddSdrh ** r-tree MATCH operator.
454365e6b0ddSdrh */
sqlite3_rtree_query_callback(sqlite3 * db,const char * zQueryFunc,int (* xQueryFunc)(sqlite3_rtree_query_info *),void * pContext,void (* xDestructor)(void *))454465e6b0ddSdrh int sqlite3_rtree_query_callback(
454565e6b0ddSdrh sqlite3 *db, /* Register SQL function on this connection */
454665e6b0ddSdrh const char *zQueryFunc, /* Name of new SQL function */
454765e6b0ddSdrh int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
454865e6b0ddSdrh void *pContext, /* Extra data passed into the callback */
454965e6b0ddSdrh void (*xDestructor)(void*) /* Destructor for the extra data */
455065e6b0ddSdrh ){
455165e6b0ddSdrh RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
455265e6b0ddSdrh
455365e6b0ddSdrh /* Allocate and populate the context object. */
455465e6b0ddSdrh pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
45558e4616c2Sdrh if( !pGeomCtx ){
45568e4616c2Sdrh if( xDestructor ) xDestructor(pContext);
45578e4616c2Sdrh return SQLITE_NOMEM;
45588e4616c2Sdrh }
455965e6b0ddSdrh pGeomCtx->xGeom = 0;
456065e6b0ddSdrh pGeomCtx->xQueryFunc = xQueryFunc;
456165e6b0ddSdrh pGeomCtx->xDestructor = xDestructor;
456265e6b0ddSdrh pGeomCtx->pContext = pContext;
456365e6b0ddSdrh return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
456465e6b0ddSdrh (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
45659508daa9Sdan );
45669508daa9Sdan }
45679508daa9Sdan
4568ebaecc14Sdanielk1977 #if !SQLITE_CORE
4569049d487eSmistachkin #ifdef _WIN32
4570049d487eSmistachkin __declspec(dllexport)
4571049d487eSmistachkin #endif
sqlite3_rtree_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)4572049d487eSmistachkin int sqlite3_rtree_init(
4573ebaecc14Sdanielk1977 sqlite3 *db,
4574ebaecc14Sdanielk1977 char **pzErrMsg,
4575ebaecc14Sdanielk1977 const sqlite3_api_routines *pApi
4576ebaecc14Sdanielk1977 ){
4577ebaecc14Sdanielk1977 SQLITE_EXTENSION_INIT2(pApi)
4578ebaecc14Sdanielk1977 return sqlite3RtreeInit(db);
4579ebaecc14Sdanielk1977 }
4580ebaecc14Sdanielk1977 #endif
4581ebaecc14Sdanielk1977
4582ebaecc14Sdanielk1977 #endif
4583