fts3_write.c 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835
  1. /*
  2. ** 2009 Oct 23
  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. **
  13. ** This file is part of the SQLite FTS3 extension module. Specifically,
  14. ** this file contains code to insert, update and delete rows from FTS3
  15. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  16. ** of the sub-routines used to merge segments are also used by the query
  17. ** code in fts3.c.
  18. */
  19. #include "fts3Int.h"
  20. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  21. #include <string.h>
  22. #include <assert.h>
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #define FTS_MAX_APPENDABLE_HEIGHT 16
  26. /*
  27. ** When full-text index nodes are loaded from disk, the buffer that they
  28. ** are loaded into has the following number of bytes of padding at the end
  29. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  30. ** of 920 bytes is allocated for it.
  31. **
  32. ** This means that if we have a pointer into a buffer containing node data,
  33. ** it is always safe to read up to two varints from it without risking an
  34. ** overread, even if the node data is corrupted.
  35. */
  36. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  37. /*
  38. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  39. ** memory incrementally instead of all at once. This can be a big performance
  40. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  41. ** method before retrieving all query results (as may happen, for example,
  42. ** if a query has a LIMIT clause).
  43. **
  44. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  45. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  46. ** The code is written so that the hard lower-limit for each of these values
  47. ** is 1. Clearly such small values would be inefficient, but can be useful
  48. ** for testing purposes.
  49. **
  50. ** If this module is built with SQLITE_TEST defined, these constants may
  51. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  52. ** a Tcl interface to read and write the values.
  53. */
  54. #ifdef SQLITE_TEST
  55. int test_fts3_node_chunksize = (4*1024);
  56. int test_fts3_node_chunk_threshold = (4*1024)*4;
  57. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  58. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  59. #else
  60. # define FTS3_NODE_CHUNKSIZE (4*1024)
  61. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  62. #endif
  63. /*
  64. ** The values that may be meaningfully bound to the :1 parameter in
  65. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  66. */
  67. #define FTS_STAT_DOCTOTAL 0
  68. #define FTS_STAT_INCRMERGEHINT 1
  69. #define FTS_STAT_AUTOINCRMERGE 2
  70. /*
  71. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  72. ** and incremental merge operation that takes place. This is used for
  73. ** debugging FTS only, it should not usually be turned on in production
  74. ** systems.
  75. */
  76. #ifdef FTS3_LOG_MERGES
  77. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  78. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  79. }
  80. #else
  81. #define fts3LogMerge(x, y)
  82. #endif
  83. typedef struct PendingList PendingList;
  84. typedef struct SegmentNode SegmentNode;
  85. typedef struct SegmentWriter SegmentWriter;
  86. /*
  87. ** An instance of the following data structure is used to build doclists
  88. ** incrementally. See function fts3PendingListAppend() for details.
  89. */
  90. struct PendingList {
  91. int nData;
  92. char *aData;
  93. int nSpace;
  94. sqlite3_int64 iLastDocid;
  95. sqlite3_int64 iLastCol;
  96. sqlite3_int64 iLastPos;
  97. };
  98. /*
  99. ** Each cursor has a (possibly empty) linked list of the following objects.
  100. */
  101. struct Fts3DeferredToken {
  102. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  103. int iCol; /* Column token must occur in */
  104. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  105. PendingList *pList; /* Doclist is assembled here */
  106. };
  107. /*
  108. ** An instance of this structure is used to iterate through the terms on
  109. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  110. ** this structure are only manipulated by code in this file, opaque handles
  111. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  112. ** terms when querying the full-text index. See functions:
  113. **
  114. ** sqlite3Fts3SegReaderNew()
  115. ** sqlite3Fts3SegReaderFree()
  116. ** sqlite3Fts3SegReaderIterate()
  117. **
  118. ** Methods used to manipulate Fts3SegReader structures:
  119. **
  120. ** fts3SegReaderNext()
  121. ** fts3SegReaderFirstDocid()
  122. ** fts3SegReaderNextDocid()
  123. */
  124. struct Fts3SegReader {
  125. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  126. u8 bLookup; /* True for a lookup only */
  127. u8 rootOnly; /* True for a root-only reader */
  128. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  129. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  130. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  131. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  132. char *aNode; /* Pointer to node data (or NULL) */
  133. int nNode; /* Size of buffer at aNode (or 0) */
  134. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  135. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  136. Fts3HashElem **ppNextElem;
  137. /* Variables set by fts3SegReaderNext(). These may be read directly
  138. ** by the caller. They are valid from the time SegmentReaderNew() returns
  139. ** until SegmentReaderNext() returns something other than SQLITE_OK
  140. ** (i.e. SQLITE_DONE).
  141. */
  142. int nTerm; /* Number of bytes in current term */
  143. char *zTerm; /* Pointer to current term */
  144. int nTermAlloc; /* Allocated size of zTerm buffer */
  145. char *aDoclist; /* Pointer to doclist of current entry */
  146. int nDoclist; /* Size of doclist in current entry */
  147. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  148. ** through the current doclist (aDoclist/nDoclist).
  149. */
  150. char *pOffsetList;
  151. int nOffsetList; /* For descending pending seg-readers only */
  152. sqlite3_int64 iDocid;
  153. };
  154. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  155. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  156. /*
  157. ** An instance of this structure is used to create a segment b-tree in the
  158. ** database. The internal details of this type are only accessed by the
  159. ** following functions:
  160. **
  161. ** fts3SegWriterAdd()
  162. ** fts3SegWriterFlush()
  163. ** fts3SegWriterFree()
  164. */
  165. struct SegmentWriter {
  166. SegmentNode *pTree; /* Pointer to interior tree structure */
  167. sqlite3_int64 iFirst; /* First slot in %_segments written */
  168. sqlite3_int64 iFree; /* Next free slot in %_segments */
  169. char *zTerm; /* Pointer to previous term buffer */
  170. int nTerm; /* Number of bytes in zTerm */
  171. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  172. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  173. int nSize; /* Size of allocation at aData */
  174. int nData; /* Bytes of data in aData */
  175. char *aData; /* Pointer to block from malloc() */
  176. i64 nLeafData; /* Number of bytes of leaf data written */
  177. };
  178. /*
  179. ** Type SegmentNode is used by the following three functions to create
  180. ** the interior part of the segment b+-tree structures (everything except
  181. ** the leaf nodes). These functions and type are only ever used by code
  182. ** within the fts3SegWriterXXX() family of functions described above.
  183. **
  184. ** fts3NodeAddTerm()
  185. ** fts3NodeWrite()
  186. ** fts3NodeFree()
  187. **
  188. ** When a b+tree is written to the database (either as a result of a merge
  189. ** or the pending-terms table being flushed), leaves are written into the
  190. ** database file as soon as they are completely populated. The interior of
  191. ** the tree is assembled in memory and written out only once all leaves have
  192. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  193. ** very large, meaning that the interior of the tree consumes relatively
  194. ** little memory.
  195. */
  196. struct SegmentNode {
  197. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  198. SegmentNode *pRight; /* Pointer to right-sibling */
  199. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  200. int nEntry; /* Number of terms written to node so far */
  201. char *zTerm; /* Pointer to previous term buffer */
  202. int nTerm; /* Number of bytes in zTerm */
  203. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  204. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  205. int nData; /* Bytes of valid data so far */
  206. char *aData; /* Node data */
  207. };
  208. /*
  209. ** Valid values for the second argument to fts3SqlStmt().
  210. */
  211. #define SQL_DELETE_CONTENT 0
  212. #define SQL_IS_EMPTY 1
  213. #define SQL_DELETE_ALL_CONTENT 2
  214. #define SQL_DELETE_ALL_SEGMENTS 3
  215. #define SQL_DELETE_ALL_SEGDIR 4
  216. #define SQL_DELETE_ALL_DOCSIZE 5
  217. #define SQL_DELETE_ALL_STAT 6
  218. #define SQL_SELECT_CONTENT_BY_ROWID 7
  219. #define SQL_NEXT_SEGMENT_INDEX 8
  220. #define SQL_INSERT_SEGMENTS 9
  221. #define SQL_NEXT_SEGMENTS_ID 10
  222. #define SQL_INSERT_SEGDIR 11
  223. #define SQL_SELECT_LEVEL 12
  224. #define SQL_SELECT_LEVEL_RANGE 13
  225. #define SQL_SELECT_LEVEL_COUNT 14
  226. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  227. #define SQL_DELETE_SEGDIR_LEVEL 16
  228. #define SQL_DELETE_SEGMENTS_RANGE 17
  229. #define SQL_CONTENT_INSERT 18
  230. #define SQL_DELETE_DOCSIZE 19
  231. #define SQL_REPLACE_DOCSIZE 20
  232. #define SQL_SELECT_DOCSIZE 21
  233. #define SQL_SELECT_STAT 22
  234. #define SQL_REPLACE_STAT 23
  235. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  236. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  237. #define SQL_DELETE_SEGDIR_RANGE 26
  238. #define SQL_SELECT_ALL_LANGID 27
  239. #define SQL_FIND_MERGE_LEVEL 28
  240. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  241. #define SQL_DELETE_SEGDIR_ENTRY 30
  242. #define SQL_SHIFT_SEGDIR_ENTRY 31
  243. #define SQL_SELECT_SEGDIR 32
  244. #define SQL_CHOMP_SEGDIR 33
  245. #define SQL_SEGMENT_IS_APPENDABLE 34
  246. #define SQL_SELECT_INDEXES 35
  247. #define SQL_SELECT_MXLEVEL 36
  248. #define SQL_SELECT_LEVEL_RANGE2 37
  249. #define SQL_UPDATE_LEVEL_IDX 38
  250. #define SQL_UPDATE_LEVEL 39
  251. /*
  252. ** This function is used to obtain an SQLite prepared statement handle
  253. ** for the statement identified by the second argument. If successful,
  254. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  255. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  256. **
  257. ** If argument apVal is not NULL, then it must point to an array with
  258. ** at least as many entries as the requested statement has bound
  259. ** parameters. The values are bound to the statements parameters before
  260. ** returning.
  261. */
  262. static int fts3SqlStmt(
  263. Fts3Table *p, /* Virtual table handle */
  264. int eStmt, /* One of the SQL_XXX constants above */
  265. sqlite3_stmt **pp, /* OUT: Statement handle */
  266. sqlite3_value **apVal /* Values to bind to statement */
  267. ){
  268. const char *azSql[] = {
  269. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  270. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  271. /* 2 */ "DELETE FROM %Q.'%q_content'",
  272. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  273. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  274. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  275. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  276. /* 7 */ "SELECT %s WHERE rowid=?",
  277. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  278. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  279. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  280. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  281. /* Return segments in order from oldest to newest.*/
  282. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  283. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  284. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  285. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  286. "ORDER BY level DESC, idx ASC",
  287. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  288. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  289. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  290. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  291. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  292. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  293. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  294. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  295. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  296. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  297. /* 24 */ "",
  298. /* 25 */ "",
  299. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  300. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  301. /* This statement is used to determine which level to read the input from
  302. ** when performing an incremental merge. It returns the absolute level number
  303. ** of the oldest level in the db that contains at least ? segments. Or,
  304. ** if no level in the FTS index contains more than ? segments, the statement
  305. ** returns zero rows. */
  306. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  307. " GROUP BY level HAVING cnt>=?"
  308. " ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1",
  309. /* Estimate the upper limit on the number of leaf nodes in a new segment
  310. ** created by merging the oldest :2 segments from absolute level :1. See
  311. ** function sqlite3Fts3Incrmerge() for details. */
  312. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  313. " FROM (SELECT * FROM %Q.'%q_segdir' "
  314. " WHERE level = ? ORDER BY idx ASC LIMIT ?"
  315. " )",
  316. /* SQL_DELETE_SEGDIR_ENTRY
  317. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  318. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  319. /* SQL_SHIFT_SEGDIR_ENTRY
  320. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  321. ** to :1. */
  322. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  323. /* SQL_SELECT_SEGDIR
  324. ** Read a single entry from the %_segdir table. The entry from absolute
  325. ** level :1 with index value :2. */
  326. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  327. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  328. /* SQL_CHOMP_SEGDIR
  329. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  330. ** entry located on absolute level :3 with index :4. */
  331. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  332. "WHERE level = ? AND idx = ?",
  333. /* SQL_SEGMENT_IS_APPENDABLE
  334. ** Return a single row if the segment with end_block=? is appendable. Or
  335. ** no rows otherwise. */
  336. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  337. /* SQL_SELECT_INDEXES
  338. ** Return the list of valid segment indexes for absolute level ? */
  339. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  340. /* SQL_SELECT_MXLEVEL
  341. ** Return the largest relative level in the FTS index or indexes. */
  342. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  343. /* Return segments in order from oldest to newest.*/
  344. /* 37 */ "SELECT level, idx, end_block "
  345. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  346. "ORDER BY level DESC, idx ASC",
  347. /* Update statements used while promoting segments */
  348. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  349. "WHERE level=? AND idx=?",
  350. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  351. };
  352. int rc = SQLITE_OK;
  353. sqlite3_stmt *pStmt;
  354. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  355. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  356. pStmt = p->aStmt[eStmt];
  357. if( !pStmt ){
  358. int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  359. char *zSql;
  360. if( eStmt==SQL_CONTENT_INSERT ){
  361. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  362. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  363. f &= ~SQLITE_PREPARE_NO_VTAB;
  364. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  365. }else{
  366. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  367. }
  368. if( !zSql ){
  369. rc = SQLITE_NOMEM;
  370. }else{
  371. rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
  372. sqlite3_free(zSql);
  373. assert( rc==SQLITE_OK || pStmt==0 );
  374. p->aStmt[eStmt] = pStmt;
  375. }
  376. }
  377. if( apVal ){
  378. int i;
  379. int nParam = sqlite3_bind_parameter_count(pStmt);
  380. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  381. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  382. }
  383. }
  384. *pp = pStmt;
  385. return rc;
  386. }
  387. static int fts3SelectDocsize(
  388. Fts3Table *pTab, /* FTS3 table handle */
  389. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  390. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  391. ){
  392. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  393. int rc; /* Return code */
  394. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  395. if( rc==SQLITE_OK ){
  396. sqlite3_bind_int64(pStmt, 1, iDocid);
  397. rc = sqlite3_step(pStmt);
  398. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  399. rc = sqlite3_reset(pStmt);
  400. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  401. pStmt = 0;
  402. }else{
  403. rc = SQLITE_OK;
  404. }
  405. }
  406. *ppStmt = pStmt;
  407. return rc;
  408. }
  409. int sqlite3Fts3SelectDoctotal(
  410. Fts3Table *pTab, /* Fts3 table handle */
  411. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  412. ){
  413. sqlite3_stmt *pStmt = 0;
  414. int rc;
  415. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  416. if( rc==SQLITE_OK ){
  417. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  418. if( sqlite3_step(pStmt)!=SQLITE_ROW
  419. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  420. ){
  421. rc = sqlite3_reset(pStmt);
  422. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  423. pStmt = 0;
  424. }
  425. }
  426. *ppStmt = pStmt;
  427. return rc;
  428. }
  429. int sqlite3Fts3SelectDocsize(
  430. Fts3Table *pTab, /* Fts3 table handle */
  431. sqlite3_int64 iDocid, /* Docid to read size data for */
  432. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  433. ){
  434. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  435. }
  436. /*
  437. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  438. ** array apVal[] to the SQL statement identified by eStmt, the statement
  439. ** is executed.
  440. **
  441. ** Returns SQLITE_OK if the statement is successfully executed, or an
  442. ** SQLite error code otherwise.
  443. */
  444. static void fts3SqlExec(
  445. int *pRC, /* Result code */
  446. Fts3Table *p, /* The FTS3 table */
  447. int eStmt, /* Index of statement to evaluate */
  448. sqlite3_value **apVal /* Parameters to bind */
  449. ){
  450. sqlite3_stmt *pStmt;
  451. int rc;
  452. if( *pRC ) return;
  453. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  454. if( rc==SQLITE_OK ){
  455. sqlite3_step(pStmt);
  456. rc = sqlite3_reset(pStmt);
  457. }
  458. *pRC = rc;
  459. }
  460. /*
  461. ** This function ensures that the caller has obtained an exclusive
  462. ** shared-cache table-lock on the %_segdir table. This is required before
  463. ** writing data to the fts3 table. If this lock is not acquired first, then
  464. ** the caller may end up attempting to take this lock as part of committing
  465. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  466. ** LOCKED_SHAREDCACHEto a COMMIT command.
  467. **
  468. ** It is best to avoid this because if FTS3 returns any error when
  469. ** committing a transaction, the whole transaction will be rolled back.
  470. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  471. ** It can still happen if the user locks the underlying tables directly
  472. ** instead of accessing them via FTS.
  473. */
  474. static int fts3Writelock(Fts3Table *p){
  475. int rc = SQLITE_OK;
  476. if( p->nPendingData==0 ){
  477. sqlite3_stmt *pStmt;
  478. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  479. if( rc==SQLITE_OK ){
  480. sqlite3_bind_null(pStmt, 1);
  481. sqlite3_step(pStmt);
  482. rc = sqlite3_reset(pStmt);
  483. }
  484. }
  485. return rc;
  486. }
  487. /*
  488. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  489. ** Within each language id, a separate index is maintained to store the
  490. ** document terms, and each configured prefix size (configured the FTS
  491. ** "prefix=" option). And each index consists of multiple levels ("relative
  492. ** levels").
  493. **
  494. ** All three of these values (the language id, the specific index and the
  495. ** level within the index) are encoded in 64-bit integer values stored
  496. ** in the %_segdir table on disk. This function is used to convert three
  497. ** separate component values into the single 64-bit integer value that
  498. ** can be used to query the %_segdir table.
  499. **
  500. ** Specifically, each language-id/index combination is allocated 1024
  501. ** 64-bit integer level values ("absolute levels"). The main terms index
  502. ** for language-id 0 is allocate values 0-1023. The first prefix index
  503. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  504. ** Language 1 indexes are allocated immediately following language 0.
  505. **
  506. ** So, for a system with nPrefix prefix indexes configured, the block of
  507. ** absolute levels that corresponds to language-id iLangid and index
  508. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  509. */
  510. static sqlite3_int64 getAbsoluteLevel(
  511. Fts3Table *p, /* FTS3 table handle */
  512. int iLangid, /* Language id */
  513. int iIndex, /* Index in p->aIndex[] */
  514. int iLevel /* Level of segments */
  515. ){
  516. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  517. assert_fts3_nc( iLangid>=0 );
  518. assert( p->nIndex>0 );
  519. assert( iIndex>=0 && iIndex<p->nIndex );
  520. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  521. return iBase + iLevel;
  522. }
  523. /*
  524. ** Set *ppStmt to a statement handle that may be used to iterate through
  525. ** all rows in the %_segdir table, from oldest to newest. If successful,
  526. ** return SQLITE_OK. If an error occurs while preparing the statement,
  527. ** return an SQLite error code.
  528. **
  529. ** There is only ever one instance of this SQL statement compiled for
  530. ** each FTS3 table.
  531. **
  532. ** The statement returns the following columns from the %_segdir table:
  533. **
  534. ** 0: idx
  535. ** 1: start_block
  536. ** 2: leaves_end_block
  537. ** 3: end_block
  538. ** 4: root
  539. */
  540. int sqlite3Fts3AllSegdirs(
  541. Fts3Table *p, /* FTS3 table */
  542. int iLangid, /* Language being queried */
  543. int iIndex, /* Index for p->aIndex[] */
  544. int iLevel, /* Level to select (relative level) */
  545. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  546. ){
  547. int rc;
  548. sqlite3_stmt *pStmt = 0;
  549. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  550. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  551. assert( iIndex>=0 && iIndex<p->nIndex );
  552. if( iLevel<0 ){
  553. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  554. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  555. if( rc==SQLITE_OK ){
  556. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  557. sqlite3_bind_int64(pStmt, 2,
  558. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  559. );
  560. }
  561. }else{
  562. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  563. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  564. if( rc==SQLITE_OK ){
  565. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  566. }
  567. }
  568. *ppStmt = pStmt;
  569. return rc;
  570. }
  571. /*
  572. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  573. ** if successful, or an SQLite error code otherwise.
  574. **
  575. ** This function also serves to allocate the PendingList structure itself.
  576. ** For example, to create a new PendingList structure containing two
  577. ** varints:
  578. **
  579. ** PendingList *p = 0;
  580. ** fts3PendingListAppendVarint(&p, 1);
  581. ** fts3PendingListAppendVarint(&p, 2);
  582. */
  583. static int fts3PendingListAppendVarint(
  584. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  585. sqlite3_int64 i /* Value to append to data */
  586. ){
  587. PendingList *p = *pp;
  588. /* Allocate or grow the PendingList as required. */
  589. if( !p ){
  590. p = sqlite3_malloc64(sizeof(*p) + 100);
  591. if( !p ){
  592. return SQLITE_NOMEM;
  593. }
  594. p->nSpace = 100;
  595. p->aData = (char *)&p[1];
  596. p->nData = 0;
  597. }
  598. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  599. i64 nNew = p->nSpace * 2;
  600. p = sqlite3_realloc64(p, sizeof(*p) + nNew);
  601. if( !p ){
  602. sqlite3_free(*pp);
  603. *pp = 0;
  604. return SQLITE_NOMEM;
  605. }
  606. p->nSpace = (int)nNew;
  607. p->aData = (char *)&p[1];
  608. }
  609. /* Append the new serialized varint to the end of the list. */
  610. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  611. p->aData[p->nData] = '\0';
  612. *pp = p;
  613. return SQLITE_OK;
  614. }
  615. /*
  616. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  617. ** is returned if the structure is sqlite3_realloced as part of adding
  618. ** the entry. Otherwise, zero.
  619. **
  620. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  621. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  622. ** it is set to SQLITE_OK.
  623. */
  624. static int fts3PendingListAppend(
  625. PendingList **pp, /* IN/OUT: PendingList structure */
  626. sqlite3_int64 iDocid, /* Docid for entry to add */
  627. sqlite3_int64 iCol, /* Column for entry to add */
  628. sqlite3_int64 iPos, /* Position of term for entry to add */
  629. int *pRc /* OUT: Return code */
  630. ){
  631. PendingList *p = *pp;
  632. int rc = SQLITE_OK;
  633. assert( !p || p->iLastDocid<=iDocid );
  634. if( !p || p->iLastDocid!=iDocid ){
  635. u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);
  636. if( p ){
  637. assert( p->nData<p->nSpace );
  638. assert( p->aData[p->nData]==0 );
  639. p->nData++;
  640. }
  641. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  642. goto pendinglistappend_out;
  643. }
  644. p->iLastCol = -1;
  645. p->iLastPos = 0;
  646. p->iLastDocid = iDocid;
  647. }
  648. if( iCol>0 && p->iLastCol!=iCol ){
  649. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  650. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  651. ){
  652. goto pendinglistappend_out;
  653. }
  654. p->iLastCol = iCol;
  655. p->iLastPos = 0;
  656. }
  657. if( iCol>=0 ){
  658. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  659. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  660. if( rc==SQLITE_OK ){
  661. p->iLastPos = iPos;
  662. }
  663. }
  664. pendinglistappend_out:
  665. *pRc = rc;
  666. if( p!=*pp ){
  667. *pp = p;
  668. return 1;
  669. }
  670. return 0;
  671. }
  672. /*
  673. ** Free a PendingList object allocated by fts3PendingListAppend().
  674. */
  675. static void fts3PendingListDelete(PendingList *pList){
  676. sqlite3_free(pList);
  677. }
  678. /*
  679. ** Add an entry to one of the pending-terms hash tables.
  680. */
  681. static int fts3PendingTermsAddOne(
  682. Fts3Table *p,
  683. int iCol,
  684. int iPos,
  685. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  686. const char *zToken,
  687. int nToken
  688. ){
  689. PendingList *pList;
  690. int rc = SQLITE_OK;
  691. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  692. if( pList ){
  693. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  694. }
  695. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  696. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  697. /* Malloc failed while inserting the new entry. This can only
  698. ** happen if there was no previous entry for this token.
  699. */
  700. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  701. sqlite3_free(pList);
  702. rc = SQLITE_NOMEM;
  703. }
  704. }
  705. if( rc==SQLITE_OK ){
  706. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  707. }
  708. return rc;
  709. }
  710. /*
  711. ** Tokenize the nul-terminated string zText and add all tokens to the
  712. ** pending-terms hash-table. The docid used is that currently stored in
  713. ** p->iPrevDocid, and the column is specified by argument iCol.
  714. **
  715. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  716. */
  717. static int fts3PendingTermsAdd(
  718. Fts3Table *p, /* Table into which text will be inserted */
  719. int iLangid, /* Language id to use */
  720. const char *zText, /* Text of document to be inserted */
  721. int iCol, /* Column into which text is being inserted */
  722. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  723. ){
  724. int rc;
  725. int iStart = 0;
  726. int iEnd = 0;
  727. int iPos = 0;
  728. int nWord = 0;
  729. char const *zToken;
  730. int nToken = 0;
  731. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  732. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  733. sqlite3_tokenizer_cursor *pCsr;
  734. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  735. const char**,int*,int*,int*,int*);
  736. assert( pTokenizer && pModule );
  737. /* If the user has inserted a NULL value, this function may be called with
  738. ** zText==0. In this case, add zero token entries to the hash table and
  739. ** return early. */
  740. if( zText==0 ){
  741. *pnWord = 0;
  742. return SQLITE_OK;
  743. }
  744. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  745. if( rc!=SQLITE_OK ){
  746. return rc;
  747. }
  748. xNext = pModule->xNext;
  749. while( SQLITE_OK==rc
  750. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  751. ){
  752. int i;
  753. if( iPos>=nWord ) nWord = iPos+1;
  754. /* Positions cannot be negative; we use -1 as a terminator internally.
  755. ** Tokens must have a non-zero length.
  756. */
  757. if( iPos<0 || !zToken || nToken<=0 ){
  758. rc = SQLITE_ERROR;
  759. break;
  760. }
  761. /* Add the term to the terms index */
  762. rc = fts3PendingTermsAddOne(
  763. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  764. );
  765. /* Add the term to each of the prefix indexes that it is not too
  766. ** short for. */
  767. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  768. struct Fts3Index *pIndex = &p->aIndex[i];
  769. if( nToken<pIndex->nPrefix ) continue;
  770. rc = fts3PendingTermsAddOne(
  771. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  772. );
  773. }
  774. }
  775. pModule->xClose(pCsr);
  776. *pnWord += nWord;
  777. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  778. }
  779. /*
  780. ** Calling this function indicates that subsequent calls to
  781. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  782. ** contents of the document with docid iDocid.
  783. */
  784. static int fts3PendingTermsDocid(
  785. Fts3Table *p, /* Full-text table handle */
  786. int bDelete, /* True if this op is a delete */
  787. int iLangid, /* Language id of row being written */
  788. sqlite_int64 iDocid /* Docid of row being written */
  789. ){
  790. assert( iLangid>=0 );
  791. assert( bDelete==1 || bDelete==0 );
  792. /* TODO(shess) Explore whether partially flushing the buffer on
  793. ** forced-flush would provide better performance. I suspect that if
  794. ** we ordered the doclists by size and flushed the largest until the
  795. ** buffer was half empty, that would let the less frequent terms
  796. ** generate longer doclists.
  797. */
  798. if( iDocid<p->iPrevDocid
  799. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  800. || p->iPrevLangid!=iLangid
  801. || p->nPendingData>p->nMaxPendingData
  802. ){
  803. int rc = sqlite3Fts3PendingTermsFlush(p);
  804. if( rc!=SQLITE_OK ) return rc;
  805. }
  806. p->iPrevDocid = iDocid;
  807. p->iPrevLangid = iLangid;
  808. p->bPrevDelete = bDelete;
  809. return SQLITE_OK;
  810. }
  811. /*
  812. ** Discard the contents of the pending-terms hash tables.
  813. */
  814. void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  815. int i;
  816. for(i=0; i<p->nIndex; i++){
  817. Fts3HashElem *pElem;
  818. Fts3Hash *pHash = &p->aIndex[i].hPending;
  819. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  820. PendingList *pList = (PendingList *)fts3HashData(pElem);
  821. fts3PendingListDelete(pList);
  822. }
  823. fts3HashClear(pHash);
  824. }
  825. p->nPendingData = 0;
  826. }
  827. /*
  828. ** This function is called by the xUpdate() method as part of an INSERT
  829. ** operation. It adds entries for each term in the new record to the
  830. ** pendingTerms hash table.
  831. **
  832. ** Argument apVal is the same as the similarly named argument passed to
  833. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  834. */
  835. static int fts3InsertTerms(
  836. Fts3Table *p,
  837. int iLangid,
  838. sqlite3_value **apVal,
  839. u32 *aSz
  840. ){
  841. int i; /* Iterator variable */
  842. for(i=2; i<p->nColumn+2; i++){
  843. int iCol = i-2;
  844. if( p->abNotindexed[iCol]==0 ){
  845. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  846. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  847. if( rc!=SQLITE_OK ){
  848. return rc;
  849. }
  850. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  851. }
  852. }
  853. return SQLITE_OK;
  854. }
  855. /*
  856. ** This function is called by the xUpdate() method for an INSERT operation.
  857. ** The apVal parameter is passed a copy of the apVal argument passed by
  858. ** SQLite to the xUpdate() method. i.e:
  859. **
  860. ** apVal[0] Not used for INSERT.
  861. ** apVal[1] rowid
  862. ** apVal[2] Left-most user-defined column
  863. ** ...
  864. ** apVal[p->nColumn+1] Right-most user-defined column
  865. ** apVal[p->nColumn+2] Hidden column with same name as table
  866. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  867. ** apVal[p->nColumn+4] Hidden languageid column
  868. */
  869. static int fts3InsertData(
  870. Fts3Table *p, /* Full-text table */
  871. sqlite3_value **apVal, /* Array of values to insert */
  872. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  873. ){
  874. int rc; /* Return code */
  875. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  876. if( p->zContentTbl ){
  877. sqlite3_value *pRowid = apVal[p->nColumn+3];
  878. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  879. pRowid = apVal[1];
  880. }
  881. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  882. return SQLITE_CONSTRAINT;
  883. }
  884. *piDocid = sqlite3_value_int64(pRowid);
  885. return SQLITE_OK;
  886. }
  887. /* Locate the statement handle used to insert data into the %_content
  888. ** table. The SQL for this statement is:
  889. **
  890. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  891. **
  892. ** The statement features N '?' variables, where N is the number of user
  893. ** defined columns in the FTS3 table, plus one for the docid field.
  894. */
  895. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  896. if( rc==SQLITE_OK && p->zLanguageid ){
  897. rc = sqlite3_bind_int(
  898. pContentInsert, p->nColumn+2,
  899. sqlite3_value_int(apVal[p->nColumn+4])
  900. );
  901. }
  902. if( rc!=SQLITE_OK ) return rc;
  903. /* There is a quirk here. The users INSERT statement may have specified
  904. ** a value for the "rowid" field, for the "docid" field, or for both.
  905. ** Which is a problem, since "rowid" and "docid" are aliases for the
  906. ** same value. For example:
  907. **
  908. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  909. **
  910. ** In FTS3, this is an error. It is an error to specify non-NULL values
  911. ** for both docid and some other rowid alias.
  912. */
  913. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  914. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  915. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  916. ){
  917. /* A rowid/docid conflict. */
  918. return SQLITE_ERROR;
  919. }
  920. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  921. if( rc!=SQLITE_OK ) return rc;
  922. }
  923. /* Execute the statement to insert the record. Set *piDocid to the
  924. ** new docid value.
  925. */
  926. sqlite3_step(pContentInsert);
  927. rc = sqlite3_reset(pContentInsert);
  928. *piDocid = sqlite3_last_insert_rowid(p->db);
  929. return rc;
  930. }
  931. /*
  932. ** Remove all data from the FTS3 table. Clear the hash table containing
  933. ** pending terms.
  934. */
  935. static int fts3DeleteAll(Fts3Table *p, int bContent){
  936. int rc = SQLITE_OK; /* Return code */
  937. /* Discard the contents of the pending-terms hash table. */
  938. sqlite3Fts3PendingTermsClear(p);
  939. /* Delete everything from the shadow tables. Except, leave %_content as
  940. ** is if bContent is false. */
  941. assert( p->zContentTbl==0 || bContent==0 );
  942. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  943. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  944. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  945. if( p->bHasDocsize ){
  946. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  947. }
  948. if( p->bHasStat ){
  949. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  950. }
  951. return rc;
  952. }
  953. /*
  954. **
  955. */
  956. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  957. int iLangid = 0;
  958. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  959. return iLangid;
  960. }
  961. /*
  962. ** The first element in the apVal[] array is assumed to contain the docid
  963. ** (an integer) of a row about to be deleted. Remove all terms from the
  964. ** full-text index.
  965. */
  966. static void fts3DeleteTerms(
  967. int *pRC, /* Result code */
  968. Fts3Table *p, /* The FTS table to delete from */
  969. sqlite3_value *pRowid, /* The docid to be deleted */
  970. u32 *aSz, /* Sizes of deleted document written here */
  971. int *pbFound /* OUT: Set to true if row really does exist */
  972. ){
  973. int rc;
  974. sqlite3_stmt *pSelect;
  975. assert( *pbFound==0 );
  976. if( *pRC ) return;
  977. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  978. if( rc==SQLITE_OK ){
  979. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  980. int i;
  981. int iLangid = langidFromSelect(p, pSelect);
  982. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  983. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  984. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  985. int iCol = i-1;
  986. if( p->abNotindexed[iCol]==0 ){
  987. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  988. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  989. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  990. }
  991. }
  992. if( rc!=SQLITE_OK ){
  993. sqlite3_reset(pSelect);
  994. *pRC = rc;
  995. return;
  996. }
  997. *pbFound = 1;
  998. }
  999. rc = sqlite3_reset(pSelect);
  1000. }else{
  1001. sqlite3_reset(pSelect);
  1002. }
  1003. *pRC = rc;
  1004. }
  1005. /*
  1006. ** Forward declaration to account for the circular dependency between
  1007. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  1008. */
  1009. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  1010. /*
  1011. ** This function allocates a new level iLevel index in the segdir table.
  1012. ** Usually, indexes are allocated within a level sequentially starting
  1013. ** with 0, so the allocated index is one greater than the value returned
  1014. ** by:
  1015. **
  1016. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  1017. **
  1018. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  1019. ** level, they are merged into a single level (iLevel+1) segment and the
  1020. ** allocated index is 0.
  1021. **
  1022. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  1023. ** returned. Otherwise, an SQLite error code is returned.
  1024. */
  1025. static int fts3AllocateSegdirIdx(
  1026. Fts3Table *p,
  1027. int iLangid, /* Language id */
  1028. int iIndex, /* Index for p->aIndex */
  1029. int iLevel,
  1030. int *piIdx
  1031. ){
  1032. int rc; /* Return Code */
  1033. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  1034. int iNext = 0; /* Result of query pNextIdx */
  1035. assert( iLangid>=0 );
  1036. assert( p->nIndex>=1 );
  1037. /* Set variable iNext to the next available segdir index at level iLevel. */
  1038. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  1039. if( rc==SQLITE_OK ){
  1040. sqlite3_bind_int64(
  1041. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  1042. );
  1043. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  1044. iNext = sqlite3_column_int(pNextIdx, 0);
  1045. }
  1046. rc = sqlite3_reset(pNextIdx);
  1047. }
  1048. if( rc==SQLITE_OK ){
  1049. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  1050. ** full, merge all segments in level iLevel into a single iLevel+1
  1051. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  1052. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  1053. */
  1054. if( iNext>=MergeCount(p) ){
  1055. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  1056. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  1057. *piIdx = 0;
  1058. }else{
  1059. *piIdx = iNext;
  1060. }
  1061. }
  1062. return rc;
  1063. }
  1064. /*
  1065. ** The %_segments table is declared as follows:
  1066. **
  1067. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  1068. **
  1069. ** This function reads data from a single row of the %_segments table. The
  1070. ** specific row is identified by the iBlockid parameter. If paBlob is not
  1071. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  1072. ** with the contents of the blob stored in the "block" column of the
  1073. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  1074. ** to the size of the blob in bytes before returning.
  1075. **
  1076. ** If an error occurs, or the table does not contain the specified row,
  1077. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  1078. ** paBlob is non-NULL, then it is the responsibility of the caller to
  1079. ** eventually free the returned buffer.
  1080. **
  1081. ** This function may leave an open sqlite3_blob* handle in the
  1082. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  1083. ** to this function. The handle may be closed by calling the
  1084. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  1085. ** performance improvement, but the blob handle should always be closed
  1086. ** before control is returned to the user (to prevent a lock being held
  1087. ** on the database file for longer than necessary). Thus, any virtual table
  1088. ** method (xFilter etc.) that may directly or indirectly call this function
  1089. ** must call sqlite3Fts3SegmentsClose() before returning.
  1090. */
  1091. int sqlite3Fts3ReadBlock(
  1092. Fts3Table *p, /* FTS3 table handle */
  1093. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  1094. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  1095. int *pnBlob, /* OUT: Size of blob data */
  1096. int *pnLoad /* OUT: Bytes actually loaded */
  1097. ){
  1098. int rc; /* Return code */
  1099. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  1100. assert( pnBlob );
  1101. if( p->pSegments ){
  1102. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  1103. }else{
  1104. if( 0==p->zSegmentsTbl ){
  1105. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  1106. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  1107. }
  1108. rc = sqlite3_blob_open(
  1109. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  1110. );
  1111. }
  1112. if( rc==SQLITE_OK ){
  1113. int nByte = sqlite3_blob_bytes(p->pSegments);
  1114. *pnBlob = nByte;
  1115. if( paBlob ){
  1116. char *aByte = sqlite3_malloc64((i64)nByte + FTS3_NODE_PADDING);
  1117. if( !aByte ){
  1118. rc = SQLITE_NOMEM;
  1119. }else{
  1120. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  1121. nByte = FTS3_NODE_CHUNKSIZE;
  1122. *pnLoad = nByte;
  1123. }
  1124. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  1125. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  1126. if( rc!=SQLITE_OK ){
  1127. sqlite3_free(aByte);
  1128. aByte = 0;
  1129. }
  1130. }
  1131. *paBlob = aByte;
  1132. }
  1133. }else if( rc==SQLITE_ERROR ){
  1134. rc = FTS_CORRUPT_VTAB;
  1135. }
  1136. return rc;
  1137. }
  1138. /*
  1139. ** Close the blob handle at p->pSegments, if it is open. See comments above
  1140. ** the sqlite3Fts3ReadBlock() function for details.
  1141. */
  1142. void sqlite3Fts3SegmentsClose(Fts3Table *p){
  1143. sqlite3_blob_close(p->pSegments);
  1144. p->pSegments = 0;
  1145. }
  1146. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  1147. int nRead; /* Number of bytes to read */
  1148. int rc; /* Return code */
  1149. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  1150. rc = sqlite3_blob_read(
  1151. pReader->pBlob,
  1152. &pReader->aNode[pReader->nPopulate],
  1153. nRead,
  1154. pReader->nPopulate
  1155. );
  1156. if( rc==SQLITE_OK ){
  1157. pReader->nPopulate += nRead;
  1158. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  1159. if( pReader->nPopulate==pReader->nNode ){
  1160. sqlite3_blob_close(pReader->pBlob);
  1161. pReader->pBlob = 0;
  1162. pReader->nPopulate = 0;
  1163. }
  1164. }
  1165. return rc;
  1166. }
  1167. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  1168. int rc = SQLITE_OK;
  1169. assert( !pReader->pBlob
  1170. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  1171. );
  1172. while( pReader->pBlob && rc==SQLITE_OK
  1173. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  1174. ){
  1175. rc = fts3SegReaderIncrRead(pReader);
  1176. }
  1177. return rc;
  1178. }
  1179. /*
  1180. ** Set an Fts3SegReader cursor to point at EOF.
  1181. */
  1182. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  1183. if( !fts3SegReaderIsRootOnly(pSeg) ){
  1184. sqlite3_free(pSeg->aNode);
  1185. sqlite3_blob_close(pSeg->pBlob);
  1186. pSeg->pBlob = 0;
  1187. }
  1188. pSeg->aNode = 0;
  1189. }
  1190. /*
  1191. ** Move the iterator passed as the first argument to the next term in the
  1192. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  1193. ** SQLITE_DONE. Otherwise, an SQLite error code.
  1194. */
  1195. static int fts3SegReaderNext(
  1196. Fts3Table *p,
  1197. Fts3SegReader *pReader,
  1198. int bIncr
  1199. ){
  1200. int rc; /* Return code of various sub-routines */
  1201. char *pNext; /* Cursor variable */
  1202. int nPrefix; /* Number of bytes in term prefix */
  1203. int nSuffix; /* Number of bytes in term suffix */
  1204. if( !pReader->aDoclist ){
  1205. pNext = pReader->aNode;
  1206. }else{
  1207. pNext = &pReader->aDoclist[pReader->nDoclist];
  1208. }
  1209. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  1210. if( fts3SegReaderIsPending(pReader) ){
  1211. Fts3HashElem *pElem = *(pReader->ppNextElem);
  1212. sqlite3_free(pReader->aNode);
  1213. pReader->aNode = 0;
  1214. if( pElem ){
  1215. char *aCopy;
  1216. PendingList *pList = (PendingList *)fts3HashData(pElem);
  1217. int nCopy = pList->nData+1;
  1218. int nTerm = fts3HashKeysize(pElem);
  1219. if( (nTerm+1)>pReader->nTermAlloc ){
  1220. sqlite3_free(pReader->zTerm);
  1221. pReader->zTerm = (char*)sqlite3_malloc64(((i64)nTerm+1)*2);
  1222. if( !pReader->zTerm ) return SQLITE_NOMEM;
  1223. pReader->nTermAlloc = (nTerm+1)*2;
  1224. }
  1225. memcpy(pReader->zTerm, fts3HashKey(pElem), nTerm);
  1226. pReader->zTerm[nTerm] = '\0';
  1227. pReader->nTerm = nTerm;
  1228. aCopy = (char*)sqlite3_malloc64(nCopy);
  1229. if( !aCopy ) return SQLITE_NOMEM;
  1230. memcpy(aCopy, pList->aData, nCopy);
  1231. pReader->nNode = pReader->nDoclist = nCopy;
  1232. pReader->aNode = pReader->aDoclist = aCopy;
  1233. pReader->ppNextElem++;
  1234. assert( pReader->aNode );
  1235. }
  1236. return SQLITE_OK;
  1237. }
  1238. fts3SegReaderSetEof(pReader);
  1239. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  1240. ** blocks have already been traversed. */
  1241. #ifdef CORRUPT_DB
  1242. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
  1243. #endif
  1244. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  1245. return SQLITE_OK;
  1246. }
  1247. rc = sqlite3Fts3ReadBlock(
  1248. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  1249. (bIncr ? &pReader->nPopulate : 0)
  1250. );
  1251. if( rc!=SQLITE_OK ) return rc;
  1252. assert( pReader->pBlob==0 );
  1253. if( bIncr && pReader->nPopulate<pReader->nNode ){
  1254. pReader->pBlob = p->pSegments;
  1255. p->pSegments = 0;
  1256. }
  1257. pNext = pReader->aNode;
  1258. }
  1259. assert( !fts3SegReaderIsPending(pReader) );
  1260. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  1261. if( rc!=SQLITE_OK ) return rc;
  1262. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  1263. ** safe (no risk of overread) even if the node data is corrupted. */
  1264. pNext += fts3GetVarint32(pNext, &nPrefix);
  1265. pNext += fts3GetVarint32(pNext, &nSuffix);
  1266. if( nSuffix<=0
  1267. || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
  1268. || nPrefix>pReader->nTerm
  1269. ){
  1270. return FTS_CORRUPT_VTAB;
  1271. }
  1272. /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
  1273. ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
  1274. ** overflow - hence the (i64) casts. */
  1275. if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
  1276. i64 nNew = ((i64)nPrefix+nSuffix)*2;
  1277. char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
  1278. if( !zNew ){
  1279. return SQLITE_NOMEM;
  1280. }
  1281. pReader->zTerm = zNew;
  1282. pReader->nTermAlloc = nNew;
  1283. }
  1284. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  1285. if( rc!=SQLITE_OK ) return rc;
  1286. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  1287. pReader->nTerm = nPrefix+nSuffix;
  1288. pNext += nSuffix;
  1289. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  1290. pReader->aDoclist = pNext;
  1291. pReader->pOffsetList = 0;
  1292. /* Check that the doclist does not appear to extend past the end of the
  1293. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  1294. ** of these statements is untrue, then the data structure is corrupt.
  1295. */
  1296. if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
  1297. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  1298. || pReader->nDoclist==0
  1299. ){
  1300. return FTS_CORRUPT_VTAB;
  1301. }
  1302. return SQLITE_OK;
  1303. }
  1304. /*
  1305. ** Set the SegReader to point to the first docid in the doclist associated
  1306. ** with the current term.
  1307. */
  1308. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  1309. int rc = SQLITE_OK;
  1310. assert( pReader->aDoclist );
  1311. assert( !pReader->pOffsetList );
  1312. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  1313. u8 bEof = 0;
  1314. pReader->iDocid = 0;
  1315. pReader->nOffsetList = 0;
  1316. sqlite3Fts3DoclistPrev(0,
  1317. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  1318. &pReader->iDocid, &pReader->nOffsetList, &bEof
  1319. );
  1320. }else{
  1321. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  1322. if( rc==SQLITE_OK ){
  1323. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  1324. pReader->pOffsetList = &pReader->aDoclist[n];
  1325. }
  1326. }
  1327. return rc;
  1328. }
  1329. /*
  1330. ** Advance the SegReader to point to the next docid in the doclist
  1331. ** associated with the current term.
  1332. **
  1333. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  1334. ** *ppOffsetList is set to point to the first column-offset list
  1335. ** in the doclist entry (i.e. immediately past the docid varint).
  1336. ** *pnOffsetList is set to the length of the set of column-offset
  1337. ** lists, not including the nul-terminator byte. For example:
  1338. */
  1339. static int fts3SegReaderNextDocid(
  1340. Fts3Table *pTab,
  1341. Fts3SegReader *pReader, /* Reader to advance to next docid */
  1342. char **ppOffsetList, /* OUT: Pointer to current position-list */
  1343. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  1344. ){
  1345. int rc = SQLITE_OK;
  1346. char *p = pReader->pOffsetList;
  1347. char c = 0;
  1348. assert( p );
  1349. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  1350. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  1351. ** Pending-terms doclists are always built up in ascending order, so
  1352. ** we have to iterate through them backwards here. */
  1353. u8 bEof = 0;
  1354. if( ppOffsetList ){
  1355. *ppOffsetList = pReader->pOffsetList;
  1356. *pnOffsetList = pReader->nOffsetList - 1;
  1357. }
  1358. sqlite3Fts3DoclistPrev(0,
  1359. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  1360. &pReader->nOffsetList, &bEof
  1361. );
  1362. if( bEof ){
  1363. pReader->pOffsetList = 0;
  1364. }else{
  1365. pReader->pOffsetList = p;
  1366. }
  1367. }else{
  1368. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  1369. /* Pointer p currently points at the first byte of an offset list. The
  1370. ** following block advances it to point one byte past the end of
  1371. ** the same offset list. */
  1372. while( 1 ){
  1373. /* The following line of code (and the "p++" below the while() loop) is
  1374. ** normally all that is required to move pointer p to the desired
  1375. ** position. The exception is if this node is being loaded from disk
  1376. ** incrementally and pointer "p" now points to the first byte past
  1377. ** the populated part of pReader->aNode[].
  1378. */
  1379. while( *p | c ) c = *p++ & 0x80;
  1380. assert( *p==0 );
  1381. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  1382. rc = fts3SegReaderIncrRead(pReader);
  1383. if( rc!=SQLITE_OK ) return rc;
  1384. }
  1385. p++;
  1386. /* If required, populate the output variables with a pointer to and the
  1387. ** size of the previous offset-list.
  1388. */
  1389. if( ppOffsetList ){
  1390. *ppOffsetList = pReader->pOffsetList;
  1391. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  1392. }
  1393. /* List may have been edited in place by fts3EvalNearTrim() */
  1394. while( p<pEnd && *p==0 ) p++;
  1395. /* If there are no more entries in the doclist, set pOffsetList to
  1396. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  1397. ** Fts3SegReader.pOffsetList to point to the next offset list before
  1398. ** returning.
  1399. */
  1400. if( p>=pEnd ){
  1401. pReader->pOffsetList = 0;
  1402. }else{
  1403. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  1404. if( rc==SQLITE_OK ){
  1405. u64 iDelta;
  1406. pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
  1407. if( pTab->bDescIdx ){
  1408. pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
  1409. }else{
  1410. pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
  1411. }
  1412. }
  1413. }
  1414. }
  1415. return rc;
  1416. }
  1417. int sqlite3Fts3MsrOvfl(
  1418. Fts3Cursor *pCsr,
  1419. Fts3MultiSegReader *pMsr,
  1420. int *pnOvfl
  1421. ){
  1422. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  1423. int nOvfl = 0;
  1424. int ii;
  1425. int rc = SQLITE_OK;
  1426. int pgsz = p->nPgsz;
  1427. assert( p->bFts4 );
  1428. assert( pgsz>0 );
  1429. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  1430. Fts3SegReader *pReader = pMsr->apSegment[ii];
  1431. if( !fts3SegReaderIsPending(pReader)
  1432. && !fts3SegReaderIsRootOnly(pReader)
  1433. ){
  1434. sqlite3_int64 jj;
  1435. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  1436. int nBlob;
  1437. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  1438. if( rc!=SQLITE_OK ) break;
  1439. if( (nBlob+35)>pgsz ){
  1440. nOvfl += (nBlob + 34)/pgsz;
  1441. }
  1442. }
  1443. }
  1444. }
  1445. *pnOvfl = nOvfl;
  1446. return rc;
  1447. }
  1448. /*
  1449. ** Free all allocations associated with the iterator passed as the
  1450. ** second argument.
  1451. */
  1452. void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  1453. if( pReader ){
  1454. sqlite3_free(pReader->zTerm);
  1455. if( !fts3SegReaderIsRootOnly(pReader) ){
  1456. sqlite3_free(pReader->aNode);
  1457. }
  1458. sqlite3_blob_close(pReader->pBlob);
  1459. }
  1460. sqlite3_free(pReader);
  1461. }
  1462. /*
  1463. ** Allocate a new SegReader object.
  1464. */
  1465. int sqlite3Fts3SegReaderNew(
  1466. int iAge, /* Segment "age". */
  1467. int bLookup, /* True for a lookup only */
  1468. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  1469. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  1470. sqlite3_int64 iEndBlock, /* Final block of segment */
  1471. const char *zRoot, /* Buffer containing root node */
  1472. int nRoot, /* Size of buffer containing root node */
  1473. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  1474. ){
  1475. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  1476. int nExtra = 0; /* Bytes to allocate segment root node */
  1477. assert( zRoot!=0 || nRoot==0 );
  1478. #ifdef CORRUPT_DB
  1479. assert( zRoot!=0 || CORRUPT_DB );
  1480. #endif
  1481. if( iStartLeaf==0 ){
  1482. if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
  1483. nExtra = nRoot + FTS3_NODE_PADDING;
  1484. }
  1485. pReader = (Fts3SegReader *)sqlite3_malloc64(sizeof(Fts3SegReader) + nExtra);
  1486. if( !pReader ){
  1487. return SQLITE_NOMEM;
  1488. }
  1489. memset(pReader, 0, sizeof(Fts3SegReader));
  1490. pReader->iIdx = iAge;
  1491. pReader->bLookup = bLookup!=0;
  1492. pReader->iStartBlock = iStartLeaf;
  1493. pReader->iLeafEndBlock = iEndLeaf;
  1494. pReader->iEndBlock = iEndBlock;
  1495. if( nExtra ){
  1496. /* The entire segment is stored in the root node. */
  1497. pReader->aNode = (char *)&pReader[1];
  1498. pReader->rootOnly = 1;
  1499. pReader->nNode = nRoot;
  1500. if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
  1501. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  1502. }else{
  1503. pReader->iCurrentBlock = iStartLeaf-1;
  1504. }
  1505. *ppReader = pReader;
  1506. return SQLITE_OK;
  1507. }
  1508. /*
  1509. ** This is a comparison function used as a qsort() callback when sorting
  1510. ** an array of pending terms by term. This occurs as part of flushing
  1511. ** the contents of the pending-terms hash table to the database.
  1512. */
  1513. static int SQLITE_CDECL fts3CompareElemByTerm(
  1514. const void *lhs,
  1515. const void *rhs
  1516. ){
  1517. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  1518. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  1519. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  1520. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  1521. int n = (n1<n2 ? n1 : n2);
  1522. int c = memcmp(z1, z2, n);
  1523. if( c==0 ){
  1524. c = n1 - n2;
  1525. }
  1526. return c;
  1527. }
  1528. /*
  1529. ** This function is used to allocate an Fts3SegReader that iterates through
  1530. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  1531. **
  1532. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  1533. ** through each term in the pending-terms table. Or, if isPrefixIter is
  1534. ** non-zero, it iterates through each term and its prefixes. For example, if
  1535. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  1536. ** "firebird", then the iterator visits the following 'terms' (in the order
  1537. ** shown):
  1538. **
  1539. ** f fi fir fire fireb firebi firebir firebird
  1540. ** m my mys mysq mysql
  1541. ** s sq sql sqli sqlit sqlite
  1542. **
  1543. ** Whereas if isPrefixIter is zero, the terms visited are:
  1544. **
  1545. ** firebird mysql sqlite
  1546. */
  1547. int sqlite3Fts3SegReaderPending(
  1548. Fts3Table *p, /* Virtual table handle */
  1549. int iIndex, /* Index for p->aIndex */
  1550. const char *zTerm, /* Term to search for */
  1551. int nTerm, /* Size of buffer zTerm */
  1552. int bPrefix, /* True for a prefix iterator */
  1553. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  1554. ){
  1555. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  1556. Fts3HashElem *pE; /* Iterator variable */
  1557. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  1558. int nElem = 0; /* Size of array at aElem */
  1559. int rc = SQLITE_OK; /* Return Code */
  1560. Fts3Hash *pHash;
  1561. pHash = &p->aIndex[iIndex].hPending;
  1562. if( bPrefix ){
  1563. int nAlloc = 0; /* Size of allocated array at aElem */
  1564. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  1565. char *zKey = (char *)fts3HashKey(pE);
  1566. int nKey = fts3HashKeysize(pE);
  1567. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  1568. if( nElem==nAlloc ){
  1569. Fts3HashElem **aElem2;
  1570. nAlloc += 16;
  1571. aElem2 = (Fts3HashElem **)sqlite3_realloc64(
  1572. aElem, nAlloc*sizeof(Fts3HashElem *)
  1573. );
  1574. if( !aElem2 ){
  1575. rc = SQLITE_NOMEM;
  1576. nElem = 0;
  1577. break;
  1578. }
  1579. aElem = aElem2;
  1580. }
  1581. aElem[nElem++] = pE;
  1582. }
  1583. }
  1584. /* If more than one term matches the prefix, sort the Fts3HashElem
  1585. ** objects in term order using qsort(). This uses the same comparison
  1586. ** callback as is used when flushing terms to disk.
  1587. */
  1588. if( nElem>1 ){
  1589. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  1590. }
  1591. }else{
  1592. /* The query is a simple term lookup that matches at most one term in
  1593. ** the index. All that is required is a straight hash-lookup.
  1594. **
  1595. ** Because the stack address of pE may be accessed via the aElem pointer
  1596. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  1597. ** within this entire function, not just this "else{...}" block.
  1598. */
  1599. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  1600. if( pE ){
  1601. aElem = &pE;
  1602. nElem = 1;
  1603. }
  1604. }
  1605. if( nElem>0 ){
  1606. sqlite3_int64 nByte;
  1607. nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  1608. pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
  1609. if( !pReader ){
  1610. rc = SQLITE_NOMEM;
  1611. }else{
  1612. memset(pReader, 0, nByte);
  1613. pReader->iIdx = 0x7FFFFFFF;
  1614. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  1615. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  1616. }
  1617. }
  1618. if( bPrefix ){
  1619. sqlite3_free(aElem);
  1620. }
  1621. *ppReader = pReader;
  1622. return rc;
  1623. }
  1624. /*
  1625. ** Compare the entries pointed to by two Fts3SegReader structures.
  1626. ** Comparison is as follows:
  1627. **
  1628. ** 1) EOF is greater than not EOF.
  1629. **
  1630. ** 2) The current terms (if any) are compared using memcmp(). If one
  1631. ** term is a prefix of another, the longer term is considered the
  1632. ** larger.
  1633. **
  1634. ** 3) By segment age. An older segment is considered larger.
  1635. */
  1636. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  1637. int rc;
  1638. if( pLhs->aNode && pRhs->aNode ){
  1639. int rc2 = pLhs->nTerm - pRhs->nTerm;
  1640. if( rc2<0 ){
  1641. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  1642. }else{
  1643. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  1644. }
  1645. if( rc==0 ){
  1646. rc = rc2;
  1647. }
  1648. }else{
  1649. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  1650. }
  1651. if( rc==0 ){
  1652. rc = pRhs->iIdx - pLhs->iIdx;
  1653. }
  1654. assert_fts3_nc( rc!=0 );
  1655. return rc;
  1656. }
  1657. /*
  1658. ** A different comparison function for SegReader structures. In this
  1659. ** version, it is assumed that each SegReader points to an entry in
  1660. ** a doclist for identical terms. Comparison is made as follows:
  1661. **
  1662. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  1663. **
  1664. ** 2) By current docid.
  1665. **
  1666. ** 3) By segment age. An older segment is considered larger.
  1667. */
  1668. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  1669. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  1670. if( rc==0 ){
  1671. if( pLhs->iDocid==pRhs->iDocid ){
  1672. rc = pRhs->iIdx - pLhs->iIdx;
  1673. }else{
  1674. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  1675. }
  1676. }
  1677. assert( pLhs->aNode && pRhs->aNode );
  1678. return rc;
  1679. }
  1680. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  1681. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  1682. if( rc==0 ){
  1683. if( pLhs->iDocid==pRhs->iDocid ){
  1684. rc = pRhs->iIdx - pLhs->iIdx;
  1685. }else{
  1686. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  1687. }
  1688. }
  1689. assert( pLhs->aNode && pRhs->aNode );
  1690. return rc;
  1691. }
  1692. /*
  1693. ** Compare the term that the Fts3SegReader object passed as the first argument
  1694. ** points to with the term specified by arguments zTerm and nTerm.
  1695. **
  1696. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  1697. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  1698. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  1699. */
  1700. static int fts3SegReaderTermCmp(
  1701. Fts3SegReader *pSeg, /* Segment reader object */
  1702. const char *zTerm, /* Term to compare to */
  1703. int nTerm /* Size of term zTerm in bytes */
  1704. ){
  1705. int res = 0;
  1706. if( pSeg->aNode ){
  1707. if( pSeg->nTerm>nTerm ){
  1708. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  1709. }else{
  1710. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  1711. }
  1712. if( res==0 ){
  1713. res = pSeg->nTerm-nTerm;
  1714. }
  1715. }
  1716. return res;
  1717. }
  1718. /*
  1719. ** Argument apSegment is an array of nSegment elements. It is known that
  1720. ** the final (nSegment-nSuspect) members are already in sorted order
  1721. ** (according to the comparison function provided). This function shuffles
  1722. ** the array around until all entries are in sorted order.
  1723. */
  1724. static void fts3SegReaderSort(
  1725. Fts3SegReader **apSegment, /* Array to sort entries of */
  1726. int nSegment, /* Size of apSegment array */
  1727. int nSuspect, /* Unsorted entry count */
  1728. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  1729. ){
  1730. int i; /* Iterator variable */
  1731. assert( nSuspect<=nSegment );
  1732. if( nSuspect==nSegment ) nSuspect--;
  1733. for(i=nSuspect-1; i>=0; i--){
  1734. int j;
  1735. for(j=i; j<(nSegment-1); j++){
  1736. Fts3SegReader *pTmp;
  1737. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  1738. pTmp = apSegment[j+1];
  1739. apSegment[j+1] = apSegment[j];
  1740. apSegment[j] = pTmp;
  1741. }
  1742. }
  1743. #ifndef NDEBUG
  1744. /* Check that the list really is sorted now. */
  1745. for(i=0; i<(nSuspect-1); i++){
  1746. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  1747. }
  1748. #endif
  1749. }
  1750. /*
  1751. ** Insert a record into the %_segments table.
  1752. */
  1753. static int fts3WriteSegment(
  1754. Fts3Table *p, /* Virtual table handle */
  1755. sqlite3_int64 iBlock, /* Block id for new block */
  1756. char *z, /* Pointer to buffer containing block data */
  1757. int n /* Size of buffer z in bytes */
  1758. ){
  1759. sqlite3_stmt *pStmt;
  1760. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  1761. if( rc==SQLITE_OK ){
  1762. sqlite3_bind_int64(pStmt, 1, iBlock);
  1763. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  1764. sqlite3_step(pStmt);
  1765. rc = sqlite3_reset(pStmt);
  1766. sqlite3_bind_null(pStmt, 2);
  1767. }
  1768. return rc;
  1769. }
  1770. /*
  1771. ** Find the largest relative level number in the table. If successful, set
  1772. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  1773. ** set *pnMax to zero and return an SQLite error code.
  1774. */
  1775. int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  1776. int rc;
  1777. int mxLevel = 0;
  1778. sqlite3_stmt *pStmt = 0;
  1779. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  1780. if( rc==SQLITE_OK ){
  1781. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  1782. mxLevel = sqlite3_column_int(pStmt, 0);
  1783. }
  1784. rc = sqlite3_reset(pStmt);
  1785. }
  1786. *pnMax = mxLevel;
  1787. return rc;
  1788. }
  1789. /*
  1790. ** Insert a record into the %_segdir table.
  1791. */
  1792. static int fts3WriteSegdir(
  1793. Fts3Table *p, /* Virtual table handle */
  1794. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  1795. int iIdx, /* Value for "idx" field */
  1796. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  1797. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  1798. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  1799. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  1800. char *zRoot, /* Blob value for "root" field */
  1801. int nRoot /* Number of bytes in buffer zRoot */
  1802. ){
  1803. sqlite3_stmt *pStmt;
  1804. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  1805. if( rc==SQLITE_OK ){
  1806. sqlite3_bind_int64(pStmt, 1, iLevel);
  1807. sqlite3_bind_int(pStmt, 2, iIdx);
  1808. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  1809. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  1810. if( nLeafData==0 ){
  1811. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  1812. }else{
  1813. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  1814. if( !zEnd ) return SQLITE_NOMEM;
  1815. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  1816. }
  1817. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  1818. sqlite3_step(pStmt);
  1819. rc = sqlite3_reset(pStmt);
  1820. sqlite3_bind_null(pStmt, 6);
  1821. }
  1822. return rc;
  1823. }
  1824. /*
  1825. ** Return the size of the common prefix (if any) shared by zPrev and
  1826. ** zNext, in bytes. For example,
  1827. **
  1828. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  1829. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  1830. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  1831. */
  1832. static int fts3PrefixCompress(
  1833. const char *zPrev, /* Buffer containing previous term */
  1834. int nPrev, /* Size of buffer zPrev in bytes */
  1835. const char *zNext, /* Buffer containing next term */
  1836. int nNext /* Size of buffer zNext in bytes */
  1837. ){
  1838. int n;
  1839. for(n=0; n<nPrev && n<nNext && zPrev[n]==zNext[n]; n++);
  1840. assert_fts3_nc( n<nNext );
  1841. return n;
  1842. }
  1843. /*
  1844. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  1845. ** (according to memcmp) than the previous term.
  1846. */
  1847. static int fts3NodeAddTerm(
  1848. Fts3Table *p, /* Virtual table handle */
  1849. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  1850. int isCopyTerm, /* True if zTerm/nTerm is transient */
  1851. const char *zTerm, /* Pointer to buffer containing term */
  1852. int nTerm /* Size of term in bytes */
  1853. ){
  1854. SegmentNode *pTree = *ppTree;
  1855. int rc;
  1856. SegmentNode *pNew;
  1857. /* First try to append the term to the current node. Return early if
  1858. ** this is possible.
  1859. */
  1860. if( pTree ){
  1861. int nData = pTree->nData; /* Current size of node in bytes */
  1862. int nReq = nData; /* Required space after adding zTerm */
  1863. int nPrefix; /* Number of bytes of prefix compression */
  1864. int nSuffix; /* Suffix length */
  1865. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  1866. nSuffix = nTerm-nPrefix;
  1867. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  1868. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  1869. ** compared with BINARY collation. This indicates corruption. */
  1870. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  1871. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  1872. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  1873. if( nReq>p->nNodeSize ){
  1874. /* An unusual case: this is the first term to be added to the node
  1875. ** and the static node buffer (p->nNodeSize bytes) is not large
  1876. ** enough. Use a separately malloced buffer instead This wastes
  1877. ** p->nNodeSize bytes, but since this scenario only comes about when
  1878. ** the database contain two terms that share a prefix of almost 2KB,
  1879. ** this is not expected to be a serious problem.
  1880. */
  1881. assert( pTree->aData==(char *)&pTree[1] );
  1882. pTree->aData = (char *)sqlite3_malloc64(nReq);
  1883. if( !pTree->aData ){
  1884. return SQLITE_NOMEM;
  1885. }
  1886. }
  1887. if( pTree->zTerm ){
  1888. /* There is no prefix-length field for first term in a node */
  1889. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  1890. }
  1891. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  1892. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  1893. pTree->nData = nData + nSuffix;
  1894. pTree->nEntry++;
  1895. if( isCopyTerm ){
  1896. if( pTree->nMalloc<nTerm ){
  1897. char *zNew = sqlite3_realloc64(pTree->zMalloc, (i64)nTerm*2);
  1898. if( !zNew ){
  1899. return SQLITE_NOMEM;
  1900. }
  1901. pTree->nMalloc = nTerm*2;
  1902. pTree->zMalloc = zNew;
  1903. }
  1904. pTree->zTerm = pTree->zMalloc;
  1905. memcpy(pTree->zTerm, zTerm, nTerm);
  1906. pTree->nTerm = nTerm;
  1907. }else{
  1908. pTree->zTerm = (char *)zTerm;
  1909. pTree->nTerm = nTerm;
  1910. }
  1911. return SQLITE_OK;
  1912. }
  1913. }
  1914. /* If control flows to here, it was not possible to append zTerm to the
  1915. ** current node. Create a new node (a right-sibling of the current node).
  1916. ** If this is the first node in the tree, the term is added to it.
  1917. **
  1918. ** Otherwise, the term is not added to the new node, it is left empty for
  1919. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  1920. ** has no parent, one is created here.
  1921. */
  1922. pNew = (SegmentNode *)sqlite3_malloc64(sizeof(SegmentNode) + p->nNodeSize);
  1923. if( !pNew ){
  1924. return SQLITE_NOMEM;
  1925. }
  1926. memset(pNew, 0, sizeof(SegmentNode));
  1927. pNew->nData = 1 + FTS3_VARINT_MAX;
  1928. pNew->aData = (char *)&pNew[1];
  1929. if( pTree ){
  1930. SegmentNode *pParent = pTree->pParent;
  1931. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  1932. if( pTree->pParent==0 ){
  1933. pTree->pParent = pParent;
  1934. }
  1935. pTree->pRight = pNew;
  1936. pNew->pLeftmost = pTree->pLeftmost;
  1937. pNew->pParent = pParent;
  1938. pNew->zMalloc = pTree->zMalloc;
  1939. pNew->nMalloc = pTree->nMalloc;
  1940. pTree->zMalloc = 0;
  1941. }else{
  1942. pNew->pLeftmost = pNew;
  1943. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  1944. }
  1945. *ppTree = pNew;
  1946. return rc;
  1947. }
  1948. /*
  1949. ** Helper function for fts3NodeWrite().
  1950. */
  1951. static int fts3TreeFinishNode(
  1952. SegmentNode *pTree,
  1953. int iHeight,
  1954. sqlite3_int64 iLeftChild
  1955. ){
  1956. int nStart;
  1957. assert( iHeight>=1 && iHeight<128 );
  1958. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  1959. pTree->aData[nStart] = (char)iHeight;
  1960. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  1961. return nStart;
  1962. }
  1963. /*
  1964. ** Write the buffer for the segment node pTree and all of its peers to the
  1965. ** database. Then call this function recursively to write the parent of
  1966. ** pTree and its peers to the database.
  1967. **
  1968. ** Except, if pTree is a root node, do not write it to the database. Instead,
  1969. ** set output variables *paRoot and *pnRoot to contain the root node.
  1970. **
  1971. ** If successful, SQLITE_OK is returned and output variable *piLast is
  1972. ** set to the largest blockid written to the database (or zero if no
  1973. ** blocks were written to the db). Otherwise, an SQLite error code is
  1974. ** returned.
  1975. */
  1976. static int fts3NodeWrite(
  1977. Fts3Table *p, /* Virtual table handle */
  1978. SegmentNode *pTree, /* SegmentNode handle */
  1979. int iHeight, /* Height of this node in tree */
  1980. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  1981. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  1982. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  1983. char **paRoot, /* OUT: Data for root node */
  1984. int *pnRoot /* OUT: Size of root node in bytes */
  1985. ){
  1986. int rc = SQLITE_OK;
  1987. if( !pTree->pParent ){
  1988. /* Root node of the tree. */
  1989. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  1990. *piLast = iFree-1;
  1991. *pnRoot = pTree->nData - nStart;
  1992. *paRoot = &pTree->aData[nStart];
  1993. }else{
  1994. SegmentNode *pIter;
  1995. sqlite3_int64 iNextFree = iFree;
  1996. sqlite3_int64 iNextLeaf = iLeaf;
  1997. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  1998. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  1999. int nWrite = pIter->nData - nStart;
  2000. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  2001. iNextFree++;
  2002. iNextLeaf += (pIter->nEntry+1);
  2003. }
  2004. if( rc==SQLITE_OK ){
  2005. assert( iNextLeaf==iFree );
  2006. rc = fts3NodeWrite(
  2007. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  2008. );
  2009. }
  2010. }
  2011. return rc;
  2012. }
  2013. /*
  2014. ** Free all memory allocations associated with the tree pTree.
  2015. */
  2016. static void fts3NodeFree(SegmentNode *pTree){
  2017. if( pTree ){
  2018. SegmentNode *p = pTree->pLeftmost;
  2019. fts3NodeFree(p->pParent);
  2020. while( p ){
  2021. SegmentNode *pRight = p->pRight;
  2022. if( p->aData!=(char *)&p[1] ){
  2023. sqlite3_free(p->aData);
  2024. }
  2025. assert( pRight==0 || p->zMalloc==0 );
  2026. sqlite3_free(p->zMalloc);
  2027. sqlite3_free(p);
  2028. p = pRight;
  2029. }
  2030. }
  2031. }
  2032. /*
  2033. ** Add a term to the segment being constructed by the SegmentWriter object
  2034. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  2035. ** be passed NULL. This function will allocate a new SegmentWriter object
  2036. ** and return it via the input/output variable *ppWriter in this case.
  2037. **
  2038. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  2039. */
  2040. static int fts3SegWriterAdd(
  2041. Fts3Table *p, /* Virtual table handle */
  2042. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  2043. int isCopyTerm, /* True if buffer zTerm must be copied */
  2044. const char *zTerm, /* Pointer to buffer containing term */
  2045. int nTerm, /* Size of term in bytes */
  2046. const char *aDoclist, /* Pointer to buffer containing doclist */
  2047. int nDoclist /* Size of doclist in bytes */
  2048. ){
  2049. int nPrefix; /* Size of term prefix in bytes */
  2050. int nSuffix; /* Size of term suffix in bytes */
  2051. i64 nReq; /* Number of bytes required on leaf page */
  2052. int nData;
  2053. SegmentWriter *pWriter = *ppWriter;
  2054. if( !pWriter ){
  2055. int rc;
  2056. sqlite3_stmt *pStmt;
  2057. /* Allocate the SegmentWriter structure */
  2058. pWriter = (SegmentWriter *)sqlite3_malloc64(sizeof(SegmentWriter));
  2059. if( !pWriter ) return SQLITE_NOMEM;
  2060. memset(pWriter, 0, sizeof(SegmentWriter));
  2061. *ppWriter = pWriter;
  2062. /* Allocate a buffer in which to accumulate data */
  2063. pWriter->aData = (char *)sqlite3_malloc64(p->nNodeSize);
  2064. if( !pWriter->aData ) return SQLITE_NOMEM;
  2065. pWriter->nSize = p->nNodeSize;
  2066. /* Find the next free blockid in the %_segments table */
  2067. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  2068. if( rc!=SQLITE_OK ) return rc;
  2069. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  2070. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  2071. pWriter->iFirst = pWriter->iFree;
  2072. }
  2073. rc = sqlite3_reset(pStmt);
  2074. if( rc!=SQLITE_OK ) return rc;
  2075. }
  2076. nData = pWriter->nData;
  2077. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  2078. nSuffix = nTerm-nPrefix;
  2079. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  2080. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  2081. ** compared with BINARY collation. This indicates corruption. */
  2082. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  2083. /* Figure out how many bytes are required by this new entry */
  2084. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  2085. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  2086. nSuffix + /* Term suffix */
  2087. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  2088. nDoclist; /* Doclist data */
  2089. if( nData>0 && nData+nReq>p->nNodeSize ){
  2090. int rc;
  2091. /* The current leaf node is full. Write it out to the database. */
  2092. if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
  2093. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  2094. if( rc!=SQLITE_OK ) return rc;
  2095. p->nLeafAdd++;
  2096. /* Add the current term to the interior node tree. The term added to
  2097. ** the interior tree must:
  2098. **
  2099. ** a) be greater than the largest term on the leaf node just written
  2100. ** to the database (still available in pWriter->zTerm), and
  2101. **
  2102. ** b) be less than or equal to the term about to be added to the new
  2103. ** leaf node (zTerm/nTerm).
  2104. **
  2105. ** In other words, it must be the prefix of zTerm 1 byte longer than
  2106. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  2107. */
  2108. assert( nPrefix<nTerm );
  2109. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  2110. if( rc!=SQLITE_OK ) return rc;
  2111. nData = 0;
  2112. pWriter->nTerm = 0;
  2113. nPrefix = 0;
  2114. nSuffix = nTerm;
  2115. nReq = 1 + /* varint containing prefix size */
  2116. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  2117. nTerm + /* Term suffix */
  2118. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  2119. nDoclist; /* Doclist data */
  2120. }
  2121. /* Increase the total number of bytes written to account for the new entry. */
  2122. pWriter->nLeafData += nReq;
  2123. /* If the buffer currently allocated is too small for this entry, realloc
  2124. ** the buffer to make it large enough.
  2125. */
  2126. if( nReq>pWriter->nSize ){
  2127. char *aNew = sqlite3_realloc64(pWriter->aData, nReq);
  2128. if( !aNew ) return SQLITE_NOMEM;
  2129. pWriter->aData = aNew;
  2130. pWriter->nSize = nReq;
  2131. }
  2132. assert( nData+nReq<=pWriter->nSize );
  2133. /* Append the prefix-compressed term and doclist to the buffer. */
  2134. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  2135. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  2136. assert( nSuffix>0 );
  2137. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  2138. nData += nSuffix;
  2139. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  2140. assert( nDoclist>0 );
  2141. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  2142. pWriter->nData = nData + nDoclist;
  2143. /* Save the current term so that it can be used to prefix-compress the next.
  2144. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  2145. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  2146. ** store a copy of the pointer.
  2147. */
  2148. if( isCopyTerm ){
  2149. if( nTerm>pWriter->nMalloc ){
  2150. char *zNew = sqlite3_realloc64(pWriter->zMalloc, (i64)nTerm*2);
  2151. if( !zNew ){
  2152. return SQLITE_NOMEM;
  2153. }
  2154. pWriter->nMalloc = nTerm*2;
  2155. pWriter->zMalloc = zNew;
  2156. pWriter->zTerm = zNew;
  2157. }
  2158. assert( pWriter->zTerm==pWriter->zMalloc );
  2159. assert( nTerm>0 );
  2160. memcpy(pWriter->zTerm, zTerm, nTerm);
  2161. }else{
  2162. pWriter->zTerm = (char *)zTerm;
  2163. }
  2164. pWriter->nTerm = nTerm;
  2165. return SQLITE_OK;
  2166. }
  2167. /*
  2168. ** Flush all data associated with the SegmentWriter object pWriter to the
  2169. ** database. This function must be called after all terms have been added
  2170. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  2171. ** returned. Otherwise, an SQLite error code.
  2172. */
  2173. static int fts3SegWriterFlush(
  2174. Fts3Table *p, /* Virtual table handle */
  2175. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  2176. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  2177. int iIdx /* Value for 'idx' column of %_segdir */
  2178. ){
  2179. int rc; /* Return code */
  2180. if( pWriter->pTree ){
  2181. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  2182. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  2183. char *zRoot = NULL; /* Pointer to buffer containing root node */
  2184. int nRoot = 0; /* Size of buffer zRoot */
  2185. iLastLeaf = pWriter->iFree;
  2186. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  2187. if( rc==SQLITE_OK ){
  2188. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  2189. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  2190. }
  2191. if( rc==SQLITE_OK ){
  2192. rc = fts3WriteSegdir(p, iLevel, iIdx,
  2193. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  2194. }
  2195. }else{
  2196. /* The entire tree fits on the root node. Write it to the segdir table. */
  2197. rc = fts3WriteSegdir(p, iLevel, iIdx,
  2198. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  2199. }
  2200. p->nLeafAdd++;
  2201. return rc;
  2202. }
  2203. /*
  2204. ** Release all memory held by the SegmentWriter object passed as the
  2205. ** first argument.
  2206. */
  2207. static void fts3SegWriterFree(SegmentWriter *pWriter){
  2208. if( pWriter ){
  2209. sqlite3_free(pWriter->aData);
  2210. sqlite3_free(pWriter->zMalloc);
  2211. fts3NodeFree(pWriter->pTree);
  2212. sqlite3_free(pWriter);
  2213. }
  2214. }
  2215. /*
  2216. ** The first value in the apVal[] array is assumed to contain an integer.
  2217. ** This function tests if there exist any documents with docid values that
  2218. ** are different from that integer. i.e. if deleting the document with docid
  2219. ** pRowid would mean the FTS3 table were empty.
  2220. **
  2221. ** If successful, *pisEmpty is set to true if the table is empty except for
  2222. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  2223. ** error occurs, an SQLite error code is returned.
  2224. */
  2225. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  2226. sqlite3_stmt *pStmt;
  2227. int rc;
  2228. if( p->zContentTbl ){
  2229. /* If using the content=xxx option, assume the table is never empty */
  2230. *pisEmpty = 0;
  2231. rc = SQLITE_OK;
  2232. }else{
  2233. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  2234. if( rc==SQLITE_OK ){
  2235. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  2236. *pisEmpty = sqlite3_column_int(pStmt, 0);
  2237. }
  2238. rc = sqlite3_reset(pStmt);
  2239. }
  2240. }
  2241. return rc;
  2242. }
  2243. /*
  2244. ** Set *pnMax to the largest segment level in the database for the index
  2245. ** iIndex.
  2246. **
  2247. ** Segment levels are stored in the 'level' column of the %_segdir table.
  2248. **
  2249. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  2250. */
  2251. static int fts3SegmentMaxLevel(
  2252. Fts3Table *p,
  2253. int iLangid,
  2254. int iIndex,
  2255. sqlite3_int64 *pnMax
  2256. ){
  2257. sqlite3_stmt *pStmt;
  2258. int rc;
  2259. assert( iIndex>=0 && iIndex<p->nIndex );
  2260. /* Set pStmt to the compiled version of:
  2261. **
  2262. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  2263. **
  2264. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  2265. */
  2266. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  2267. if( rc!=SQLITE_OK ) return rc;
  2268. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  2269. sqlite3_bind_int64(pStmt, 2,
  2270. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  2271. );
  2272. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  2273. *pnMax = sqlite3_column_int64(pStmt, 0);
  2274. }
  2275. return sqlite3_reset(pStmt);
  2276. }
  2277. /*
  2278. ** iAbsLevel is an absolute level that may be assumed to exist within
  2279. ** the database. This function checks if it is the largest level number
  2280. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  2281. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  2282. ** is returned. If an error occurs, an error code is returned and the
  2283. ** final value of *pbMax is undefined.
  2284. */
  2285. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  2286. /* Set pStmt to the compiled version of:
  2287. **
  2288. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  2289. **
  2290. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  2291. */
  2292. sqlite3_stmt *pStmt;
  2293. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  2294. if( rc!=SQLITE_OK ) return rc;
  2295. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  2296. sqlite3_bind_int64(pStmt, 2,
  2297. (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  2298. );
  2299. *pbMax = 0;
  2300. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  2301. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  2302. }
  2303. return sqlite3_reset(pStmt);
  2304. }
  2305. /*
  2306. ** Delete all entries in the %_segments table associated with the segment
  2307. ** opened with seg-reader pSeg. This function does not affect the contents
  2308. ** of the %_segdir table.
  2309. */
  2310. static int fts3DeleteSegment(
  2311. Fts3Table *p, /* FTS table handle */
  2312. Fts3SegReader *pSeg /* Segment to delete */
  2313. ){
  2314. int rc = SQLITE_OK; /* Return code */
  2315. if( pSeg->iStartBlock ){
  2316. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  2317. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  2318. if( rc==SQLITE_OK ){
  2319. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  2320. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  2321. sqlite3_step(pDelete);
  2322. rc = sqlite3_reset(pDelete);
  2323. }
  2324. }
  2325. return rc;
  2326. }
  2327. /*
  2328. ** This function is used after merging multiple segments into a single large
  2329. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  2330. ** it:
  2331. **
  2332. ** 1) Deletes all %_segments entries for the segments associated with
  2333. ** each of the SegReader objects in the array passed as the third
  2334. ** argument, and
  2335. **
  2336. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  2337. ** entries regardless of level if (iLevel<0).
  2338. **
  2339. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  2340. */
  2341. static int fts3DeleteSegdir(
  2342. Fts3Table *p, /* Virtual table handle */
  2343. int iLangid, /* Language id */
  2344. int iIndex, /* Index for p->aIndex */
  2345. int iLevel, /* Level of %_segdir entries to delete */
  2346. Fts3SegReader **apSegment, /* Array of SegReader objects */
  2347. int nReader /* Size of array apSegment */
  2348. ){
  2349. int rc = SQLITE_OK; /* Return Code */
  2350. int i; /* Iterator variable */
  2351. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  2352. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  2353. rc = fts3DeleteSegment(p, apSegment[i]);
  2354. }
  2355. if( rc!=SQLITE_OK ){
  2356. return rc;
  2357. }
  2358. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  2359. if( iLevel==FTS3_SEGCURSOR_ALL ){
  2360. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  2361. if( rc==SQLITE_OK ){
  2362. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  2363. sqlite3_bind_int64(pDelete, 2,
  2364. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  2365. );
  2366. }
  2367. }else{
  2368. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  2369. if( rc==SQLITE_OK ){
  2370. sqlite3_bind_int64(
  2371. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  2372. );
  2373. }
  2374. }
  2375. if( rc==SQLITE_OK ){
  2376. sqlite3_step(pDelete);
  2377. rc = sqlite3_reset(pDelete);
  2378. }
  2379. return rc;
  2380. }
  2381. /*
  2382. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  2383. ** a position list that may (or may not) feature multiple columns. This
  2384. ** function adjusts the pointer *ppList and the length *pnList so that they
  2385. ** identify the subset of the position list that corresponds to column iCol.
  2386. **
  2387. ** If there are no entries in the input position list for column iCol, then
  2388. ** *pnList is set to zero before returning.
  2389. **
  2390. ** If parameter bZero is non-zero, then any part of the input list following
  2391. ** the end of the output list is zeroed before returning.
  2392. */
  2393. static void fts3ColumnFilter(
  2394. int iCol, /* Column to filter on */
  2395. int bZero, /* Zero out anything following *ppList */
  2396. char **ppList, /* IN/OUT: Pointer to position list */
  2397. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  2398. ){
  2399. char *pList = *ppList;
  2400. int nList = *pnList;
  2401. char *pEnd = &pList[nList];
  2402. int iCurrent = 0;
  2403. char *p = pList;
  2404. assert( iCol>=0 );
  2405. while( 1 ){
  2406. char c = 0;
  2407. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  2408. if( iCol==iCurrent ){
  2409. nList = (int)(p - pList);
  2410. break;
  2411. }
  2412. nList -= (int)(p - pList);
  2413. pList = p;
  2414. if( nList<=0 ){
  2415. break;
  2416. }
  2417. p = &pList[1];
  2418. p += fts3GetVarint32(p, &iCurrent);
  2419. }
  2420. if( bZero && (pEnd - &pList[nList])>0){
  2421. memset(&pList[nList], 0, pEnd - &pList[nList]);
  2422. }
  2423. *ppList = pList;
  2424. *pnList = nList;
  2425. }
  2426. /*
  2427. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  2428. ** existing data). Grow the buffer if required.
  2429. **
  2430. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  2431. ** trying to resize the buffer, return SQLITE_NOMEM.
  2432. */
  2433. static int fts3MsrBufferData(
  2434. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  2435. char *pList,
  2436. i64 nList
  2437. ){
  2438. if( (nList+FTS3_NODE_PADDING)>pMsr->nBuffer ){
  2439. char *pNew;
  2440. int nNew = nList*2 + FTS3_NODE_PADDING;
  2441. pNew = (char *)sqlite3_realloc64(pMsr->aBuffer, nNew);
  2442. if( !pNew ) return SQLITE_NOMEM;
  2443. pMsr->aBuffer = pNew;
  2444. pMsr->nBuffer = nNew;
  2445. }
  2446. assert( nList>0 );
  2447. memcpy(pMsr->aBuffer, pList, nList);
  2448. memset(&pMsr->aBuffer[nList], 0, FTS3_NODE_PADDING);
  2449. return SQLITE_OK;
  2450. }
  2451. int sqlite3Fts3MsrIncrNext(
  2452. Fts3Table *p, /* Virtual table handle */
  2453. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  2454. sqlite3_int64 *piDocid, /* OUT: Docid value */
  2455. char **paPoslist, /* OUT: Pointer to position list */
  2456. int *pnPoslist /* OUT: Size of position list in bytes */
  2457. ){
  2458. int nMerge = pMsr->nAdvance;
  2459. Fts3SegReader **apSegment = pMsr->apSegment;
  2460. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  2461. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  2462. );
  2463. if( nMerge==0 ){
  2464. *paPoslist = 0;
  2465. return SQLITE_OK;
  2466. }
  2467. while( 1 ){
  2468. Fts3SegReader *pSeg;
  2469. pSeg = pMsr->apSegment[0];
  2470. if( pSeg->pOffsetList==0 ){
  2471. *paPoslist = 0;
  2472. break;
  2473. }else{
  2474. int rc;
  2475. char *pList;
  2476. int nList;
  2477. int j;
  2478. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  2479. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  2480. j = 1;
  2481. while( rc==SQLITE_OK
  2482. && j<nMerge
  2483. && apSegment[j]->pOffsetList
  2484. && apSegment[j]->iDocid==iDocid
  2485. ){
  2486. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  2487. j++;
  2488. }
  2489. if( rc!=SQLITE_OK ) return rc;
  2490. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  2491. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  2492. rc = fts3MsrBufferData(pMsr, pList, (i64)nList+1);
  2493. if( rc!=SQLITE_OK ) return rc;
  2494. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  2495. pList = pMsr->aBuffer;
  2496. }
  2497. if( pMsr->iColFilter>=0 ){
  2498. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  2499. }
  2500. if( nList>0 ){
  2501. *paPoslist = pList;
  2502. *piDocid = iDocid;
  2503. *pnPoslist = nList;
  2504. break;
  2505. }
  2506. }
  2507. }
  2508. return SQLITE_OK;
  2509. }
  2510. static int fts3SegReaderStart(
  2511. Fts3Table *p, /* Virtual table handle */
  2512. Fts3MultiSegReader *pCsr, /* Cursor object */
  2513. const char *zTerm, /* Term searched for (or NULL) */
  2514. int nTerm /* Length of zTerm in bytes */
  2515. ){
  2516. int i;
  2517. int nSeg = pCsr->nSegment;
  2518. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  2519. ** for, then advance each segment iterator until it points to a term of
  2520. ** equal or greater value than the specified term. This prevents many
  2521. ** unnecessary merge/sort operations for the case where single segment
  2522. ** b-tree leaf nodes contain more than one term.
  2523. */
  2524. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  2525. int res = 0;
  2526. Fts3SegReader *pSeg = pCsr->apSegment[i];
  2527. do {
  2528. int rc = fts3SegReaderNext(p, pSeg, 0);
  2529. if( rc!=SQLITE_OK ) return rc;
  2530. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  2531. if( pSeg->bLookup && res!=0 ){
  2532. fts3SegReaderSetEof(pSeg);
  2533. }
  2534. }
  2535. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  2536. return SQLITE_OK;
  2537. }
  2538. int sqlite3Fts3SegReaderStart(
  2539. Fts3Table *p, /* Virtual table handle */
  2540. Fts3MultiSegReader *pCsr, /* Cursor object */
  2541. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  2542. ){
  2543. pCsr->pFilter = pFilter;
  2544. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  2545. }
  2546. int sqlite3Fts3MsrIncrStart(
  2547. Fts3Table *p, /* Virtual table handle */
  2548. Fts3MultiSegReader *pCsr, /* Cursor object */
  2549. int iCol, /* Column to match on. */
  2550. const char *zTerm, /* Term to iterate through a doclist for */
  2551. int nTerm /* Number of bytes in zTerm */
  2552. ){
  2553. int i;
  2554. int rc;
  2555. int nSegment = pCsr->nSegment;
  2556. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  2557. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  2558. );
  2559. assert( pCsr->pFilter==0 );
  2560. assert( zTerm && nTerm>0 );
  2561. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  2562. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  2563. if( rc!=SQLITE_OK ) return rc;
  2564. /* Determine how many of the segments actually point to zTerm/nTerm. */
  2565. for(i=0; i<nSegment; i++){
  2566. Fts3SegReader *pSeg = pCsr->apSegment[i];
  2567. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  2568. break;
  2569. }
  2570. }
  2571. pCsr->nAdvance = i;
  2572. /* Advance each of the segments to point to the first docid. */
  2573. for(i=0; i<pCsr->nAdvance; i++){
  2574. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  2575. if( rc!=SQLITE_OK ) return rc;
  2576. }
  2577. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  2578. assert( iCol<0 || iCol<p->nColumn );
  2579. pCsr->iColFilter = iCol;
  2580. return SQLITE_OK;
  2581. }
  2582. /*
  2583. ** This function is called on a MultiSegReader that has been started using
  2584. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  2585. ** have been made. Calling this function puts the MultiSegReader in such
  2586. ** a state that if the next two calls are:
  2587. **
  2588. ** sqlite3Fts3SegReaderStart()
  2589. ** sqlite3Fts3SegReaderStep()
  2590. **
  2591. ** then the entire doclist for the term is available in
  2592. ** MultiSegReader.aDoclist/nDoclist.
  2593. */
  2594. int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  2595. int i; /* Used to iterate through segment-readers */
  2596. assert( pCsr->zTerm==0 );
  2597. assert( pCsr->nTerm==0 );
  2598. assert( pCsr->aDoclist==0 );
  2599. assert( pCsr->nDoclist==0 );
  2600. pCsr->nAdvance = 0;
  2601. pCsr->bRestart = 1;
  2602. for(i=0; i<pCsr->nSegment; i++){
  2603. pCsr->apSegment[i]->pOffsetList = 0;
  2604. pCsr->apSegment[i]->nOffsetList = 0;
  2605. pCsr->apSegment[i]->iDocid = 0;
  2606. }
  2607. return SQLITE_OK;
  2608. }
  2609. static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, i64 nReq){
  2610. if( nReq>pCsr->nBuffer ){
  2611. char *aNew;
  2612. pCsr->nBuffer = nReq*2;
  2613. aNew = sqlite3_realloc64(pCsr->aBuffer, pCsr->nBuffer);
  2614. if( !aNew ){
  2615. return SQLITE_NOMEM;
  2616. }
  2617. pCsr->aBuffer = aNew;
  2618. }
  2619. return SQLITE_OK;
  2620. }
  2621. int sqlite3Fts3SegReaderStep(
  2622. Fts3Table *p, /* Virtual table handle */
  2623. Fts3MultiSegReader *pCsr /* Cursor object */
  2624. ){
  2625. int rc = SQLITE_OK;
  2626. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  2627. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  2628. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  2629. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  2630. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  2631. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  2632. Fts3SegReader **apSegment = pCsr->apSegment;
  2633. int nSegment = pCsr->nSegment;
  2634. Fts3SegFilter *pFilter = pCsr->pFilter;
  2635. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  2636. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  2637. );
  2638. if( pCsr->nSegment==0 ) return SQLITE_OK;
  2639. do {
  2640. int nMerge;
  2641. int i;
  2642. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  2643. ** forward. Then sort the list in order of current term again.
  2644. */
  2645. for(i=0; i<pCsr->nAdvance; i++){
  2646. Fts3SegReader *pSeg = apSegment[i];
  2647. if( pSeg->bLookup ){
  2648. fts3SegReaderSetEof(pSeg);
  2649. }else{
  2650. rc = fts3SegReaderNext(p, pSeg, 0);
  2651. }
  2652. if( rc!=SQLITE_OK ) return rc;
  2653. }
  2654. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  2655. pCsr->nAdvance = 0;
  2656. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  2657. assert( rc==SQLITE_OK );
  2658. if( apSegment[0]->aNode==0 ) break;
  2659. pCsr->nTerm = apSegment[0]->nTerm;
  2660. pCsr->zTerm = apSegment[0]->zTerm;
  2661. /* If this is a prefix-search, and if the term that apSegment[0] points
  2662. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  2663. ** required callbacks have been made. In this case exit early.
  2664. **
  2665. ** Similarly, if this is a search for an exact match, and the first term
  2666. ** of segment apSegment[0] is not a match, exit early.
  2667. */
  2668. if( pFilter->zTerm && !isScan ){
  2669. if( pCsr->nTerm<pFilter->nTerm
  2670. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  2671. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  2672. ){
  2673. break;
  2674. }
  2675. }
  2676. nMerge = 1;
  2677. while( nMerge<nSegment
  2678. && apSegment[nMerge]->aNode
  2679. && apSegment[nMerge]->nTerm==pCsr->nTerm
  2680. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  2681. ){
  2682. nMerge++;
  2683. }
  2684. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  2685. if( nMerge==1
  2686. && !isIgnoreEmpty
  2687. && !isFirst
  2688. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  2689. ){
  2690. pCsr->nDoclist = apSegment[0]->nDoclist;
  2691. if( fts3SegReaderIsPending(apSegment[0]) ){
  2692. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist,
  2693. (i64)pCsr->nDoclist);
  2694. pCsr->aDoclist = pCsr->aBuffer;
  2695. }else{
  2696. pCsr->aDoclist = apSegment[0]->aDoclist;
  2697. }
  2698. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  2699. }else{
  2700. int nDoclist = 0; /* Size of doclist */
  2701. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  2702. /* The current term of the first nMerge entries in the array
  2703. ** of Fts3SegReader objects is the same. The doclists must be merged
  2704. ** and a single term returned with the merged doclist.
  2705. */
  2706. for(i=0; i<nMerge; i++){
  2707. fts3SegReaderFirstDocid(p, apSegment[i]);
  2708. }
  2709. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  2710. while( apSegment[0]->pOffsetList ){
  2711. int j; /* Number of segments that share a docid */
  2712. char *pList = 0;
  2713. int nList = 0;
  2714. int nByte;
  2715. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  2716. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  2717. j = 1;
  2718. while( j<nMerge
  2719. && apSegment[j]->pOffsetList
  2720. && apSegment[j]->iDocid==iDocid
  2721. ){
  2722. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  2723. j++;
  2724. }
  2725. if( isColFilter ){
  2726. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  2727. }
  2728. if( !isIgnoreEmpty || nList>0 ){
  2729. /* Calculate the 'docid' delta value to write into the merged
  2730. ** doclist. */
  2731. sqlite3_int64 iDelta;
  2732. if( p->bDescIdx && nDoclist>0 ){
  2733. if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
  2734. iDelta = (i64)((u64)iPrev - (u64)iDocid);
  2735. }else{
  2736. if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
  2737. iDelta = (i64)((u64)iDocid - (u64)iPrev);
  2738. }
  2739. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  2740. rc = fts3GrowSegReaderBuffer(pCsr,
  2741. (i64)nByte+nDoclist+FTS3_NODE_PADDING);
  2742. if( rc ) return rc;
  2743. if( isFirst ){
  2744. char *a = &pCsr->aBuffer[nDoclist];
  2745. int nWrite;
  2746. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  2747. if( nWrite ){
  2748. iPrev = iDocid;
  2749. nDoclist += nWrite;
  2750. }
  2751. }else{
  2752. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  2753. iPrev = iDocid;
  2754. if( isRequirePos ){
  2755. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  2756. nDoclist += nList;
  2757. pCsr->aBuffer[nDoclist++] = '\0';
  2758. }
  2759. }
  2760. }
  2761. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  2762. }
  2763. if( nDoclist>0 ){
  2764. rc = fts3GrowSegReaderBuffer(pCsr, (i64)nDoclist+FTS3_NODE_PADDING);
  2765. if( rc ) return rc;
  2766. memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING);
  2767. pCsr->aDoclist = pCsr->aBuffer;
  2768. pCsr->nDoclist = nDoclist;
  2769. rc = SQLITE_ROW;
  2770. }
  2771. }
  2772. pCsr->nAdvance = nMerge;
  2773. }while( rc==SQLITE_OK );
  2774. return rc;
  2775. }
  2776. void sqlite3Fts3SegReaderFinish(
  2777. Fts3MultiSegReader *pCsr /* Cursor object */
  2778. ){
  2779. if( pCsr ){
  2780. int i;
  2781. for(i=0; i<pCsr->nSegment; i++){
  2782. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  2783. }
  2784. sqlite3_free(pCsr->apSegment);
  2785. sqlite3_free(pCsr->aBuffer);
  2786. pCsr->nSegment = 0;
  2787. pCsr->apSegment = 0;
  2788. pCsr->aBuffer = 0;
  2789. }
  2790. }
  2791. /*
  2792. ** Decode the "end_block" field, selected by column iCol of the SELECT
  2793. ** statement passed as the first argument.
  2794. **
  2795. ** The "end_block" field may contain either an integer, or a text field
  2796. ** containing the text representation of two non-negative integers separated
  2797. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  2798. ** to the integer value and *pnByte to zero before returning. In the second,
  2799. ** set *piEndBlock to the first value and *pnByte to the second.
  2800. */
  2801. static void fts3ReadEndBlockField(
  2802. sqlite3_stmt *pStmt,
  2803. int iCol,
  2804. i64 *piEndBlock,
  2805. i64 *pnByte
  2806. ){
  2807. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  2808. if( zText ){
  2809. int i;
  2810. int iMul = 1;
  2811. u64 iVal = 0;
  2812. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  2813. iVal = iVal*10 + (zText[i] - '0');
  2814. }
  2815. *piEndBlock = (i64)iVal;
  2816. while( zText[i]==' ' ) i++;
  2817. iVal = 0;
  2818. if( zText[i]=='-' ){
  2819. i++;
  2820. iMul = -1;
  2821. }
  2822. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  2823. iVal = iVal*10 + (zText[i] - '0');
  2824. }
  2825. *pnByte = ((i64)iVal * (i64)iMul);
  2826. }
  2827. }
  2828. /*
  2829. ** A segment of size nByte bytes has just been written to absolute level
  2830. ** iAbsLevel. Promote any segments that should be promoted as a result.
  2831. */
  2832. static int fts3PromoteSegments(
  2833. Fts3Table *p, /* FTS table handle */
  2834. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  2835. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  2836. ){
  2837. int rc = SQLITE_OK;
  2838. sqlite3_stmt *pRange;
  2839. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  2840. if( rc==SQLITE_OK ){
  2841. int bOk = 0;
  2842. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  2843. i64 nLimit = (nByte*3)/2;
  2844. /* Loop through all entries in the %_segdir table corresponding to
  2845. ** segments in this index on levels greater than iAbsLevel. If there is
  2846. ** at least one such segment, and it is possible to determine that all
  2847. ** such segments are smaller than nLimit bytes in size, they will be
  2848. ** promoted to level iAbsLevel. */
  2849. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  2850. sqlite3_bind_int64(pRange, 2, iLast);
  2851. while( SQLITE_ROW==sqlite3_step(pRange) ){
  2852. i64 nSize = 0, dummy;
  2853. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  2854. if( nSize<=0 || nSize>nLimit ){
  2855. /* If nSize==0, then the %_segdir.end_block field does not not
  2856. ** contain a size value. This happens if it was written by an
  2857. ** old version of FTS. In this case it is not possible to determine
  2858. ** the size of the segment, and so segment promotion does not
  2859. ** take place. */
  2860. bOk = 0;
  2861. break;
  2862. }
  2863. bOk = 1;
  2864. }
  2865. rc = sqlite3_reset(pRange);
  2866. if( bOk ){
  2867. int iIdx = 0;
  2868. sqlite3_stmt *pUpdate1 = 0;
  2869. sqlite3_stmt *pUpdate2 = 0;
  2870. if( rc==SQLITE_OK ){
  2871. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  2872. }
  2873. if( rc==SQLITE_OK ){
  2874. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  2875. }
  2876. if( rc==SQLITE_OK ){
  2877. /* Loop through all %_segdir entries for segments in this index with
  2878. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  2879. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  2880. ** oldest segment in the range, 1 for the next oldest, and so on.
  2881. **
  2882. ** In other words, move all segments being promoted to level -1,
  2883. ** setting the "idx" fields as appropriate to keep them in the same
  2884. ** order. The contents of level -1 (which is never used, except
  2885. ** transiently here), will be moved back to level iAbsLevel below. */
  2886. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  2887. while( SQLITE_ROW==sqlite3_step(pRange) ){
  2888. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  2889. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  2890. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  2891. sqlite3_step(pUpdate1);
  2892. rc = sqlite3_reset(pUpdate1);
  2893. if( rc!=SQLITE_OK ){
  2894. sqlite3_reset(pRange);
  2895. break;
  2896. }
  2897. }
  2898. }
  2899. if( rc==SQLITE_OK ){
  2900. rc = sqlite3_reset(pRange);
  2901. }
  2902. /* Move level -1 to level iAbsLevel */
  2903. if( rc==SQLITE_OK ){
  2904. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  2905. sqlite3_step(pUpdate2);
  2906. rc = sqlite3_reset(pUpdate2);
  2907. }
  2908. }
  2909. }
  2910. return rc;
  2911. }
  2912. /*
  2913. ** Merge all level iLevel segments in the database into a single
  2914. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  2915. ** single segment with a level equal to the numerically largest level
  2916. ** currently present in the database.
  2917. **
  2918. ** If this function is called with iLevel<0, but there is only one
  2919. ** segment in the database, SQLITE_DONE is returned immediately.
  2920. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  2921. ** an SQLite error code is returned.
  2922. */
  2923. static int fts3SegmentMerge(
  2924. Fts3Table *p,
  2925. int iLangid, /* Language id to merge */
  2926. int iIndex, /* Index in p->aIndex[] to merge */
  2927. int iLevel /* Level to merge */
  2928. ){
  2929. int rc; /* Return code */
  2930. int iIdx = 0; /* Index of new segment */
  2931. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  2932. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  2933. Fts3SegFilter filter; /* Segment term filter condition */
  2934. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  2935. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  2936. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  2937. assert( iLevel==FTS3_SEGCURSOR_ALL
  2938. || iLevel==FTS3_SEGCURSOR_PENDING
  2939. || iLevel>=0
  2940. );
  2941. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  2942. assert( iIndex>=0 && iIndex<p->nIndex );
  2943. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  2944. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  2945. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  2946. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  2947. if( rc!=SQLITE_OK ) goto finished;
  2948. }
  2949. if( iLevel==FTS3_SEGCURSOR_ALL ){
  2950. /* This call is to merge all segments in the database to a single
  2951. ** segment. The level of the new segment is equal to the numerically
  2952. ** greatest segment level currently present in the database for this
  2953. ** index. The idx of the new segment is always 0. */
  2954. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  2955. rc = SQLITE_DONE;
  2956. goto finished;
  2957. }
  2958. iNewLevel = iMaxLevel;
  2959. bIgnoreEmpty = 1;
  2960. }else{
  2961. /* This call is to merge all segments at level iLevel. find the next
  2962. ** available segment index at level iLevel+1. The call to
  2963. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  2964. ** a single iLevel+2 segment if necessary. */
  2965. assert( FTS3_SEGCURSOR_PENDING==-1 );
  2966. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  2967. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  2968. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  2969. }
  2970. if( rc!=SQLITE_OK ) goto finished;
  2971. assert( csr.nSegment>0 );
  2972. assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  2973. assert_fts3_nc(
  2974. iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
  2975. );
  2976. memset(&filter, 0, sizeof(Fts3SegFilter));
  2977. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  2978. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  2979. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  2980. while( SQLITE_OK==rc ){
  2981. rc = sqlite3Fts3SegReaderStep(p, &csr);
  2982. if( rc!=SQLITE_ROW ) break;
  2983. rc = fts3SegWriterAdd(p, &pWriter, 1,
  2984. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  2985. }
  2986. if( rc!=SQLITE_OK ) goto finished;
  2987. assert_fts3_nc( pWriter || bIgnoreEmpty );
  2988. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  2989. rc = fts3DeleteSegdir(
  2990. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  2991. );
  2992. if( rc!=SQLITE_OK ) goto finished;
  2993. }
  2994. if( pWriter ){
  2995. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  2996. if( rc==SQLITE_OK ){
  2997. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  2998. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  2999. }
  3000. }
  3001. }
  3002. finished:
  3003. fts3SegWriterFree(pWriter);
  3004. sqlite3Fts3SegReaderFinish(&csr);
  3005. return rc;
  3006. }
  3007. /*
  3008. ** Flush the contents of pendingTerms to level 0 segments.
  3009. */
  3010. int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  3011. int rc = SQLITE_OK;
  3012. int i;
  3013. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  3014. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  3015. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  3016. }
  3017. /* Determine the auto-incr-merge setting if unknown. If enabled,
  3018. ** estimate the number of leaf blocks of content to be written
  3019. */
  3020. if( rc==SQLITE_OK && p->bHasStat
  3021. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  3022. ){
  3023. sqlite3_stmt *pStmt = 0;
  3024. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  3025. if( rc==SQLITE_OK ){
  3026. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  3027. rc = sqlite3_step(pStmt);
  3028. if( rc==SQLITE_ROW ){
  3029. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  3030. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  3031. }else if( rc==SQLITE_DONE ){
  3032. p->nAutoincrmerge = 0;
  3033. }
  3034. rc = sqlite3_reset(pStmt);
  3035. }
  3036. }
  3037. if( rc==SQLITE_OK ){
  3038. sqlite3Fts3PendingTermsClear(p);
  3039. }
  3040. return rc;
  3041. }
  3042. /*
  3043. ** Encode N integers as varints into a blob.
  3044. */
  3045. static void fts3EncodeIntArray(
  3046. int N, /* The number of integers to encode */
  3047. u32 *a, /* The integer values */
  3048. char *zBuf, /* Write the BLOB here */
  3049. int *pNBuf /* Write number of bytes if zBuf[] used here */
  3050. ){
  3051. int i, j;
  3052. for(i=j=0; i<N; i++){
  3053. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  3054. }
  3055. *pNBuf = j;
  3056. }
  3057. /*
  3058. ** Decode a blob of varints into N integers
  3059. */
  3060. static void fts3DecodeIntArray(
  3061. int N, /* The number of integers to decode */
  3062. u32 *a, /* Write the integer values */
  3063. const char *zBuf, /* The BLOB containing the varints */
  3064. int nBuf /* size of the BLOB */
  3065. ){
  3066. int i = 0;
  3067. if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
  3068. int j;
  3069. for(i=j=0; i<N && j<nBuf; i++){
  3070. sqlite3_int64 x;
  3071. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  3072. a[i] = (u32)(x & 0xffffffff);
  3073. }
  3074. }
  3075. while( i<N ) a[i++] = 0;
  3076. }
  3077. /*
  3078. ** Insert the sizes (in tokens) for each column of the document
  3079. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  3080. ** a blob of varints.
  3081. */
  3082. static void fts3InsertDocsize(
  3083. int *pRC, /* Result code */
  3084. Fts3Table *p, /* Table into which to insert */
  3085. u32 *aSz /* Sizes of each column, in tokens */
  3086. ){
  3087. char *pBlob; /* The BLOB encoding of the document size */
  3088. int nBlob; /* Number of bytes in the BLOB */
  3089. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  3090. int rc; /* Result code from subfunctions */
  3091. if( *pRC ) return;
  3092. pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
  3093. if( pBlob==0 ){
  3094. *pRC = SQLITE_NOMEM;
  3095. return;
  3096. }
  3097. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  3098. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  3099. if( rc ){
  3100. sqlite3_free(pBlob);
  3101. *pRC = rc;
  3102. return;
  3103. }
  3104. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  3105. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  3106. sqlite3_step(pStmt);
  3107. *pRC = sqlite3_reset(pStmt);
  3108. }
  3109. /*
  3110. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  3111. ** where N is the number of user defined columns in the fts3 table plus
  3112. ** two. If nCol is the number of user defined columns, then values of the
  3113. ** varints are set as follows:
  3114. **
  3115. ** Varint 0: Total number of rows in the table.
  3116. **
  3117. ** Varint 1..nCol: For each column, the total number of tokens stored in
  3118. ** the column for all rows of the table.
  3119. **
  3120. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  3121. ** columns of all rows of the table.
  3122. **
  3123. */
  3124. static void fts3UpdateDocTotals(
  3125. int *pRC, /* The result code */
  3126. Fts3Table *p, /* Table being updated */
  3127. u32 *aSzIns, /* Size increases */
  3128. u32 *aSzDel, /* Size decreases */
  3129. int nChng /* Change in the number of documents */
  3130. ){
  3131. char *pBlob; /* Storage for BLOB written into %_stat */
  3132. int nBlob; /* Size of BLOB written into %_stat */
  3133. u32 *a; /* Array of integers that becomes the BLOB */
  3134. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  3135. int i; /* Loop counter */
  3136. int rc; /* Result code from subfunctions */
  3137. const int nStat = p->nColumn+2;
  3138. if( *pRC ) return;
  3139. a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
  3140. if( a==0 ){
  3141. *pRC = SQLITE_NOMEM;
  3142. return;
  3143. }
  3144. pBlob = (char*)&a[nStat];
  3145. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  3146. if( rc ){
  3147. sqlite3_free(a);
  3148. *pRC = rc;
  3149. return;
  3150. }
  3151. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  3152. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  3153. fts3DecodeIntArray(nStat, a,
  3154. sqlite3_column_blob(pStmt, 0),
  3155. sqlite3_column_bytes(pStmt, 0));
  3156. }else{
  3157. memset(a, 0, sizeof(u32)*(nStat) );
  3158. }
  3159. rc = sqlite3_reset(pStmt);
  3160. if( rc!=SQLITE_OK ){
  3161. sqlite3_free(a);
  3162. *pRC = rc;
  3163. return;
  3164. }
  3165. if( nChng<0 && a[0]<(u32)(-nChng) ){
  3166. a[0] = 0;
  3167. }else{
  3168. a[0] += nChng;
  3169. }
  3170. for(i=0; i<p->nColumn+1; i++){
  3171. u32 x = a[i+1];
  3172. if( x+aSzIns[i] < aSzDel[i] ){
  3173. x = 0;
  3174. }else{
  3175. x = x + aSzIns[i] - aSzDel[i];
  3176. }
  3177. a[i+1] = x;
  3178. }
  3179. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  3180. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  3181. if( rc ){
  3182. sqlite3_free(a);
  3183. *pRC = rc;
  3184. return;
  3185. }
  3186. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  3187. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  3188. sqlite3_step(pStmt);
  3189. *pRC = sqlite3_reset(pStmt);
  3190. sqlite3_bind_null(pStmt, 2);
  3191. sqlite3_free(a);
  3192. }
  3193. /*
  3194. ** Merge the entire database so that there is one segment for each
  3195. ** iIndex/iLangid combination.
  3196. */
  3197. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  3198. int bSeenDone = 0;
  3199. int rc;
  3200. sqlite3_stmt *pAllLangid = 0;
  3201. rc = sqlite3Fts3PendingTermsFlush(p);
  3202. if( rc==SQLITE_OK ){
  3203. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  3204. }
  3205. if( rc==SQLITE_OK ){
  3206. int rc2;
  3207. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  3208. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  3209. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  3210. int i;
  3211. int iLangid = sqlite3_column_int(pAllLangid, 0);
  3212. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  3213. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  3214. if( rc==SQLITE_DONE ){
  3215. bSeenDone = 1;
  3216. rc = SQLITE_OK;
  3217. }
  3218. }
  3219. }
  3220. rc2 = sqlite3_reset(pAllLangid);
  3221. if( rc==SQLITE_OK ) rc = rc2;
  3222. }
  3223. sqlite3Fts3SegmentsClose(p);
  3224. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  3225. }
  3226. /*
  3227. ** This function is called when the user executes the following statement:
  3228. **
  3229. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  3230. **
  3231. ** The entire FTS index is discarded and rebuilt. If the table is one
  3232. ** created using the content=xxx option, then the new index is based on
  3233. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  3234. ** on the contents of the %_content table.
  3235. */
  3236. static int fts3DoRebuild(Fts3Table *p){
  3237. int rc; /* Return Code */
  3238. rc = fts3DeleteAll(p, 0);
  3239. if( rc==SQLITE_OK ){
  3240. u32 *aSz = 0;
  3241. u32 *aSzIns = 0;
  3242. u32 *aSzDel = 0;
  3243. sqlite3_stmt *pStmt = 0;
  3244. int nEntry = 0;
  3245. /* Compose and prepare an SQL statement to loop through the content table */
  3246. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  3247. if( !zSql ){
  3248. rc = SQLITE_NOMEM;
  3249. }else{
  3250. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3251. sqlite3_free(zSql);
  3252. }
  3253. if( rc==SQLITE_OK ){
  3254. sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
  3255. aSz = (u32 *)sqlite3_malloc64(nByte);
  3256. if( aSz==0 ){
  3257. rc = SQLITE_NOMEM;
  3258. }else{
  3259. memset(aSz, 0, nByte);
  3260. aSzIns = &aSz[p->nColumn+1];
  3261. aSzDel = &aSzIns[p->nColumn+1];
  3262. }
  3263. }
  3264. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  3265. int iCol;
  3266. int iLangid = langidFromSelect(p, pStmt);
  3267. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  3268. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  3269. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  3270. if( p->abNotindexed[iCol]==0 ){
  3271. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  3272. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  3273. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  3274. }
  3275. }
  3276. if( p->bHasDocsize ){
  3277. fts3InsertDocsize(&rc, p, aSz);
  3278. }
  3279. if( rc!=SQLITE_OK ){
  3280. sqlite3_finalize(pStmt);
  3281. pStmt = 0;
  3282. }else{
  3283. nEntry++;
  3284. for(iCol=0; iCol<=p->nColumn; iCol++){
  3285. aSzIns[iCol] += aSz[iCol];
  3286. }
  3287. }
  3288. }
  3289. if( p->bFts4 ){
  3290. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  3291. }
  3292. sqlite3_free(aSz);
  3293. if( pStmt ){
  3294. int rc2 = sqlite3_finalize(pStmt);
  3295. if( rc==SQLITE_OK ){
  3296. rc = rc2;
  3297. }
  3298. }
  3299. }
  3300. return rc;
  3301. }
  3302. /*
  3303. ** This function opens a cursor used to read the input data for an
  3304. ** incremental merge operation. Specifically, it opens a cursor to scan
  3305. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  3306. ** level iAbsLevel.
  3307. */
  3308. static int fts3IncrmergeCsr(
  3309. Fts3Table *p, /* FTS3 table handle */
  3310. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  3311. int nSeg, /* Number of segments to merge */
  3312. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  3313. ){
  3314. int rc; /* Return Code */
  3315. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  3316. sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */
  3317. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  3318. memset(pCsr, 0, sizeof(*pCsr));
  3319. nByte = sizeof(Fts3SegReader *) * nSeg;
  3320. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
  3321. if( pCsr->apSegment==0 ){
  3322. rc = SQLITE_NOMEM;
  3323. }else{
  3324. memset(pCsr->apSegment, 0, nByte);
  3325. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  3326. }
  3327. if( rc==SQLITE_OK ){
  3328. int i;
  3329. int rc2;
  3330. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  3331. assert( pCsr->nSegment==0 );
  3332. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  3333. rc = sqlite3Fts3SegReaderNew(i, 0,
  3334. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  3335. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  3336. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  3337. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  3338. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  3339. &pCsr->apSegment[i]
  3340. );
  3341. pCsr->nSegment++;
  3342. }
  3343. rc2 = sqlite3_reset(pStmt);
  3344. if( rc==SQLITE_OK ) rc = rc2;
  3345. }
  3346. return rc;
  3347. }
  3348. typedef struct IncrmergeWriter IncrmergeWriter;
  3349. typedef struct NodeWriter NodeWriter;
  3350. typedef struct Blob Blob;
  3351. typedef struct NodeReader NodeReader;
  3352. /*
  3353. ** An instance of the following structure is used as a dynamic buffer
  3354. ** to build up nodes or other blobs of data in.
  3355. **
  3356. ** The function blobGrowBuffer() is used to extend the allocation.
  3357. */
  3358. struct Blob {
  3359. char *a; /* Pointer to allocation */
  3360. int n; /* Number of valid bytes of data in a[] */
  3361. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  3362. };
  3363. /*
  3364. ** This structure is used to build up buffers containing segment b-tree
  3365. ** nodes (blocks).
  3366. */
  3367. struct NodeWriter {
  3368. sqlite3_int64 iBlock; /* Current block id */
  3369. Blob key; /* Last key written to the current block */
  3370. Blob block; /* Current block image */
  3371. };
  3372. /*
  3373. ** An object of this type contains the state required to create or append
  3374. ** to an appendable b-tree segment.
  3375. */
  3376. struct IncrmergeWriter {
  3377. int nLeafEst; /* Space allocated for leaf blocks */
  3378. int nWork; /* Number of leaf pages flushed */
  3379. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  3380. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  3381. sqlite3_int64 iStart; /* Block number of first allocated block */
  3382. sqlite3_int64 iEnd; /* Block number of last allocated block */
  3383. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  3384. u8 bNoLeafData; /* If true, store 0 for segment size */
  3385. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  3386. };
  3387. /*
  3388. ** An object of the following type is used to read data from a single
  3389. ** FTS segment node. See the following functions:
  3390. **
  3391. ** nodeReaderInit()
  3392. ** nodeReaderNext()
  3393. ** nodeReaderRelease()
  3394. */
  3395. struct NodeReader {
  3396. const char *aNode;
  3397. int nNode;
  3398. int iOff; /* Current offset within aNode[] */
  3399. /* Output variables. Containing the current node entry. */
  3400. sqlite3_int64 iChild; /* Pointer to child node */
  3401. Blob term; /* Current term */
  3402. const char *aDoclist; /* Pointer to doclist */
  3403. int nDoclist; /* Size of doclist in bytes */
  3404. };
  3405. /*
  3406. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  3407. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  3408. ** bytes in size, extend (realloc) it to be so.
  3409. **
  3410. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  3411. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  3412. ** to reflect the new size of the pBlob->a[] buffer.
  3413. */
  3414. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  3415. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  3416. int nAlloc = nMin;
  3417. char *a = (char *)sqlite3_realloc64(pBlob->a, nAlloc);
  3418. if( a ){
  3419. pBlob->nAlloc = nAlloc;
  3420. pBlob->a = a;
  3421. }else{
  3422. *pRc = SQLITE_NOMEM;
  3423. }
  3424. }
  3425. }
  3426. /*
  3427. ** Attempt to advance the node-reader object passed as the first argument to
  3428. ** the next entry on the node.
  3429. **
  3430. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  3431. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  3432. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  3433. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  3434. ** variables for the new entry.
  3435. */
  3436. static int nodeReaderNext(NodeReader *p){
  3437. int bFirst = (p->term.n==0); /* True for first term on the node */
  3438. int nPrefix = 0; /* Bytes to copy from previous term */
  3439. int nSuffix = 0; /* Bytes to append to the prefix */
  3440. int rc = SQLITE_OK; /* Return code */
  3441. assert( p->aNode );
  3442. if( p->iChild && bFirst==0 ) p->iChild++;
  3443. if( p->iOff>=p->nNode ){
  3444. /* EOF */
  3445. p->aNode = 0;
  3446. }else{
  3447. if( bFirst==0 ){
  3448. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  3449. }
  3450. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  3451. if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
  3452. return FTS_CORRUPT_VTAB;
  3453. }
  3454. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  3455. if( rc==SQLITE_OK && ALWAYS(p->term.a!=0) ){
  3456. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  3457. p->term.n = nPrefix+nSuffix;
  3458. p->iOff += nSuffix;
  3459. if( p->iChild==0 ){
  3460. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  3461. if( (p->nNode-p->iOff)<p->nDoclist ){
  3462. return FTS_CORRUPT_VTAB;
  3463. }
  3464. p->aDoclist = &p->aNode[p->iOff];
  3465. p->iOff += p->nDoclist;
  3466. }
  3467. }
  3468. }
  3469. assert_fts3_nc( p->iOff<=p->nNode );
  3470. return rc;
  3471. }
  3472. /*
  3473. ** Release all dynamic resources held by node-reader object *p.
  3474. */
  3475. static void nodeReaderRelease(NodeReader *p){
  3476. sqlite3_free(p->term.a);
  3477. }
  3478. /*
  3479. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  3480. **
  3481. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  3482. ** point to the first entry on the node (if any). Otherwise, an SQLite
  3483. ** error code is returned.
  3484. */
  3485. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  3486. memset(p, 0, sizeof(NodeReader));
  3487. p->aNode = aNode;
  3488. p->nNode = nNode;
  3489. /* Figure out if this is a leaf or an internal node. */
  3490. if( aNode && aNode[0] ){
  3491. /* An internal node. */
  3492. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  3493. }else{
  3494. p->iOff = 1;
  3495. }
  3496. return aNode ? nodeReaderNext(p) : SQLITE_OK;
  3497. }
  3498. /*
  3499. ** This function is called while writing an FTS segment each time a leaf o
  3500. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  3501. ** to be greater than the largest key on the node just written, but smaller
  3502. ** than or equal to the first key that will be written to the next leaf
  3503. ** node.
  3504. **
  3505. ** The block id of the leaf node just written to disk may be found in
  3506. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  3507. */
  3508. static int fts3IncrmergePush(
  3509. Fts3Table *p, /* Fts3 table handle */
  3510. IncrmergeWriter *pWriter, /* Writer object */
  3511. const char *zTerm, /* Term to write to internal node */
  3512. int nTerm /* Bytes at zTerm */
  3513. ){
  3514. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  3515. int iLayer;
  3516. assert( nTerm>0 );
  3517. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  3518. sqlite3_int64 iNextPtr = 0;
  3519. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  3520. int rc = SQLITE_OK;
  3521. int nPrefix;
  3522. int nSuffix;
  3523. int nSpace;
  3524. /* Figure out how much space the key will consume if it is written to
  3525. ** the current node of layer iLayer. Due to the prefix compression,
  3526. ** the space required changes depending on which node the key is to
  3527. ** be added to. */
  3528. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  3529. nSuffix = nTerm - nPrefix;
  3530. if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  3531. nSpace = sqlite3Fts3VarintLen(nPrefix);
  3532. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  3533. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  3534. /* If the current node of layer iLayer contains zero keys, or if adding
  3535. ** the key to it will not cause it to grow to larger than nNodeSize
  3536. ** bytes in size, write the key here. */
  3537. Blob *pBlk = &pNode->block;
  3538. if( pBlk->n==0 ){
  3539. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  3540. if( rc==SQLITE_OK ){
  3541. pBlk->a[0] = (char)iLayer;
  3542. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  3543. }
  3544. }
  3545. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  3546. blobGrowBuffer(&pNode->key, nTerm, &rc);
  3547. if( rc==SQLITE_OK ){
  3548. if( pNode->key.n ){
  3549. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  3550. }
  3551. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  3552. assert( nPrefix+nSuffix<=nTerm );
  3553. assert( nPrefix>=0 );
  3554. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  3555. pBlk->n += nSuffix;
  3556. memcpy(pNode->key.a, zTerm, nTerm);
  3557. pNode->key.n = nTerm;
  3558. }
  3559. }else{
  3560. /* Otherwise, flush the current node of layer iLayer to disk.
  3561. ** Then allocate a new, empty sibling node. The key will be written
  3562. ** into the parent of this node. */
  3563. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  3564. assert( pNode->block.nAlloc>=p->nNodeSize );
  3565. pNode->block.a[0] = (char)iLayer;
  3566. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  3567. iNextPtr = pNode->iBlock;
  3568. pNode->iBlock++;
  3569. pNode->key.n = 0;
  3570. }
  3571. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  3572. iPtr = iNextPtr;
  3573. }
  3574. assert( 0 );
  3575. return 0;
  3576. }
  3577. /*
  3578. ** Append a term and (optionally) doclist to the FTS segment node currently
  3579. ** stored in blob *pNode. The node need not contain any terms, but the
  3580. ** header must be written before this function is called.
  3581. **
  3582. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  3583. ** followed by the left-hand-child varint for an internal node.
  3584. **
  3585. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  3586. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  3587. ** node, both aDoclist and nDoclist must be passed 0.
  3588. **
  3589. ** If the size of the value in blob pPrev is zero, then this is the first
  3590. ** term written to the node. Otherwise, pPrev contains a copy of the
  3591. ** previous term. Before this function returns, it is updated to contain a
  3592. ** copy of zTerm/nTerm.
  3593. **
  3594. ** It is assumed that the buffer associated with pNode is already large
  3595. ** enough to accommodate the new entry. The buffer associated with pPrev
  3596. ** is extended by this function if requrired.
  3597. **
  3598. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  3599. ** returned. Otherwise, SQLITE_OK.
  3600. */
  3601. static int fts3AppendToNode(
  3602. Blob *pNode, /* Current node image to append to */
  3603. Blob *pPrev, /* Buffer containing previous term written */
  3604. const char *zTerm, /* New term to write */
  3605. int nTerm, /* Size of zTerm in bytes */
  3606. const char *aDoclist, /* Doclist (or NULL) to write */
  3607. int nDoclist /* Size of aDoclist in bytes */
  3608. ){
  3609. int rc = SQLITE_OK; /* Return code */
  3610. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  3611. int nPrefix; /* Size of term prefix in bytes */
  3612. int nSuffix; /* Size of term suffix in bytes */
  3613. /* Node must have already been started. There must be a doclist for a
  3614. ** leaf node, and there must not be a doclist for an internal node. */
  3615. assert( pNode->n>0 );
  3616. assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
  3617. blobGrowBuffer(pPrev, nTerm, &rc);
  3618. if( rc!=SQLITE_OK ) return rc;
  3619. assert( pPrev!=0 );
  3620. assert( pPrev->a!=0 );
  3621. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  3622. nSuffix = nTerm - nPrefix;
  3623. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  3624. memcpy(pPrev->a, zTerm, nTerm);
  3625. pPrev->n = nTerm;
  3626. if( bFirst==0 ){
  3627. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  3628. }
  3629. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  3630. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  3631. pNode->n += nSuffix;
  3632. if( aDoclist ){
  3633. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  3634. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  3635. pNode->n += nDoclist;
  3636. }
  3637. assert( pNode->n<=pNode->nAlloc );
  3638. return SQLITE_OK;
  3639. }
  3640. /*
  3641. ** Append the current term and doclist pointed to by cursor pCsr to the
  3642. ** appendable b-tree segment opened for writing by pWriter.
  3643. **
  3644. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  3645. */
  3646. static int fts3IncrmergeAppend(
  3647. Fts3Table *p, /* Fts3 table handle */
  3648. IncrmergeWriter *pWriter, /* Writer object */
  3649. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  3650. ){
  3651. const char *zTerm = pCsr->zTerm;
  3652. int nTerm = pCsr->nTerm;
  3653. const char *aDoclist = pCsr->aDoclist;
  3654. int nDoclist = pCsr->nDoclist;
  3655. int rc = SQLITE_OK; /* Return code */
  3656. int nSpace; /* Total space in bytes required on leaf */
  3657. int nPrefix; /* Size of prefix shared with previous term */
  3658. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  3659. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  3660. pLeaf = &pWriter->aNodeWriter[0];
  3661. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  3662. nSuffix = nTerm - nPrefix;
  3663. if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  3664. nSpace = sqlite3Fts3VarintLen(nPrefix);
  3665. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  3666. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  3667. /* If the current block is not empty, and if adding this term/doclist
  3668. ** to the current block would make it larger than Fts3Table.nNodeSize bytes,
  3669. ** and if there is still room for another leaf page, write this block out to
  3670. ** the database. */
  3671. if( pLeaf->block.n>0
  3672. && (pLeaf->block.n + nSpace)>p->nNodeSize
  3673. && pLeaf->iBlock < (pWriter->iStart + pWriter->nLeafEst)
  3674. ){
  3675. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  3676. pWriter->nWork++;
  3677. /* Add the current term to the parent node. The term added to the
  3678. ** parent must:
  3679. **
  3680. ** a) be greater than the largest term on the leaf node just written
  3681. ** to the database (still available in pLeaf->key), and
  3682. **
  3683. ** b) be less than or equal to the term about to be added to the new
  3684. ** leaf node (zTerm/nTerm).
  3685. **
  3686. ** In other words, it must be the prefix of zTerm 1 byte longer than
  3687. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  3688. */
  3689. if( rc==SQLITE_OK ){
  3690. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  3691. }
  3692. /* Advance to the next output block */
  3693. pLeaf->iBlock++;
  3694. pLeaf->key.n = 0;
  3695. pLeaf->block.n = 0;
  3696. nSuffix = nTerm;
  3697. nSpace = 1;
  3698. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  3699. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  3700. }
  3701. pWriter->nLeafData += nSpace;
  3702. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  3703. if( rc==SQLITE_OK ){
  3704. if( pLeaf->block.n==0 ){
  3705. pLeaf->block.n = 1;
  3706. pLeaf->block.a[0] = '\0';
  3707. }
  3708. rc = fts3AppendToNode(
  3709. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  3710. );
  3711. }
  3712. return rc;
  3713. }
  3714. /*
  3715. ** This function is called to release all dynamic resources held by the
  3716. ** merge-writer object pWriter, and if no error has occurred, to flush
  3717. ** all outstanding node buffers held by pWriter to disk.
  3718. **
  3719. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  3720. ** is made to write any data to disk. Instead, this function serves only
  3721. ** to release outstanding resources.
  3722. **
  3723. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  3724. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  3725. ** returning.
  3726. */
  3727. static void fts3IncrmergeRelease(
  3728. Fts3Table *p, /* FTS3 table handle */
  3729. IncrmergeWriter *pWriter, /* Merge-writer object */
  3730. int *pRc /* IN/OUT: Error code */
  3731. ){
  3732. int i; /* Used to iterate through non-root layers */
  3733. int iRoot; /* Index of root in pWriter->aNodeWriter */
  3734. NodeWriter *pRoot; /* NodeWriter for root node */
  3735. int rc = *pRc; /* Error code */
  3736. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  3737. ** root node. If the segment fits entirely on a single leaf node, iRoot
  3738. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  3739. ** will be 1. And so on. */
  3740. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  3741. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  3742. if( pNode->block.n>0 ) break;
  3743. assert( *pRc || pNode->block.nAlloc==0 );
  3744. assert( *pRc || pNode->key.nAlloc==0 );
  3745. sqlite3_free(pNode->block.a);
  3746. sqlite3_free(pNode->key.a);
  3747. }
  3748. /* Empty output segment. This is a no-op. */
  3749. if( iRoot<0 ) return;
  3750. /* The entire output segment fits on a single node. Normally, this means
  3751. ** the node would be stored as a blob in the "root" column of the %_segdir
  3752. ** table. However, this is not permitted in this case. The problem is that
  3753. ** space has already been reserved in the %_segments table, and so the
  3754. ** start_block and end_block fields of the %_segdir table must be populated.
  3755. ** And, by design or by accident, released versions of FTS cannot handle
  3756. ** segments that fit entirely on the root node with start_block!=0.
  3757. **
  3758. ** Instead, create a synthetic root node that contains nothing but a
  3759. ** pointer to the single content node. So that the segment consists of a
  3760. ** single leaf and a single interior (root) node.
  3761. **
  3762. ** Todo: Better might be to defer allocating space in the %_segments
  3763. ** table until we are sure it is needed.
  3764. */
  3765. if( iRoot==0 ){
  3766. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  3767. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  3768. if( rc==SQLITE_OK ){
  3769. pBlock->a[0] = 0x01;
  3770. pBlock->n = 1 + sqlite3Fts3PutVarint(
  3771. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  3772. );
  3773. }
  3774. iRoot = 1;
  3775. }
  3776. pRoot = &pWriter->aNodeWriter[iRoot];
  3777. /* Flush all currently outstanding nodes to disk. */
  3778. for(i=0; i<iRoot; i++){
  3779. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  3780. if( pNode->block.n>0 && rc==SQLITE_OK ){
  3781. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  3782. }
  3783. sqlite3_free(pNode->block.a);
  3784. sqlite3_free(pNode->key.a);
  3785. }
  3786. /* Write the %_segdir record. */
  3787. if( rc==SQLITE_OK ){
  3788. rc = fts3WriteSegdir(p,
  3789. pWriter->iAbsLevel+1, /* level */
  3790. pWriter->iIdx, /* idx */
  3791. pWriter->iStart, /* start_block */
  3792. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  3793. pWriter->iEnd, /* end_block */
  3794. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  3795. pRoot->block.a, pRoot->block.n /* root */
  3796. );
  3797. }
  3798. sqlite3_free(pRoot->block.a);
  3799. sqlite3_free(pRoot->key.a);
  3800. *pRc = rc;
  3801. }
  3802. /*
  3803. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  3804. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  3805. ** the other, it is considered to be smaller than the other.
  3806. **
  3807. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  3808. ** if it is greater.
  3809. */
  3810. static int fts3TermCmp(
  3811. const char *zLhs, int nLhs, /* LHS of comparison */
  3812. const char *zRhs, int nRhs /* RHS of comparison */
  3813. ){
  3814. int nCmp = MIN(nLhs, nRhs);
  3815. int res;
  3816. if( nCmp && ALWAYS(zLhs) && ALWAYS(zRhs) ){
  3817. res = memcmp(zLhs, zRhs, nCmp);
  3818. }else{
  3819. res = 0;
  3820. }
  3821. if( res==0 ) res = nLhs - nRhs;
  3822. return res;
  3823. }
  3824. /*
  3825. ** Query to see if the entry in the %_segments table with blockid iEnd is
  3826. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  3827. ** returning. Otherwise, set *pbRes to 0.
  3828. **
  3829. ** Or, if an error occurs while querying the database, return an SQLite
  3830. ** error code. The final value of *pbRes is undefined in this case.
  3831. **
  3832. ** This is used to test if a segment is an "appendable" segment. If it
  3833. ** is, then a NULL entry has been inserted into the %_segments table
  3834. ** with blockid %_segdir.end_block.
  3835. */
  3836. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  3837. int bRes = 0; /* Result to set *pbRes to */
  3838. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  3839. int rc; /* Return code */
  3840. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  3841. if( rc==SQLITE_OK ){
  3842. sqlite3_bind_int64(pCheck, 1, iEnd);
  3843. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  3844. rc = sqlite3_reset(pCheck);
  3845. }
  3846. *pbRes = bRes;
  3847. return rc;
  3848. }
  3849. /*
  3850. ** This function is called when initializing an incremental-merge operation.
  3851. ** It checks if the existing segment with index value iIdx at absolute level
  3852. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  3853. ** merge-writer object *pWriter is initialized to write to it.
  3854. **
  3855. ** An existing segment can be appended to by an incremental merge if:
  3856. **
  3857. ** * It was initially created as an appendable segment (with all required
  3858. ** space pre-allocated), and
  3859. **
  3860. ** * The first key read from the input (arguments zKey and nKey) is
  3861. ** greater than the largest key currently stored in the potential
  3862. ** output segment.
  3863. */
  3864. static int fts3IncrmergeLoad(
  3865. Fts3Table *p, /* Fts3 table handle */
  3866. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  3867. int iIdx, /* Index of candidate output segment */
  3868. const char *zKey, /* First key to write */
  3869. int nKey, /* Number of bytes in nKey */
  3870. IncrmergeWriter *pWriter /* Populate this object */
  3871. ){
  3872. int rc; /* Return code */
  3873. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  3874. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  3875. if( rc==SQLITE_OK ){
  3876. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  3877. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  3878. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  3879. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  3880. int nRoot = 0; /* Size of aRoot[] in bytes */
  3881. int rc2; /* Return code from sqlite3_reset() */
  3882. int bAppendable = 0; /* Set to true if segment is appendable */
  3883. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  3884. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  3885. sqlite3_bind_int(pSelect, 2, iIdx);
  3886. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  3887. iStart = sqlite3_column_int64(pSelect, 1);
  3888. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  3889. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  3890. if( pWriter->nLeafData<0 ){
  3891. pWriter->nLeafData = pWriter->nLeafData * -1;
  3892. }
  3893. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  3894. nRoot = sqlite3_column_bytes(pSelect, 4);
  3895. aRoot = sqlite3_column_blob(pSelect, 4);
  3896. if( aRoot==0 ){
  3897. sqlite3_reset(pSelect);
  3898. return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
  3899. }
  3900. }else{
  3901. return sqlite3_reset(pSelect);
  3902. }
  3903. /* Check for the zero-length marker in the %_segments table */
  3904. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  3905. /* Check that zKey/nKey is larger than the largest key the candidate */
  3906. if( rc==SQLITE_OK && bAppendable ){
  3907. char *aLeaf = 0;
  3908. int nLeaf = 0;
  3909. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  3910. if( rc==SQLITE_OK ){
  3911. NodeReader reader;
  3912. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  3913. rc==SQLITE_OK && reader.aNode;
  3914. rc = nodeReaderNext(&reader)
  3915. ){
  3916. assert( reader.aNode );
  3917. }
  3918. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  3919. bAppendable = 0;
  3920. }
  3921. nodeReaderRelease(&reader);
  3922. }
  3923. sqlite3_free(aLeaf);
  3924. }
  3925. if( rc==SQLITE_OK && bAppendable ){
  3926. /* It is possible to append to this segment. Set up the IncrmergeWriter
  3927. ** object to do so. */
  3928. int i;
  3929. int nHeight = (int)aRoot[0];
  3930. NodeWriter *pNode;
  3931. if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
  3932. sqlite3_reset(pSelect);
  3933. return FTS_CORRUPT_VTAB;
  3934. }
  3935. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  3936. pWriter->iStart = iStart;
  3937. pWriter->iEnd = iEnd;
  3938. pWriter->iAbsLevel = iAbsLevel;
  3939. pWriter->iIdx = iIdx;
  3940. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  3941. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  3942. }
  3943. pNode = &pWriter->aNodeWriter[nHeight];
  3944. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  3945. blobGrowBuffer(&pNode->block,
  3946. MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  3947. );
  3948. if( rc==SQLITE_OK ){
  3949. memcpy(pNode->block.a, aRoot, nRoot);
  3950. pNode->block.n = nRoot;
  3951. memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
  3952. }
  3953. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  3954. NodeReader reader;
  3955. memset(&reader, 0, sizeof(reader));
  3956. pNode = &pWriter->aNodeWriter[i];
  3957. if( pNode->block.a){
  3958. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  3959. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  3960. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  3961. if( rc==SQLITE_OK ){
  3962. assert_fts3_nc( reader.term.n>0 || reader.aNode==0 );
  3963. if( reader.term.n>0 ){
  3964. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  3965. }
  3966. pNode->key.n = reader.term.n;
  3967. if( i>0 ){
  3968. char *aBlock = 0;
  3969. int nBlock = 0;
  3970. pNode = &pWriter->aNodeWriter[i-1];
  3971. pNode->iBlock = reader.iChild;
  3972. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock,0);
  3973. blobGrowBuffer(&pNode->block,
  3974. MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  3975. );
  3976. if( rc==SQLITE_OK ){
  3977. memcpy(pNode->block.a, aBlock, nBlock);
  3978. pNode->block.n = nBlock;
  3979. memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
  3980. }
  3981. sqlite3_free(aBlock);
  3982. }
  3983. }
  3984. }
  3985. nodeReaderRelease(&reader);
  3986. }
  3987. }
  3988. rc2 = sqlite3_reset(pSelect);
  3989. if( rc==SQLITE_OK ) rc = rc2;
  3990. }
  3991. return rc;
  3992. }
  3993. /*
  3994. ** Determine the largest segment index value that exists within absolute
  3995. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  3996. ** one before returning SQLITE_OK. Or, if there are no segments at all
  3997. ** within level iAbsLevel, set *piIdx to zero.
  3998. **
  3999. ** If an error occurs, return an SQLite error code. The final value of
  4000. ** *piIdx is undefined in this case.
  4001. */
  4002. static int fts3IncrmergeOutputIdx(
  4003. Fts3Table *p, /* FTS Table handle */
  4004. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  4005. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  4006. ){
  4007. int rc;
  4008. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  4009. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  4010. if( rc==SQLITE_OK ){
  4011. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  4012. sqlite3_step(pOutputIdx);
  4013. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  4014. rc = sqlite3_reset(pOutputIdx);
  4015. }
  4016. return rc;
  4017. }
  4018. /*
  4019. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  4020. ** with idx value iIdx.
  4021. **
  4022. ** In the %_segdir table, a segment is defined by the values in three
  4023. ** columns:
  4024. **
  4025. ** start_block
  4026. ** leaves_end_block
  4027. ** end_block
  4028. **
  4029. ** When an appendable segment is allocated, it is estimated that the
  4030. ** maximum number of leaf blocks that may be required is the sum of the
  4031. ** number of leaf blocks consumed by the input segments, plus the number
  4032. ** of input segments, multiplied by two. This value is stored in stack
  4033. ** variable nLeafEst.
  4034. **
  4035. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  4036. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  4037. ** array of leaf nodes starts at the first block allocated. The array
  4038. ** of interior nodes that are parents of the leaf nodes start at block
  4039. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  4040. **
  4041. ** In the actual code below, the value "16" is replaced with the
  4042. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  4043. */
  4044. static int fts3IncrmergeWriter(
  4045. Fts3Table *p, /* Fts3 table handle */
  4046. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  4047. int iIdx, /* Index of new output segment */
  4048. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  4049. IncrmergeWriter *pWriter /* Populate this object */
  4050. ){
  4051. int rc; /* Return Code */
  4052. int i; /* Iterator variable */
  4053. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  4054. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  4055. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  4056. /* Calculate nLeafEst. */
  4057. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  4058. if( rc==SQLITE_OK ){
  4059. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  4060. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  4061. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  4062. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  4063. }
  4064. rc = sqlite3_reset(pLeafEst);
  4065. }
  4066. if( rc!=SQLITE_OK ) return rc;
  4067. /* Calculate the first block to use in the output segment */
  4068. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  4069. if( rc==SQLITE_OK ){
  4070. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  4071. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  4072. pWriter->iEnd = pWriter->iStart - 1;
  4073. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  4074. }
  4075. rc = sqlite3_reset(pFirstBlock);
  4076. }
  4077. if( rc!=SQLITE_OK ) return rc;
  4078. /* Insert the marker in the %_segments table to make sure nobody tries
  4079. ** to steal the space just allocated. This is also used to identify
  4080. ** appendable segments. */
  4081. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  4082. if( rc!=SQLITE_OK ) return rc;
  4083. pWriter->iAbsLevel = iAbsLevel;
  4084. pWriter->nLeafEst = nLeafEst;
  4085. pWriter->iIdx = iIdx;
  4086. /* Set up the array of NodeWriter objects */
  4087. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  4088. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  4089. }
  4090. return SQLITE_OK;
  4091. }
  4092. /*
  4093. ** Remove an entry from the %_segdir table. This involves running the
  4094. ** following two statements:
  4095. **
  4096. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  4097. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  4098. **
  4099. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  4100. ** statement ensures that the remaining segments have contiguously allocated
  4101. ** idx values.
  4102. */
  4103. static int fts3RemoveSegdirEntry(
  4104. Fts3Table *p, /* FTS3 table handle */
  4105. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  4106. int iIdx /* Index of %_segdir entry to delete */
  4107. ){
  4108. int rc; /* Return code */
  4109. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  4110. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  4111. if( rc==SQLITE_OK ){
  4112. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  4113. sqlite3_bind_int(pDelete, 2, iIdx);
  4114. sqlite3_step(pDelete);
  4115. rc = sqlite3_reset(pDelete);
  4116. }
  4117. return rc;
  4118. }
  4119. /*
  4120. ** One or more segments have just been removed from absolute level iAbsLevel.
  4121. ** Update the 'idx' values of the remaining segments in the level so that
  4122. ** the idx values are a contiguous sequence starting from 0.
  4123. */
  4124. static int fts3RepackSegdirLevel(
  4125. Fts3Table *p, /* FTS3 table handle */
  4126. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  4127. ){
  4128. int rc; /* Return code */
  4129. int *aIdx = 0; /* Array of remaining idx values */
  4130. int nIdx = 0; /* Valid entries in aIdx[] */
  4131. int nAlloc = 0; /* Allocated size of aIdx[] */
  4132. int i; /* Iterator variable */
  4133. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  4134. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  4135. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  4136. if( rc==SQLITE_OK ){
  4137. int rc2;
  4138. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  4139. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  4140. if( nIdx>=nAlloc ){
  4141. int *aNew;
  4142. nAlloc += 16;
  4143. aNew = sqlite3_realloc64(aIdx, nAlloc*sizeof(int));
  4144. if( !aNew ){
  4145. rc = SQLITE_NOMEM;
  4146. break;
  4147. }
  4148. aIdx = aNew;
  4149. }
  4150. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  4151. }
  4152. rc2 = sqlite3_reset(pSelect);
  4153. if( rc==SQLITE_OK ) rc = rc2;
  4154. }
  4155. if( rc==SQLITE_OK ){
  4156. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  4157. }
  4158. if( rc==SQLITE_OK ){
  4159. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  4160. }
  4161. assert( p->bIgnoreSavepoint==0 );
  4162. p->bIgnoreSavepoint = 1;
  4163. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  4164. if( aIdx[i]!=i ){
  4165. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  4166. sqlite3_bind_int(pUpdate, 1, i);
  4167. sqlite3_step(pUpdate);
  4168. rc = sqlite3_reset(pUpdate);
  4169. }
  4170. }
  4171. p->bIgnoreSavepoint = 0;
  4172. sqlite3_free(aIdx);
  4173. return rc;
  4174. }
  4175. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  4176. pNode->a[0] = (char)iHeight;
  4177. if( iChild ){
  4178. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  4179. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  4180. }else{
  4181. assert( pNode->nAlloc>=1 );
  4182. pNode->n = 1;
  4183. }
  4184. }
  4185. /*
  4186. ** The first two arguments are a pointer to and the size of a segment b-tree
  4187. ** node. The node may be a leaf or an internal node.
  4188. **
  4189. ** This function creates a new node image in blob object *pNew by copying
  4190. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  4191. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  4192. */
  4193. static int fts3TruncateNode(
  4194. const char *aNode, /* Current node image */
  4195. int nNode, /* Size of aNode in bytes */
  4196. Blob *pNew, /* OUT: Write new node image here */
  4197. const char *zTerm, /* Omit all terms smaller than this */
  4198. int nTerm, /* Size of zTerm in bytes */
  4199. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  4200. ){
  4201. NodeReader reader; /* Reader object */
  4202. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  4203. int rc = SQLITE_OK; /* Return code */
  4204. int bLeaf; /* True for a leaf node */
  4205. if( nNode<1 ) return FTS_CORRUPT_VTAB;
  4206. bLeaf = aNode[0]=='\0';
  4207. /* Allocate required output space */
  4208. blobGrowBuffer(pNew, nNode, &rc);
  4209. if( rc!=SQLITE_OK ) return rc;
  4210. pNew->n = 0;
  4211. /* Populate new node buffer */
  4212. for(rc = nodeReaderInit(&reader, aNode, nNode);
  4213. rc==SQLITE_OK && reader.aNode;
  4214. rc = nodeReaderNext(&reader)
  4215. ){
  4216. if( pNew->n==0 ){
  4217. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  4218. if( res<0 || (bLeaf==0 && res==0) ) continue;
  4219. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  4220. *piBlock = reader.iChild;
  4221. }
  4222. rc = fts3AppendToNode(
  4223. pNew, &prev, reader.term.a, reader.term.n,
  4224. reader.aDoclist, reader.nDoclist
  4225. );
  4226. if( rc!=SQLITE_OK ) break;
  4227. }
  4228. if( pNew->n==0 ){
  4229. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  4230. *piBlock = reader.iChild;
  4231. }
  4232. assert( pNew->n<=pNew->nAlloc );
  4233. nodeReaderRelease(&reader);
  4234. sqlite3_free(prev.a);
  4235. return rc;
  4236. }
  4237. /*
  4238. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  4239. ** level iAbsLevel. This may involve deleting entries from the %_segments
  4240. ** table, and modifying existing entries in both the %_segments and %_segdir
  4241. ** tables.
  4242. **
  4243. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  4244. ** SQLite error code otherwise.
  4245. */
  4246. static int fts3TruncateSegment(
  4247. Fts3Table *p, /* FTS3 table handle */
  4248. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  4249. int iIdx, /* Index within level of segment to modify */
  4250. const char *zTerm, /* Remove terms smaller than this */
  4251. int nTerm /* Number of bytes in buffer zTerm */
  4252. ){
  4253. int rc = SQLITE_OK; /* Return code */
  4254. Blob root = {0,0,0}; /* New root page image */
  4255. Blob block = {0,0,0}; /* Buffer used for any other block */
  4256. sqlite3_int64 iBlock = 0; /* Block id */
  4257. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  4258. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  4259. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  4260. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  4261. if( rc==SQLITE_OK ){
  4262. int rc2; /* sqlite3_reset() return code */
  4263. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  4264. sqlite3_bind_int(pFetch, 2, iIdx);
  4265. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  4266. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  4267. int nRoot = sqlite3_column_bytes(pFetch, 4);
  4268. iOldStart = sqlite3_column_int64(pFetch, 1);
  4269. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  4270. }
  4271. rc2 = sqlite3_reset(pFetch);
  4272. if( rc==SQLITE_OK ) rc = rc2;
  4273. }
  4274. while( rc==SQLITE_OK && iBlock ){
  4275. char *aBlock = 0;
  4276. int nBlock = 0;
  4277. iNewStart = iBlock;
  4278. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  4279. if( rc==SQLITE_OK ){
  4280. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  4281. }
  4282. if( rc==SQLITE_OK ){
  4283. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  4284. }
  4285. sqlite3_free(aBlock);
  4286. }
  4287. /* Variable iNewStart now contains the first valid leaf node. */
  4288. if( rc==SQLITE_OK && iNewStart ){
  4289. sqlite3_stmt *pDel = 0;
  4290. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  4291. if( rc==SQLITE_OK ){
  4292. sqlite3_bind_int64(pDel, 1, iOldStart);
  4293. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  4294. sqlite3_step(pDel);
  4295. rc = sqlite3_reset(pDel);
  4296. }
  4297. }
  4298. if( rc==SQLITE_OK ){
  4299. sqlite3_stmt *pChomp = 0;
  4300. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  4301. if( rc==SQLITE_OK ){
  4302. sqlite3_bind_int64(pChomp, 1, iNewStart);
  4303. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  4304. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  4305. sqlite3_bind_int(pChomp, 4, iIdx);
  4306. sqlite3_step(pChomp);
  4307. rc = sqlite3_reset(pChomp);
  4308. sqlite3_bind_null(pChomp, 2);
  4309. }
  4310. }
  4311. sqlite3_free(root.a);
  4312. sqlite3_free(block.a);
  4313. return rc;
  4314. }
  4315. /*
  4316. ** This function is called after an incrmental-merge operation has run to
  4317. ** merge (or partially merge) two or more segments from absolute level
  4318. ** iAbsLevel.
  4319. **
  4320. ** Each input segment is either removed from the db completely (if all of
  4321. ** its data was copied to the output segment by the incrmerge operation)
  4322. ** or modified in place so that it no longer contains those entries that
  4323. ** have been duplicated in the output segment.
  4324. */
  4325. static int fts3IncrmergeChomp(
  4326. Fts3Table *p, /* FTS table handle */
  4327. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  4328. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  4329. int *pnRem /* Number of segments not deleted */
  4330. ){
  4331. int i;
  4332. int nRem = 0;
  4333. int rc = SQLITE_OK;
  4334. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  4335. Fts3SegReader *pSeg = 0;
  4336. int j;
  4337. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  4338. ** somewhere in the pCsr->apSegment[] array. */
  4339. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  4340. pSeg = pCsr->apSegment[j];
  4341. if( pSeg->iIdx==i ) break;
  4342. }
  4343. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  4344. if( pSeg->aNode==0 ){
  4345. /* Seg-reader is at EOF. Remove the entire input segment. */
  4346. rc = fts3DeleteSegment(p, pSeg);
  4347. if( rc==SQLITE_OK ){
  4348. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  4349. }
  4350. *pnRem = 0;
  4351. }else{
  4352. /* The incremental merge did not copy all the data from this
  4353. ** segment to the upper level. The segment is modified in place
  4354. ** so that it contains no keys smaller than zTerm/nTerm. */
  4355. const char *zTerm = pSeg->zTerm;
  4356. int nTerm = pSeg->nTerm;
  4357. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  4358. nRem++;
  4359. }
  4360. }
  4361. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  4362. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  4363. }
  4364. *pnRem = nRem;
  4365. return rc;
  4366. }
  4367. /*
  4368. ** Store an incr-merge hint in the database.
  4369. */
  4370. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  4371. sqlite3_stmt *pReplace = 0;
  4372. int rc; /* Return code */
  4373. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  4374. if( rc==SQLITE_OK ){
  4375. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  4376. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  4377. sqlite3_step(pReplace);
  4378. rc = sqlite3_reset(pReplace);
  4379. sqlite3_bind_null(pReplace, 2);
  4380. }
  4381. return rc;
  4382. }
  4383. /*
  4384. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  4385. ** exists, is stored in the rowid==1 row of the %_stat table.
  4386. **
  4387. ** If successful, populate blob *pHint with the value read from the %_stat
  4388. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  4389. ** SQLite error code.
  4390. */
  4391. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  4392. sqlite3_stmt *pSelect = 0;
  4393. int rc;
  4394. pHint->n = 0;
  4395. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  4396. if( rc==SQLITE_OK ){
  4397. int rc2;
  4398. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  4399. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  4400. const char *aHint = sqlite3_column_blob(pSelect, 0);
  4401. int nHint = sqlite3_column_bytes(pSelect, 0);
  4402. if( aHint ){
  4403. blobGrowBuffer(pHint, nHint, &rc);
  4404. if( rc==SQLITE_OK ){
  4405. if( ALWAYS(pHint->a!=0) ) memcpy(pHint->a, aHint, nHint);
  4406. pHint->n = nHint;
  4407. }
  4408. }
  4409. }
  4410. rc2 = sqlite3_reset(pSelect);
  4411. if( rc==SQLITE_OK ) rc = rc2;
  4412. }
  4413. return rc;
  4414. }
  4415. /*
  4416. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  4417. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  4418. ** consists of two varints, the absolute level number of the input segments
  4419. ** and the number of input segments.
  4420. **
  4421. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  4422. ** set *pRc to an SQLite error code before returning.
  4423. */
  4424. static void fts3IncrmergeHintPush(
  4425. Blob *pHint, /* Hint blob to append to */
  4426. i64 iAbsLevel, /* First varint to store in hint */
  4427. int nInput, /* Second varint to store in hint */
  4428. int *pRc /* IN/OUT: Error code */
  4429. ){
  4430. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  4431. if( *pRc==SQLITE_OK ){
  4432. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  4433. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  4434. }
  4435. }
  4436. /*
  4437. ** Read the last entry (most recently pushed) from the hint blob *pHint
  4438. ** and then remove the entry. Write the two values read to *piAbsLevel and
  4439. ** *pnInput before returning.
  4440. **
  4441. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  4442. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  4443. */
  4444. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  4445. const int nHint = pHint->n;
  4446. int i;
  4447. i = pHint->n-1;
  4448. if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
  4449. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  4450. if( i==0 ) return FTS_CORRUPT_VTAB;
  4451. i--;
  4452. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  4453. pHint->n = i;
  4454. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  4455. i += fts3GetVarint32(&pHint->a[i], pnInput);
  4456. assert( i<=nHint );
  4457. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  4458. return SQLITE_OK;
  4459. }
  4460. /*
  4461. ** Attempt an incremental merge that writes nMerge leaf blocks.
  4462. **
  4463. ** Incremental merges happen nMin segments at a time. The segments
  4464. ** to be merged are the nMin oldest segments (the ones with the smallest
  4465. ** values for the _segdir.idx field) in the highest level that contains
  4466. ** at least nMin segments. Multiple merges might occur in an attempt to
  4467. ** write the quota of nMerge leaf blocks.
  4468. */
  4469. int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  4470. int rc; /* Return code */
  4471. int nRem = nMerge; /* Number of leaf pages yet to be written */
  4472. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  4473. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  4474. IncrmergeWriter *pWriter; /* Writer object */
  4475. int nSeg = 0; /* Number of input segments */
  4476. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  4477. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  4478. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  4479. /* Allocate space for the cursor, filter and writer objects */
  4480. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  4481. pWriter = (IncrmergeWriter *)sqlite3_malloc64(nAlloc);
  4482. if( !pWriter ) return SQLITE_NOMEM;
  4483. pFilter = (Fts3SegFilter *)&pWriter[1];
  4484. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  4485. rc = fts3IncrmergeHintLoad(p, &hint);
  4486. while( rc==SQLITE_OK && nRem>0 ){
  4487. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  4488. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  4489. int bUseHint = 0; /* True if attempting to append */
  4490. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  4491. /* Search the %_segdir table for the absolute level with the smallest
  4492. ** relative level number that contains at least nMin segments, if any.
  4493. ** If one is found, set iAbsLevel to the absolute level number and
  4494. ** nSeg to nMin. If no level with at least nMin segments can be found,
  4495. ** set nSeg to -1.
  4496. */
  4497. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  4498. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  4499. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  4500. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  4501. nSeg = sqlite3_column_int(pFindLevel, 1);
  4502. assert( nSeg>=2 );
  4503. }else{
  4504. nSeg = -1;
  4505. }
  4506. rc = sqlite3_reset(pFindLevel);
  4507. /* If the hint read from the %_stat table is not empty, check if the
  4508. ** last entry in it specifies a relative level smaller than or equal
  4509. ** to the level identified by the block above (if any). If so, this
  4510. ** iteration of the loop will work on merging at the hinted level.
  4511. */
  4512. if( rc==SQLITE_OK && hint.n ){
  4513. int nHint = hint.n;
  4514. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  4515. int nHintSeg = 0; /* Hint number of segments */
  4516. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  4517. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  4518. /* Based on the scan in the block above, it is known that there
  4519. ** are no levels with a relative level smaller than that of
  4520. ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
  4521. ** no levels with more than nMin segments. Use this to limit the
  4522. ** value of nHintSeg to avoid a large memory allocation in case the
  4523. ** merge-hint is corrupt*/
  4524. iAbsLevel = iHintAbsLevel;
  4525. nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
  4526. bUseHint = 1;
  4527. bDirtyHint = 1;
  4528. }else{
  4529. /* This undoes the effect of the HintPop() above - so that no entry
  4530. ** is removed from the hint blob. */
  4531. hint.n = nHint;
  4532. }
  4533. }
  4534. /* If nSeg is less that zero, then there is no level with at least
  4535. ** nMin segments and no hint in the %_stat table. No work to do.
  4536. ** Exit early in this case. */
  4537. if( nSeg<=0 ) break;
  4538. assert( nMod<=0x7FFFFFFF );
  4539. if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){
  4540. rc = FTS_CORRUPT_VTAB;
  4541. break;
  4542. }
  4543. /* Open a cursor to iterate through the contents of the oldest nSeg
  4544. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  4545. ** the 'hint' parameters, it is possible that there are less than nSeg
  4546. ** segments available in level iAbsLevel. In this case, no work is
  4547. ** done on iAbsLevel - fall through to the next iteration of the loop
  4548. ** to start work on some other level. */
  4549. memset(pWriter, 0, nAlloc);
  4550. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  4551. if( rc==SQLITE_OK ){
  4552. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  4553. assert( bUseHint==1 || bUseHint==0 );
  4554. if( iIdx==0 || (bUseHint && iIdx==1) ){
  4555. int bIgnore = 0;
  4556. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  4557. if( bIgnore ){
  4558. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  4559. }
  4560. }
  4561. }
  4562. if( rc==SQLITE_OK ){
  4563. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  4564. }
  4565. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  4566. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  4567. ){
  4568. int bEmpty = 0;
  4569. rc = sqlite3Fts3SegReaderStep(p, pCsr);
  4570. if( rc==SQLITE_OK ){
  4571. bEmpty = 1;
  4572. }else if( rc!=SQLITE_ROW ){
  4573. sqlite3Fts3SegReaderFinish(pCsr);
  4574. break;
  4575. }
  4576. if( bUseHint && iIdx>0 ){
  4577. const char *zKey = pCsr->zTerm;
  4578. int nKey = pCsr->nTerm;
  4579. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  4580. }else{
  4581. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  4582. }
  4583. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  4584. fts3LogMerge(nSeg, iAbsLevel);
  4585. if( bEmpty==0 ){
  4586. do {
  4587. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  4588. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  4589. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  4590. }while( rc==SQLITE_ROW );
  4591. }
  4592. /* Update or delete the input segments */
  4593. if( rc==SQLITE_OK ){
  4594. nRem -= (1 + pWriter->nWork);
  4595. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  4596. if( nSeg!=0 ){
  4597. bDirtyHint = 1;
  4598. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  4599. }
  4600. }
  4601. }
  4602. if( nSeg!=0 ){
  4603. pWriter->nLeafData = pWriter->nLeafData * -1;
  4604. }
  4605. fts3IncrmergeRelease(p, pWriter, &rc);
  4606. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  4607. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  4608. }
  4609. }
  4610. sqlite3Fts3SegReaderFinish(pCsr);
  4611. }
  4612. /* Write the hint values into the %_stat table for the next incr-merger */
  4613. if( bDirtyHint && rc==SQLITE_OK ){
  4614. rc = fts3IncrmergeHintStore(p, &hint);
  4615. }
  4616. sqlite3_free(pWriter);
  4617. sqlite3_free(hint.a);
  4618. return rc;
  4619. }
  4620. /*
  4621. ** Convert the text beginning at *pz into an integer and return
  4622. ** its value. Advance *pz to point to the first character past
  4623. ** the integer.
  4624. **
  4625. ** This function used for parameters to merge= and incrmerge=
  4626. ** commands.
  4627. */
  4628. static int fts3Getint(const char **pz){
  4629. const char *z = *pz;
  4630. int i = 0;
  4631. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  4632. *pz = z;
  4633. return i;
  4634. }
  4635. /*
  4636. ** Process statements of the form:
  4637. **
  4638. ** INSERT INTO table(table) VALUES('merge=A,B');
  4639. **
  4640. ** A and B are integers that decode to be the number of leaf pages
  4641. ** written for the merge, and the minimum number of segments on a level
  4642. ** before it will be selected for a merge, respectively.
  4643. */
  4644. static int fts3DoIncrmerge(
  4645. Fts3Table *p, /* FTS3 table handle */
  4646. const char *zParam /* Nul-terminated string containing "A,B" */
  4647. ){
  4648. int rc;
  4649. int nMin = (MergeCount(p) / 2);
  4650. int nMerge = 0;
  4651. const char *z = zParam;
  4652. /* Read the first integer value */
  4653. nMerge = fts3Getint(&z);
  4654. /* If the first integer value is followed by a ',', read the second
  4655. ** integer value. */
  4656. if( z[0]==',' && z[1]!='\0' ){
  4657. z++;
  4658. nMin = fts3Getint(&z);
  4659. }
  4660. if( z[0]!='\0' || nMin<2 ){
  4661. rc = SQLITE_ERROR;
  4662. }else{
  4663. rc = SQLITE_OK;
  4664. if( !p->bHasStat ){
  4665. assert( p->bFts4==0 );
  4666. sqlite3Fts3CreateStatTable(&rc, p);
  4667. }
  4668. if( rc==SQLITE_OK ){
  4669. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  4670. }
  4671. sqlite3Fts3SegmentsClose(p);
  4672. }
  4673. return rc;
  4674. }
  4675. /*
  4676. ** Process statements of the form:
  4677. **
  4678. ** INSERT INTO table(table) VALUES('automerge=X');
  4679. **
  4680. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  4681. ** turn it on. The setting is persistent.
  4682. */
  4683. static int fts3DoAutoincrmerge(
  4684. Fts3Table *p, /* FTS3 table handle */
  4685. const char *zParam /* Nul-terminated string containing boolean */
  4686. ){
  4687. int rc = SQLITE_OK;
  4688. sqlite3_stmt *pStmt = 0;
  4689. p->nAutoincrmerge = fts3Getint(&zParam);
  4690. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
  4691. p->nAutoincrmerge = 8;
  4692. }
  4693. if( !p->bHasStat ){
  4694. assert( p->bFts4==0 );
  4695. sqlite3Fts3CreateStatTable(&rc, p);
  4696. if( rc ) return rc;
  4697. }
  4698. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  4699. if( rc ) return rc;
  4700. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  4701. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  4702. sqlite3_step(pStmt);
  4703. rc = sqlite3_reset(pStmt);
  4704. return rc;
  4705. }
  4706. /*
  4707. ** Return a 64-bit checksum for the FTS index entry specified by the
  4708. ** arguments to this function.
  4709. */
  4710. static u64 fts3ChecksumEntry(
  4711. const char *zTerm, /* Pointer to buffer containing term */
  4712. int nTerm, /* Size of zTerm in bytes */
  4713. int iLangid, /* Language id for current row */
  4714. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  4715. i64 iDocid, /* Docid for current row. */
  4716. int iCol, /* Column number */
  4717. int iPos /* Position */
  4718. ){
  4719. int i;
  4720. u64 ret = (u64)iDocid;
  4721. ret += (ret<<3) + iLangid;
  4722. ret += (ret<<3) + iIndex;
  4723. ret += (ret<<3) + iCol;
  4724. ret += (ret<<3) + iPos;
  4725. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  4726. return ret;
  4727. }
  4728. /*
  4729. ** Return a checksum of all entries in the FTS index that correspond to
  4730. ** language id iLangid. The checksum is calculated by XORing the checksums
  4731. ** of each individual entry (see fts3ChecksumEntry()) together.
  4732. **
  4733. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  4734. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  4735. ** return value is undefined in this case.
  4736. */
  4737. static u64 fts3ChecksumIndex(
  4738. Fts3Table *p, /* FTS3 table handle */
  4739. int iLangid, /* Language id to return cksum for */
  4740. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  4741. int *pRc /* OUT: Return code */
  4742. ){
  4743. Fts3SegFilter filter;
  4744. Fts3MultiSegReader csr;
  4745. int rc;
  4746. u64 cksum = 0;
  4747. if( *pRc ) return 0;
  4748. memset(&filter, 0, sizeof(filter));
  4749. memset(&csr, 0, sizeof(csr));
  4750. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  4751. filter.flags |= FTS3_SEGMENT_SCAN;
  4752. rc = sqlite3Fts3SegReaderCursor(
  4753. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  4754. );
  4755. if( rc==SQLITE_OK ){
  4756. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  4757. }
  4758. if( rc==SQLITE_OK ){
  4759. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  4760. char *pCsr = csr.aDoclist;
  4761. char *pEnd = &pCsr[csr.nDoclist];
  4762. i64 iDocid = 0;
  4763. i64 iCol = 0;
  4764. u64 iPos = 0;
  4765. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  4766. while( pCsr<pEnd ){
  4767. u64 iVal = 0;
  4768. pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
  4769. if( pCsr<pEnd ){
  4770. if( iVal==0 || iVal==1 ){
  4771. iCol = 0;
  4772. iPos = 0;
  4773. if( iVal ){
  4774. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  4775. }else{
  4776. pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
  4777. if( p->bDescIdx ){
  4778. iDocid = (i64)((u64)iDocid - iVal);
  4779. }else{
  4780. iDocid = (i64)((u64)iDocid + iVal);
  4781. }
  4782. }
  4783. }else{
  4784. iPos += (iVal - 2);
  4785. cksum = cksum ^ fts3ChecksumEntry(
  4786. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  4787. (int)iCol, (int)iPos
  4788. );
  4789. }
  4790. }
  4791. }
  4792. }
  4793. }
  4794. sqlite3Fts3SegReaderFinish(&csr);
  4795. *pRc = rc;
  4796. return cksum;
  4797. }
  4798. /*
  4799. ** Check if the contents of the FTS index match the current contents of the
  4800. ** content table. If no error occurs and the contents do match, set *pbOk
  4801. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  4802. ** to false before returning.
  4803. **
  4804. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  4805. ** code. The final value of *pbOk is undefined in this case.
  4806. */
  4807. int sqlite3Fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  4808. int rc = SQLITE_OK; /* Return code */
  4809. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  4810. u64 cksum2 = 0; /* Checksum based on %_content contents */
  4811. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  4812. /* This block calculates the checksum according to the FTS index. */
  4813. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  4814. if( rc==SQLITE_OK ){
  4815. int rc2;
  4816. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  4817. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  4818. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  4819. int iLangid = sqlite3_column_int(pAllLangid, 0);
  4820. int i;
  4821. for(i=0; i<p->nIndex; i++){
  4822. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  4823. }
  4824. }
  4825. rc2 = sqlite3_reset(pAllLangid);
  4826. if( rc==SQLITE_OK ) rc = rc2;
  4827. }
  4828. /* This block calculates the checksum according to the %_content table */
  4829. if( rc==SQLITE_OK ){
  4830. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  4831. sqlite3_stmt *pStmt = 0;
  4832. char *zSql;
  4833. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  4834. if( !zSql ){
  4835. rc = SQLITE_NOMEM;
  4836. }else{
  4837. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  4838. sqlite3_free(zSql);
  4839. }
  4840. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  4841. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  4842. int iLang = langidFromSelect(p, pStmt);
  4843. int iCol;
  4844. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  4845. if( p->abNotindexed[iCol]==0 ){
  4846. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  4847. sqlite3_tokenizer_cursor *pT = 0;
  4848. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
  4849. while( rc==SQLITE_OK ){
  4850. char const *zToken; /* Buffer containing token */
  4851. int nToken = 0; /* Number of bytes in token */
  4852. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  4853. int iPos = 0; /* Position of token in zText */
  4854. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  4855. if( rc==SQLITE_OK ){
  4856. int i;
  4857. cksum2 = cksum2 ^ fts3ChecksumEntry(
  4858. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  4859. );
  4860. for(i=1; i<p->nIndex; i++){
  4861. if( p->aIndex[i].nPrefix<=nToken ){
  4862. cksum2 = cksum2 ^ fts3ChecksumEntry(
  4863. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  4864. );
  4865. }
  4866. }
  4867. }
  4868. }
  4869. if( pT ) pModule->xClose(pT);
  4870. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  4871. }
  4872. }
  4873. }
  4874. sqlite3_finalize(pStmt);
  4875. }
  4876. if( rc==SQLITE_CORRUPT_VTAB ){
  4877. rc = SQLITE_OK;
  4878. *pbOk = 0;
  4879. }else{
  4880. *pbOk = (rc==SQLITE_OK && cksum1==cksum2);
  4881. }
  4882. return rc;
  4883. }
  4884. /*
  4885. ** Run the integrity-check. If no error occurs and the current contents of
  4886. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  4887. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  4888. **
  4889. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  4890. ** error code.
  4891. **
  4892. ** The integrity-check works as follows. For each token and indexed token
  4893. ** prefix in the document set, a 64-bit checksum is calculated (by code
  4894. ** in fts3ChecksumEntry()) based on the following:
  4895. **
  4896. ** + The index number (0 for the main index, 1 for the first prefix
  4897. ** index etc.),
  4898. ** + The token (or token prefix) text itself,
  4899. ** + The language-id of the row it appears in,
  4900. ** + The docid of the row it appears in,
  4901. ** + The column it appears in, and
  4902. ** + The tokens position within that column.
  4903. **
  4904. ** The checksums for all entries in the index are XORed together to create
  4905. ** a single checksum for the entire index.
  4906. **
  4907. ** The integrity-check code calculates the same checksum in two ways:
  4908. **
  4909. ** 1. By scanning the contents of the FTS index, and
  4910. ** 2. By scanning and tokenizing the content table.
  4911. **
  4912. ** If the two checksums are identical, the integrity-check is deemed to have
  4913. ** passed.
  4914. */
  4915. static int fts3DoIntegrityCheck(
  4916. Fts3Table *p /* FTS3 table handle */
  4917. ){
  4918. int rc;
  4919. int bOk = 0;
  4920. rc = sqlite3Fts3IntegrityCheck(p, &bOk);
  4921. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  4922. return rc;
  4923. }
  4924. /*
  4925. ** Handle a 'special' INSERT of the form:
  4926. **
  4927. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  4928. **
  4929. ** Argument pVal contains the result of <expr>. Currently the only
  4930. ** meaningful value to insert is the text 'optimize'.
  4931. */
  4932. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  4933. int rc = SQLITE_ERROR; /* Return Code */
  4934. const char *zVal = (const char *)sqlite3_value_text(pVal);
  4935. int nVal = sqlite3_value_bytes(pVal);
  4936. if( !zVal ){
  4937. return SQLITE_NOMEM;
  4938. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  4939. rc = fts3DoOptimize(p, 0);
  4940. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  4941. rc = fts3DoRebuild(p);
  4942. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  4943. rc = fts3DoIntegrityCheck(p);
  4944. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  4945. rc = fts3DoIncrmerge(p, &zVal[6]);
  4946. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  4947. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  4948. }else if( nVal==5 && 0==sqlite3_strnicmp(zVal, "flush", 5) ){
  4949. rc = sqlite3Fts3PendingTermsFlush(p);
  4950. }
  4951. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  4952. else{
  4953. int v;
  4954. if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  4955. v = atoi(&zVal[9]);
  4956. if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
  4957. rc = SQLITE_OK;
  4958. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  4959. v = atoi(&zVal[11]);
  4960. if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
  4961. rc = SQLITE_OK;
  4962. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
  4963. p->bNoIncrDoclist = atoi(&zVal[21]);
  4964. rc = SQLITE_OK;
  4965. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
  4966. v = atoi(&zVal[11]);
  4967. if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
  4968. rc = SQLITE_OK;
  4969. }
  4970. }
  4971. #endif
  4972. return rc;
  4973. }
  4974. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  4975. /*
  4976. ** Delete all cached deferred doclists. Deferred doclists are cached
  4977. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  4978. */
  4979. void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  4980. Fts3DeferredToken *pDef;
  4981. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  4982. fts3PendingListDelete(pDef->pList);
  4983. pDef->pList = 0;
  4984. }
  4985. }
  4986. /*
  4987. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  4988. ** this list using sqlite3Fts3DeferToken().
  4989. */
  4990. void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  4991. Fts3DeferredToken *pDef;
  4992. Fts3DeferredToken *pNext;
  4993. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  4994. pNext = pDef->pNext;
  4995. fts3PendingListDelete(pDef->pList);
  4996. sqlite3_free(pDef);
  4997. }
  4998. pCsr->pDeferred = 0;
  4999. }
  5000. /*
  5001. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  5002. ** based on the row that pCsr currently points to.
  5003. **
  5004. ** A deferred-doclist is like any other doclist with position information
  5005. ** included, except that it only contains entries for a single row of the
  5006. ** table, not for all rows.
  5007. */
  5008. int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  5009. int rc = SQLITE_OK; /* Return code */
  5010. if( pCsr->pDeferred ){
  5011. int i; /* Used to iterate through table columns */
  5012. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  5013. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  5014. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  5015. sqlite3_tokenizer *pT = p->pTokenizer;
  5016. sqlite3_tokenizer_module const *pModule = pT->pModule;
  5017. assert( pCsr->isRequireSeek==0 );
  5018. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  5019. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  5020. if( p->abNotindexed[i]==0 ){
  5021. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  5022. sqlite3_tokenizer_cursor *pTC = 0;
  5023. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  5024. while( rc==SQLITE_OK ){
  5025. char const *zToken; /* Buffer containing token */
  5026. int nToken = 0; /* Number of bytes in token */
  5027. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  5028. int iPos = 0; /* Position of token in zText */
  5029. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  5030. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  5031. Fts3PhraseToken *pPT = pDef->pToken;
  5032. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  5033. && (pPT->bFirst==0 || iPos==0)
  5034. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  5035. && (0==memcmp(zToken, pPT->z, pPT->n))
  5036. ){
  5037. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  5038. }
  5039. }
  5040. }
  5041. if( pTC ) pModule->xClose(pTC);
  5042. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  5043. }
  5044. }
  5045. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  5046. if( pDef->pList ){
  5047. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  5048. }
  5049. }
  5050. }
  5051. return rc;
  5052. }
  5053. int sqlite3Fts3DeferredTokenList(
  5054. Fts3DeferredToken *p,
  5055. char **ppData,
  5056. int *pnData
  5057. ){
  5058. char *pRet;
  5059. int nSkip;
  5060. sqlite3_int64 dummy;
  5061. *ppData = 0;
  5062. *pnData = 0;
  5063. if( p->pList==0 ){
  5064. return SQLITE_OK;
  5065. }
  5066. pRet = (char *)sqlite3_malloc64(p->pList->nData);
  5067. if( !pRet ) return SQLITE_NOMEM;
  5068. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  5069. *pnData = p->pList->nData - nSkip;
  5070. *ppData = pRet;
  5071. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  5072. return SQLITE_OK;
  5073. }
  5074. /*
  5075. ** Add an entry for token pToken to the pCsr->pDeferred list.
  5076. */
  5077. int sqlite3Fts3DeferToken(
  5078. Fts3Cursor *pCsr, /* Fts3 table cursor */
  5079. Fts3PhraseToken *pToken, /* Token to defer */
  5080. int iCol /* Column that token must appear in (or -1) */
  5081. ){
  5082. Fts3DeferredToken *pDeferred;
  5083. pDeferred = sqlite3_malloc64(sizeof(*pDeferred));
  5084. if( !pDeferred ){
  5085. return SQLITE_NOMEM;
  5086. }
  5087. memset(pDeferred, 0, sizeof(*pDeferred));
  5088. pDeferred->pToken = pToken;
  5089. pDeferred->pNext = pCsr->pDeferred;
  5090. pDeferred->iCol = iCol;
  5091. pCsr->pDeferred = pDeferred;
  5092. assert( pToken->pDeferred==0 );
  5093. pToken->pDeferred = pDeferred;
  5094. return SQLITE_OK;
  5095. }
  5096. #endif
  5097. /*
  5098. ** SQLite value pRowid contains the rowid of a row that may or may not be
  5099. ** present in the FTS3 table. If it is, delete it and adjust the contents
  5100. ** of subsiduary data structures accordingly.
  5101. */
  5102. static int fts3DeleteByRowid(
  5103. Fts3Table *p,
  5104. sqlite3_value *pRowid,
  5105. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  5106. u32 *aSzDel
  5107. ){
  5108. int rc = SQLITE_OK; /* Return code */
  5109. int bFound = 0; /* True if *pRowid really is in the table */
  5110. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  5111. if( bFound && rc==SQLITE_OK ){
  5112. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  5113. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  5114. if( rc==SQLITE_OK ){
  5115. if( isEmpty ){
  5116. /* Deleting this row means the whole table is empty. In this case
  5117. ** delete the contents of all three tables and throw away any
  5118. ** data in the pendingTerms hash table. */
  5119. rc = fts3DeleteAll(p, 1);
  5120. *pnChng = 0;
  5121. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  5122. }else{
  5123. *pnChng = *pnChng - 1;
  5124. if( p->zContentTbl==0 ){
  5125. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  5126. }
  5127. if( p->bHasDocsize ){
  5128. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  5129. }
  5130. }
  5131. }
  5132. }
  5133. return rc;
  5134. }
  5135. /*
  5136. ** This function does the work for the xUpdate method of FTS3 virtual
  5137. ** tables. The schema of the virtual table being:
  5138. **
  5139. ** CREATE TABLE <table name>(
  5140. ** <user columns>,
  5141. ** <table name> HIDDEN,
  5142. ** docid HIDDEN,
  5143. ** <langid> HIDDEN
  5144. ** );
  5145. **
  5146. **
  5147. */
  5148. int sqlite3Fts3UpdateMethod(
  5149. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  5150. int nArg, /* Size of argument array */
  5151. sqlite3_value **apVal, /* Array of arguments */
  5152. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  5153. ){
  5154. Fts3Table *p = (Fts3Table *)pVtab;
  5155. int rc = SQLITE_OK; /* Return Code */
  5156. u32 *aSzIns = 0; /* Sizes of inserted documents */
  5157. u32 *aSzDel = 0; /* Sizes of deleted documents */
  5158. int nChng = 0; /* Net change in number of documents */
  5159. int bInsertDone = 0;
  5160. /* At this point it must be known if the %_stat table exists or not.
  5161. ** So bHasStat may not be 2. */
  5162. assert( p->bHasStat==0 || p->bHasStat==1 );
  5163. assert( p->pSegments==0 );
  5164. assert(
  5165. nArg==1 /* DELETE operations */
  5166. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  5167. );
  5168. /* Check for a "special" INSERT operation. One of the form:
  5169. **
  5170. ** INSERT INTO xyz(xyz) VALUES('command');
  5171. */
  5172. if( nArg>1
  5173. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  5174. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  5175. ){
  5176. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  5177. goto update_out;
  5178. }
  5179. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  5180. rc = SQLITE_CONSTRAINT;
  5181. goto update_out;
  5182. }
  5183. /* Allocate space to hold the change in document sizes */
  5184. aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
  5185. if( aSzDel==0 ){
  5186. rc = SQLITE_NOMEM;
  5187. goto update_out;
  5188. }
  5189. aSzIns = &aSzDel[p->nColumn+1];
  5190. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  5191. rc = fts3Writelock(p);
  5192. if( rc!=SQLITE_OK ) goto update_out;
  5193. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  5194. ** value, then this operation requires constraint handling.
  5195. **
  5196. ** If the on-conflict mode is REPLACE, this means that the existing row
  5197. ** should be deleted from the database before inserting the new row. Or,
  5198. ** if the on-conflict mode is other than REPLACE, then this method must
  5199. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  5200. ** modify the database file.
  5201. */
  5202. if( nArg>1 && p->zContentTbl==0 ){
  5203. /* Find the value object that holds the new rowid value. */
  5204. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  5205. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  5206. pNewRowid = apVal[1];
  5207. }
  5208. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  5209. sqlite3_value_type(apVal[0])==SQLITE_NULL
  5210. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  5211. )){
  5212. /* The new rowid is not NULL (in this case the rowid will be
  5213. ** automatically assigned and there is no chance of a conflict), and
  5214. ** the statement is either an INSERT or an UPDATE that modifies the
  5215. ** rowid column. So if the conflict mode is REPLACE, then delete any
  5216. ** existing row with rowid=pNewRowid.
  5217. **
  5218. ** Or, if the conflict mode is not REPLACE, insert the new record into
  5219. ** the %_content table. If we hit the duplicate rowid constraint (or any
  5220. ** other error) while doing so, return immediately.
  5221. **
  5222. ** This branch may also run if pNewRowid contains a value that cannot
  5223. ** be losslessly converted to an integer. In this case, the eventual
  5224. ** call to fts3InsertData() (either just below or further on in this
  5225. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  5226. ** invoked, it will delete zero rows (since no row will have
  5227. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  5228. */
  5229. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  5230. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  5231. }else{
  5232. rc = fts3InsertData(p, apVal, pRowid);
  5233. bInsertDone = 1;
  5234. }
  5235. }
  5236. }
  5237. if( rc!=SQLITE_OK ){
  5238. goto update_out;
  5239. }
  5240. /* If this is a DELETE or UPDATE operation, remove the old record. */
  5241. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  5242. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  5243. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  5244. }
  5245. /* If this is an INSERT or UPDATE operation, insert the new record. */
  5246. if( nArg>1 && rc==SQLITE_OK ){
  5247. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  5248. if( bInsertDone==0 ){
  5249. rc = fts3InsertData(p, apVal, pRowid);
  5250. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  5251. rc = FTS_CORRUPT_VTAB;
  5252. }
  5253. }
  5254. if( rc==SQLITE_OK ){
  5255. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  5256. }
  5257. if( rc==SQLITE_OK ){
  5258. assert( p->iPrevDocid==*pRowid );
  5259. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  5260. }
  5261. if( p->bHasDocsize ){
  5262. fts3InsertDocsize(&rc, p, aSzIns);
  5263. }
  5264. nChng++;
  5265. }
  5266. if( p->bFts4 ){
  5267. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  5268. }
  5269. update_out:
  5270. sqlite3_free(aSzDel);
  5271. sqlite3Fts3SegmentsClose(p);
  5272. return rc;
  5273. }
  5274. /*
  5275. ** Flush any data in the pending-terms hash table to disk. If successful,
  5276. ** merge all segments in the database (including the new segment, if
  5277. ** there was any data to flush) into a single segment.
  5278. */
  5279. int sqlite3Fts3Optimize(Fts3Table *p){
  5280. int rc;
  5281. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  5282. if( rc==SQLITE_OK ){
  5283. rc = fts3DoOptimize(p, 1);
  5284. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  5285. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  5286. if( rc2!=SQLITE_OK ) rc = rc2;
  5287. }else{
  5288. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  5289. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  5290. }
  5291. }
  5292. sqlite3Fts3SegmentsClose(p);
  5293. return rc;
  5294. }
  5295. #endif