rtree.c 94 KB

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