fts5_index.c 277 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077
  1. /*
  2. ** 2014 May 31
  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. ** Low level access to the FTS index stored in the database file. The
  14. ** routines in this file file implement all read and write access to the
  15. ** %_data table. Other parts of the system access this functionality via
  16. ** the interface defined in fts5Int.h.
  17. */
  18. #include "fts5Int.h"
  19. /*
  20. ** Overview:
  21. **
  22. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  23. ** As well as the main term index, there may be up to 31 prefix indexes.
  24. ** The format is similar to FTS3/4, except that:
  25. **
  26. ** * all segment b-tree leaf data is stored in fixed size page records
  27. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  28. ** taken to ensure it is possible to iterate in either direction through
  29. ** the entries in a doclist, or to seek to a specific entry within a
  30. ** doclist, without loading it into memory.
  31. **
  32. ** * large doclists that span many pages have associated "doclist index"
  33. ** records that contain a copy of the first rowid on each page spanned by
  34. ** the doclist. This is used to speed up seek operations, and merges of
  35. ** large doclists with very small doclists.
  36. **
  37. ** * extra fields in the "structure record" record the state of ongoing
  38. ** incremental merge operations.
  39. **
  40. */
  41. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  42. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  43. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  44. #define FTS5_MAIN_PREFIX '0'
  45. #if FTS5_MAX_PREFIX_INDEXES > 31
  46. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  47. #endif
  48. #define FTS5_MAX_LEVEL 64
  49. /*
  50. ** There are two versions of the format used for the structure record:
  51. **
  52. ** 1. the legacy format, that may be read by all fts5 versions, and
  53. **
  54. ** 2. the V2 format, which is used by contentless_delete=1 databases.
  55. **
  56. ** Both begin with a 4-byte "configuration cookie" value. Then, a legacy
  57. ** format structure record contains a varint - the number of levels in
  58. ** the structure. Whereas a V2 structure record contains the constant
  59. ** 4 bytes [0xff 0x00 0x00 0x01]. This is unambiguous as the value of a
  60. ** varint has to be at least 16256 to begin with "0xFF". And the default
  61. ** maximum number of levels is 64.
  62. **
  63. ** See below for more on structure record formats.
  64. */
  65. #define FTS5_STRUCTURE_V2 "\xFF\x00\x00\x01"
  66. /*
  67. ** Details:
  68. **
  69. ** The %_data table managed by this module,
  70. **
  71. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  72. **
  73. ** , contains the following 6 types of records. See the comments surrounding
  74. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  75. ** assigned to each fo them.
  76. **
  77. ** 1. Structure Records:
  78. **
  79. ** The set of segments that make up an index - the index structure - are
  80. ** recorded in a single record within the %_data table. The record consists
  81. ** of a single 32-bit configuration cookie value followed by a list of
  82. ** SQLite varints.
  83. **
  84. ** If the structure record is a V2 record, the configuration cookie is
  85. ** followed by the following 4 bytes: [0xFF 0x00 0x00 0x01].
  86. **
  87. ** Next, the record continues with three varints:
  88. **
  89. ** + number of levels,
  90. ** + total number of segments on all levels,
  91. ** + value of write counter.
  92. **
  93. ** Then, for each level from 0 to nMax:
  94. **
  95. ** + number of input segments in ongoing merge.
  96. ** + total number of segments in level.
  97. ** + for each segment from oldest to newest:
  98. ** + segment id (always > 0)
  99. ** + first leaf page number (often 1, always greater than 0)
  100. ** + final leaf page number
  101. **
  102. ** Then, for V2 structures only:
  103. **
  104. ** + lower origin counter value,
  105. ** + upper origin counter value,
  106. ** + the number of tombstone hash pages.
  107. **
  108. ** 2. The Averages Record:
  109. **
  110. ** A single record within the %_data table. The data is a list of varints.
  111. ** The first value is the number of rows in the index. Then, for each column
  112. ** from left to right, the total number of tokens in the column for all
  113. ** rows of the table.
  114. **
  115. ** 3. Segment leaves:
  116. **
  117. ** TERM/DOCLIST FORMAT:
  118. **
  119. ** Most of each segment leaf is taken up by term/doclist data. The
  120. ** general format of term/doclist, starting with the first term
  121. ** on the leaf page, is:
  122. **
  123. ** varint : size of first term
  124. ** blob: first term data
  125. ** doclist: first doclist
  126. ** zero-or-more {
  127. ** varint: number of bytes in common with previous term
  128. ** varint: number of bytes of new term data (nNew)
  129. ** blob: nNew bytes of new term data
  130. ** doclist: next doclist
  131. ** }
  132. **
  133. ** doclist format:
  134. **
  135. ** varint: first rowid
  136. ** poslist: first poslist
  137. ** zero-or-more {
  138. ** varint: rowid delta (always > 0)
  139. ** poslist: next poslist
  140. ** }
  141. **
  142. ** poslist format:
  143. **
  144. ** varint: size of poslist in bytes multiplied by 2, not including
  145. ** this field. Plus 1 if this entry carries the "delete" flag.
  146. ** collist: collist for column 0
  147. ** zero-or-more {
  148. ** 0x01 byte
  149. ** varint: column number (I)
  150. ** collist: collist for column I
  151. ** }
  152. **
  153. ** collist format:
  154. **
  155. ** varint: first offset + 2
  156. ** zero-or-more {
  157. ** varint: offset delta + 2
  158. ** }
  159. **
  160. ** PAGE FORMAT
  161. **
  162. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  163. ** unsigned integer fields in big-endian format. They are:
  164. **
  165. ** * The byte offset of the first rowid on the page, if it exists
  166. ** and occurs before the first term (otherwise 0).
  167. **
  168. ** * The byte offset of the start of the page footer. If the page
  169. ** footer is 0 bytes in size, then this field is the same as the
  170. ** size of the leaf page in bytes.
  171. **
  172. ** The page footer consists of a single varint for each term located
  173. ** on the page. Each varint is the byte offset of the current term
  174. ** within the page, delta-compressed against the previous value. In
  175. ** other words, the first varint in the footer is the byte offset of
  176. ** the first term, the second is the byte offset of the second less that
  177. ** of the first, and so on.
  178. **
  179. ** The term/doclist format described above is accurate if the entire
  180. ** term/doclist data fits on a single leaf page. If this is not the case,
  181. ** the format is changed in two ways:
  182. **
  183. ** + if the first rowid on a page occurs before the first term, it
  184. ** is stored as a literal value:
  185. **
  186. ** varint: first rowid
  187. **
  188. ** + the first term on each page is stored in the same way as the
  189. ** very first term of the segment:
  190. **
  191. ** varint : size of first term
  192. ** blob: first term data
  193. **
  194. ** 5. Segment doclist indexes:
  195. **
  196. ** Doclist indexes are themselves b-trees, however they usually consist of
  197. ** a single leaf record only. The format of each doclist index leaf page
  198. ** is:
  199. **
  200. ** * Flags byte. Bits are:
  201. ** 0x01: Clear if leaf is also the root page, otherwise set.
  202. **
  203. ** * Page number of fts index leaf page. As a varint.
  204. **
  205. ** * First rowid on page indicated by previous field. As a varint.
  206. **
  207. ** * A list of varints, one for each subsequent termless page. A
  208. ** positive delta if the termless page contains at least one rowid,
  209. ** or an 0x00 byte otherwise.
  210. **
  211. ** Internal doclist index nodes are:
  212. **
  213. ** * Flags byte. Bits are:
  214. ** 0x01: Clear for root page, otherwise set.
  215. **
  216. ** * Page number of first child page. As a varint.
  217. **
  218. ** * Copy of first rowid on page indicated by previous field. As a varint.
  219. **
  220. ** * A list of delta-encoded varints - the first rowid on each subsequent
  221. ** child page.
  222. **
  223. ** 6. Tombstone Hash Page
  224. **
  225. ** These records are only ever present in contentless_delete=1 tables.
  226. ** There are zero or more of these associated with each segment. They
  227. ** are used to store the tombstone rowids for rows contained in the
  228. ** associated segments.
  229. **
  230. ** The set of nHashPg tombstone hash pages associated with a single
  231. ** segment together form a single hash table containing tombstone rowids.
  232. ** To find the page of the hash on which a key might be stored:
  233. **
  234. ** iPg = (rowid % nHashPg)
  235. **
  236. ** Then, within page iPg, which has nSlot slots:
  237. **
  238. ** iSlot = (rowid / nHashPg) % nSlot
  239. **
  240. ** Each tombstone hash page begins with an 8 byte header:
  241. **
  242. ** 1-byte: Key-size (the size in bytes of each slot). Either 4 or 8.
  243. ** 1-byte: rowid-0-tombstone flag. This flag is only valid on the
  244. ** first tombstone hash page for each segment (iPg=0). If set,
  245. ** the hash table contains rowid 0. If clear, it does not.
  246. ** Rowid 0 is handled specially.
  247. ** 2-bytes: unused.
  248. ** 4-bytes: Big-endian integer containing number of entries on page.
  249. **
  250. ** Following this are nSlot 4 or 8 byte slots (depending on the key-size
  251. ** in the first byte of the page header). The number of slots may be
  252. ** determined based on the size of the page record and the key-size:
  253. **
  254. ** nSlot = (nByte - 8) / key-size
  255. */
  256. /*
  257. ** Rowids for the averages and structure records in the %_data table.
  258. */
  259. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  260. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  261. /*
  262. ** Macros determining the rowids used by segment leaves and dlidx leaves
  263. ** and nodes. All nodes and leaves are stored in the %_data table with large
  264. ** positive rowids.
  265. **
  266. ** Each segment has a unique non-zero 16-bit id.
  267. **
  268. ** The rowid for each segment leaf is found by passing the segment id and
  269. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  270. ** sequentially starting from 1.
  271. */
  272. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  273. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  274. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  275. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  276. #define fts5_dri(segid, dlidx, height, pgno) ( \
  277. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  278. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  279. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  280. ((i64)(pgno)) \
  281. )
  282. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  283. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  284. #define FTS5_TOMBSTONE_ROWID(segid,ipg) fts5_dri(segid+(1<<16), 0, 0, ipg)
  285. #ifdef SQLITE_DEBUG
  286. int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  287. #endif
  288. /*
  289. ** Each time a blob is read from the %_data table, it is padded with this
  290. ** many zero bytes. This makes it easier to decode the various record formats
  291. ** without overreading if the records are corrupt.
  292. */
  293. #define FTS5_DATA_ZERO_PADDING 8
  294. #define FTS5_DATA_PADDING 20
  295. typedef struct Fts5Data Fts5Data;
  296. typedef struct Fts5DlidxIter Fts5DlidxIter;
  297. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  298. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  299. typedef struct Fts5Iter Fts5Iter;
  300. typedef struct Fts5PageWriter Fts5PageWriter;
  301. typedef struct Fts5SegIter Fts5SegIter;
  302. typedef struct Fts5DoclistIter Fts5DoclistIter;
  303. typedef struct Fts5SegWriter Fts5SegWriter;
  304. typedef struct Fts5Structure Fts5Structure;
  305. typedef struct Fts5StructureLevel Fts5StructureLevel;
  306. typedef struct Fts5StructureSegment Fts5StructureSegment;
  307. typedef struct Fts5TokenDataIter Fts5TokenDataIter;
  308. typedef struct Fts5TokenDataMap Fts5TokenDataMap;
  309. typedef struct Fts5TombstoneArray Fts5TombstoneArray;
  310. struct Fts5Data {
  311. u8 *p; /* Pointer to buffer containing record */
  312. int nn; /* Size of record in bytes */
  313. int szLeaf; /* Size of leaf without page-index */
  314. };
  315. /*
  316. ** One object per %_data table.
  317. **
  318. ** nContentlessDelete:
  319. ** The number of contentless delete operations since the most recent
  320. ** call to fts5IndexFlush() or fts5IndexDiscardData(). This is tracked
  321. ** so that extra auto-merge work can be done by fts5IndexFlush() to
  322. ** account for the delete operations.
  323. */
  324. struct Fts5Index {
  325. Fts5Config *pConfig; /* Virtual table configuration */
  326. char *zDataTbl; /* Name of %_data table */
  327. int nWorkUnit; /* Leaf pages in a "unit" of work */
  328. /*
  329. ** Variables related to the accumulation of tokens and doclists within the
  330. ** in-memory hash tables before they are flushed to disk.
  331. */
  332. Fts5Hash *pHash; /* Hash table for in-memory data */
  333. int nPendingData; /* Current bytes of pending data */
  334. i64 iWriteRowid; /* Rowid for current doc being written */
  335. int bDelete; /* Current write is a delete */
  336. int nContentlessDelete; /* Number of contentless delete ops */
  337. int nPendingRow; /* Number of INSERT in hash table */
  338. /* Error state. */
  339. int rc; /* Current error code */
  340. int flushRc;
  341. /* State used by the fts5DataXXX() functions. */
  342. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  343. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  344. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  345. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  346. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=?" */
  347. sqlite3_stmt *pIdxSelect;
  348. sqlite3_stmt *pIdxNextSelect;
  349. int nRead; /* Total number of blocks read */
  350. sqlite3_stmt *pDeleteFromIdx;
  351. sqlite3_stmt *pDataVersion;
  352. i64 iStructVersion; /* data_version when pStruct read */
  353. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  354. };
  355. struct Fts5DoclistIter {
  356. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  357. /* Output variables. aPoslist==0 at EOF */
  358. i64 iRowid;
  359. u8 *aPoslist;
  360. int nPoslist;
  361. int nSize;
  362. };
  363. /*
  364. ** The contents of the "structure" record for each index are represented
  365. ** using an Fts5Structure record in memory. Which uses instances of the
  366. ** other Fts5StructureXXX types as components.
  367. **
  368. ** nOriginCntr:
  369. ** This value is set to non-zero for structure records created for
  370. ** contentlessdelete=1 tables only. In that case it represents the
  371. ** origin value to apply to the next top-level segment created.
  372. */
  373. struct Fts5StructureSegment {
  374. int iSegid; /* Segment id */
  375. int pgnoFirst; /* First leaf page number in segment */
  376. int pgnoLast; /* Last leaf page number in segment */
  377. /* contentlessdelete=1 tables only: */
  378. u64 iOrigin1;
  379. u64 iOrigin2;
  380. int nPgTombstone; /* Number of tombstone hash table pages */
  381. u64 nEntryTombstone; /* Number of tombstone entries that "count" */
  382. u64 nEntry; /* Number of rows in this segment */
  383. };
  384. struct Fts5StructureLevel {
  385. int nMerge; /* Number of segments in incr-merge */
  386. int nSeg; /* Total number of segments on level */
  387. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  388. };
  389. struct Fts5Structure {
  390. int nRef; /* Object reference count */
  391. u64 nWriteCounter; /* Total leaves written to level 0 */
  392. u64 nOriginCntr; /* Origin value for next top-level segment */
  393. int nSegment; /* Total segments in this structure */
  394. int nLevel; /* Number of levels in this index */
  395. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  396. };
  397. /*
  398. ** An object of type Fts5SegWriter is used to write to segments.
  399. */
  400. struct Fts5PageWriter {
  401. int pgno; /* Page number for this page */
  402. int iPrevPgidx; /* Previous value written into pgidx */
  403. Fts5Buffer buf; /* Buffer containing leaf data */
  404. Fts5Buffer pgidx; /* Buffer containing page-index */
  405. Fts5Buffer term; /* Buffer containing previous term on page */
  406. };
  407. struct Fts5DlidxWriter {
  408. int pgno; /* Page number for this page */
  409. int bPrevValid; /* True if iPrev is valid */
  410. i64 iPrev; /* Previous rowid value written to page */
  411. Fts5Buffer buf; /* Buffer containing page data */
  412. };
  413. struct Fts5SegWriter {
  414. int iSegid; /* Segid to write to */
  415. Fts5PageWriter writer; /* PageWriter object */
  416. i64 iPrevRowid; /* Previous rowid written to current leaf */
  417. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  418. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  419. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  420. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  421. int nLeafWritten; /* Number of leaf pages written */
  422. int nEmpty; /* Number of contiguous term-less nodes */
  423. int nDlidx; /* Allocated size of aDlidx[] array */
  424. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  425. /* Values to insert into the %_idx table */
  426. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  427. int iBtPage; /* Page number corresponding to btterm */
  428. };
  429. typedef struct Fts5CResult Fts5CResult;
  430. struct Fts5CResult {
  431. u16 iFirst; /* aSeg[] index of firstest iterator */
  432. u8 bTermEq; /* True if the terms are equal */
  433. };
  434. /*
  435. ** Object for iterating through a single segment, visiting each term/rowid
  436. ** pair in the segment.
  437. **
  438. ** pSeg:
  439. ** The segment to iterate through.
  440. **
  441. ** iLeafPgno:
  442. ** Current leaf page number within segment.
  443. **
  444. ** iLeafOffset:
  445. ** Byte offset within the current leaf that is the first byte of the
  446. ** position list data (one byte passed the position-list size field).
  447. **
  448. ** pLeaf:
  449. ** Buffer containing current leaf page data. Set to NULL at EOF.
  450. **
  451. ** iTermLeafPgno, iTermLeafOffset:
  452. ** Leaf page number containing the last term read from the segment. And
  453. ** the offset immediately following the term data.
  454. **
  455. ** flags:
  456. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  457. **
  458. ** FTS5_SEGITER_ONETERM:
  459. ** If set, set the iterator to point to EOF after the current doclist
  460. ** has been exhausted. Do not proceed to the next term in the segment.
  461. **
  462. ** FTS5_SEGITER_REVERSE:
  463. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  464. ** it is set, iterate through rowid in descending order instead of the
  465. ** default ascending order.
  466. **
  467. ** iRowidOffset/nRowidOffset/aRowidOffset:
  468. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  469. **
  470. ** For each rowid on the page corresponding to the current term, the
  471. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  472. ** start of the "position-list-size" field within the page.
  473. **
  474. ** iTermIdx:
  475. ** Index of current term on iTermLeafPgno.
  476. **
  477. ** apTombstone/nTombstone:
  478. ** These are used for contentless_delete=1 tables only. When the cursor
  479. ** is first allocated, the apTombstone[] array is allocated so that it
  480. ** is large enough for all tombstones hash pages associated with the
  481. ** segment. The pages themselves are loaded lazily from the database as
  482. ** they are required.
  483. */
  484. struct Fts5SegIter {
  485. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  486. int flags; /* Mask of configuration flags */
  487. int iLeafPgno; /* Current leaf page number */
  488. Fts5Data *pLeaf; /* Current leaf data */
  489. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  490. i64 iLeafOffset; /* Byte offset within current leaf */
  491. Fts5TombstoneArray *pTombArray; /* Array of tombstone pages */
  492. /* Next method */
  493. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  494. /* The page and offset from which the current term was read. The offset
  495. ** is the offset of the first rowid in the current doclist. */
  496. int iTermLeafPgno;
  497. int iTermLeafOffset;
  498. int iPgidxOff; /* Next offset in pgidx */
  499. int iEndofDoclist;
  500. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  501. int iRowidOffset; /* Current entry in aRowidOffset[] */
  502. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  503. int *aRowidOffset; /* Array of offset to rowid fields */
  504. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  505. /* Variables populated based on current entry. */
  506. Fts5Buffer term; /* Current term */
  507. i64 iRowid; /* Current rowid */
  508. int nPos; /* Number of bytes in current position list */
  509. u8 bDel; /* True if the delete flag is set */
  510. };
  511. /*
  512. ** Array of tombstone pages. Reference counted.
  513. */
  514. struct Fts5TombstoneArray {
  515. int nRef; /* Number of pointers to this object */
  516. int nTombstone;
  517. Fts5Data *apTombstone[1]; /* Array of tombstone pages */
  518. };
  519. /*
  520. ** Argument is a pointer to an Fts5Data structure that contains a
  521. ** leaf page.
  522. */
  523. #define ASSERT_SZLEAF_OK(x) assert( \
  524. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  525. )
  526. #define FTS5_SEGITER_ONETERM 0x01
  527. #define FTS5_SEGITER_REVERSE 0x02
  528. /*
  529. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  530. ** page. This macro evaluates to true if the leaf contains no terms, or
  531. ** false if it contains at least one term.
  532. */
  533. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  534. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  535. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  536. /*
  537. ** Object for iterating through the merged results of one or more segments,
  538. ** visiting each term/rowid pair in the merged data.
  539. **
  540. ** nSeg is always a power of two greater than or equal to the number of
  541. ** segments that this object is merging data from. Both the aSeg[] and
  542. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  543. ** with zeroed objects - these are handled as if they were iterators opened
  544. ** on empty segments.
  545. **
  546. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  547. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  548. ** comparison in this context is the index of the iterator that currently
  549. ** points to the smaller term/rowid combination. Iterators at EOF are
  550. ** considered to be greater than all other iterators.
  551. **
  552. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  553. ** the smallest key overall. aFirst[0] is unused.
  554. **
  555. ** poslist:
  556. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  557. ** There is no way to tell if this is populated or not.
  558. **
  559. ** pColset:
  560. ** If not NULL, points to an object containing a set of column indices.
  561. ** Only matches that occur in one of these columns will be returned.
  562. ** The Fts5Iter does not own the Fts5Colset object, and so it is not
  563. ** freed when the iterator is closed - it is owned by the upper layer.
  564. */
  565. struct Fts5Iter {
  566. Fts5IndexIter base; /* Base class containing output vars */
  567. Fts5TokenDataIter *pTokenDataIter;
  568. Fts5Index *pIndex; /* Index that owns this iterator */
  569. Fts5Buffer poslist; /* Buffer containing current poslist */
  570. Fts5Colset *pColset; /* Restrict matches to these columns */
  571. /* Invoked to set output variables. */
  572. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  573. int nSeg; /* Size of aSeg[] array */
  574. int bRev; /* True to iterate in reverse order */
  575. u8 bSkipEmpty; /* True to skip deleted entries */
  576. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  577. Fts5CResult *aFirst; /* Current merge state (see above) */
  578. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  579. };
  580. /*
  581. ** An instance of the following type is used to iterate through the contents
  582. ** of a doclist-index record.
  583. **
  584. ** pData:
  585. ** Record containing the doclist-index data.
  586. **
  587. ** bEof:
  588. ** Set to true once iterator has reached EOF.
  589. **
  590. ** iOff:
  591. ** Set to the current offset within record pData.
  592. */
  593. struct Fts5DlidxLvl {
  594. Fts5Data *pData; /* Data for current page of this level */
  595. int iOff; /* Current offset into pData */
  596. int bEof; /* At EOF already */
  597. int iFirstOff; /* Used by reverse iterators */
  598. /* Output variables */
  599. int iLeafPgno; /* Page number of current leaf page */
  600. i64 iRowid; /* First rowid on leaf iLeafPgno */
  601. };
  602. struct Fts5DlidxIter {
  603. int nLvl;
  604. int iSegid;
  605. Fts5DlidxLvl aLvl[1];
  606. };
  607. static void fts5PutU16(u8 *aOut, u16 iVal){
  608. aOut[0] = (iVal>>8);
  609. aOut[1] = (iVal&0xFF);
  610. }
  611. static u16 fts5GetU16(const u8 *aIn){
  612. return ((u16)aIn[0] << 8) + aIn[1];
  613. }
  614. /*
  615. ** The only argument points to a buffer at least 8 bytes in size. This
  616. ** function interprets the first 8 bytes of the buffer as a 64-bit big-endian
  617. ** unsigned integer and returns the result.
  618. */
  619. static u64 fts5GetU64(u8 *a){
  620. return ((u64)a[0] << 56)
  621. + ((u64)a[1] << 48)
  622. + ((u64)a[2] << 40)
  623. + ((u64)a[3] << 32)
  624. + ((u64)a[4] << 24)
  625. + ((u64)a[5] << 16)
  626. + ((u64)a[6] << 8)
  627. + ((u64)a[7] << 0);
  628. }
  629. /*
  630. ** The only argument points to a buffer at least 4 bytes in size. This
  631. ** function interprets the first 4 bytes of the buffer as a 32-bit big-endian
  632. ** unsigned integer and returns the result.
  633. */
  634. static u32 fts5GetU32(const u8 *a){
  635. return ((u32)a[0] << 24)
  636. + ((u32)a[1] << 16)
  637. + ((u32)a[2] << 8)
  638. + ((u32)a[3] << 0);
  639. }
  640. /*
  641. ** Write iVal, formated as a 64-bit big-endian unsigned integer, to the
  642. ** buffer indicated by the first argument.
  643. */
  644. static void fts5PutU64(u8 *a, u64 iVal){
  645. a[0] = ((iVal >> 56) & 0xFF);
  646. a[1] = ((iVal >> 48) & 0xFF);
  647. a[2] = ((iVal >> 40) & 0xFF);
  648. a[3] = ((iVal >> 32) & 0xFF);
  649. a[4] = ((iVal >> 24) & 0xFF);
  650. a[5] = ((iVal >> 16) & 0xFF);
  651. a[6] = ((iVal >> 8) & 0xFF);
  652. a[7] = ((iVal >> 0) & 0xFF);
  653. }
  654. /*
  655. ** Write iVal, formated as a 32-bit big-endian unsigned integer, to the
  656. ** buffer indicated by the first argument.
  657. */
  658. static void fts5PutU32(u8 *a, u32 iVal){
  659. a[0] = ((iVal >> 24) & 0xFF);
  660. a[1] = ((iVal >> 16) & 0xFF);
  661. a[2] = ((iVal >> 8) & 0xFF);
  662. a[3] = ((iVal >> 0) & 0xFF);
  663. }
  664. /*
  665. ** Allocate and return a buffer at least nByte bytes in size.
  666. **
  667. ** If an OOM error is encountered, return NULL and set the error code in
  668. ** the Fts5Index handle passed as the first argument.
  669. */
  670. static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
  671. return sqlite3Fts5MallocZero(&p->rc, nByte);
  672. }
  673. /*
  674. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  675. **
  676. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  677. ** +ve if pRight is smaller than pLeft. In other words:
  678. **
  679. ** res = *pLeft - *pRight
  680. */
  681. #ifdef SQLITE_DEBUG
  682. static int fts5BufferCompareBlob(
  683. Fts5Buffer *pLeft, /* Left hand side of comparison */
  684. const u8 *pRight, int nRight /* Right hand side of comparison */
  685. ){
  686. int nCmp = MIN(pLeft->n, nRight);
  687. int res = memcmp(pLeft->p, pRight, nCmp);
  688. return (res==0 ? (pLeft->n - nRight) : res);
  689. }
  690. #endif
  691. /*
  692. ** Compare the contents of the two buffers using memcmp(). If one buffer
  693. ** is a prefix of the other, it is considered the lesser.
  694. **
  695. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  696. ** +ve if pRight is smaller than pLeft. In other words:
  697. **
  698. ** res = *pLeft - *pRight
  699. */
  700. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  701. int nCmp, res;
  702. nCmp = MIN(pLeft->n, pRight->n);
  703. assert( nCmp<=0 || pLeft->p!=0 );
  704. assert( nCmp<=0 || pRight->p!=0 );
  705. res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
  706. return (res==0 ? (pLeft->n - pRight->n) : res);
  707. }
  708. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  709. int ret;
  710. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  711. return ret;
  712. }
  713. /*
  714. ** Close the read-only blob handle, if it is open.
  715. */
  716. void sqlite3Fts5IndexCloseReader(Fts5Index *p){
  717. if( p->pReader ){
  718. sqlite3_blob *pReader = p->pReader;
  719. p->pReader = 0;
  720. sqlite3_blob_close(pReader);
  721. }
  722. }
  723. /*
  724. ** Retrieve a record from the %_data table.
  725. **
  726. ** If an error occurs, NULL is returned and an error left in the
  727. ** Fts5Index object.
  728. */
  729. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  730. Fts5Data *pRet = 0;
  731. if( p->rc==SQLITE_OK ){
  732. int rc = SQLITE_OK;
  733. if( p->pReader ){
  734. /* This call may return SQLITE_ABORT if there has been a savepoint
  735. ** rollback since it was last used. In this case a new blob handle
  736. ** is required. */
  737. sqlite3_blob *pBlob = p->pReader;
  738. p->pReader = 0;
  739. rc = sqlite3_blob_reopen(pBlob, iRowid);
  740. assert( p->pReader==0 );
  741. p->pReader = pBlob;
  742. if( rc!=SQLITE_OK ){
  743. sqlite3Fts5IndexCloseReader(p);
  744. }
  745. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  746. }
  747. /* If the blob handle is not open at this point, open it and seek
  748. ** to the requested entry. */
  749. if( p->pReader==0 && rc==SQLITE_OK ){
  750. Fts5Config *pConfig = p->pConfig;
  751. rc = sqlite3_blob_open(pConfig->db,
  752. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  753. );
  754. }
  755. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  756. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  757. ** All the reasons those functions might return SQLITE_ERROR - missing
  758. ** table, missing row, non-blob/text in block column - indicate
  759. ** backing store corruption. */
  760. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  761. if( rc==SQLITE_OK ){
  762. u8 *aOut = 0; /* Read blob data into this buffer */
  763. int nByte = sqlite3_blob_bytes(p->pReader);
  764. int szData = (sizeof(Fts5Data) + 7) & ~7;
  765. sqlite3_int64 nAlloc = szData + nByte + FTS5_DATA_PADDING;
  766. pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
  767. if( pRet ){
  768. pRet->nn = nByte;
  769. aOut = pRet->p = (u8*)pRet + szData;
  770. }else{
  771. rc = SQLITE_NOMEM;
  772. }
  773. if( rc==SQLITE_OK ){
  774. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  775. }
  776. if( rc!=SQLITE_OK ){
  777. sqlite3_free(pRet);
  778. pRet = 0;
  779. }else{
  780. /* TODO1: Fix this */
  781. pRet->p[nByte] = 0x00;
  782. pRet->p[nByte+1] = 0x00;
  783. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  784. }
  785. }
  786. p->rc = rc;
  787. p->nRead++;
  788. }
  789. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  790. assert( pRet==0 || EIGHT_BYTE_ALIGNMENT( pRet->p ) );
  791. return pRet;
  792. }
  793. /*
  794. ** Release a reference to data record returned by an earlier call to
  795. ** fts5DataRead().
  796. */
  797. static void fts5DataRelease(Fts5Data *pData){
  798. sqlite3_free(pData);
  799. }
  800. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  801. Fts5Data *pRet = fts5DataRead(p, iRowid);
  802. if( pRet ){
  803. if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){
  804. p->rc = FTS5_CORRUPT;
  805. fts5DataRelease(pRet);
  806. pRet = 0;
  807. }
  808. }
  809. return pRet;
  810. }
  811. static int fts5IndexPrepareStmt(
  812. Fts5Index *p,
  813. sqlite3_stmt **ppStmt,
  814. char *zSql
  815. ){
  816. if( p->rc==SQLITE_OK ){
  817. if( zSql ){
  818. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  819. SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
  820. ppStmt, 0);
  821. }else{
  822. p->rc = SQLITE_NOMEM;
  823. }
  824. }
  825. sqlite3_free(zSql);
  826. return p->rc;
  827. }
  828. /*
  829. ** INSERT OR REPLACE a record into the %_data table.
  830. */
  831. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  832. if( p->rc!=SQLITE_OK ) return;
  833. if( p->pWriter==0 ){
  834. Fts5Config *pConfig = p->pConfig;
  835. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  836. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  837. pConfig->zDb, pConfig->zName
  838. ));
  839. if( p->rc ) return;
  840. }
  841. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  842. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  843. sqlite3_step(p->pWriter);
  844. p->rc = sqlite3_reset(p->pWriter);
  845. sqlite3_bind_null(p->pWriter, 2);
  846. }
  847. /*
  848. ** Execute the following SQL:
  849. **
  850. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  851. */
  852. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  853. if( p->rc!=SQLITE_OK ) return;
  854. if( p->pDeleter==0 ){
  855. Fts5Config *pConfig = p->pConfig;
  856. char *zSql = sqlite3_mprintf(
  857. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  858. pConfig->zDb, pConfig->zName
  859. );
  860. if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
  861. }
  862. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  863. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  864. sqlite3_step(p->pDeleter);
  865. p->rc = sqlite3_reset(p->pDeleter);
  866. }
  867. /*
  868. ** Remove all records associated with segment iSegid.
  869. */
  870. static void fts5DataRemoveSegment(Fts5Index *p, Fts5StructureSegment *pSeg){
  871. int iSegid = pSeg->iSegid;
  872. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  873. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  874. fts5DataDelete(p, iFirst, iLast);
  875. if( pSeg->nPgTombstone ){
  876. i64 iTomb1 = FTS5_TOMBSTONE_ROWID(iSegid, 0);
  877. i64 iTomb2 = FTS5_TOMBSTONE_ROWID(iSegid, pSeg->nPgTombstone-1);
  878. fts5DataDelete(p, iTomb1, iTomb2);
  879. }
  880. if( p->pIdxDeleter==0 ){
  881. Fts5Config *pConfig = p->pConfig;
  882. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  883. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  884. pConfig->zDb, pConfig->zName
  885. ));
  886. }
  887. if( p->rc==SQLITE_OK ){
  888. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  889. sqlite3_step(p->pIdxDeleter);
  890. p->rc = sqlite3_reset(p->pIdxDeleter);
  891. }
  892. }
  893. /*
  894. ** Release a reference to an Fts5Structure object returned by an earlier
  895. ** call to fts5StructureRead() or fts5StructureDecode().
  896. */
  897. static void fts5StructureRelease(Fts5Structure *pStruct){
  898. if( pStruct && 0>=(--pStruct->nRef) ){
  899. int i;
  900. assert( pStruct->nRef==0 );
  901. for(i=0; i<pStruct->nLevel; i++){
  902. sqlite3_free(pStruct->aLevel[i].aSeg);
  903. }
  904. sqlite3_free(pStruct);
  905. }
  906. }
  907. static void fts5StructureRef(Fts5Structure *pStruct){
  908. pStruct->nRef++;
  909. }
  910. void *sqlite3Fts5StructureRef(Fts5Index *p){
  911. fts5StructureRef(p->pStruct);
  912. return (void*)p->pStruct;
  913. }
  914. void sqlite3Fts5StructureRelease(void *p){
  915. if( p ){
  916. fts5StructureRelease((Fts5Structure*)p);
  917. }
  918. }
  919. int sqlite3Fts5StructureTest(Fts5Index *p, void *pStruct){
  920. if( p->pStruct!=(Fts5Structure*)pStruct ){
  921. return SQLITE_ABORT;
  922. }
  923. return SQLITE_OK;
  924. }
  925. /*
  926. ** Ensure that structure object (*pp) is writable.
  927. **
  928. ** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. If
  929. ** an error occurs, (*pRc) is set to an SQLite error code before returning.
  930. */
  931. static void fts5StructureMakeWritable(int *pRc, Fts5Structure **pp){
  932. Fts5Structure *p = *pp;
  933. if( *pRc==SQLITE_OK && p->nRef>1 ){
  934. i64 nByte = sizeof(Fts5Structure)+(p->nLevel-1)*sizeof(Fts5StructureLevel);
  935. Fts5Structure *pNew;
  936. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(pRc, nByte);
  937. if( pNew ){
  938. int i;
  939. memcpy(pNew, p, nByte);
  940. for(i=0; i<p->nLevel; i++) pNew->aLevel[i].aSeg = 0;
  941. for(i=0; i<p->nLevel; i++){
  942. Fts5StructureLevel *pLvl = &pNew->aLevel[i];
  943. nByte = sizeof(Fts5StructureSegment) * pNew->aLevel[i].nSeg;
  944. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(pRc, nByte);
  945. if( pLvl->aSeg==0 ){
  946. for(i=0; i<p->nLevel; i++){
  947. sqlite3_free(pNew->aLevel[i].aSeg);
  948. }
  949. sqlite3_free(pNew);
  950. return;
  951. }
  952. memcpy(pLvl->aSeg, p->aLevel[i].aSeg, nByte);
  953. }
  954. p->nRef--;
  955. pNew->nRef = 1;
  956. }
  957. *pp = pNew;
  958. }
  959. }
  960. /*
  961. ** Deserialize and return the structure record currently stored in serialized
  962. ** form within buffer pData/nData.
  963. **
  964. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  965. ** are over-allocated by one slot. This allows the structure contents
  966. ** to be more easily edited.
  967. **
  968. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  969. ** returned. Otherwise, *ppOut is set to point to the new object and
  970. ** SQLITE_OK returned.
  971. */
  972. static int fts5StructureDecode(
  973. const u8 *pData, /* Buffer containing serialized structure */
  974. int nData, /* Size of buffer pData in bytes */
  975. int *piCookie, /* Configuration cookie value */
  976. Fts5Structure **ppOut /* OUT: Deserialized object */
  977. ){
  978. int rc = SQLITE_OK;
  979. int i = 0;
  980. int iLvl;
  981. int nLevel = 0;
  982. int nSegment = 0;
  983. sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
  984. Fts5Structure *pRet = 0; /* Structure object to return */
  985. int bStructureV2 = 0; /* True for FTS5_STRUCTURE_V2 */
  986. u64 nOriginCntr = 0; /* Largest origin value seen so far */
  987. /* Grab the cookie value */
  988. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  989. i = 4;
  990. /* Check if this is a V2 structure record. Set bStructureV2 if it is. */
  991. if( 0==memcmp(&pData[i], FTS5_STRUCTURE_V2, 4) ){
  992. i += 4;
  993. bStructureV2 = 1;
  994. }
  995. /* Read the total number of levels and segments from the start of the
  996. ** structure record. */
  997. i += fts5GetVarint32(&pData[i], nLevel);
  998. i += fts5GetVarint32(&pData[i], nSegment);
  999. if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
  1000. || nSegment>FTS5_MAX_SEGMENT || nSegment<0
  1001. ){
  1002. return FTS5_CORRUPT;
  1003. }
  1004. nByte = (
  1005. sizeof(Fts5Structure) + /* Main structure */
  1006. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  1007. );
  1008. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  1009. if( pRet ){
  1010. pRet->nRef = 1;
  1011. pRet->nLevel = nLevel;
  1012. pRet->nSegment = nSegment;
  1013. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  1014. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  1015. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  1016. int nTotal = 0;
  1017. int iSeg;
  1018. if( i>=nData ){
  1019. rc = FTS5_CORRUPT;
  1020. }else{
  1021. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  1022. i += fts5GetVarint32(&pData[i], nTotal);
  1023. if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
  1024. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  1025. nTotal * sizeof(Fts5StructureSegment)
  1026. );
  1027. nSegment -= nTotal;
  1028. }
  1029. if( rc==SQLITE_OK ){
  1030. pLvl->nSeg = nTotal;
  1031. for(iSeg=0; iSeg<nTotal; iSeg++){
  1032. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  1033. if( i>=nData ){
  1034. rc = FTS5_CORRUPT;
  1035. break;
  1036. }
  1037. assert( pSeg!=0 );
  1038. i += fts5GetVarint32(&pData[i], pSeg->iSegid);
  1039. i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
  1040. i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
  1041. if( bStructureV2 ){
  1042. i += fts5GetVarint(&pData[i], &pSeg->iOrigin1);
  1043. i += fts5GetVarint(&pData[i], &pSeg->iOrigin2);
  1044. i += fts5GetVarint32(&pData[i], pSeg->nPgTombstone);
  1045. i += fts5GetVarint(&pData[i], &pSeg->nEntryTombstone);
  1046. i += fts5GetVarint(&pData[i], &pSeg->nEntry);
  1047. nOriginCntr = MAX(nOriginCntr, pSeg->iOrigin2);
  1048. }
  1049. if( pSeg->pgnoLast<pSeg->pgnoFirst ){
  1050. rc = FTS5_CORRUPT;
  1051. break;
  1052. }
  1053. }
  1054. if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
  1055. if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
  1056. }
  1057. }
  1058. if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
  1059. if( bStructureV2 ){
  1060. pRet->nOriginCntr = nOriginCntr+1;
  1061. }
  1062. if( rc!=SQLITE_OK ){
  1063. fts5StructureRelease(pRet);
  1064. pRet = 0;
  1065. }
  1066. }
  1067. *ppOut = pRet;
  1068. return rc;
  1069. }
  1070. /*
  1071. ** Add a level to the Fts5Structure.aLevel[] array of structure object
  1072. ** (*ppStruct).
  1073. */
  1074. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  1075. fts5StructureMakeWritable(pRc, ppStruct);
  1076. assert( (ppStruct!=0 && (*ppStruct)!=0) || (*pRc)!=SQLITE_OK );
  1077. if( *pRc==SQLITE_OK ){
  1078. Fts5Structure *pStruct = *ppStruct;
  1079. int nLevel = pStruct->nLevel;
  1080. sqlite3_int64 nByte = (
  1081. sizeof(Fts5Structure) + /* Main structure */
  1082. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  1083. );
  1084. pStruct = sqlite3_realloc64(pStruct, nByte);
  1085. if( pStruct ){
  1086. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  1087. pStruct->nLevel++;
  1088. *ppStruct = pStruct;
  1089. }else{
  1090. *pRc = SQLITE_NOMEM;
  1091. }
  1092. }
  1093. }
  1094. /*
  1095. ** Extend level iLvl so that there is room for at least nExtra more
  1096. ** segments.
  1097. */
  1098. static void fts5StructureExtendLevel(
  1099. int *pRc,
  1100. Fts5Structure *pStruct,
  1101. int iLvl,
  1102. int nExtra,
  1103. int bInsert
  1104. ){
  1105. if( *pRc==SQLITE_OK ){
  1106. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  1107. Fts5StructureSegment *aNew;
  1108. sqlite3_int64 nByte;
  1109. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  1110. aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
  1111. if( aNew ){
  1112. if( bInsert==0 ){
  1113. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  1114. }else{
  1115. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  1116. memmove(&aNew[nExtra], aNew, nMove);
  1117. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  1118. }
  1119. pLvl->aSeg = aNew;
  1120. }else{
  1121. *pRc = SQLITE_NOMEM;
  1122. }
  1123. }
  1124. }
  1125. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  1126. Fts5Structure *pRet = 0;
  1127. Fts5Config *pConfig = p->pConfig;
  1128. int iCookie; /* Configuration cookie */
  1129. Fts5Data *pData;
  1130. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  1131. if( p->rc==SQLITE_OK ){
  1132. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  1133. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  1134. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  1135. if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
  1136. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  1137. }
  1138. fts5DataRelease(pData);
  1139. if( p->rc!=SQLITE_OK ){
  1140. fts5StructureRelease(pRet);
  1141. pRet = 0;
  1142. }
  1143. }
  1144. return pRet;
  1145. }
  1146. static i64 fts5IndexDataVersion(Fts5Index *p){
  1147. i64 iVersion = 0;
  1148. if( p->rc==SQLITE_OK ){
  1149. if( p->pDataVersion==0 ){
  1150. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  1151. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  1152. );
  1153. if( p->rc ) return 0;
  1154. }
  1155. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  1156. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  1157. }
  1158. p->rc = sqlite3_reset(p->pDataVersion);
  1159. }
  1160. return iVersion;
  1161. }
  1162. /*
  1163. ** Read, deserialize and return the structure record.
  1164. **
  1165. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  1166. ** are over-allocated as described for function fts5StructureDecode()
  1167. ** above.
  1168. **
  1169. ** If an error occurs, NULL is returned and an error code left in the
  1170. ** Fts5Index handle. If an error has already occurred when this function
  1171. ** is called, it is a no-op.
  1172. */
  1173. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  1174. if( p->pStruct==0 ){
  1175. p->iStructVersion = fts5IndexDataVersion(p);
  1176. if( p->rc==SQLITE_OK ){
  1177. p->pStruct = fts5StructureReadUncached(p);
  1178. }
  1179. }
  1180. #if 0
  1181. else{
  1182. Fts5Structure *pTest = fts5StructureReadUncached(p);
  1183. if( pTest ){
  1184. int i, j;
  1185. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  1186. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  1187. for(i=0; i<pTest->nLevel; i++){
  1188. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  1189. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  1190. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  1191. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  1192. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  1193. assert_nc( p1->iSegid==p2->iSegid );
  1194. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  1195. assert_nc( p1->pgnoLast==p2->pgnoLast );
  1196. }
  1197. }
  1198. fts5StructureRelease(pTest);
  1199. }
  1200. }
  1201. #endif
  1202. if( p->rc!=SQLITE_OK ) return 0;
  1203. assert( p->iStructVersion!=0 );
  1204. assert( p->pStruct!=0 );
  1205. fts5StructureRef(p->pStruct);
  1206. return p->pStruct;
  1207. }
  1208. static void fts5StructureInvalidate(Fts5Index *p){
  1209. if( p->pStruct ){
  1210. fts5StructureRelease(p->pStruct);
  1211. p->pStruct = 0;
  1212. }
  1213. }
  1214. /*
  1215. ** Return the total number of segments in index structure pStruct. This
  1216. ** function is only ever used as part of assert() conditions.
  1217. */
  1218. #ifdef SQLITE_DEBUG
  1219. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  1220. int nSegment = 0; /* Total number of segments */
  1221. if( pStruct ){
  1222. int iLvl; /* Used to iterate through levels */
  1223. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  1224. nSegment += pStruct->aLevel[iLvl].nSeg;
  1225. }
  1226. }
  1227. return nSegment;
  1228. }
  1229. #endif
  1230. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  1231. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  1232. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  1233. (pBuf)->n += nBlob; \
  1234. }
  1235. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  1236. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  1237. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  1238. }
  1239. /*
  1240. ** Serialize and store the "structure" record.
  1241. **
  1242. ** If an error occurs, leave an error code in the Fts5Index object. If an
  1243. ** error has already occurred, this function is a no-op.
  1244. */
  1245. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  1246. if( p->rc==SQLITE_OK ){
  1247. Fts5Buffer buf; /* Buffer to serialize record into */
  1248. int iLvl; /* Used to iterate through levels */
  1249. int iCookie; /* Cookie value to store */
  1250. int nHdr = (pStruct->nOriginCntr>0 ? (4+4+9+9+9) : (4+9+9));
  1251. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  1252. memset(&buf, 0, sizeof(Fts5Buffer));
  1253. /* Append the current configuration cookie */
  1254. iCookie = p->pConfig->iCookie;
  1255. if( iCookie<0 ) iCookie = 0;
  1256. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, nHdr) ){
  1257. sqlite3Fts5Put32(buf.p, iCookie);
  1258. buf.n = 4;
  1259. if( pStruct->nOriginCntr>0 ){
  1260. fts5BufferSafeAppendBlob(&buf, FTS5_STRUCTURE_V2, 4);
  1261. }
  1262. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  1263. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  1264. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  1265. }
  1266. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  1267. int iSeg; /* Used to iterate through segments */
  1268. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  1269. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  1270. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  1271. assert( pLvl->nMerge<=pLvl->nSeg );
  1272. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  1273. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  1274. fts5BufferAppendVarint(&p->rc, &buf, pSeg->iSegid);
  1275. fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoFirst);
  1276. fts5BufferAppendVarint(&p->rc, &buf, pSeg->pgnoLast);
  1277. if( pStruct->nOriginCntr>0 ){
  1278. fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin1);
  1279. fts5BufferAppendVarint(&p->rc, &buf, pSeg->iOrigin2);
  1280. fts5BufferAppendVarint(&p->rc, &buf, pSeg->nPgTombstone);
  1281. fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntryTombstone);
  1282. fts5BufferAppendVarint(&p->rc, &buf, pSeg->nEntry);
  1283. }
  1284. }
  1285. }
  1286. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  1287. fts5BufferFree(&buf);
  1288. }
  1289. }
  1290. #if 0
  1291. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  1292. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  1293. int rc = SQLITE_OK;
  1294. Fts5Buffer buf;
  1295. memset(&buf, 0, sizeof(buf));
  1296. fts5DebugStructure(&rc, &buf, pStruct);
  1297. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  1298. fflush(stdout);
  1299. fts5BufferFree(&buf);
  1300. }
  1301. #else
  1302. # define fts5PrintStructure(x,y)
  1303. #endif
  1304. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  1305. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  1306. }
  1307. /*
  1308. ** Return a copy of index structure pStruct. Except, promote as many
  1309. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  1310. ** returned.
  1311. */
  1312. static void fts5StructurePromoteTo(
  1313. Fts5Index *p,
  1314. int iPromote,
  1315. int szPromote,
  1316. Fts5Structure *pStruct
  1317. ){
  1318. int il, is;
  1319. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  1320. if( pOut->nMerge==0 ){
  1321. for(il=iPromote+1; il<pStruct->nLevel; il++){
  1322. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  1323. if( pLvl->nMerge ) return;
  1324. for(is=pLvl->nSeg-1; is>=0; is--){
  1325. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  1326. if( sz>szPromote ) return;
  1327. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  1328. if( p->rc ) return;
  1329. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  1330. pOut->nSeg++;
  1331. pLvl->nSeg--;
  1332. }
  1333. }
  1334. }
  1335. }
  1336. /*
  1337. ** A new segment has just been written to level iLvl of index structure
  1338. ** pStruct. This function determines if any segments should be promoted
  1339. ** as a result. Segments are promoted in two scenarios:
  1340. **
  1341. ** a) If the segment just written is smaller than one or more segments
  1342. ** within the previous populated level, it is promoted to the previous
  1343. ** populated level.
  1344. **
  1345. ** b) If the segment just written is larger than the newest segment on
  1346. ** the next populated level, then that segment, and any other adjacent
  1347. ** segments that are also smaller than the one just written, are
  1348. ** promoted.
  1349. **
  1350. ** If one or more segments are promoted, the structure object is updated
  1351. ** to reflect this.
  1352. */
  1353. static void fts5StructurePromote(
  1354. Fts5Index *p, /* FTS5 backend object */
  1355. int iLvl, /* Index level just updated */
  1356. Fts5Structure *pStruct /* Index structure */
  1357. ){
  1358. if( p->rc==SQLITE_OK ){
  1359. int iTst;
  1360. int iPromote = -1;
  1361. int szPromote = 0; /* Promote anything this size or smaller */
  1362. Fts5StructureSegment *pSeg; /* Segment just written */
  1363. int szSeg; /* Size of segment just written */
  1364. int nSeg = pStruct->aLevel[iLvl].nSeg;
  1365. if( nSeg==0 ) return;
  1366. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  1367. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  1368. /* Check for condition (a) */
  1369. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  1370. if( iTst>=0 ){
  1371. int i;
  1372. int szMax = 0;
  1373. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  1374. assert( pTst->nMerge==0 );
  1375. for(i=0; i<pTst->nSeg; i++){
  1376. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  1377. if( sz>szMax ) szMax = sz;
  1378. }
  1379. if( szMax>=szSeg ){
  1380. /* Condition (a) is true. Promote the newest segment on level
  1381. ** iLvl to level iTst. */
  1382. iPromote = iTst;
  1383. szPromote = szMax;
  1384. }
  1385. }
  1386. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  1387. ** is a no-op if it is not. */
  1388. if( iPromote<0 ){
  1389. iPromote = iLvl;
  1390. szPromote = szSeg;
  1391. }
  1392. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  1393. }
  1394. }
  1395. /*
  1396. ** Advance the iterator passed as the only argument. If the end of the
  1397. ** doclist-index page is reached, return non-zero.
  1398. */
  1399. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  1400. Fts5Data *pData = pLvl->pData;
  1401. if( pLvl->iOff==0 ){
  1402. assert( pLvl->bEof==0 );
  1403. pLvl->iOff = 1;
  1404. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  1405. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  1406. pLvl->iFirstOff = pLvl->iOff;
  1407. }else{
  1408. int iOff;
  1409. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  1410. if( pData->p[iOff] ) break;
  1411. }
  1412. if( iOff<pData->nn ){
  1413. u64 iVal;
  1414. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  1415. iOff += fts5GetVarint(&pData->p[iOff], &iVal);
  1416. pLvl->iRowid += iVal;
  1417. pLvl->iOff = iOff;
  1418. }else{
  1419. pLvl->bEof = 1;
  1420. }
  1421. }
  1422. return pLvl->bEof;
  1423. }
  1424. /*
  1425. ** Advance the iterator passed as the only argument.
  1426. */
  1427. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  1428. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  1429. assert( iLvl<pIter->nLvl );
  1430. if( fts5DlidxLvlNext(pLvl) ){
  1431. if( (iLvl+1) < pIter->nLvl ){
  1432. fts5DlidxIterNextR(p, pIter, iLvl+1);
  1433. if( pLvl[1].bEof==0 ){
  1434. fts5DataRelease(pLvl->pData);
  1435. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  1436. pLvl->pData = fts5DataRead(p,
  1437. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  1438. );
  1439. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  1440. }
  1441. }
  1442. }
  1443. return pIter->aLvl[0].bEof;
  1444. }
  1445. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  1446. return fts5DlidxIterNextR(p, pIter, 0);
  1447. }
  1448. /*
  1449. ** The iterator passed as the first argument has the following fields set
  1450. ** as follows. This function sets up the rest of the iterator so that it
  1451. ** points to the first rowid in the doclist-index.
  1452. **
  1453. ** pData:
  1454. ** pointer to doclist-index record,
  1455. **
  1456. ** When this function is called pIter->iLeafPgno is the page number the
  1457. ** doclist is associated with (the one featuring the term).
  1458. */
  1459. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  1460. int i;
  1461. for(i=0; i<pIter->nLvl; i++){
  1462. fts5DlidxLvlNext(&pIter->aLvl[i]);
  1463. }
  1464. return pIter->aLvl[0].bEof;
  1465. }
  1466. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  1467. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  1468. }
  1469. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  1470. int i;
  1471. /* Advance each level to the last entry on the last page */
  1472. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  1473. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  1474. while( fts5DlidxLvlNext(pLvl)==0 );
  1475. pLvl->bEof = 0;
  1476. if( i>0 ){
  1477. Fts5DlidxLvl *pChild = &pLvl[-1];
  1478. fts5DataRelease(pChild->pData);
  1479. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  1480. pChild->pData = fts5DataRead(p,
  1481. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  1482. );
  1483. }
  1484. }
  1485. }
  1486. /*
  1487. ** Move the iterator passed as the only argument to the previous entry.
  1488. */
  1489. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  1490. int iOff = pLvl->iOff;
  1491. assert( pLvl->bEof==0 );
  1492. if( iOff<=pLvl->iFirstOff ){
  1493. pLvl->bEof = 1;
  1494. }else{
  1495. u8 *a = pLvl->pData->p;
  1496. pLvl->iOff = 0;
  1497. fts5DlidxLvlNext(pLvl);
  1498. while( 1 ){
  1499. int nZero = 0;
  1500. int ii = pLvl->iOff;
  1501. u64 delta = 0;
  1502. while( a[ii]==0 ){
  1503. nZero++;
  1504. ii++;
  1505. }
  1506. ii += sqlite3Fts5GetVarint(&a[ii], &delta);
  1507. if( ii>=iOff ) break;
  1508. pLvl->iLeafPgno += nZero+1;
  1509. pLvl->iRowid += delta;
  1510. pLvl->iOff = ii;
  1511. }
  1512. }
  1513. return pLvl->bEof;
  1514. }
  1515. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  1516. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  1517. assert( iLvl<pIter->nLvl );
  1518. if( fts5DlidxLvlPrev(pLvl) ){
  1519. if( (iLvl+1) < pIter->nLvl ){
  1520. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  1521. if( pLvl[1].bEof==0 ){
  1522. fts5DataRelease(pLvl->pData);
  1523. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  1524. pLvl->pData = fts5DataRead(p,
  1525. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  1526. );
  1527. if( pLvl->pData ){
  1528. while( fts5DlidxLvlNext(pLvl)==0 );
  1529. pLvl->bEof = 0;
  1530. }
  1531. }
  1532. }
  1533. }
  1534. return pIter->aLvl[0].bEof;
  1535. }
  1536. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  1537. return fts5DlidxIterPrevR(p, pIter, 0);
  1538. }
  1539. /*
  1540. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  1541. */
  1542. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  1543. if( pIter ){
  1544. int i;
  1545. for(i=0; i<pIter->nLvl; i++){
  1546. fts5DataRelease(pIter->aLvl[i].pData);
  1547. }
  1548. sqlite3_free(pIter);
  1549. }
  1550. }
  1551. static Fts5DlidxIter *fts5DlidxIterInit(
  1552. Fts5Index *p, /* Fts5 Backend to iterate within */
  1553. int bRev, /* True for ORDER BY ASC */
  1554. int iSegid, /* Segment id */
  1555. int iLeafPg /* Leaf page number to load dlidx for */
  1556. ){
  1557. Fts5DlidxIter *pIter = 0;
  1558. int i;
  1559. int bDone = 0;
  1560. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  1561. sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  1562. Fts5DlidxIter *pNew;
  1563. pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
  1564. if( pNew==0 ){
  1565. p->rc = SQLITE_NOMEM;
  1566. }else{
  1567. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  1568. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  1569. pIter = pNew;
  1570. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  1571. pLvl->pData = fts5DataRead(p, iRowid);
  1572. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  1573. bDone = 1;
  1574. }
  1575. pIter->nLvl = i+1;
  1576. }
  1577. }
  1578. if( p->rc==SQLITE_OK ){
  1579. pIter->iSegid = iSegid;
  1580. if( bRev==0 ){
  1581. fts5DlidxIterFirst(pIter);
  1582. }else{
  1583. fts5DlidxIterLast(p, pIter);
  1584. }
  1585. }
  1586. if( p->rc!=SQLITE_OK ){
  1587. fts5DlidxIterFree(pIter);
  1588. pIter = 0;
  1589. }
  1590. return pIter;
  1591. }
  1592. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  1593. return pIter->aLvl[0].iRowid;
  1594. }
  1595. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  1596. return pIter->aLvl[0].iLeafPgno;
  1597. }
  1598. /*
  1599. ** Load the next leaf page into the segment iterator.
  1600. */
  1601. static void fts5SegIterNextPage(
  1602. Fts5Index *p, /* FTS5 backend object */
  1603. Fts5SegIter *pIter /* Iterator to advance to next page */
  1604. ){
  1605. Fts5Data *pLeaf;
  1606. Fts5StructureSegment *pSeg = pIter->pSeg;
  1607. fts5DataRelease(pIter->pLeaf);
  1608. pIter->iLeafPgno++;
  1609. if( pIter->pNextLeaf ){
  1610. pIter->pLeaf = pIter->pNextLeaf;
  1611. pIter->pNextLeaf = 0;
  1612. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  1613. pIter->pLeaf = fts5LeafRead(p,
  1614. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  1615. );
  1616. }else{
  1617. pIter->pLeaf = 0;
  1618. }
  1619. pLeaf = pIter->pLeaf;
  1620. if( pLeaf ){
  1621. pIter->iPgidxOff = pLeaf->szLeaf;
  1622. if( fts5LeafIsTermless(pLeaf) ){
  1623. pIter->iEndofDoclist = pLeaf->nn+1;
  1624. }else{
  1625. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  1626. pIter->iEndofDoclist
  1627. );
  1628. }
  1629. }
  1630. }
  1631. /*
  1632. ** Argument p points to a buffer containing a varint to be interpreted as a
  1633. ** position list size field. Read the varint and return the number of bytes
  1634. ** read. Before returning, set *pnSz to the number of bytes in the position
  1635. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  1636. */
  1637. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  1638. int nSz;
  1639. int n = 0;
  1640. fts5FastGetVarint32(p, n, nSz);
  1641. assert_nc( nSz>=0 );
  1642. *pnSz = nSz/2;
  1643. *pbDel = nSz & 0x0001;
  1644. return n;
  1645. }
  1646. /*
  1647. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  1648. ** position-list size field. Read the value of the field and store it
  1649. ** in the following variables:
  1650. **
  1651. ** Fts5SegIter.nPos
  1652. ** Fts5SegIter.bDel
  1653. **
  1654. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  1655. ** position list content (if any).
  1656. */
  1657. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  1658. if( p->rc==SQLITE_OK ){
  1659. int iOff = pIter->iLeafOffset; /* Offset to read at */
  1660. ASSERT_SZLEAF_OK(pIter->pLeaf);
  1661. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  1662. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  1663. pIter->bDel = 0;
  1664. pIter->nPos = 1;
  1665. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  1666. pIter->bDel = 1;
  1667. iOff++;
  1668. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  1669. pIter->nPos = 1;
  1670. iOff++;
  1671. }else{
  1672. pIter->nPos = 0;
  1673. }
  1674. }
  1675. }else{
  1676. int nSz;
  1677. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  1678. pIter->bDel = (nSz & 0x0001);
  1679. pIter->nPos = nSz>>1;
  1680. assert_nc( pIter->nPos>=0 );
  1681. }
  1682. pIter->iLeafOffset = iOff;
  1683. }
  1684. }
  1685. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  1686. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  1687. i64 iOff = pIter->iLeafOffset;
  1688. ASSERT_SZLEAF_OK(pIter->pLeaf);
  1689. while( iOff>=pIter->pLeaf->szLeaf ){
  1690. fts5SegIterNextPage(p, pIter);
  1691. if( pIter->pLeaf==0 ){
  1692. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  1693. return;
  1694. }
  1695. iOff = 4;
  1696. a = pIter->pLeaf->p;
  1697. }
  1698. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  1699. pIter->iLeafOffset = iOff;
  1700. }
  1701. /*
  1702. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  1703. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  1704. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  1705. ** the first term in the segment).
  1706. **
  1707. ** This function populates:
  1708. **
  1709. ** Fts5SegIter.term
  1710. ** Fts5SegIter.rowid
  1711. **
  1712. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  1713. ** the first position list. The position list belonging to document
  1714. ** (Fts5SegIter.iRowid).
  1715. */
  1716. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  1717. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  1718. i64 iOff = pIter->iLeafOffset; /* Offset to read at */
  1719. int nNew; /* Bytes of new data */
  1720. iOff += fts5GetVarint32(&a[iOff], nNew);
  1721. if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
  1722. p->rc = FTS5_CORRUPT;
  1723. return;
  1724. }
  1725. pIter->term.n = nKeep;
  1726. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  1727. assert( pIter->term.n<=pIter->term.nSpace );
  1728. iOff += nNew;
  1729. pIter->iTermLeafOffset = iOff;
  1730. pIter->iTermLeafPgno = pIter->iLeafPgno;
  1731. pIter->iLeafOffset = iOff;
  1732. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  1733. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  1734. }else{
  1735. int nExtra;
  1736. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  1737. pIter->iEndofDoclist += nExtra;
  1738. }
  1739. fts5SegIterLoadRowid(p, pIter);
  1740. }
  1741. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  1742. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  1743. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  1744. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  1745. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  1746. pIter->xNext = fts5SegIterNext_Reverse;
  1747. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  1748. pIter->xNext = fts5SegIterNext_None;
  1749. }else{
  1750. pIter->xNext = fts5SegIterNext;
  1751. }
  1752. }
  1753. /*
  1754. ** Allocate a tombstone hash page array object (pIter->pTombArray) for
  1755. ** the iterator passed as the second argument. If an OOM error occurs,
  1756. ** leave an error in the Fts5Index object.
  1757. */
  1758. static void fts5SegIterAllocTombstone(Fts5Index *p, Fts5SegIter *pIter){
  1759. const int nTomb = pIter->pSeg->nPgTombstone;
  1760. if( nTomb>0 ){
  1761. int nByte = nTomb * sizeof(Fts5Data*) + sizeof(Fts5TombstoneArray);
  1762. Fts5TombstoneArray *pNew;
  1763. pNew = (Fts5TombstoneArray*)sqlite3Fts5MallocZero(&p->rc, nByte);
  1764. if( pNew ){
  1765. pNew->nTombstone = nTomb;
  1766. pNew->nRef = 1;
  1767. pIter->pTombArray = pNew;
  1768. }
  1769. }
  1770. }
  1771. /*
  1772. ** Initialize the iterator object pIter to iterate through the entries in
  1773. ** segment pSeg. The iterator is left pointing to the first entry when
  1774. ** this function returns.
  1775. **
  1776. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  1777. ** an error has already occurred when this function is called, it is a no-op.
  1778. */
  1779. static void fts5SegIterInit(
  1780. Fts5Index *p, /* FTS index object */
  1781. Fts5StructureSegment *pSeg, /* Description of segment */
  1782. Fts5SegIter *pIter /* Object to populate */
  1783. ){
  1784. if( pSeg->pgnoFirst==0 ){
  1785. /* This happens if the segment is being used as an input to an incremental
  1786. ** merge and all data has already been "trimmed". See function
  1787. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  1788. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  1789. ** at EOF already. */
  1790. assert( pIter->pLeaf==0 );
  1791. return;
  1792. }
  1793. if( p->rc==SQLITE_OK ){
  1794. memset(pIter, 0, sizeof(*pIter));
  1795. fts5SegIterSetNext(p, pIter);
  1796. pIter->pSeg = pSeg;
  1797. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  1798. do {
  1799. fts5SegIterNextPage(p, pIter);
  1800. }while( p->rc==SQLITE_OK && pIter->pLeaf && pIter->pLeaf->nn==4 );
  1801. }
  1802. if( p->rc==SQLITE_OK && pIter->pLeaf ){
  1803. pIter->iLeafOffset = 4;
  1804. assert( pIter->pLeaf!=0 );
  1805. assert_nc( pIter->pLeaf->nn>4 );
  1806. assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  1807. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  1808. fts5SegIterLoadTerm(p, pIter, 0);
  1809. fts5SegIterLoadNPos(p, pIter);
  1810. fts5SegIterAllocTombstone(p, pIter);
  1811. }
  1812. }
  1813. /*
  1814. ** This function is only ever called on iterators created by calls to
  1815. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  1816. **
  1817. ** The iterator is in an unusual state when this function is called: the
  1818. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  1819. ** the position-list size field for the first relevant rowid on the page.
  1820. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  1821. **
  1822. ** This function advances the iterator so that it points to the last
  1823. ** relevant rowid on the page and, if necessary, initializes the
  1824. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  1825. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  1826. ** byte of the position list content associated with said rowid.
  1827. */
  1828. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  1829. int eDetail = p->pConfig->eDetail;
  1830. int n = pIter->pLeaf->szLeaf;
  1831. int i = pIter->iLeafOffset;
  1832. u8 *a = pIter->pLeaf->p;
  1833. int iRowidOffset = 0;
  1834. if( n>pIter->iEndofDoclist ){
  1835. n = pIter->iEndofDoclist;
  1836. }
  1837. ASSERT_SZLEAF_OK(pIter->pLeaf);
  1838. while( 1 ){
  1839. u64 iDelta = 0;
  1840. if( eDetail==FTS5_DETAIL_NONE ){
  1841. /* todo */
  1842. if( i<n && a[i]==0 ){
  1843. i++;
  1844. if( i<n && a[i]==0 ) i++;
  1845. }
  1846. }else{
  1847. int nPos;
  1848. int bDummy;
  1849. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  1850. i += nPos;
  1851. }
  1852. if( i>=n ) break;
  1853. i += fts5GetVarint(&a[i], &iDelta);
  1854. pIter->iRowid += iDelta;
  1855. /* If necessary, grow the pIter->aRowidOffset[] array. */
  1856. if( iRowidOffset>=pIter->nRowidOffset ){
  1857. int nNew = pIter->nRowidOffset + 8;
  1858. int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
  1859. if( aNew==0 ){
  1860. p->rc = SQLITE_NOMEM;
  1861. break;
  1862. }
  1863. pIter->aRowidOffset = aNew;
  1864. pIter->nRowidOffset = nNew;
  1865. }
  1866. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  1867. pIter->iLeafOffset = i;
  1868. }
  1869. pIter->iRowidOffset = iRowidOffset;
  1870. fts5SegIterLoadNPos(p, pIter);
  1871. }
  1872. /*
  1873. **
  1874. */
  1875. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  1876. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  1877. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  1878. fts5DataRelease(pIter->pLeaf);
  1879. pIter->pLeaf = 0;
  1880. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  1881. Fts5Data *pNew;
  1882. pIter->iLeafPgno--;
  1883. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  1884. pIter->pSeg->iSegid, pIter->iLeafPgno
  1885. ));
  1886. if( pNew ){
  1887. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  1888. ** thing on the page - i.e. the first rowid is on the following page.
  1889. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  1890. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  1891. assert( pIter->pLeaf==0 );
  1892. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  1893. pIter->pLeaf = pNew;
  1894. pIter->iLeafOffset = pIter->iTermLeafOffset;
  1895. }
  1896. }else{
  1897. int iRowidOff;
  1898. iRowidOff = fts5LeafFirstRowidOff(pNew);
  1899. if( iRowidOff ){
  1900. if( iRowidOff>=pNew->szLeaf ){
  1901. p->rc = FTS5_CORRUPT;
  1902. }else{
  1903. pIter->pLeaf = pNew;
  1904. pIter->iLeafOffset = iRowidOff;
  1905. }
  1906. }
  1907. }
  1908. if( pIter->pLeaf ){
  1909. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  1910. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  1911. break;
  1912. }else{
  1913. fts5DataRelease(pNew);
  1914. }
  1915. }
  1916. }
  1917. if( pIter->pLeaf ){
  1918. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  1919. fts5SegIterReverseInitPage(p, pIter);
  1920. }
  1921. }
  1922. /*
  1923. ** Return true if the iterator passed as the second argument currently
  1924. ** points to a delete marker. A delete marker is an entry with a 0 byte
  1925. ** position-list.
  1926. */
  1927. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  1928. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  1929. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  1930. }
  1931. /*
  1932. ** Advance iterator pIter to the next entry.
  1933. **
  1934. ** This version of fts5SegIterNext() is only used by reverse iterators.
  1935. */
  1936. static void fts5SegIterNext_Reverse(
  1937. Fts5Index *p, /* FTS5 backend object */
  1938. Fts5SegIter *pIter, /* Iterator to advance */
  1939. int *pbUnused /* Unused */
  1940. ){
  1941. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  1942. assert( pIter->pNextLeaf==0 );
  1943. UNUSED_PARAM(pbUnused);
  1944. if( pIter->iRowidOffset>0 ){
  1945. u8 *a = pIter->pLeaf->p;
  1946. int iOff;
  1947. u64 iDelta;
  1948. pIter->iRowidOffset--;
  1949. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  1950. fts5SegIterLoadNPos(p, pIter);
  1951. iOff = pIter->iLeafOffset;
  1952. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  1953. iOff += pIter->nPos;
  1954. }
  1955. fts5GetVarint(&a[iOff], &iDelta);
  1956. pIter->iRowid -= iDelta;
  1957. }else{
  1958. fts5SegIterReverseNewPage(p, pIter);
  1959. }
  1960. }
  1961. /*
  1962. ** Advance iterator pIter to the next entry.
  1963. **
  1964. ** This version of fts5SegIterNext() is only used if detail=none and the
  1965. ** iterator is not a reverse direction iterator.
  1966. */
  1967. static void fts5SegIterNext_None(
  1968. Fts5Index *p, /* FTS5 backend object */
  1969. Fts5SegIter *pIter, /* Iterator to advance */
  1970. int *pbNewTerm /* OUT: Set for new term */
  1971. ){
  1972. int iOff;
  1973. assert( p->rc==SQLITE_OK );
  1974. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  1975. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  1976. ASSERT_SZLEAF_OK(pIter->pLeaf);
  1977. iOff = pIter->iLeafOffset;
  1978. /* Next entry is on the next page */
  1979. while( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  1980. fts5SegIterNextPage(p, pIter);
  1981. if( p->rc || pIter->pLeaf==0 ) return;
  1982. pIter->iRowid = 0;
  1983. iOff = 4;
  1984. }
  1985. if( iOff<pIter->iEndofDoclist ){
  1986. /* Next entry is on the current page */
  1987. u64 iDelta;
  1988. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  1989. pIter->iLeafOffset = iOff;
  1990. pIter->iRowid += iDelta;
  1991. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  1992. if( pIter->pSeg ){
  1993. int nKeep = 0;
  1994. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  1995. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  1996. }
  1997. pIter->iLeafOffset = iOff;
  1998. fts5SegIterLoadTerm(p, pIter, nKeep);
  1999. }else{
  2000. const u8 *pList = 0;
  2001. const char *zTerm = 0;
  2002. int nTerm = 0;
  2003. int nList;
  2004. sqlite3Fts5HashScanNext(p->pHash);
  2005. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
  2006. if( pList==0 ) goto next_none_eof;
  2007. pIter->pLeaf->p = (u8*)pList;
  2008. pIter->pLeaf->nn = nList;
  2009. pIter->pLeaf->szLeaf = nList;
  2010. pIter->iEndofDoclist = nList;
  2011. sqlite3Fts5BufferSet(&p->rc,&pIter->term, nTerm, (u8*)zTerm);
  2012. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  2013. }
  2014. if( pbNewTerm ) *pbNewTerm = 1;
  2015. }else{
  2016. goto next_none_eof;
  2017. }
  2018. fts5SegIterLoadNPos(p, pIter);
  2019. return;
  2020. next_none_eof:
  2021. fts5DataRelease(pIter->pLeaf);
  2022. pIter->pLeaf = 0;
  2023. }
  2024. /*
  2025. ** Advance iterator pIter to the next entry.
  2026. **
  2027. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  2028. ** is not considered an error if the iterator reaches EOF. If an error has
  2029. ** already occurred when this function is called, it is a no-op.
  2030. */
  2031. static void fts5SegIterNext(
  2032. Fts5Index *p, /* FTS5 backend object */
  2033. Fts5SegIter *pIter, /* Iterator to advance */
  2034. int *pbNewTerm /* OUT: Set for new term */
  2035. ){
  2036. Fts5Data *pLeaf = pIter->pLeaf;
  2037. int iOff;
  2038. int bNewTerm = 0;
  2039. int nKeep = 0;
  2040. u8 *a;
  2041. int n;
  2042. assert( pbNewTerm==0 || *pbNewTerm==0 );
  2043. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  2044. /* Search for the end of the position list within the current page. */
  2045. a = pLeaf->p;
  2046. n = pLeaf->szLeaf;
  2047. ASSERT_SZLEAF_OK(pLeaf);
  2048. iOff = pIter->iLeafOffset + pIter->nPos;
  2049. if( iOff<n ){
  2050. /* The next entry is on the current page. */
  2051. assert_nc( iOff<=pIter->iEndofDoclist );
  2052. if( iOff>=pIter->iEndofDoclist ){
  2053. bNewTerm = 1;
  2054. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  2055. iOff += fts5GetVarint32(&a[iOff], nKeep);
  2056. }
  2057. }else{
  2058. u64 iDelta;
  2059. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  2060. pIter->iRowid += iDelta;
  2061. assert_nc( iDelta>0 );
  2062. }
  2063. pIter->iLeafOffset = iOff;
  2064. }else if( pIter->pSeg==0 ){
  2065. const u8 *pList = 0;
  2066. const char *zTerm = 0;
  2067. int nTerm = 0;
  2068. int nList = 0;
  2069. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  2070. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  2071. sqlite3Fts5HashScanNext(p->pHash);
  2072. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &nTerm, &pList, &nList);
  2073. }
  2074. if( pList==0 ){
  2075. fts5DataRelease(pIter->pLeaf);
  2076. pIter->pLeaf = 0;
  2077. }else{
  2078. pIter->pLeaf->p = (u8*)pList;
  2079. pIter->pLeaf->nn = nList;
  2080. pIter->pLeaf->szLeaf = nList;
  2081. pIter->iEndofDoclist = nList+1;
  2082. sqlite3Fts5BufferSet(&p->rc, &pIter->term, nTerm, (u8*)zTerm);
  2083. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  2084. *pbNewTerm = 1;
  2085. }
  2086. }else{
  2087. iOff = 0;
  2088. /* Next entry is not on the current page */
  2089. while( iOff==0 ){
  2090. fts5SegIterNextPage(p, pIter);
  2091. pLeaf = pIter->pLeaf;
  2092. if( pLeaf==0 ) break;
  2093. ASSERT_SZLEAF_OK(pLeaf);
  2094. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  2095. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  2096. pIter->iLeafOffset = iOff;
  2097. if( pLeaf->nn>pLeaf->szLeaf ){
  2098. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  2099. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  2100. );
  2101. }
  2102. }
  2103. else if( pLeaf->nn>pLeaf->szLeaf ){
  2104. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  2105. &pLeaf->p[pLeaf->szLeaf], iOff
  2106. );
  2107. pIter->iLeafOffset = iOff;
  2108. pIter->iEndofDoclist = iOff;
  2109. bNewTerm = 1;
  2110. }
  2111. assert_nc( iOff<pLeaf->szLeaf );
  2112. if( iOff>pLeaf->szLeaf ){
  2113. p->rc = FTS5_CORRUPT;
  2114. return;
  2115. }
  2116. }
  2117. }
  2118. /* Check if the iterator is now at EOF. If so, return early. */
  2119. if( pIter->pLeaf ){
  2120. if( bNewTerm ){
  2121. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  2122. fts5DataRelease(pIter->pLeaf);
  2123. pIter->pLeaf = 0;
  2124. }else{
  2125. fts5SegIterLoadTerm(p, pIter, nKeep);
  2126. fts5SegIterLoadNPos(p, pIter);
  2127. if( pbNewTerm ) *pbNewTerm = 1;
  2128. }
  2129. }else{
  2130. /* The following could be done by calling fts5SegIterLoadNPos(). But
  2131. ** this block is particularly performance critical, so equivalent
  2132. ** code is inlined. */
  2133. int nSz;
  2134. assert_nc( pIter->iLeafOffset<=pIter->pLeaf->nn );
  2135. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  2136. pIter->bDel = (nSz & 0x0001);
  2137. pIter->nPos = nSz>>1;
  2138. assert_nc( pIter->nPos>=0 );
  2139. }
  2140. }
  2141. }
  2142. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  2143. #define fts5IndexSkipVarint(a, iOff) { \
  2144. int iEnd = iOff+9; \
  2145. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  2146. }
  2147. /*
  2148. ** Iterator pIter currently points to the first rowid in a doclist. This
  2149. ** function sets the iterator up so that iterates in reverse order through
  2150. ** the doclist.
  2151. */
  2152. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  2153. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  2154. Fts5Data *pLast = 0;
  2155. int pgnoLast = 0;
  2156. if( pDlidx && p->pConfig->iVersion==FTS5_CURRENT_VERSION ){
  2157. int iSegid = pIter->pSeg->iSegid;
  2158. pgnoLast = fts5DlidxIterPgno(pDlidx);
  2159. pLast = fts5LeafRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  2160. }else{
  2161. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  2162. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  2163. ** position-list content for the current rowid. Back it up so that it
  2164. ** points to the start of the position-list size field. */
  2165. int iPoslist;
  2166. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  2167. iPoslist = pIter->iTermLeafOffset;
  2168. }else{
  2169. iPoslist = 4;
  2170. }
  2171. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  2172. pIter->iLeafOffset = iPoslist;
  2173. /* If this condition is true then the largest rowid for the current
  2174. ** term may not be stored on the current page. So search forward to
  2175. ** see where said rowid really is. */
  2176. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  2177. int pgno;
  2178. Fts5StructureSegment *pSeg = pIter->pSeg;
  2179. /* The last rowid in the doclist may not be on the current page. Search
  2180. ** forward to find the page containing the last rowid. */
  2181. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  2182. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  2183. Fts5Data *pNew = fts5LeafRead(p, iAbs);
  2184. if( pNew ){
  2185. int iRowid, bTermless;
  2186. iRowid = fts5LeafFirstRowidOff(pNew);
  2187. bTermless = fts5LeafIsTermless(pNew);
  2188. if( iRowid ){
  2189. SWAPVAL(Fts5Data*, pNew, pLast);
  2190. pgnoLast = pgno;
  2191. }
  2192. fts5DataRelease(pNew);
  2193. if( bTermless==0 ) break;
  2194. }
  2195. }
  2196. }
  2197. }
  2198. /* If pLast is NULL at this point, then the last rowid for this doclist
  2199. ** lies on the page currently indicated by the iterator. In this case
  2200. ** pIter->iLeafOffset is already set to point to the position-list size
  2201. ** field associated with the first relevant rowid on the page.
  2202. **
  2203. ** Or, if pLast is non-NULL, then it is the page that contains the last
  2204. ** rowid. In this case configure the iterator so that it points to the
  2205. ** first rowid on this page.
  2206. */
  2207. if( pLast ){
  2208. int iOff;
  2209. fts5DataRelease(pIter->pLeaf);
  2210. pIter->pLeaf = pLast;
  2211. pIter->iLeafPgno = pgnoLast;
  2212. iOff = fts5LeafFirstRowidOff(pLast);
  2213. if( iOff>pLast->szLeaf ){
  2214. p->rc = FTS5_CORRUPT;
  2215. return;
  2216. }
  2217. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  2218. pIter->iLeafOffset = iOff;
  2219. if( fts5LeafIsTermless(pLast) ){
  2220. pIter->iEndofDoclist = pLast->nn+1;
  2221. }else{
  2222. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  2223. }
  2224. }
  2225. fts5SegIterReverseInitPage(p, pIter);
  2226. }
  2227. /*
  2228. ** Iterator pIter currently points to the first rowid of a doclist.
  2229. ** There is a doclist-index associated with the final term on the current
  2230. ** page. If the current term is the last term on the page, load the
  2231. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  2232. */
  2233. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  2234. int iSeg = pIter->pSeg->iSegid;
  2235. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  2236. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  2237. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  2238. assert( pIter->pDlidx==0 );
  2239. /* Check if the current doclist ends on this page. If it does, return
  2240. ** early without loading the doclist-index (as it belongs to a different
  2241. ** term. */
  2242. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  2243. && pIter->iEndofDoclist<pLeaf->szLeaf
  2244. ){
  2245. return;
  2246. }
  2247. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  2248. }
  2249. /*
  2250. ** The iterator object passed as the second argument currently contains
  2251. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  2252. ** function searches the leaf page for a term matching (pTerm/nTerm).
  2253. **
  2254. ** If the specified term is found on the page, then the iterator is left
  2255. ** pointing to it. If argument bGe is zero and the term is not found,
  2256. ** the iterator is left pointing at EOF.
  2257. **
  2258. ** If bGe is non-zero and the specified term is not found, then the
  2259. ** iterator is left pointing to the smallest term in the segment that
  2260. ** is larger than the specified term, even if this term is not on the
  2261. ** current page.
  2262. */
  2263. static void fts5LeafSeek(
  2264. Fts5Index *p, /* Leave any error code here */
  2265. int bGe, /* True for a >= search */
  2266. Fts5SegIter *pIter, /* Iterator to seek */
  2267. const u8 *pTerm, int nTerm /* Term to search for */
  2268. ){
  2269. u32 iOff;
  2270. const u8 *a = pIter->pLeaf->p;
  2271. u32 n = (u32)pIter->pLeaf->nn;
  2272. u32 nMatch = 0;
  2273. u32 nKeep = 0;
  2274. u32 nNew = 0;
  2275. u32 iTermOff;
  2276. u32 iPgidx; /* Current offset in pgidx */
  2277. int bEndOfPage = 0;
  2278. assert( p->rc==SQLITE_OK );
  2279. iPgidx = (u32)pIter->pLeaf->szLeaf;
  2280. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  2281. iOff = iTermOff;
  2282. if( iOff>n ){
  2283. p->rc = FTS5_CORRUPT;
  2284. return;
  2285. }
  2286. while( 1 ){
  2287. /* Figure out how many new bytes are in this term */
  2288. fts5FastGetVarint32(a, iOff, nNew);
  2289. if( nKeep<nMatch ){
  2290. goto search_failed;
  2291. }
  2292. assert( nKeep>=nMatch );
  2293. if( nKeep==nMatch ){
  2294. u32 nCmp;
  2295. u32 i;
  2296. nCmp = (u32)MIN(nNew, nTerm-nMatch);
  2297. for(i=0; i<nCmp; i++){
  2298. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  2299. }
  2300. nMatch += i;
  2301. if( (u32)nTerm==nMatch ){
  2302. if( i==nNew ){
  2303. goto search_success;
  2304. }else{
  2305. goto search_failed;
  2306. }
  2307. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  2308. goto search_failed;
  2309. }
  2310. }
  2311. if( iPgidx>=n ){
  2312. bEndOfPage = 1;
  2313. break;
  2314. }
  2315. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  2316. iTermOff += nKeep;
  2317. iOff = iTermOff;
  2318. if( iOff>=n ){
  2319. p->rc = FTS5_CORRUPT;
  2320. return;
  2321. }
  2322. /* Read the nKeep field of the next term. */
  2323. fts5FastGetVarint32(a, iOff, nKeep);
  2324. }
  2325. search_failed:
  2326. if( bGe==0 ){
  2327. fts5DataRelease(pIter->pLeaf);
  2328. pIter->pLeaf = 0;
  2329. return;
  2330. }else if( bEndOfPage ){
  2331. do {
  2332. fts5SegIterNextPage(p, pIter);
  2333. if( pIter->pLeaf==0 ) return;
  2334. a = pIter->pLeaf->p;
  2335. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  2336. iPgidx = (u32)pIter->pLeaf->szLeaf;
  2337. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  2338. if( iOff<4 || (i64)iOff>=pIter->pLeaf->szLeaf ){
  2339. p->rc = FTS5_CORRUPT;
  2340. return;
  2341. }else{
  2342. nKeep = 0;
  2343. iTermOff = iOff;
  2344. n = (u32)pIter->pLeaf->nn;
  2345. iOff += fts5GetVarint32(&a[iOff], nNew);
  2346. break;
  2347. }
  2348. }
  2349. }while( 1 );
  2350. }
  2351. search_success:
  2352. if( (i64)iOff+nNew>n || nNew<1 ){
  2353. p->rc = FTS5_CORRUPT;
  2354. return;
  2355. }
  2356. pIter->iLeafOffset = iOff + nNew;
  2357. pIter->iTermLeafOffset = pIter->iLeafOffset;
  2358. pIter->iTermLeafPgno = pIter->iLeafPgno;
  2359. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  2360. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  2361. if( iPgidx>=n ){
  2362. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  2363. }else{
  2364. int nExtra;
  2365. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  2366. pIter->iEndofDoclist = iTermOff + nExtra;
  2367. }
  2368. pIter->iPgidxOff = iPgidx;
  2369. fts5SegIterLoadRowid(p, pIter);
  2370. fts5SegIterLoadNPos(p, pIter);
  2371. }
  2372. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  2373. if( p->pIdxSelect==0 ){
  2374. Fts5Config *pConfig = p->pConfig;
  2375. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  2376. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  2377. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  2378. pConfig->zDb, pConfig->zName
  2379. ));
  2380. }
  2381. return p->pIdxSelect;
  2382. }
  2383. /*
  2384. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  2385. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  2386. **
  2387. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  2388. ** an error has already occurred when this function is called, it is a no-op.
  2389. */
  2390. static void fts5SegIterSeekInit(
  2391. Fts5Index *p, /* FTS5 backend */
  2392. const u8 *pTerm, int nTerm, /* Term to seek to */
  2393. int flags, /* Mask of FTS5INDEX_XXX flags */
  2394. Fts5StructureSegment *pSeg, /* Description of segment */
  2395. Fts5SegIter *pIter /* Object to populate */
  2396. ){
  2397. int iPg = 1;
  2398. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  2399. int bDlidx = 0; /* True if there is a doclist-index */
  2400. sqlite3_stmt *pIdxSelect = 0;
  2401. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  2402. assert( pTerm && nTerm );
  2403. memset(pIter, 0, sizeof(*pIter));
  2404. pIter->pSeg = pSeg;
  2405. /* This block sets stack variable iPg to the leaf page number that may
  2406. ** contain term (pTerm/nTerm), if it is present in the segment. */
  2407. pIdxSelect = fts5IdxSelectStmt(p);
  2408. if( p->rc ) return;
  2409. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  2410. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  2411. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  2412. i64 val = sqlite3_column_int(pIdxSelect, 0);
  2413. iPg = (int)(val>>1);
  2414. bDlidx = (val & 0x0001);
  2415. }
  2416. p->rc = sqlite3_reset(pIdxSelect);
  2417. sqlite3_bind_null(pIdxSelect, 2);
  2418. if( iPg<pSeg->pgnoFirst ){
  2419. iPg = pSeg->pgnoFirst;
  2420. bDlidx = 0;
  2421. }
  2422. pIter->iLeafPgno = iPg - 1;
  2423. fts5SegIterNextPage(p, pIter);
  2424. if( pIter->pLeaf ){
  2425. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  2426. }
  2427. if( p->rc==SQLITE_OK && (bGe==0 || (flags & FTS5INDEX_QUERY_SCANONETERM)) ){
  2428. pIter->flags |= FTS5_SEGITER_ONETERM;
  2429. if( pIter->pLeaf ){
  2430. if( flags & FTS5INDEX_QUERY_DESC ){
  2431. pIter->flags |= FTS5_SEGITER_REVERSE;
  2432. }
  2433. if( bDlidx ){
  2434. fts5SegIterLoadDlidx(p, pIter);
  2435. }
  2436. if( flags & FTS5INDEX_QUERY_DESC ){
  2437. fts5SegIterReverse(p, pIter);
  2438. }
  2439. }
  2440. }
  2441. fts5SegIterSetNext(p, pIter);
  2442. if( 0==(flags & FTS5INDEX_QUERY_SCANONETERM) ){
  2443. fts5SegIterAllocTombstone(p, pIter);
  2444. }
  2445. /* Either:
  2446. **
  2447. ** 1) an error has occurred, or
  2448. ** 2) the iterator points to EOF, or
  2449. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  2450. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  2451. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  2452. */
  2453. assert_nc( p->rc!=SQLITE_OK /* 1 */
  2454. || pIter->pLeaf==0 /* 2 */
  2455. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  2456. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  2457. );
  2458. }
  2459. /*
  2460. ** SQL used by fts5SegIterNextInit() to find the page to open.
  2461. */
  2462. static sqlite3_stmt *fts5IdxNextStmt(Fts5Index *p){
  2463. if( p->pIdxNextSelect==0 ){
  2464. Fts5Config *pConfig = p->pConfig;
  2465. fts5IndexPrepareStmt(p, &p->pIdxNextSelect, sqlite3_mprintf(
  2466. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  2467. "segid=? AND term>? ORDER BY term ASC LIMIT 1",
  2468. pConfig->zDb, pConfig->zName
  2469. ));
  2470. }
  2471. return p->pIdxNextSelect;
  2472. }
  2473. /*
  2474. ** This is similar to fts5SegIterSeekInit(), except that it initializes
  2475. ** the segment iterator to point to the first term following the page
  2476. ** with pToken/nToken on it.
  2477. */
  2478. static void fts5SegIterNextInit(
  2479. Fts5Index *p,
  2480. const char *pTerm, int nTerm,
  2481. Fts5StructureSegment *pSeg, /* Description of segment */
  2482. Fts5SegIter *pIter /* Object to populate */
  2483. ){
  2484. int iPg = -1; /* Page of segment to open */
  2485. int bDlidx = 0;
  2486. sqlite3_stmt *pSel = 0; /* SELECT to find iPg */
  2487. pSel = fts5IdxNextStmt(p);
  2488. if( pSel ){
  2489. assert( p->rc==SQLITE_OK );
  2490. sqlite3_bind_int(pSel, 1, pSeg->iSegid);
  2491. sqlite3_bind_blob(pSel, 2, pTerm, nTerm, SQLITE_STATIC);
  2492. if( sqlite3_step(pSel)==SQLITE_ROW ){
  2493. i64 val = sqlite3_column_int64(pSel, 0);
  2494. iPg = (int)(val>>1);
  2495. bDlidx = (val & 0x0001);
  2496. }
  2497. p->rc = sqlite3_reset(pSel);
  2498. sqlite3_bind_null(pSel, 2);
  2499. if( p->rc ) return;
  2500. }
  2501. memset(pIter, 0, sizeof(*pIter));
  2502. pIter->pSeg = pSeg;
  2503. pIter->flags |= FTS5_SEGITER_ONETERM;
  2504. if( iPg>=0 ){
  2505. pIter->iLeafPgno = iPg - 1;
  2506. fts5SegIterNextPage(p, pIter);
  2507. fts5SegIterSetNext(p, pIter);
  2508. }
  2509. if( pIter->pLeaf ){
  2510. const u8 *a = pIter->pLeaf->p;
  2511. int iTermOff = 0;
  2512. pIter->iPgidxOff = pIter->pLeaf->szLeaf;
  2513. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], iTermOff);
  2514. pIter->iLeafOffset = iTermOff;
  2515. fts5SegIterLoadTerm(p, pIter, 0);
  2516. fts5SegIterLoadNPos(p, pIter);
  2517. if( bDlidx ) fts5SegIterLoadDlidx(p, pIter);
  2518. assert( p->rc!=SQLITE_OK ||
  2519. fts5BufferCompareBlob(&pIter->term, (const u8*)pTerm, nTerm)>0
  2520. );
  2521. }
  2522. }
  2523. /*
  2524. ** Initialize the object pIter to point to term pTerm/nTerm within the
  2525. ** in-memory hash table. If there is no such term in the hash-table, the
  2526. ** iterator is set to EOF.
  2527. **
  2528. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  2529. ** an error has already occurred when this function is called, it is a no-op.
  2530. */
  2531. static void fts5SegIterHashInit(
  2532. Fts5Index *p, /* FTS5 backend */
  2533. const u8 *pTerm, int nTerm, /* Term to seek to */
  2534. int flags, /* Mask of FTS5INDEX_XXX flags */
  2535. Fts5SegIter *pIter /* Object to populate */
  2536. ){
  2537. int nList = 0;
  2538. const u8 *z = 0;
  2539. int n = 0;
  2540. Fts5Data *pLeaf = 0;
  2541. assert( p->pHash );
  2542. assert( p->rc==SQLITE_OK );
  2543. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  2544. const u8 *pList = 0;
  2545. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  2546. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &n, &pList, &nList);
  2547. if( pList ){
  2548. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  2549. if( pLeaf ){
  2550. pLeaf->p = (u8*)pList;
  2551. }
  2552. }
  2553. /* The call to sqlite3Fts5HashScanInit() causes the hash table to
  2554. ** fill the size field of all existing position lists. This means they
  2555. ** can no longer be appended to. Since the only scenario in which they
  2556. ** can be appended to is if the previous operation on this table was
  2557. ** a DELETE, by clearing the Fts5Index.bDelete flag we can avoid this
  2558. ** possibility altogether. */
  2559. p->bDelete = 0;
  2560. }else{
  2561. p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
  2562. (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
  2563. );
  2564. if( pLeaf ){
  2565. pLeaf->p = (u8*)&pLeaf[1];
  2566. }
  2567. z = pTerm;
  2568. n = nTerm;
  2569. pIter->flags |= FTS5_SEGITER_ONETERM;
  2570. }
  2571. if( pLeaf ){
  2572. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  2573. pLeaf->nn = pLeaf->szLeaf = nList;
  2574. pIter->pLeaf = pLeaf;
  2575. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  2576. pIter->iEndofDoclist = pLeaf->nn;
  2577. if( flags & FTS5INDEX_QUERY_DESC ){
  2578. pIter->flags |= FTS5_SEGITER_REVERSE;
  2579. fts5SegIterReverseInitPage(p, pIter);
  2580. }else{
  2581. fts5SegIterLoadNPos(p, pIter);
  2582. }
  2583. }
  2584. fts5SegIterSetNext(p, pIter);
  2585. }
  2586. /*
  2587. ** Array ap[] contains n elements. Release each of these elements using
  2588. ** fts5DataRelease(). Then free the array itself using sqlite3_free().
  2589. */
  2590. static void fts5IndexFreeArray(Fts5Data **ap, int n){
  2591. if( ap ){
  2592. int ii;
  2593. for(ii=0; ii<n; ii++){
  2594. fts5DataRelease(ap[ii]);
  2595. }
  2596. sqlite3_free(ap);
  2597. }
  2598. }
  2599. /*
  2600. ** Decrement the ref-count of the object passed as the only argument. If it
  2601. ** reaches 0, free it and its contents.
  2602. */
  2603. static void fts5TombstoneArrayDelete(Fts5TombstoneArray *p){
  2604. if( p ){
  2605. p->nRef--;
  2606. if( p->nRef<=0 ){
  2607. int ii;
  2608. for(ii=0; ii<p->nTombstone; ii++){
  2609. fts5DataRelease(p->apTombstone[ii]);
  2610. }
  2611. sqlite3_free(p);
  2612. }
  2613. }
  2614. }
  2615. /*
  2616. ** Zero the iterator passed as the only argument.
  2617. */
  2618. static void fts5SegIterClear(Fts5SegIter *pIter){
  2619. fts5BufferFree(&pIter->term);
  2620. fts5DataRelease(pIter->pLeaf);
  2621. fts5DataRelease(pIter->pNextLeaf);
  2622. fts5TombstoneArrayDelete(pIter->pTombArray);
  2623. fts5DlidxIterFree(pIter->pDlidx);
  2624. sqlite3_free(pIter->aRowidOffset);
  2625. memset(pIter, 0, sizeof(Fts5SegIter));
  2626. }
  2627. #ifdef SQLITE_DEBUG
  2628. /*
  2629. ** This function is used as part of the big assert() procedure implemented by
  2630. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  2631. ** in *pRes is the correct result of comparing the current positions of the
  2632. ** two iterators.
  2633. */
  2634. static void fts5AssertComparisonResult(
  2635. Fts5Iter *pIter,
  2636. Fts5SegIter *p1,
  2637. Fts5SegIter *p2,
  2638. Fts5CResult *pRes
  2639. ){
  2640. int i1 = p1 - pIter->aSeg;
  2641. int i2 = p2 - pIter->aSeg;
  2642. if( p1->pLeaf || p2->pLeaf ){
  2643. if( p1->pLeaf==0 ){
  2644. assert( pRes->iFirst==i2 );
  2645. }else if( p2->pLeaf==0 ){
  2646. assert( pRes->iFirst==i1 );
  2647. }else{
  2648. int nMin = MIN(p1->term.n, p2->term.n);
  2649. int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
  2650. if( res==0 ) res = p1->term.n - p2->term.n;
  2651. if( res==0 ){
  2652. assert( pRes->bTermEq==1 );
  2653. assert( p1->iRowid!=p2->iRowid );
  2654. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  2655. }else{
  2656. assert( pRes->bTermEq==0 );
  2657. }
  2658. if( res<0 ){
  2659. assert( pRes->iFirst==i1 );
  2660. }else{
  2661. assert( pRes->iFirst==i2 );
  2662. }
  2663. }
  2664. }
  2665. }
  2666. /*
  2667. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  2668. ** is compiled. In that case, this function is essentially an assert()
  2669. ** statement used to verify that the contents of the pIter->aFirst[] array
  2670. ** are correct.
  2671. */
  2672. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  2673. if( p->rc==SQLITE_OK ){
  2674. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  2675. int i;
  2676. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  2677. /* Check that pIter->iSwitchRowid is set correctly. */
  2678. for(i=0; i<pIter->nSeg; i++){
  2679. Fts5SegIter *p1 = &pIter->aSeg[i];
  2680. assert( p1==pFirst
  2681. || p1->pLeaf==0
  2682. || fts5BufferCompare(&pFirst->term, &p1->term)
  2683. || p1->iRowid==pIter->iSwitchRowid
  2684. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  2685. );
  2686. }
  2687. for(i=0; i<pIter->nSeg; i+=2){
  2688. Fts5SegIter *p1 = &pIter->aSeg[i];
  2689. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  2690. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  2691. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  2692. }
  2693. for(i=1; i<(pIter->nSeg / 2); i+=2){
  2694. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  2695. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  2696. Fts5CResult *pRes = &pIter->aFirst[i];
  2697. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  2698. }
  2699. }
  2700. }
  2701. #else
  2702. # define fts5AssertMultiIterSetup(x,y)
  2703. #endif
  2704. /*
  2705. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  2706. **
  2707. ** If the returned value is non-zero, then it is the index of an entry
  2708. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  2709. ** to a key that is a duplicate of another, higher priority,
  2710. ** segment-iterator in the pSeg->aSeg[] array.
  2711. */
  2712. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  2713. int i1; /* Index of left-hand Fts5SegIter */
  2714. int i2; /* Index of right-hand Fts5SegIter */
  2715. int iRes;
  2716. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  2717. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  2718. Fts5CResult *pRes = &pIter->aFirst[iOut];
  2719. assert( iOut<pIter->nSeg && iOut>0 );
  2720. assert( pIter->bRev==0 || pIter->bRev==1 );
  2721. if( iOut>=(pIter->nSeg/2) ){
  2722. i1 = (iOut - pIter->nSeg/2) * 2;
  2723. i2 = i1 + 1;
  2724. }else{
  2725. i1 = pIter->aFirst[iOut*2].iFirst;
  2726. i2 = pIter->aFirst[iOut*2+1].iFirst;
  2727. }
  2728. p1 = &pIter->aSeg[i1];
  2729. p2 = &pIter->aSeg[i2];
  2730. pRes->bTermEq = 0;
  2731. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  2732. iRes = i2;
  2733. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  2734. iRes = i1;
  2735. }else{
  2736. int res = fts5BufferCompare(&p1->term, &p2->term);
  2737. if( res==0 ){
  2738. assert_nc( i2>i1 );
  2739. assert_nc( i2!=0 );
  2740. pRes->bTermEq = 1;
  2741. if( p1->iRowid==p2->iRowid ){
  2742. return i2;
  2743. }
  2744. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  2745. }
  2746. assert( res!=0 );
  2747. if( res<0 ){
  2748. iRes = i1;
  2749. }else{
  2750. iRes = i2;
  2751. }
  2752. }
  2753. pRes->iFirst = (u16)iRes;
  2754. return 0;
  2755. }
  2756. /*
  2757. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  2758. ** It is an error if leaf iLeafPgno does not exist. Unless the db is
  2759. ** a 'secure-delete' db, if it contains no rowids then this is also an error.
  2760. */
  2761. static void fts5SegIterGotoPage(
  2762. Fts5Index *p, /* FTS5 backend object */
  2763. Fts5SegIter *pIter, /* Iterator to advance */
  2764. int iLeafPgno
  2765. ){
  2766. assert( iLeafPgno>pIter->iLeafPgno );
  2767. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  2768. p->rc = FTS5_CORRUPT;
  2769. }else{
  2770. fts5DataRelease(pIter->pNextLeaf);
  2771. pIter->pNextLeaf = 0;
  2772. pIter->iLeafPgno = iLeafPgno-1;
  2773. while( p->rc==SQLITE_OK ){
  2774. int iOff;
  2775. fts5SegIterNextPage(p, pIter);
  2776. if( pIter->pLeaf==0 ) break;
  2777. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  2778. if( iOff>0 ){
  2779. u8 *a = pIter->pLeaf->p;
  2780. int n = pIter->pLeaf->szLeaf;
  2781. if( iOff<4 || iOff>=n ){
  2782. p->rc = FTS5_CORRUPT;
  2783. }else{
  2784. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  2785. pIter->iLeafOffset = iOff;
  2786. fts5SegIterLoadNPos(p, pIter);
  2787. }
  2788. break;
  2789. }
  2790. }
  2791. }
  2792. }
  2793. /*
  2794. ** Advance the iterator passed as the second argument until it is at or
  2795. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  2796. ** always advanced at least once.
  2797. */
  2798. static void fts5SegIterNextFrom(
  2799. Fts5Index *p, /* FTS5 backend object */
  2800. Fts5SegIter *pIter, /* Iterator to advance */
  2801. i64 iMatch /* Advance iterator at least this far */
  2802. ){
  2803. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  2804. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  2805. int iLeafPgno = pIter->iLeafPgno;
  2806. int bMove = 1;
  2807. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  2808. assert( pIter->pDlidx );
  2809. assert( pIter->pLeaf );
  2810. if( bRev==0 ){
  2811. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  2812. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  2813. fts5DlidxIterNext(p, pDlidx);
  2814. }
  2815. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  2816. if( iLeafPgno>pIter->iLeafPgno ){
  2817. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  2818. bMove = 0;
  2819. }
  2820. }else{
  2821. assert( pIter->pNextLeaf==0 );
  2822. assert( iMatch<pIter->iRowid );
  2823. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  2824. fts5DlidxIterPrev(p, pDlidx);
  2825. }
  2826. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  2827. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  2828. if( iLeafPgno<pIter->iLeafPgno ){
  2829. pIter->iLeafPgno = iLeafPgno+1;
  2830. fts5SegIterReverseNewPage(p, pIter);
  2831. bMove = 0;
  2832. }
  2833. }
  2834. do{
  2835. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  2836. if( pIter->pLeaf==0 ) break;
  2837. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  2838. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  2839. bMove = 1;
  2840. }while( p->rc==SQLITE_OK );
  2841. }
  2842. /*
  2843. ** Free the iterator object passed as the second argument.
  2844. */
  2845. static void fts5MultiIterFree(Fts5Iter *pIter){
  2846. if( pIter ){
  2847. int i;
  2848. for(i=0; i<pIter->nSeg; i++){
  2849. fts5SegIterClear(&pIter->aSeg[i]);
  2850. }
  2851. fts5BufferFree(&pIter->poslist);
  2852. sqlite3_free(pIter);
  2853. }
  2854. }
  2855. static void fts5MultiIterAdvanced(
  2856. Fts5Index *p, /* FTS5 backend to iterate within */
  2857. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  2858. int iChanged, /* Index of sub-iterator just advanced */
  2859. int iMinset /* Minimum entry in aFirst[] to set */
  2860. ){
  2861. int i;
  2862. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  2863. int iEq;
  2864. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  2865. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  2866. assert( p->rc==SQLITE_OK );
  2867. pSeg->xNext(p, pSeg, 0);
  2868. i = pIter->nSeg + iEq;
  2869. }
  2870. }
  2871. }
  2872. /*
  2873. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  2874. ** points to the same term though - just a different rowid. This function
  2875. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  2876. ** If it does so successfully, 0 is returned. Otherwise 1.
  2877. **
  2878. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  2879. ** on the iterator instead. That function does the same as this one, except
  2880. ** that it deals with more complicated cases as well.
  2881. */
  2882. static int fts5MultiIterAdvanceRowid(
  2883. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  2884. int iChanged, /* Index of sub-iterator just advanced */
  2885. Fts5SegIter **ppFirst
  2886. ){
  2887. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  2888. if( pNew->iRowid==pIter->iSwitchRowid
  2889. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  2890. ){
  2891. int i;
  2892. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  2893. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  2894. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  2895. Fts5CResult *pRes = &pIter->aFirst[i];
  2896. assert( pNew->pLeaf );
  2897. assert( pRes->bTermEq==0 || pOther->pLeaf );
  2898. if( pRes->bTermEq ){
  2899. if( pNew->iRowid==pOther->iRowid ){
  2900. return 1;
  2901. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  2902. pIter->iSwitchRowid = pOther->iRowid;
  2903. pNew = pOther;
  2904. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  2905. pIter->iSwitchRowid = pOther->iRowid;
  2906. }
  2907. }
  2908. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  2909. if( i==1 ) break;
  2910. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  2911. }
  2912. }
  2913. *ppFirst = pNew;
  2914. return 0;
  2915. }
  2916. /*
  2917. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  2918. */
  2919. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  2920. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  2921. pIter->base.bEof = pSeg->pLeaf==0;
  2922. pIter->iSwitchRowid = pSeg->iRowid;
  2923. }
  2924. /*
  2925. ** The argument to this macro must be an Fts5Data structure containing a
  2926. ** tombstone hash page. This macro returns the key-size of the hash-page.
  2927. */
  2928. #define TOMBSTONE_KEYSIZE(pPg) (pPg->p[0]==4 ? 4 : 8)
  2929. #define TOMBSTONE_NSLOT(pPg) \
  2930. ((pPg->nn > 16) ? ((pPg->nn-8) / TOMBSTONE_KEYSIZE(pPg)) : 1)
  2931. /*
  2932. ** Query a single tombstone hash table for rowid iRowid. Return true if
  2933. ** it is found or false otherwise. The tombstone hash table is one of
  2934. ** nHashTable tables.
  2935. */
  2936. static int fts5IndexTombstoneQuery(
  2937. Fts5Data *pHash, /* Hash table page to query */
  2938. int nHashTable, /* Number of pages attached to segment */
  2939. u64 iRowid /* Rowid to query hash for */
  2940. ){
  2941. const int szKey = TOMBSTONE_KEYSIZE(pHash);
  2942. const int nSlot = TOMBSTONE_NSLOT(pHash);
  2943. int iSlot = (iRowid / nHashTable) % nSlot;
  2944. int nCollide = nSlot;
  2945. if( iRowid==0 ){
  2946. return pHash->p[1];
  2947. }else if( szKey==4 ){
  2948. u32 *aSlot = (u32*)&pHash->p[8];
  2949. while( aSlot[iSlot] ){
  2950. if( fts5GetU32((u8*)&aSlot[iSlot])==iRowid ) return 1;
  2951. if( nCollide--==0 ) break;
  2952. iSlot = (iSlot+1)%nSlot;
  2953. }
  2954. }else{
  2955. u64 *aSlot = (u64*)&pHash->p[8];
  2956. while( aSlot[iSlot] ){
  2957. if( fts5GetU64((u8*)&aSlot[iSlot])==iRowid ) return 1;
  2958. if( nCollide--==0 ) break;
  2959. iSlot = (iSlot+1)%nSlot;
  2960. }
  2961. }
  2962. return 0;
  2963. }
  2964. /*
  2965. ** Return true if the iterator passed as the only argument points
  2966. ** to an segment entry for which there is a tombstone. Return false
  2967. ** if there is no tombstone or if the iterator is already at EOF.
  2968. */
  2969. static int fts5MultiIterIsDeleted(Fts5Iter *pIter){
  2970. int iFirst = pIter->aFirst[1].iFirst;
  2971. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  2972. Fts5TombstoneArray *pArray = pSeg->pTombArray;
  2973. if( pSeg->pLeaf && pArray ){
  2974. /* Figure out which page the rowid might be present on. */
  2975. int iPg = ((u64)pSeg->iRowid) % pArray->nTombstone;
  2976. assert( iPg>=0 );
  2977. /* If tombstone hash page iPg has not yet been loaded from the
  2978. ** database, load it now. */
  2979. if( pArray->apTombstone[iPg]==0 ){
  2980. pArray->apTombstone[iPg] = fts5DataRead(pIter->pIndex,
  2981. FTS5_TOMBSTONE_ROWID(pSeg->pSeg->iSegid, iPg)
  2982. );
  2983. if( pArray->apTombstone[iPg]==0 ) return 0;
  2984. }
  2985. return fts5IndexTombstoneQuery(
  2986. pArray->apTombstone[iPg],
  2987. pArray->nTombstone,
  2988. pSeg->iRowid
  2989. );
  2990. }
  2991. return 0;
  2992. }
  2993. /*
  2994. ** Move the iterator to the next entry.
  2995. **
  2996. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  2997. ** considered an error if the iterator reaches EOF, or if it is already at
  2998. ** EOF when this function is called.
  2999. */
  3000. static void fts5MultiIterNext(
  3001. Fts5Index *p,
  3002. Fts5Iter *pIter,
  3003. int bFrom, /* True if argument iFrom is valid */
  3004. i64 iFrom /* Advance at least as far as this */
  3005. ){
  3006. int bUseFrom = bFrom;
  3007. assert( pIter->base.bEof==0 );
  3008. while( p->rc==SQLITE_OK ){
  3009. int iFirst = pIter->aFirst[1].iFirst;
  3010. int bNewTerm = 0;
  3011. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  3012. assert( p->rc==SQLITE_OK );
  3013. if( bUseFrom && pSeg->pDlidx ){
  3014. fts5SegIterNextFrom(p, pSeg, iFrom);
  3015. }else{
  3016. pSeg->xNext(p, pSeg, &bNewTerm);
  3017. }
  3018. if( pSeg->pLeaf==0 || bNewTerm
  3019. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  3020. ){
  3021. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  3022. fts5MultiIterSetEof(pIter);
  3023. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  3024. if( pSeg->pLeaf==0 ) return;
  3025. }
  3026. fts5AssertMultiIterSetup(p, pIter);
  3027. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  3028. if( (pIter->bSkipEmpty==0 || pSeg->nPos)
  3029. && 0==fts5MultiIterIsDeleted(pIter)
  3030. ){
  3031. pIter->xSetOutputs(pIter, pSeg);
  3032. return;
  3033. }
  3034. bUseFrom = 0;
  3035. }
  3036. }
  3037. static void fts5MultiIterNext2(
  3038. Fts5Index *p,
  3039. Fts5Iter *pIter,
  3040. int *pbNewTerm /* OUT: True if *might* be new term */
  3041. ){
  3042. assert( pIter->bSkipEmpty );
  3043. if( p->rc==SQLITE_OK ){
  3044. *pbNewTerm = 0;
  3045. do{
  3046. int iFirst = pIter->aFirst[1].iFirst;
  3047. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  3048. int bNewTerm = 0;
  3049. assert( p->rc==SQLITE_OK );
  3050. pSeg->xNext(p, pSeg, &bNewTerm);
  3051. if( pSeg->pLeaf==0 || bNewTerm
  3052. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  3053. ){
  3054. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  3055. fts5MultiIterSetEof(pIter);
  3056. *pbNewTerm = 1;
  3057. }
  3058. fts5AssertMultiIterSetup(p, pIter);
  3059. }while( (fts5MultiIterIsEmpty(p, pIter) || fts5MultiIterIsDeleted(pIter))
  3060. && (p->rc==SQLITE_OK)
  3061. );
  3062. }
  3063. }
  3064. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  3065. UNUSED_PARAM2(pUnused1, pUnused2);
  3066. }
  3067. static Fts5Iter *fts5MultiIterAlloc(
  3068. Fts5Index *p, /* FTS5 backend to iterate within */
  3069. int nSeg
  3070. ){
  3071. Fts5Iter *pNew;
  3072. i64 nSlot; /* Power of two >= nSeg */
  3073. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  3074. pNew = fts5IdxMalloc(p,
  3075. sizeof(Fts5Iter) + /* pNew */
  3076. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  3077. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  3078. );
  3079. if( pNew ){
  3080. pNew->nSeg = nSlot;
  3081. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  3082. pNew->pIndex = p;
  3083. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  3084. }
  3085. return pNew;
  3086. }
  3087. static void fts5PoslistCallback(
  3088. Fts5Index *pUnused,
  3089. void *pContext,
  3090. const u8 *pChunk, int nChunk
  3091. ){
  3092. UNUSED_PARAM(pUnused);
  3093. assert_nc( nChunk>=0 );
  3094. if( nChunk>0 ){
  3095. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  3096. }
  3097. }
  3098. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  3099. struct PoslistCallbackCtx {
  3100. Fts5Buffer *pBuf; /* Append to this buffer */
  3101. Fts5Colset *pColset; /* Restrict matches to this column */
  3102. int eState; /* See above */
  3103. };
  3104. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  3105. struct PoslistOffsetsCtx {
  3106. Fts5Buffer *pBuf; /* Append to this buffer */
  3107. Fts5Colset *pColset; /* Restrict matches to this column */
  3108. int iRead;
  3109. int iWrite;
  3110. };
  3111. /*
  3112. ** TODO: Make this more efficient!
  3113. */
  3114. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  3115. int i;
  3116. for(i=0; i<pColset->nCol; i++){
  3117. if( pColset->aiCol[i]==iCol ) return 1;
  3118. }
  3119. return 0;
  3120. }
  3121. static void fts5PoslistOffsetsCallback(
  3122. Fts5Index *pUnused,
  3123. void *pContext,
  3124. const u8 *pChunk, int nChunk
  3125. ){
  3126. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  3127. UNUSED_PARAM(pUnused);
  3128. assert_nc( nChunk>=0 );
  3129. if( nChunk>0 ){
  3130. int i = 0;
  3131. while( i<nChunk ){
  3132. int iVal;
  3133. i += fts5GetVarint32(&pChunk[i], iVal);
  3134. iVal += pCtx->iRead - 2;
  3135. pCtx->iRead = iVal;
  3136. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  3137. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  3138. pCtx->iWrite = iVal;
  3139. }
  3140. }
  3141. }
  3142. }
  3143. static void fts5PoslistFilterCallback(
  3144. Fts5Index *pUnused,
  3145. void *pContext,
  3146. const u8 *pChunk, int nChunk
  3147. ){
  3148. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  3149. UNUSED_PARAM(pUnused);
  3150. assert_nc( nChunk>=0 );
  3151. if( nChunk>0 ){
  3152. /* Search through to find the first varint with value 1. This is the
  3153. ** start of the next columns hits. */
  3154. int i = 0;
  3155. int iStart = 0;
  3156. if( pCtx->eState==2 ){
  3157. int iCol;
  3158. fts5FastGetVarint32(pChunk, i, iCol);
  3159. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  3160. pCtx->eState = 1;
  3161. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  3162. }else{
  3163. pCtx->eState = 0;
  3164. }
  3165. }
  3166. do {
  3167. while( i<nChunk && pChunk[i]!=0x01 ){
  3168. while( pChunk[i] & 0x80 ) i++;
  3169. i++;
  3170. }
  3171. if( pCtx->eState ){
  3172. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  3173. }
  3174. if( i<nChunk ){
  3175. int iCol;
  3176. iStart = i;
  3177. i++;
  3178. if( i>=nChunk ){
  3179. pCtx->eState = 2;
  3180. }else{
  3181. fts5FastGetVarint32(pChunk, i, iCol);
  3182. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  3183. if( pCtx->eState ){
  3184. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  3185. iStart = i;
  3186. }
  3187. }
  3188. }
  3189. }while( i<nChunk );
  3190. }
  3191. }
  3192. static void fts5ChunkIterate(
  3193. Fts5Index *p, /* Index object */
  3194. Fts5SegIter *pSeg, /* Poslist of this iterator */
  3195. void *pCtx, /* Context pointer for xChunk callback */
  3196. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  3197. ){
  3198. int nRem = pSeg->nPos; /* Number of bytes still to come */
  3199. Fts5Data *pData = 0;
  3200. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  3201. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  3202. int pgno = pSeg->iLeafPgno;
  3203. int pgnoSave = 0;
  3204. /* This function does not work with detail=none databases. */
  3205. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  3206. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  3207. pgnoSave = pgno+1;
  3208. }
  3209. while( 1 ){
  3210. xChunk(p, pCtx, pChunk, nChunk);
  3211. nRem -= nChunk;
  3212. fts5DataRelease(pData);
  3213. if( nRem<=0 ){
  3214. break;
  3215. }else if( pSeg->pSeg==0 ){
  3216. p->rc = FTS5_CORRUPT;
  3217. return;
  3218. }else{
  3219. pgno++;
  3220. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  3221. if( pData==0 ) break;
  3222. pChunk = &pData->p[4];
  3223. nChunk = MIN(nRem, pData->szLeaf - 4);
  3224. if( pgno==pgnoSave ){
  3225. assert( pSeg->pNextLeaf==0 );
  3226. pSeg->pNextLeaf = pData;
  3227. pData = 0;
  3228. }
  3229. }
  3230. }
  3231. }
  3232. /*
  3233. ** Iterator pIter currently points to a valid entry (not EOF). This
  3234. ** function appends the position list data for the current entry to
  3235. ** buffer pBuf. It does not make a copy of the position-list size
  3236. ** field.
  3237. */
  3238. static void fts5SegiterPoslist(
  3239. Fts5Index *p,
  3240. Fts5SegIter *pSeg,
  3241. Fts5Colset *pColset,
  3242. Fts5Buffer *pBuf
  3243. ){
  3244. assert( pBuf!=0 );
  3245. assert( pSeg!=0 );
  3246. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
  3247. assert( pBuf->p!=0 );
  3248. assert( pBuf->nSpace >= pBuf->n+pSeg->nPos+FTS5_DATA_ZERO_PADDING );
  3249. memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
  3250. if( pColset==0 ){
  3251. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  3252. }else{
  3253. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  3254. PoslistCallbackCtx sCtx;
  3255. sCtx.pBuf = pBuf;
  3256. sCtx.pColset = pColset;
  3257. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  3258. assert( sCtx.eState==0 || sCtx.eState==1 );
  3259. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  3260. }else{
  3261. PoslistOffsetsCtx sCtx;
  3262. memset(&sCtx, 0, sizeof(sCtx));
  3263. sCtx.pBuf = pBuf;
  3264. sCtx.pColset = pColset;
  3265. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  3266. }
  3267. }
  3268. }
  3269. }
  3270. /*
  3271. ** Parameter pPos points to a buffer containing a position list, size nPos.
  3272. ** This function filters it according to pColset (which must be non-NULL)
  3273. ** and sets pIter->base.pData/nData to point to the new position list.
  3274. ** If memory is required for the new position list, use buffer pIter->poslist.
  3275. ** Or, if the new position list is a contiguous subset of the input, set
  3276. ** pIter->base.pData/nData to point directly to it.
  3277. **
  3278. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  3279. ** called. If an OOM error is encountered, *pRc is set to SQLITE_NOMEM
  3280. ** before returning.
  3281. */
  3282. static void fts5IndexExtractColset(
  3283. int *pRc,
  3284. Fts5Colset *pColset, /* Colset to filter on */
  3285. const u8 *pPos, int nPos, /* Position list */
  3286. Fts5Iter *pIter
  3287. ){
  3288. if( *pRc==SQLITE_OK ){
  3289. const u8 *p = pPos;
  3290. const u8 *aCopy = p;
  3291. const u8 *pEnd = &p[nPos]; /* One byte past end of position list */
  3292. int i = 0;
  3293. int iCurrent = 0;
  3294. if( pColset->nCol>1 && sqlite3Fts5BufferSize(pRc, &pIter->poslist, nPos) ){
  3295. return;
  3296. }
  3297. while( 1 ){
  3298. while( pColset->aiCol[i]<iCurrent ){
  3299. i++;
  3300. if( i==pColset->nCol ){
  3301. pIter->base.pData = pIter->poslist.p;
  3302. pIter->base.nData = pIter->poslist.n;
  3303. return;
  3304. }
  3305. }
  3306. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  3307. ** not part of a varint */
  3308. while( p<pEnd && *p!=0x01 ){
  3309. while( *p++ & 0x80 );
  3310. }
  3311. if( pColset->aiCol[i]==iCurrent ){
  3312. if( pColset->nCol==1 ){
  3313. pIter->base.pData = aCopy;
  3314. pIter->base.nData = p-aCopy;
  3315. return;
  3316. }
  3317. fts5BufferSafeAppendBlob(&pIter->poslist, aCopy, p-aCopy);
  3318. }
  3319. if( p>=pEnd ){
  3320. pIter->base.pData = pIter->poslist.p;
  3321. pIter->base.nData = pIter->poslist.n;
  3322. return;
  3323. }
  3324. aCopy = p++;
  3325. iCurrent = *p++;
  3326. if( iCurrent & 0x80 ){
  3327. p--;
  3328. p += fts5GetVarint32(p, iCurrent);
  3329. }
  3330. }
  3331. }
  3332. }
  3333. /*
  3334. ** xSetOutputs callback used by detail=none tables.
  3335. */
  3336. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3337. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  3338. pIter->base.iRowid = pSeg->iRowid;
  3339. pIter->base.nData = pSeg->nPos;
  3340. }
  3341. /*
  3342. ** xSetOutputs callback used by detail=full and detail=col tables when no
  3343. ** column filters are specified.
  3344. */
  3345. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3346. pIter->base.iRowid = pSeg->iRowid;
  3347. pIter->base.nData = pSeg->nPos;
  3348. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  3349. assert( pIter->pColset==0 );
  3350. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  3351. /* All data is stored on the current page. Populate the output
  3352. ** variables to point into the body of the page object. */
  3353. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  3354. }else{
  3355. /* The data is distributed over two or more pages. Copy it into the
  3356. ** Fts5Iter.poslist buffer and then set the output pointer to point
  3357. ** to this buffer. */
  3358. fts5BufferZero(&pIter->poslist);
  3359. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  3360. pIter->base.pData = pIter->poslist.p;
  3361. }
  3362. }
  3363. /*
  3364. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  3365. ** against no columns at all).
  3366. */
  3367. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3368. UNUSED_PARAM(pSeg);
  3369. pIter->base.nData = 0;
  3370. }
  3371. /*
  3372. ** xSetOutputs callback used by detail=col when there is a column filter
  3373. ** and there are 100 or more columns. Also called as a fallback from
  3374. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  3375. */
  3376. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3377. fts5BufferZero(&pIter->poslist);
  3378. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  3379. pIter->base.iRowid = pSeg->iRowid;
  3380. pIter->base.pData = pIter->poslist.p;
  3381. pIter->base.nData = pIter->poslist.n;
  3382. }
  3383. /*
  3384. ** xSetOutputs callback used when:
  3385. **
  3386. ** * detail=col,
  3387. ** * there is a column filter, and
  3388. ** * the table contains 100 or fewer columns.
  3389. **
  3390. ** The last point is to ensure all column numbers are stored as
  3391. ** single-byte varints.
  3392. */
  3393. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3394. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  3395. assert( pIter->pColset );
  3396. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  3397. fts5IterSetOutputs_Col(pIter, pSeg);
  3398. }else{
  3399. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  3400. u8 *pEnd = (u8*)&a[pSeg->nPos];
  3401. int iPrev = 0;
  3402. int *aiCol = pIter->pColset->aiCol;
  3403. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  3404. u8 *aOut = pIter->poslist.p;
  3405. int iPrevOut = 0;
  3406. pIter->base.iRowid = pSeg->iRowid;
  3407. while( a<pEnd ){
  3408. iPrev += (int)a++[0] - 2;
  3409. while( *aiCol<iPrev ){
  3410. aiCol++;
  3411. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  3412. }
  3413. if( *aiCol==iPrev ){
  3414. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  3415. iPrevOut = iPrev;
  3416. }
  3417. }
  3418. setoutputs_col_out:
  3419. pIter->base.pData = pIter->poslist.p;
  3420. pIter->base.nData = aOut - pIter->poslist.p;
  3421. }
  3422. }
  3423. /*
  3424. ** xSetOutputs callback used by detail=full when there is a column filter.
  3425. */
  3426. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  3427. Fts5Colset *pColset = pIter->pColset;
  3428. pIter->base.iRowid = pSeg->iRowid;
  3429. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  3430. assert( pColset );
  3431. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  3432. /* All data is stored on the current page. Populate the output
  3433. ** variables to point into the body of the page object. */
  3434. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  3435. int *pRc = &pIter->pIndex->rc;
  3436. fts5BufferZero(&pIter->poslist);
  3437. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, pIter);
  3438. }else{
  3439. /* The data is distributed over two or more pages. Copy it into the
  3440. ** Fts5Iter.poslist buffer and then set the output pointer to point
  3441. ** to this buffer. */
  3442. fts5BufferZero(&pIter->poslist);
  3443. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  3444. pIter->base.pData = pIter->poslist.p;
  3445. pIter->base.nData = pIter->poslist.n;
  3446. }
  3447. }
  3448. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  3449. assert( pIter!=0 || (*pRc)!=SQLITE_OK );
  3450. if( *pRc==SQLITE_OK ){
  3451. Fts5Config *pConfig = pIter->pIndex->pConfig;
  3452. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  3453. pIter->xSetOutputs = fts5IterSetOutputs_None;
  3454. }
  3455. else if( pIter->pColset==0 ){
  3456. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  3457. }
  3458. else if( pIter->pColset->nCol==0 ){
  3459. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  3460. }
  3461. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  3462. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  3463. }
  3464. else{
  3465. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  3466. if( pConfig->nCol<=100 ){
  3467. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  3468. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  3469. }else{
  3470. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  3471. }
  3472. }
  3473. }
  3474. }
  3475. /*
  3476. ** All the component segment-iterators of pIter have been set up. This
  3477. ** functions finishes setup for iterator pIter itself.
  3478. */
  3479. static void fts5MultiIterFinishSetup(Fts5Index *p, Fts5Iter *pIter){
  3480. int iIter;
  3481. for(iIter=pIter->nSeg-1; iIter>0; iIter--){
  3482. int iEq;
  3483. if( (iEq = fts5MultiIterDoCompare(pIter, iIter)) ){
  3484. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  3485. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  3486. fts5MultiIterAdvanced(p, pIter, iEq, iIter);
  3487. }
  3488. }
  3489. fts5MultiIterSetEof(pIter);
  3490. fts5AssertMultiIterSetup(p, pIter);
  3491. if( (pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter))
  3492. || fts5MultiIterIsDeleted(pIter)
  3493. ){
  3494. fts5MultiIterNext(p, pIter, 0, 0);
  3495. }else if( pIter->base.bEof==0 ){
  3496. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  3497. pIter->xSetOutputs(pIter, pSeg);
  3498. }
  3499. }
  3500. /*
  3501. ** Allocate a new Fts5Iter object.
  3502. **
  3503. ** The new object will be used to iterate through data in structure pStruct.
  3504. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  3505. ** is zero or greater, data from the first nSegment segments on level iLevel
  3506. ** is merged.
  3507. **
  3508. ** The iterator initially points to the first term/rowid entry in the
  3509. ** iterated data.
  3510. */
  3511. static void fts5MultiIterNew(
  3512. Fts5Index *p, /* FTS5 backend to iterate within */
  3513. Fts5Structure *pStruct, /* Structure of specific index */
  3514. int flags, /* FTS5INDEX_QUERY_XXX flags */
  3515. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  3516. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  3517. int iLevel, /* Level to iterate (-1 for all) */
  3518. int nSegment, /* Number of segments to merge (iLevel>=0) */
  3519. Fts5Iter **ppOut /* New object */
  3520. ){
  3521. int nSeg = 0; /* Number of segment-iters in use */
  3522. int iIter = 0; /* */
  3523. int iSeg; /* Used to iterate through segments */
  3524. Fts5StructureLevel *pLvl;
  3525. Fts5Iter *pNew;
  3526. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  3527. /* Allocate space for the new multi-seg-iterator. */
  3528. if( p->rc==SQLITE_OK ){
  3529. if( iLevel<0 ){
  3530. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  3531. nSeg = pStruct->nSegment;
  3532. nSeg += (p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH));
  3533. }else{
  3534. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  3535. }
  3536. }
  3537. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  3538. if( pNew==0 ){
  3539. assert( p->rc!=SQLITE_OK );
  3540. goto fts5MultiIterNew_post_check;
  3541. }
  3542. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  3543. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  3544. pNew->pColset = pColset;
  3545. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  3546. fts5IterSetOutputCb(&p->rc, pNew);
  3547. }
  3548. /* Initialize each of the component segment iterators. */
  3549. if( p->rc==SQLITE_OK ){
  3550. if( iLevel<0 ){
  3551. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  3552. if( p->pHash && 0==(flags & FTS5INDEX_QUERY_SKIPHASH) ){
  3553. /* Add a segment iterator for the current contents of the hash table. */
  3554. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  3555. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  3556. }
  3557. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  3558. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  3559. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  3560. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  3561. if( pTerm==0 ){
  3562. fts5SegIterInit(p, pSeg, pIter);
  3563. }else{
  3564. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  3565. }
  3566. }
  3567. }
  3568. }else{
  3569. pLvl = &pStruct->aLevel[iLevel];
  3570. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  3571. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  3572. }
  3573. }
  3574. assert( iIter==nSeg );
  3575. }
  3576. /* If the above was successful, each component iterator now points
  3577. ** to the first entry in its segment. In this case initialize the
  3578. ** aFirst[] array. Or, if an error has occurred, free the iterator
  3579. ** object and set the output variable to NULL. */
  3580. if( p->rc==SQLITE_OK ){
  3581. fts5MultiIterFinishSetup(p, pNew);
  3582. }else{
  3583. fts5MultiIterFree(pNew);
  3584. *ppOut = 0;
  3585. }
  3586. fts5MultiIterNew_post_check:
  3587. assert( (*ppOut)!=0 || p->rc!=SQLITE_OK );
  3588. return;
  3589. }
  3590. /*
  3591. ** Create an Fts5Iter that iterates through the doclist provided
  3592. ** as the second argument.
  3593. */
  3594. static void fts5MultiIterNew2(
  3595. Fts5Index *p, /* FTS5 backend to iterate within */
  3596. Fts5Data *pData, /* Doclist to iterate through */
  3597. int bDesc, /* True for descending rowid order */
  3598. Fts5Iter **ppOut /* New object */
  3599. ){
  3600. Fts5Iter *pNew;
  3601. pNew = fts5MultiIterAlloc(p, 2);
  3602. if( pNew ){
  3603. Fts5SegIter *pIter = &pNew->aSeg[1];
  3604. pIter->flags = FTS5_SEGITER_ONETERM;
  3605. if( pData->szLeaf>0 ){
  3606. pIter->pLeaf = pData;
  3607. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  3608. pIter->iEndofDoclist = pData->nn;
  3609. pNew->aFirst[1].iFirst = 1;
  3610. if( bDesc ){
  3611. pNew->bRev = 1;
  3612. pIter->flags |= FTS5_SEGITER_REVERSE;
  3613. fts5SegIterReverseInitPage(p, pIter);
  3614. }else{
  3615. fts5SegIterLoadNPos(p, pIter);
  3616. }
  3617. pData = 0;
  3618. }else{
  3619. pNew->base.bEof = 1;
  3620. }
  3621. fts5SegIterSetNext(p, pIter);
  3622. *ppOut = pNew;
  3623. }
  3624. fts5DataRelease(pData);
  3625. }
  3626. /*
  3627. ** Return true if the iterator is at EOF or if an error has occurred.
  3628. ** False otherwise.
  3629. */
  3630. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  3631. assert( pIter!=0 || p->rc!=SQLITE_OK );
  3632. assert( p->rc!=SQLITE_OK
  3633. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  3634. );
  3635. return (p->rc || pIter->base.bEof);
  3636. }
  3637. /*
  3638. ** Return the rowid of the entry that the iterator currently points
  3639. ** to. If the iterator points to EOF when this function is called the
  3640. ** results are undefined.
  3641. */
  3642. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  3643. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  3644. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  3645. }
  3646. /*
  3647. ** Move the iterator to the next entry at or following iMatch.
  3648. */
  3649. static void fts5MultiIterNextFrom(
  3650. Fts5Index *p,
  3651. Fts5Iter *pIter,
  3652. i64 iMatch
  3653. ){
  3654. while( 1 ){
  3655. i64 iRowid;
  3656. fts5MultiIterNext(p, pIter, 1, iMatch);
  3657. if( fts5MultiIterEof(p, pIter) ) break;
  3658. iRowid = fts5MultiIterRowid(pIter);
  3659. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  3660. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  3661. }
  3662. }
  3663. /*
  3664. ** Return a pointer to a buffer containing the term associated with the
  3665. ** entry that the iterator currently points to.
  3666. */
  3667. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  3668. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  3669. *pn = p->term.n;
  3670. return p->term.p;
  3671. }
  3672. /*
  3673. ** Allocate a new segment-id for the structure pStruct. The new segment
  3674. ** id must be between 1 and 65335 inclusive, and must not be used by
  3675. ** any currently existing segment. If a free segment id cannot be found,
  3676. ** SQLITE_FULL is returned.
  3677. **
  3678. ** If an error has already occurred, this function is a no-op. 0 is
  3679. ** returned in this case.
  3680. */
  3681. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  3682. int iSegid = 0;
  3683. if( p->rc==SQLITE_OK ){
  3684. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  3685. p->rc = SQLITE_FULL;
  3686. }else{
  3687. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  3688. ** array is 63 elements, or 252 bytes, in size. */
  3689. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  3690. int iLvl, iSeg;
  3691. int i;
  3692. u32 mask;
  3693. memset(aUsed, 0, sizeof(aUsed));
  3694. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  3695. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  3696. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  3697. if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
  3698. aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
  3699. }
  3700. }
  3701. }
  3702. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  3703. mask = aUsed[i];
  3704. for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
  3705. iSegid += 1 + i*32;
  3706. #ifdef SQLITE_DEBUG
  3707. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  3708. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  3709. assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  3710. }
  3711. }
  3712. assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  3713. {
  3714. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  3715. if( p->rc==SQLITE_OK ){
  3716. u8 aBlob[2] = {0xff, 0xff};
  3717. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  3718. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  3719. assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  3720. p->rc = sqlite3_reset(pIdxSelect);
  3721. sqlite3_bind_null(pIdxSelect, 2);
  3722. }
  3723. }
  3724. #endif
  3725. }
  3726. }
  3727. return iSegid;
  3728. }
  3729. /*
  3730. ** Discard all data currently cached in the hash-tables.
  3731. */
  3732. static void fts5IndexDiscardData(Fts5Index *p){
  3733. assert( p->pHash || p->nPendingData==0 );
  3734. if( p->pHash ){
  3735. sqlite3Fts5HashClear(p->pHash);
  3736. p->nPendingData = 0;
  3737. p->nPendingRow = 0;
  3738. p->flushRc = SQLITE_OK;
  3739. }
  3740. p->nContentlessDelete = 0;
  3741. }
  3742. /*
  3743. ** Return the size of the prefix, in bytes, that buffer
  3744. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  3745. **
  3746. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  3747. ** than buffer (pOld/nOld).
  3748. */
  3749. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  3750. int i;
  3751. for(i=0; i<nOld; i++){
  3752. if( pOld[i]!=pNew[i] ) break;
  3753. }
  3754. return i;
  3755. }
  3756. static void fts5WriteDlidxClear(
  3757. Fts5Index *p,
  3758. Fts5SegWriter *pWriter,
  3759. int bFlush /* If true, write dlidx to disk */
  3760. ){
  3761. int i;
  3762. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  3763. for(i=0; i<pWriter->nDlidx; i++){
  3764. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  3765. if( pDlidx->buf.n==0 ) break;
  3766. if( bFlush ){
  3767. assert( pDlidx->pgno!=0 );
  3768. fts5DataWrite(p,
  3769. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  3770. pDlidx->buf.p, pDlidx->buf.n
  3771. );
  3772. }
  3773. sqlite3Fts5BufferZero(&pDlidx->buf);
  3774. pDlidx->bPrevValid = 0;
  3775. }
  3776. }
  3777. /*
  3778. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  3779. ** Any new array elements are zeroed before returning.
  3780. */
  3781. static int fts5WriteDlidxGrow(
  3782. Fts5Index *p,
  3783. Fts5SegWriter *pWriter,
  3784. int nLvl
  3785. ){
  3786. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  3787. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
  3788. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  3789. );
  3790. if( aDlidx==0 ){
  3791. p->rc = SQLITE_NOMEM;
  3792. }else{
  3793. size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  3794. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  3795. pWriter->aDlidx = aDlidx;
  3796. pWriter->nDlidx = nLvl;
  3797. }
  3798. }
  3799. return p->rc;
  3800. }
  3801. /*
  3802. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  3803. ** enough, flush it to disk and return 1. Otherwise discard it and return
  3804. ** zero.
  3805. */
  3806. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  3807. int bFlag = 0;
  3808. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  3809. ** to the database, also write the doclist-index to disk. */
  3810. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  3811. bFlag = 1;
  3812. }
  3813. fts5WriteDlidxClear(p, pWriter, bFlag);
  3814. pWriter->nEmpty = 0;
  3815. return bFlag;
  3816. }
  3817. /*
  3818. ** This function is called whenever processing of the doclist for the
  3819. ** last term on leaf page (pWriter->iBtPage) is completed.
  3820. **
  3821. ** The doclist-index for that term is currently stored in-memory within the
  3822. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  3823. ** writes it out to disk. Or, if it is too small to bother with, discards
  3824. ** it.
  3825. **
  3826. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  3827. */
  3828. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  3829. int bFlag;
  3830. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  3831. if( pWriter->iBtPage==0 ) return;
  3832. bFlag = fts5WriteFlushDlidx(p, pWriter);
  3833. if( p->rc==SQLITE_OK ){
  3834. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  3835. /* The following was already done in fts5WriteInit(): */
  3836. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  3837. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  3838. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  3839. sqlite3_step(p->pIdxWriter);
  3840. p->rc = sqlite3_reset(p->pIdxWriter);
  3841. sqlite3_bind_null(p->pIdxWriter, 2);
  3842. }
  3843. pWriter->iBtPage = 0;
  3844. }
  3845. /*
  3846. ** This is called once for each leaf page except the first that contains
  3847. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  3848. ** is larger than all terms written to earlier leaves, and equal to or
  3849. ** smaller than the first term on the new leaf.
  3850. **
  3851. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  3852. ** has already occurred when this function is called, it is a no-op.
  3853. */
  3854. static void fts5WriteBtreeTerm(
  3855. Fts5Index *p, /* FTS5 backend object */
  3856. Fts5SegWriter *pWriter, /* Writer object */
  3857. int nTerm, const u8 *pTerm /* First term on new page */
  3858. ){
  3859. fts5WriteFlushBtree(p, pWriter);
  3860. if( p->rc==SQLITE_OK ){
  3861. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  3862. pWriter->iBtPage = pWriter->writer.pgno;
  3863. }
  3864. }
  3865. /*
  3866. ** This function is called when flushing a leaf page that contains no
  3867. ** terms at all to disk.
  3868. */
  3869. static void fts5WriteBtreeNoTerm(
  3870. Fts5Index *p, /* FTS5 backend object */
  3871. Fts5SegWriter *pWriter /* Writer object */
  3872. ){
  3873. /* If there were no rowids on the leaf page either and the doclist-index
  3874. ** has already been started, append an 0x00 byte to it. */
  3875. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  3876. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  3877. assert( pDlidx->bPrevValid );
  3878. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  3879. }
  3880. /* Increment the "number of sequential leaves without a term" counter. */
  3881. pWriter->nEmpty++;
  3882. }
  3883. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  3884. i64 iRowid;
  3885. int iOff;
  3886. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  3887. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  3888. return iRowid;
  3889. }
  3890. /*
  3891. ** Rowid iRowid has just been appended to the current leaf page. It is the
  3892. ** first on the page. This function appends an appropriate entry to the current
  3893. ** doclist-index.
  3894. */
  3895. static void fts5WriteDlidxAppend(
  3896. Fts5Index *p,
  3897. Fts5SegWriter *pWriter,
  3898. i64 iRowid
  3899. ){
  3900. int i;
  3901. int bDone = 0;
  3902. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  3903. i64 iVal;
  3904. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  3905. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  3906. /* The current doclist-index page is full. Write it to disk and push
  3907. ** a copy of iRowid (which will become the first rowid on the next
  3908. ** doclist-index leaf page) up into the next level of the b-tree
  3909. ** hierarchy. If the node being flushed is currently the root node,
  3910. ** also push its first rowid upwards. */
  3911. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  3912. fts5DataWrite(p,
  3913. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  3914. pDlidx->buf.p, pDlidx->buf.n
  3915. );
  3916. fts5WriteDlidxGrow(p, pWriter, i+2);
  3917. pDlidx = &pWriter->aDlidx[i];
  3918. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  3919. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  3920. /* This was the root node. Push its first rowid up to the new root. */
  3921. pDlidx[1].pgno = pDlidx->pgno;
  3922. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  3923. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  3924. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  3925. pDlidx[1].bPrevValid = 1;
  3926. pDlidx[1].iPrev = iFirst;
  3927. }
  3928. sqlite3Fts5BufferZero(&pDlidx->buf);
  3929. pDlidx->bPrevValid = 0;
  3930. pDlidx->pgno++;
  3931. }else{
  3932. bDone = 1;
  3933. }
  3934. if( pDlidx->bPrevValid ){
  3935. iVal = (u64)iRowid - (u64)pDlidx->iPrev;
  3936. }else{
  3937. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  3938. assert( pDlidx->buf.n==0 );
  3939. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  3940. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  3941. iVal = iRowid;
  3942. }
  3943. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  3944. pDlidx->bPrevValid = 1;
  3945. pDlidx->iPrev = iRowid;
  3946. }
  3947. }
  3948. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  3949. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  3950. Fts5PageWriter *pPage = &pWriter->writer;
  3951. i64 iRowid;
  3952. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  3953. /* Set the szLeaf header field. */
  3954. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  3955. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  3956. if( pWriter->bFirstTermInPage ){
  3957. /* No term was written to this page. */
  3958. assert( pPage->pgidx.n==0 );
  3959. fts5WriteBtreeNoTerm(p, pWriter);
  3960. }else{
  3961. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  3962. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  3963. }
  3964. /* Write the page out to disk */
  3965. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  3966. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  3967. /* Initialize the next page. */
  3968. fts5BufferZero(&pPage->buf);
  3969. fts5BufferZero(&pPage->pgidx);
  3970. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  3971. pPage->iPrevPgidx = 0;
  3972. pPage->pgno++;
  3973. /* Increase the leaves written counter */
  3974. pWriter->nLeafWritten++;
  3975. /* The new leaf holds no terms or rowids */
  3976. pWriter->bFirstTermInPage = 1;
  3977. pWriter->bFirstRowidInPage = 1;
  3978. }
  3979. /*
  3980. ** Append term pTerm/nTerm to the segment being written by the writer passed
  3981. ** as the second argument.
  3982. **
  3983. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  3984. ** already occurred, this function is a no-op.
  3985. */
  3986. static void fts5WriteAppendTerm(
  3987. Fts5Index *p,
  3988. Fts5SegWriter *pWriter,
  3989. int nTerm, const u8 *pTerm
  3990. ){
  3991. int nPrefix; /* Bytes of prefix compression for term */
  3992. Fts5PageWriter *pPage = &pWriter->writer;
  3993. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  3994. int nMin = MIN(pPage->term.n, nTerm);
  3995. assert( p->rc==SQLITE_OK );
  3996. assert( pPage->buf.n>=4 );
  3997. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  3998. /* If the current leaf page is full, flush it to disk. */
  3999. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  4000. if( pPage->buf.n>4 ){
  4001. fts5WriteFlushLeaf(p, pWriter);
  4002. if( p->rc!=SQLITE_OK ) return;
  4003. }
  4004. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  4005. }
  4006. /* TODO1: Updating pgidx here. */
  4007. pPgidx->n += sqlite3Fts5PutVarint(
  4008. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  4009. );
  4010. pPage->iPrevPgidx = pPage->buf.n;
  4011. #if 0
  4012. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  4013. pPgidx->n += 2;
  4014. #endif
  4015. if( pWriter->bFirstTermInPage ){
  4016. nPrefix = 0;
  4017. if( pPage->pgno!=1 ){
  4018. /* This is the first term on a leaf that is not the leftmost leaf in
  4019. ** the segment b-tree. In this case it is necessary to add a term to
  4020. ** the b-tree hierarchy that is (a) larger than the largest term
  4021. ** already written to the segment and (b) smaller than or equal to
  4022. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  4023. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  4024. ** previous term.
  4025. **
  4026. ** Usually, the previous term is available in pPage->term. The exception
  4027. ** is if this is the first term written in an incremental-merge step.
  4028. ** In this case the previous term is not available, so just write a
  4029. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  4030. ** inefficient, but still correct. */
  4031. int n = nTerm;
  4032. if( pPage->term.n ){
  4033. n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  4034. }
  4035. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  4036. if( p->rc!=SQLITE_OK ) return;
  4037. pPage = &pWriter->writer;
  4038. }
  4039. }else{
  4040. nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  4041. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  4042. }
  4043. /* Append the number of bytes of new data, then the term data itself
  4044. ** to the page. */
  4045. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  4046. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  4047. /* Update the Fts5PageWriter.term field. */
  4048. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  4049. pWriter->bFirstTermInPage = 0;
  4050. pWriter->bFirstRowidInPage = 0;
  4051. pWriter->bFirstRowidInDoclist = 1;
  4052. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  4053. pWriter->aDlidx[0].pgno = pPage->pgno;
  4054. }
  4055. /*
  4056. ** Append a rowid and position-list size field to the writers output.
  4057. */
  4058. static void fts5WriteAppendRowid(
  4059. Fts5Index *p,
  4060. Fts5SegWriter *pWriter,
  4061. i64 iRowid
  4062. ){
  4063. if( p->rc==SQLITE_OK ){
  4064. Fts5PageWriter *pPage = &pWriter->writer;
  4065. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  4066. fts5WriteFlushLeaf(p, pWriter);
  4067. }
  4068. /* If this is to be the first rowid written to the page, set the
  4069. ** rowid-pointer in the page-header. Also append a value to the dlidx
  4070. ** buffer, in case a doclist-index is required. */
  4071. if( pWriter->bFirstRowidInPage ){
  4072. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  4073. fts5WriteDlidxAppend(p, pWriter, iRowid);
  4074. }
  4075. /* Write the rowid. */
  4076. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  4077. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  4078. }else{
  4079. assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
  4080. fts5BufferAppendVarint(&p->rc, &pPage->buf,
  4081. (u64)iRowid - (u64)pWriter->iPrevRowid
  4082. );
  4083. }
  4084. pWriter->iPrevRowid = iRowid;
  4085. pWriter->bFirstRowidInDoclist = 0;
  4086. pWriter->bFirstRowidInPage = 0;
  4087. }
  4088. }
  4089. static void fts5WriteAppendPoslistData(
  4090. Fts5Index *p,
  4091. Fts5SegWriter *pWriter,
  4092. const u8 *aData,
  4093. int nData
  4094. ){
  4095. Fts5PageWriter *pPage = &pWriter->writer;
  4096. const u8 *a = aData;
  4097. int n = nData;
  4098. assert( p->pConfig->pgsz>0 || p->rc!=SQLITE_OK );
  4099. while( p->rc==SQLITE_OK
  4100. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  4101. ){
  4102. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  4103. int nCopy = 0;
  4104. while( nCopy<nReq ){
  4105. i64 dummy;
  4106. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  4107. }
  4108. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  4109. a += nCopy;
  4110. n -= nCopy;
  4111. fts5WriteFlushLeaf(p, pWriter);
  4112. }
  4113. if( n>0 ){
  4114. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  4115. }
  4116. }
  4117. /*
  4118. ** Flush any data cached by the writer object to the database. Free any
  4119. ** allocations associated with the writer.
  4120. */
  4121. static void fts5WriteFinish(
  4122. Fts5Index *p,
  4123. Fts5SegWriter *pWriter, /* Writer object */
  4124. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  4125. ){
  4126. int i;
  4127. Fts5PageWriter *pLeaf = &pWriter->writer;
  4128. if( p->rc==SQLITE_OK ){
  4129. assert( pLeaf->pgno>=1 );
  4130. if( pLeaf->buf.n>4 ){
  4131. fts5WriteFlushLeaf(p, pWriter);
  4132. }
  4133. *pnLeaf = pLeaf->pgno-1;
  4134. if( pLeaf->pgno>1 ){
  4135. fts5WriteFlushBtree(p, pWriter);
  4136. }
  4137. }
  4138. fts5BufferFree(&pLeaf->term);
  4139. fts5BufferFree(&pLeaf->buf);
  4140. fts5BufferFree(&pLeaf->pgidx);
  4141. fts5BufferFree(&pWriter->btterm);
  4142. for(i=0; i<pWriter->nDlidx; i++){
  4143. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  4144. }
  4145. sqlite3_free(pWriter->aDlidx);
  4146. }
  4147. static void fts5WriteInit(
  4148. Fts5Index *p,
  4149. Fts5SegWriter *pWriter,
  4150. int iSegid
  4151. ){
  4152. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  4153. memset(pWriter, 0, sizeof(Fts5SegWriter));
  4154. pWriter->iSegid = iSegid;
  4155. fts5WriteDlidxGrow(p, pWriter, 1);
  4156. pWriter->writer.pgno = 1;
  4157. pWriter->bFirstTermInPage = 1;
  4158. pWriter->iBtPage = 1;
  4159. assert( pWriter->writer.buf.n==0 );
  4160. assert( pWriter->writer.pgidx.n==0 );
  4161. /* Grow the two buffers to pgsz + padding bytes in size. */
  4162. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  4163. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  4164. if( p->pIdxWriter==0 ){
  4165. Fts5Config *pConfig = p->pConfig;
  4166. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  4167. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  4168. pConfig->zDb, pConfig->zName
  4169. ));
  4170. }
  4171. if( p->rc==SQLITE_OK ){
  4172. /* Initialize the 4-byte leaf-page header to 0x00. */
  4173. memset(pWriter->writer.buf.p, 0, 4);
  4174. pWriter->writer.buf.n = 4;
  4175. /* Bind the current output segment id to the index-writer. This is an
  4176. ** optimization over binding the same value over and over as rows are
  4177. ** inserted into %_idx by the current writer. */
  4178. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  4179. }
  4180. }
  4181. /*
  4182. ** Iterator pIter was used to iterate through the input segments of on an
  4183. ** incremental merge operation. This function is called if the incremental
  4184. ** merge step has finished but the input has not been completely exhausted.
  4185. */
  4186. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  4187. int i;
  4188. Fts5Buffer buf;
  4189. memset(&buf, 0, sizeof(Fts5Buffer));
  4190. for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
  4191. Fts5SegIter *pSeg = &pIter->aSeg[i];
  4192. if( pSeg->pSeg==0 ){
  4193. /* no-op */
  4194. }else if( pSeg->pLeaf==0 ){
  4195. /* All keys from this input segment have been transfered to the output.
  4196. ** Set both the first and last page-numbers to 0 to indicate that the
  4197. ** segment is now empty. */
  4198. pSeg->pSeg->pgnoLast = 0;
  4199. pSeg->pSeg->pgnoFirst = 0;
  4200. }else{
  4201. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  4202. i64 iLeafRowid;
  4203. Fts5Data *pData;
  4204. int iId = pSeg->pSeg->iSegid;
  4205. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  4206. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  4207. pData = fts5LeafRead(p, iLeafRowid);
  4208. if( pData ){
  4209. if( iOff>pData->szLeaf ){
  4210. /* This can occur if the pages that the segments occupy overlap - if
  4211. ** a single page has been assigned to more than one segment. In
  4212. ** this case a prior iteration of this loop may have corrupted the
  4213. ** segment currently being trimmed. */
  4214. p->rc = FTS5_CORRUPT;
  4215. }else{
  4216. fts5BufferZero(&buf);
  4217. fts5BufferGrow(&p->rc, &buf, pData->nn);
  4218. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  4219. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  4220. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  4221. fts5BufferAppendBlob(&p->rc, &buf,pData->szLeaf-iOff,&pData->p[iOff]);
  4222. if( p->rc==SQLITE_OK ){
  4223. /* Set the szLeaf field */
  4224. fts5PutU16(&buf.p[2], (u16)buf.n);
  4225. }
  4226. /* Set up the new page-index array */
  4227. fts5BufferAppendVarint(&p->rc, &buf, 4);
  4228. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  4229. && pSeg->iEndofDoclist<pData->szLeaf
  4230. && pSeg->iPgidxOff<=pData->nn
  4231. ){
  4232. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  4233. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  4234. fts5BufferAppendBlob(&p->rc, &buf,
  4235. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  4236. );
  4237. }
  4238. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  4239. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  4240. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  4241. }
  4242. fts5DataRelease(pData);
  4243. }
  4244. }
  4245. }
  4246. fts5BufferFree(&buf);
  4247. }
  4248. static void fts5MergeChunkCallback(
  4249. Fts5Index *p,
  4250. void *pCtx,
  4251. const u8 *pChunk, int nChunk
  4252. ){
  4253. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  4254. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  4255. }
  4256. /*
  4257. **
  4258. */
  4259. static void fts5IndexMergeLevel(
  4260. Fts5Index *p, /* FTS5 backend object */
  4261. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  4262. int iLvl, /* Level to read input from */
  4263. int *pnRem /* Write up to this many output leaves */
  4264. ){
  4265. Fts5Structure *pStruct = *ppStruct;
  4266. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  4267. Fts5StructureLevel *pLvlOut;
  4268. Fts5Iter *pIter = 0; /* Iterator to read input data */
  4269. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  4270. int nInput; /* Number of input segments */
  4271. Fts5SegWriter writer; /* Writer object */
  4272. Fts5StructureSegment *pSeg; /* Output segment */
  4273. Fts5Buffer term;
  4274. int bOldest; /* True if the output segment is the oldest */
  4275. int eDetail = p->pConfig->eDetail;
  4276. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  4277. int bTermWritten = 0; /* True if current term already output */
  4278. assert( iLvl<pStruct->nLevel );
  4279. assert( pLvl->nMerge<=pLvl->nSeg );
  4280. memset(&writer, 0, sizeof(Fts5SegWriter));
  4281. memset(&term, 0, sizeof(Fts5Buffer));
  4282. if( pLvl->nMerge ){
  4283. pLvlOut = &pStruct->aLevel[iLvl+1];
  4284. assert( pLvlOut->nSeg>0 );
  4285. nInput = pLvl->nMerge;
  4286. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  4287. fts5WriteInit(p, &writer, pSeg->iSegid);
  4288. writer.writer.pgno = pSeg->pgnoLast+1;
  4289. writer.iBtPage = 0;
  4290. }else{
  4291. int iSegid = fts5AllocateSegid(p, pStruct);
  4292. /* Extend the Fts5Structure object as required to ensure the output
  4293. ** segment exists. */
  4294. if( iLvl==pStruct->nLevel-1 ){
  4295. fts5StructureAddLevel(&p->rc, ppStruct);
  4296. pStruct = *ppStruct;
  4297. }
  4298. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  4299. if( p->rc ) return;
  4300. pLvl = &pStruct->aLevel[iLvl];
  4301. pLvlOut = &pStruct->aLevel[iLvl+1];
  4302. fts5WriteInit(p, &writer, iSegid);
  4303. /* Add the new segment to the output level */
  4304. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  4305. pLvlOut->nSeg++;
  4306. pSeg->pgnoFirst = 1;
  4307. pSeg->iSegid = iSegid;
  4308. pStruct->nSegment++;
  4309. /* Read input from all segments in the input level */
  4310. nInput = pLvl->nSeg;
  4311. /* Set the range of origins that will go into the output segment. */
  4312. if( pStruct->nOriginCntr>0 ){
  4313. pSeg->iOrigin1 = pLvl->aSeg[0].iOrigin1;
  4314. pSeg->iOrigin2 = pLvl->aSeg[pLvl->nSeg-1].iOrigin2;
  4315. }
  4316. }
  4317. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  4318. assert( iLvl>=0 );
  4319. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  4320. fts5MultiIterEof(p, pIter)==0;
  4321. fts5MultiIterNext(p, pIter, 0, 0)
  4322. ){
  4323. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  4324. int nPos; /* position-list size field value */
  4325. int nTerm;
  4326. const u8 *pTerm;
  4327. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  4328. if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
  4329. if( pnRem && writer.nLeafWritten>nRem ){
  4330. break;
  4331. }
  4332. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  4333. bTermWritten =0;
  4334. }
  4335. /* Check for key annihilation. */
  4336. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  4337. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  4338. /* This is a new term. Append a term to the output segment. */
  4339. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  4340. bTermWritten = 1;
  4341. }
  4342. /* Append the rowid to the output */
  4343. /* WRITEPOSLISTSIZE */
  4344. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  4345. if( eDetail==FTS5_DETAIL_NONE ){
  4346. if( pSegIter->bDel ){
  4347. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  4348. if( pSegIter->nPos>0 ){
  4349. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  4350. }
  4351. }
  4352. }else{
  4353. /* Append the position-list data to the output */
  4354. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  4355. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  4356. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  4357. }
  4358. }
  4359. /* Flush the last leaf page to disk. Set the output segment b-tree height
  4360. ** and last leaf page number at the same time. */
  4361. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  4362. assert( pIter!=0 || p->rc!=SQLITE_OK );
  4363. if( fts5MultiIterEof(p, pIter) ){
  4364. int i;
  4365. /* Remove the redundant segments from the %_data table */
  4366. assert( pSeg->nEntry==0 );
  4367. for(i=0; i<nInput; i++){
  4368. Fts5StructureSegment *pOld = &pLvl->aSeg[i];
  4369. pSeg->nEntry += (pOld->nEntry - pOld->nEntryTombstone);
  4370. fts5DataRemoveSegment(p, pOld);
  4371. }
  4372. /* Remove the redundant segments from the input level */
  4373. if( pLvl->nSeg!=nInput ){
  4374. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  4375. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  4376. }
  4377. pStruct->nSegment -= nInput;
  4378. pLvl->nSeg -= nInput;
  4379. pLvl->nMerge = 0;
  4380. if( pSeg->pgnoLast==0 ){
  4381. pLvlOut->nSeg--;
  4382. pStruct->nSegment--;
  4383. }
  4384. }else{
  4385. assert( pSeg->pgnoLast>0 );
  4386. fts5TrimSegments(p, pIter);
  4387. pLvl->nMerge = nInput;
  4388. }
  4389. fts5MultiIterFree(pIter);
  4390. fts5BufferFree(&term);
  4391. if( pnRem ) *pnRem -= writer.nLeafWritten;
  4392. }
  4393. /*
  4394. ** If this is not a contentless_delete=1 table, or if the 'deletemerge'
  4395. ** configuration option is set to 0, then this function always returns -1.
  4396. ** Otherwise, it searches the structure object passed as the second argument
  4397. ** for a level suitable for merging due to having a large number of
  4398. ** tombstones in the tombstone hash. If one is found, its index is returned.
  4399. ** Otherwise, if there is no suitable level, -1.
  4400. */
  4401. static int fts5IndexFindDeleteMerge(Fts5Index *p, Fts5Structure *pStruct){
  4402. Fts5Config *pConfig = p->pConfig;
  4403. int iRet = -1;
  4404. if( pConfig->bContentlessDelete && pConfig->nDeleteMerge>0 ){
  4405. int ii;
  4406. int nBest = 0;
  4407. for(ii=0; ii<pStruct->nLevel; ii++){
  4408. Fts5StructureLevel *pLvl = &pStruct->aLevel[ii];
  4409. i64 nEntry = 0;
  4410. i64 nTomb = 0;
  4411. int iSeg;
  4412. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  4413. nEntry += pLvl->aSeg[iSeg].nEntry;
  4414. nTomb += pLvl->aSeg[iSeg].nEntryTombstone;
  4415. }
  4416. assert_nc( nEntry>0 || pLvl->nSeg==0 );
  4417. if( nEntry>0 ){
  4418. int nPercent = (nTomb * 100) / nEntry;
  4419. if( nPercent>=pConfig->nDeleteMerge && nPercent>nBest ){
  4420. iRet = ii;
  4421. nBest = nPercent;
  4422. }
  4423. }
  4424. /* If pLvl is already the input level to an ongoing merge, look no
  4425. ** further for a merge candidate. The caller should be allowed to
  4426. ** continue merging from pLvl first. */
  4427. if( pLvl->nMerge ) break;
  4428. }
  4429. }
  4430. return iRet;
  4431. }
  4432. /*
  4433. ** Do up to nPg pages of automerge work on the index.
  4434. **
  4435. ** Return true if any changes were actually made, or false otherwise.
  4436. */
  4437. static int fts5IndexMerge(
  4438. Fts5Index *p, /* FTS5 backend object */
  4439. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  4440. int nPg, /* Pages of work to do */
  4441. int nMin /* Minimum number of segments to merge */
  4442. ){
  4443. int nRem = nPg;
  4444. int bRet = 0;
  4445. Fts5Structure *pStruct = *ppStruct;
  4446. while( nRem>0 && p->rc==SQLITE_OK ){
  4447. int iLvl; /* To iterate through levels */
  4448. int iBestLvl = 0; /* Level offering the most input segments */
  4449. int nBest = 0; /* Number of input segments on best level */
  4450. /* Set iBestLvl to the level to read input segments from. Or to -1 if
  4451. ** there is no level suitable to merge segments from. */
  4452. assert( pStruct->nLevel>0 );
  4453. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  4454. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  4455. if( pLvl->nMerge ){
  4456. if( pLvl->nMerge>nBest ){
  4457. iBestLvl = iLvl;
  4458. nBest = nMin;
  4459. }
  4460. break;
  4461. }
  4462. if( pLvl->nSeg>nBest ){
  4463. nBest = pLvl->nSeg;
  4464. iBestLvl = iLvl;
  4465. }
  4466. }
  4467. if( nBest<nMin ){
  4468. iBestLvl = fts5IndexFindDeleteMerge(p, pStruct);
  4469. }
  4470. if( iBestLvl<0 ) break;
  4471. bRet = 1;
  4472. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  4473. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  4474. fts5StructurePromote(p, iBestLvl+1, pStruct);
  4475. }
  4476. if( nMin==1 ) nMin = 2;
  4477. }
  4478. *ppStruct = pStruct;
  4479. return bRet;
  4480. }
  4481. /*
  4482. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  4483. ** segment. This function updates the write-counter accordingly and, if
  4484. ** necessary, performs incremental merge work.
  4485. **
  4486. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  4487. ** already occurred, this function is a no-op.
  4488. */
  4489. static void fts5IndexAutomerge(
  4490. Fts5Index *p, /* FTS5 backend object */
  4491. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  4492. int nLeaf /* Number of output leaves just written */
  4493. ){
  4494. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 && ALWAYS((*ppStruct)!=0) ){
  4495. Fts5Structure *pStruct = *ppStruct;
  4496. u64 nWrite; /* Initial value of write-counter */
  4497. int nWork; /* Number of work-quanta to perform */
  4498. int nRem; /* Number of leaf pages left to write */
  4499. /* Update the write-counter. While doing so, set nWork. */
  4500. nWrite = pStruct->nWriteCounter;
  4501. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  4502. pStruct->nWriteCounter += nLeaf;
  4503. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  4504. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  4505. }
  4506. }
  4507. static void fts5IndexCrisismerge(
  4508. Fts5Index *p, /* FTS5 backend object */
  4509. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  4510. ){
  4511. const int nCrisis = p->pConfig->nCrisisMerge;
  4512. Fts5Structure *pStruct = *ppStruct;
  4513. if( pStruct && pStruct->nLevel>0 ){
  4514. int iLvl = 0;
  4515. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  4516. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  4517. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  4518. fts5StructurePromote(p, iLvl+1, pStruct);
  4519. iLvl++;
  4520. }
  4521. *ppStruct = pStruct;
  4522. }
  4523. }
  4524. static int fts5IndexReturn(Fts5Index *p){
  4525. int rc = p->rc;
  4526. p->rc = SQLITE_OK;
  4527. return rc;
  4528. }
  4529. typedef struct Fts5FlushCtx Fts5FlushCtx;
  4530. struct Fts5FlushCtx {
  4531. Fts5Index *pIdx;
  4532. Fts5SegWriter writer;
  4533. };
  4534. /*
  4535. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  4536. ** in a 32-bit integer. Return the size of the largest prefix of this
  4537. ** list nMax bytes or less in size.
  4538. */
  4539. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  4540. int ret;
  4541. u32 dummy;
  4542. ret = fts5GetVarint32(aBuf, dummy);
  4543. if( ret<nMax ){
  4544. while( 1 ){
  4545. int i = fts5GetVarint32(&aBuf[ret], dummy);
  4546. if( (ret + i) > nMax ) break;
  4547. ret += i;
  4548. }
  4549. }
  4550. return ret;
  4551. }
  4552. /*
  4553. ** Execute the SQL statement:
  4554. **
  4555. ** DELETE FROM %_idx WHERE (segid, (pgno/2)) = ($iSegid, $iPgno);
  4556. **
  4557. ** This is used when a secure-delete operation removes the last term
  4558. ** from a segment leaf page. In that case the %_idx entry is removed
  4559. ** too. This is done to ensure that if all instances of a token are
  4560. ** removed from an fts5 database in secure-delete mode, no trace of
  4561. ** the token itself remains in the database.
  4562. */
  4563. static void fts5SecureDeleteIdxEntry(
  4564. Fts5Index *p, /* FTS5 backend object */
  4565. int iSegid, /* Id of segment to delete entry for */
  4566. int iPgno /* Page number within segment */
  4567. ){
  4568. if( iPgno!=1 ){
  4569. assert( p->pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE );
  4570. if( p->pDeleteFromIdx==0 ){
  4571. fts5IndexPrepareStmt(p, &p->pDeleteFromIdx, sqlite3_mprintf(
  4572. "DELETE FROM '%q'.'%q_idx' WHERE (segid, (pgno/2)) = (?1, ?2)",
  4573. p->pConfig->zDb, p->pConfig->zName
  4574. ));
  4575. }
  4576. if( p->rc==SQLITE_OK ){
  4577. sqlite3_bind_int(p->pDeleteFromIdx, 1, iSegid);
  4578. sqlite3_bind_int(p->pDeleteFromIdx, 2, iPgno);
  4579. sqlite3_step(p->pDeleteFromIdx);
  4580. p->rc = sqlite3_reset(p->pDeleteFromIdx);
  4581. }
  4582. }
  4583. }
  4584. /*
  4585. ** This is called when a secure-delete operation removes a position-list
  4586. ** that overflows onto segment page iPgno of segment pSeg. This function
  4587. ** rewrites node iPgno, and possibly one or more of its right-hand peers,
  4588. ** to remove this portion of the position list.
  4589. **
  4590. ** Output variable (*pbLastInDoclist) is set to true if the position-list
  4591. ** removed is followed by a new term or the end-of-segment, or false if
  4592. ** it is followed by another rowid/position list.
  4593. */
  4594. static void fts5SecureDeleteOverflow(
  4595. Fts5Index *p,
  4596. Fts5StructureSegment *pSeg,
  4597. int iPgno,
  4598. int *pbLastInDoclist
  4599. ){
  4600. const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
  4601. int pgno;
  4602. Fts5Data *pLeaf = 0;
  4603. assert( iPgno!=1 );
  4604. *pbLastInDoclist = 1;
  4605. for(pgno=iPgno; p->rc==SQLITE_OK && pgno<=pSeg->pgnoLast; pgno++){
  4606. i64 iRowid = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  4607. int iNext = 0;
  4608. u8 *aPg = 0;
  4609. pLeaf = fts5DataRead(p, iRowid);
  4610. if( pLeaf==0 ) break;
  4611. aPg = pLeaf->p;
  4612. iNext = fts5GetU16(&aPg[0]);
  4613. if( iNext!=0 ){
  4614. *pbLastInDoclist = 0;
  4615. }
  4616. if( iNext==0 && pLeaf->szLeaf!=pLeaf->nn ){
  4617. fts5GetVarint32(&aPg[pLeaf->szLeaf], iNext);
  4618. }
  4619. if( iNext==0 ){
  4620. /* The page contains no terms or rowids. Replace it with an empty
  4621. ** page and move on to the right-hand peer. */
  4622. const u8 aEmpty[] = {0x00, 0x00, 0x00, 0x04};
  4623. assert_nc( bDetailNone==0 || pLeaf->nn==4 );
  4624. if( bDetailNone==0 ) fts5DataWrite(p, iRowid, aEmpty, sizeof(aEmpty));
  4625. fts5DataRelease(pLeaf);
  4626. pLeaf = 0;
  4627. }else if( bDetailNone ){
  4628. break;
  4629. }else if( iNext>=pLeaf->szLeaf || pLeaf->nn<pLeaf->szLeaf || iNext<4 ){
  4630. p->rc = FTS5_CORRUPT;
  4631. break;
  4632. }else{
  4633. int nShift = iNext - 4;
  4634. int nPg;
  4635. int nIdx = 0;
  4636. u8 *aIdx = 0;
  4637. /* Unless the current page footer is 0 bytes in size (in which case
  4638. ** the new page footer will be as well), allocate and populate a
  4639. ** buffer containing the new page footer. Set stack variables aIdx
  4640. ** and nIdx accordingly. */
  4641. if( pLeaf->nn>pLeaf->szLeaf ){
  4642. int iFirst = 0;
  4643. int i1 = pLeaf->szLeaf;
  4644. int i2 = 0;
  4645. i1 += fts5GetVarint32(&aPg[i1], iFirst);
  4646. if( iFirst<iNext ){
  4647. p->rc = FTS5_CORRUPT;
  4648. break;
  4649. }
  4650. aIdx = sqlite3Fts5MallocZero(&p->rc, (pLeaf->nn-pLeaf->szLeaf)+2);
  4651. if( aIdx==0 ) break;
  4652. i2 = sqlite3Fts5PutVarint(aIdx, iFirst-nShift);
  4653. if( i1<pLeaf->nn ){
  4654. memcpy(&aIdx[i2], &aPg[i1], pLeaf->nn-i1);
  4655. i2 += (pLeaf->nn-i1);
  4656. }
  4657. nIdx = i2;
  4658. }
  4659. /* Modify the contents of buffer aPg[]. Set nPg to the new size
  4660. ** in bytes. The new page is always smaller than the old. */
  4661. nPg = pLeaf->szLeaf - nShift;
  4662. memmove(&aPg[4], &aPg[4+nShift], nPg-4);
  4663. fts5PutU16(&aPg[2], nPg);
  4664. if( fts5GetU16(&aPg[0]) ) fts5PutU16(&aPg[0], 4);
  4665. if( nIdx>0 ){
  4666. memcpy(&aPg[nPg], aIdx, nIdx);
  4667. nPg += nIdx;
  4668. }
  4669. sqlite3_free(aIdx);
  4670. /* Write the new page to disk and exit the loop */
  4671. assert( nPg>4 || fts5GetU16(aPg)==0 );
  4672. fts5DataWrite(p, iRowid, aPg, nPg);
  4673. break;
  4674. }
  4675. }
  4676. fts5DataRelease(pLeaf);
  4677. }
  4678. /*
  4679. ** Completely remove the entry that pSeg currently points to from
  4680. ** the database.
  4681. */
  4682. static void fts5DoSecureDelete(
  4683. Fts5Index *p,
  4684. Fts5SegIter *pSeg
  4685. ){
  4686. const int bDetailNone = (p->pConfig->eDetail==FTS5_DETAIL_NONE);
  4687. int iSegid = pSeg->pSeg->iSegid;
  4688. u8 *aPg = pSeg->pLeaf->p;
  4689. int nPg = pSeg->pLeaf->nn;
  4690. int iPgIdx = pSeg->pLeaf->szLeaf;
  4691. u64 iDelta = 0;
  4692. int iNextOff = 0;
  4693. int iOff = 0;
  4694. int nIdx = 0;
  4695. u8 *aIdx = 0;
  4696. int bLastInDoclist = 0;
  4697. int iIdx = 0;
  4698. int iStart = 0;
  4699. int iDelKeyOff = 0; /* Offset of deleted key, if any */
  4700. nIdx = nPg-iPgIdx;
  4701. aIdx = sqlite3Fts5MallocZero(&p->rc, nIdx+16);
  4702. if( p->rc ) return;
  4703. memcpy(aIdx, &aPg[iPgIdx], nIdx);
  4704. /* At this point segment iterator pSeg points to the entry
  4705. ** this function should remove from the b-tree segment.
  4706. **
  4707. ** In detail=full or detail=column mode, pSeg->iLeafOffset is the
  4708. ** offset of the first byte in the position-list for the entry to
  4709. ** remove. Immediately before this comes two varints that will also
  4710. ** need to be removed:
  4711. **
  4712. ** + the rowid or delta rowid value for the entry, and
  4713. ** + the size of the position list in bytes.
  4714. **
  4715. ** Or, in detail=none mode, there is a single varint prior to
  4716. ** pSeg->iLeafOffset - the rowid or delta rowid value.
  4717. **
  4718. ** This block sets the following variables:
  4719. **
  4720. ** iStart:
  4721. ** The offset of the first byte of the rowid or delta-rowid
  4722. ** value for the doclist entry being removed.
  4723. **
  4724. ** iDelta:
  4725. ** The value of the rowid or delta-rowid value for the doclist
  4726. ** entry being removed.
  4727. **
  4728. ** iNextOff:
  4729. ** The offset of the next entry following the position list
  4730. ** for the one being removed. If the position list for this
  4731. ** entry overflows onto the next leaf page, this value will be
  4732. ** greater than pLeaf->szLeaf.
  4733. */
  4734. {
  4735. int iSOP; /* Start-Of-Position-list */
  4736. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno ){
  4737. iStart = pSeg->iTermLeafOffset;
  4738. }else{
  4739. iStart = fts5GetU16(&aPg[0]);
  4740. }
  4741. iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
  4742. assert_nc( iSOP<=pSeg->iLeafOffset );
  4743. if( bDetailNone ){
  4744. while( iSOP<pSeg->iLeafOffset ){
  4745. if( aPg[iSOP]==0x00 ) iSOP++;
  4746. if( aPg[iSOP]==0x00 ) iSOP++;
  4747. iStart = iSOP;
  4748. iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
  4749. }
  4750. iNextOff = iSOP;
  4751. if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
  4752. if( iNextOff<pSeg->iEndofDoclist && aPg[iNextOff]==0x00 ) iNextOff++;
  4753. }else{
  4754. int nPos = 0;
  4755. iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
  4756. while( iSOP<pSeg->iLeafOffset ){
  4757. iStart = iSOP + (nPos/2);
  4758. iSOP = iStart + fts5GetVarint(&aPg[iStart], &iDelta);
  4759. iSOP += fts5GetVarint32(&aPg[iSOP], nPos);
  4760. }
  4761. assert_nc( iSOP==pSeg->iLeafOffset );
  4762. iNextOff = pSeg->iLeafOffset + pSeg->nPos;
  4763. }
  4764. }
  4765. iOff = iStart;
  4766. /* If the position-list for the entry being removed flows over past
  4767. ** the end of this page, delete the portion of the position-list on the
  4768. ** next page and beyond.
  4769. **
  4770. ** Set variable bLastInDoclist to true if this entry happens
  4771. ** to be the last rowid in the doclist for its term. */
  4772. if( iNextOff>=iPgIdx ){
  4773. int pgno = pSeg->iLeafPgno+1;
  4774. fts5SecureDeleteOverflow(p, pSeg->pSeg, pgno, &bLastInDoclist);
  4775. iNextOff = iPgIdx;
  4776. }
  4777. if( pSeg->bDel==0 ){
  4778. if( iNextOff!=iPgIdx ){
  4779. /* Loop through the page-footer. If iNextOff (offset of the
  4780. ** entry following the one we are removing) is equal to the
  4781. ** offset of a key on this page, then the entry is the last
  4782. ** in its doclist. */
  4783. int iKeyOff = 0;
  4784. for(iIdx=0; iIdx<nIdx; /* no-op */){
  4785. u32 iVal = 0;
  4786. iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
  4787. iKeyOff += iVal;
  4788. if( iKeyOff==iNextOff ){
  4789. bLastInDoclist = 1;
  4790. }
  4791. }
  4792. }
  4793. /* If this is (a) the first rowid on a page and (b) is not followed by
  4794. ** another position list on the same page, set the "first-rowid" field
  4795. ** of the header to 0. */
  4796. if( fts5GetU16(&aPg[0])==iStart && (bLastInDoclist || iNextOff==iPgIdx) ){
  4797. fts5PutU16(&aPg[0], 0);
  4798. }
  4799. }
  4800. if( pSeg->bDel ){
  4801. iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta);
  4802. aPg[iOff++] = 0x01;
  4803. }else if( bLastInDoclist==0 ){
  4804. if( iNextOff!=iPgIdx ){
  4805. u64 iNextDelta = 0;
  4806. iNextOff += fts5GetVarint(&aPg[iNextOff], &iNextDelta);
  4807. iOff += sqlite3Fts5PutVarint(&aPg[iOff], iDelta + iNextDelta);
  4808. }
  4809. }else if(
  4810. pSeg->iLeafPgno==pSeg->iTermLeafPgno
  4811. && iStart==pSeg->iTermLeafOffset
  4812. ){
  4813. /* The entry being removed was the only position list in its
  4814. ** doclist. Therefore the term needs to be removed as well. */
  4815. int iKey = 0;
  4816. int iKeyOff = 0;
  4817. /* Set iKeyOff to the offset of the term that will be removed - the
  4818. ** last offset in the footer that is not greater than iStart. */
  4819. for(iIdx=0; iIdx<nIdx; iKey++){
  4820. u32 iVal = 0;
  4821. iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
  4822. if( (iKeyOff+iVal)>(u32)iStart ) break;
  4823. iKeyOff += iVal;
  4824. }
  4825. assert_nc( iKey>=1 );
  4826. /* Set iDelKeyOff to the value of the footer entry to remove from
  4827. ** the page. */
  4828. iDelKeyOff = iOff = iKeyOff;
  4829. if( iNextOff!=iPgIdx ){
  4830. /* This is the only position-list associated with the term, and there
  4831. ** is another term following it on this page. So the subsequent term
  4832. ** needs to be moved to replace the term associated with the entry
  4833. ** being removed. */
  4834. int nPrefix = 0;
  4835. int nSuffix = 0;
  4836. int nPrefix2 = 0;
  4837. int nSuffix2 = 0;
  4838. iDelKeyOff = iNextOff;
  4839. iNextOff += fts5GetVarint32(&aPg[iNextOff], nPrefix2);
  4840. iNextOff += fts5GetVarint32(&aPg[iNextOff], nSuffix2);
  4841. if( iKey!=1 ){
  4842. iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nPrefix);
  4843. }
  4844. iKeyOff += fts5GetVarint32(&aPg[iKeyOff], nSuffix);
  4845. nPrefix = MIN(nPrefix, nPrefix2);
  4846. nSuffix = (nPrefix2 + nSuffix2) - nPrefix;
  4847. if( (iKeyOff+nSuffix)>iPgIdx || (iNextOff+nSuffix2)>iPgIdx ){
  4848. p->rc = FTS5_CORRUPT;
  4849. }else{
  4850. if( iKey!=1 ){
  4851. iOff += sqlite3Fts5PutVarint(&aPg[iOff], nPrefix);
  4852. }
  4853. iOff += sqlite3Fts5PutVarint(&aPg[iOff], nSuffix);
  4854. if( nPrefix2>pSeg->term.n ){
  4855. p->rc = FTS5_CORRUPT;
  4856. }else if( nPrefix2>nPrefix ){
  4857. memcpy(&aPg[iOff], &pSeg->term.p[nPrefix], nPrefix2-nPrefix);
  4858. iOff += (nPrefix2-nPrefix);
  4859. }
  4860. memmove(&aPg[iOff], &aPg[iNextOff], nSuffix2);
  4861. iOff += nSuffix2;
  4862. iNextOff += nSuffix2;
  4863. }
  4864. }
  4865. }else if( iStart==4 ){
  4866. int iPgno;
  4867. assert_nc( pSeg->iLeafPgno>pSeg->iTermLeafPgno );
  4868. /* The entry being removed may be the only position list in
  4869. ** its doclist. */
  4870. for(iPgno=pSeg->iLeafPgno-1; iPgno>pSeg->iTermLeafPgno; iPgno-- ){
  4871. Fts5Data *pPg = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, iPgno));
  4872. int bEmpty = (pPg && pPg->nn==4);
  4873. fts5DataRelease(pPg);
  4874. if( bEmpty==0 ) break;
  4875. }
  4876. if( iPgno==pSeg->iTermLeafPgno ){
  4877. i64 iId = FTS5_SEGMENT_ROWID(iSegid, pSeg->iTermLeafPgno);
  4878. Fts5Data *pTerm = fts5DataRead(p, iId);
  4879. if( pTerm && pTerm->szLeaf==pSeg->iTermLeafOffset ){
  4880. u8 *aTermIdx = &pTerm->p[pTerm->szLeaf];
  4881. int nTermIdx = pTerm->nn - pTerm->szLeaf;
  4882. int iTermIdx = 0;
  4883. int iTermOff = 0;
  4884. while( 1 ){
  4885. u32 iVal = 0;
  4886. int nByte = fts5GetVarint32(&aTermIdx[iTermIdx], iVal);
  4887. iTermOff += iVal;
  4888. if( (iTermIdx+nByte)>=nTermIdx ) break;
  4889. iTermIdx += nByte;
  4890. }
  4891. nTermIdx = iTermIdx;
  4892. memmove(&pTerm->p[iTermOff], &pTerm->p[pTerm->szLeaf], nTermIdx);
  4893. fts5PutU16(&pTerm->p[2], iTermOff);
  4894. fts5DataWrite(p, iId, pTerm->p, iTermOff+nTermIdx);
  4895. if( nTermIdx==0 ){
  4896. fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iTermLeafPgno);
  4897. }
  4898. }
  4899. fts5DataRelease(pTerm);
  4900. }
  4901. }
  4902. /* Assuming no error has occurred, this block does final edits to the
  4903. ** leaf page before writing it back to disk. Input variables are:
  4904. **
  4905. ** nPg: Total initial size of leaf page.
  4906. ** iPgIdx: Initial offset of page footer.
  4907. **
  4908. ** iOff: Offset to move data to
  4909. ** iNextOff: Offset to move data from
  4910. */
  4911. if( p->rc==SQLITE_OK ){
  4912. const int nMove = nPg - iNextOff; /* Number of bytes to move */
  4913. int nShift = iNextOff - iOff; /* Distance to move them */
  4914. int iPrevKeyOut = 0;
  4915. int iKeyIn = 0;
  4916. memmove(&aPg[iOff], &aPg[iNextOff], nMove);
  4917. iPgIdx -= nShift;
  4918. nPg = iPgIdx;
  4919. fts5PutU16(&aPg[2], iPgIdx);
  4920. for(iIdx=0; iIdx<nIdx; /* no-op */){
  4921. u32 iVal = 0;
  4922. iIdx += fts5GetVarint32(&aIdx[iIdx], iVal);
  4923. iKeyIn += iVal;
  4924. if( iKeyIn!=iDelKeyOff ){
  4925. int iKeyOut = (iKeyIn - (iKeyIn>iOff ? nShift : 0));
  4926. nPg += sqlite3Fts5PutVarint(&aPg[nPg], iKeyOut - iPrevKeyOut);
  4927. iPrevKeyOut = iKeyOut;
  4928. }
  4929. }
  4930. if( iPgIdx==nPg && nIdx>0 && pSeg->iLeafPgno!=1 ){
  4931. fts5SecureDeleteIdxEntry(p, iSegid, pSeg->iLeafPgno);
  4932. }
  4933. assert_nc( nPg>4 || fts5GetU16(aPg)==0 );
  4934. fts5DataWrite(p, FTS5_SEGMENT_ROWID(iSegid,pSeg->iLeafPgno), aPg, nPg);
  4935. }
  4936. sqlite3_free(aIdx);
  4937. }
  4938. /*
  4939. ** This is called as part of flushing a delete to disk in 'secure-delete'
  4940. ** mode. It edits the segments within the database described by argument
  4941. ** pStruct to remove the entries for term zTerm, rowid iRowid.
  4942. */
  4943. static void fts5FlushSecureDelete(
  4944. Fts5Index *p,
  4945. Fts5Structure *pStruct,
  4946. const char *zTerm,
  4947. int nTerm,
  4948. i64 iRowid
  4949. ){
  4950. const int f = FTS5INDEX_QUERY_SKIPHASH;
  4951. Fts5Iter *pIter = 0; /* Used to find term instance */
  4952. fts5MultiIterNew(p, pStruct, f, 0, (const u8*)zTerm, nTerm, -1, 0, &pIter);
  4953. if( fts5MultiIterEof(p, pIter)==0 ){
  4954. i64 iThis = fts5MultiIterRowid(pIter);
  4955. if( iThis<iRowid ){
  4956. fts5MultiIterNextFrom(p, pIter, iRowid);
  4957. }
  4958. if( p->rc==SQLITE_OK
  4959. && fts5MultiIterEof(p, pIter)==0
  4960. && iRowid==fts5MultiIterRowid(pIter)
  4961. ){
  4962. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  4963. fts5DoSecureDelete(p, pSeg);
  4964. }
  4965. }
  4966. fts5MultiIterFree(pIter);
  4967. }
  4968. /*
  4969. ** Flush the contents of in-memory hash table iHash to a new level-0
  4970. ** segment on disk. Also update the corresponding structure record.
  4971. **
  4972. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  4973. ** already occurred, this function is a no-op.
  4974. */
  4975. static void fts5FlushOneHash(Fts5Index *p){
  4976. Fts5Hash *pHash = p->pHash;
  4977. Fts5Structure *pStruct;
  4978. int iSegid;
  4979. int pgnoLast = 0; /* Last leaf page number in segment */
  4980. /* Obtain a reference to the index structure and allocate a new segment-id
  4981. ** for the new level-0 segment. */
  4982. pStruct = fts5StructureRead(p);
  4983. fts5StructureInvalidate(p);
  4984. if( sqlite3Fts5HashIsEmpty(pHash)==0 ){
  4985. iSegid = fts5AllocateSegid(p, pStruct);
  4986. if( iSegid ){
  4987. const int pgsz = p->pConfig->pgsz;
  4988. int eDetail = p->pConfig->eDetail;
  4989. int bSecureDelete = p->pConfig->bSecureDelete;
  4990. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  4991. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  4992. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  4993. Fts5SegWriter writer;
  4994. fts5WriteInit(p, &writer, iSegid);
  4995. pBuf = &writer.writer.buf;
  4996. pPgidx = &writer.writer.pgidx;
  4997. /* fts5WriteInit() should have initialized the buffers to (most likely)
  4998. ** the maximum space required. */
  4999. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  5000. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  5001. /* Begin scanning through hash table entries. This loop runs once for each
  5002. ** term/doclist currently stored within the hash table. */
  5003. if( p->rc==SQLITE_OK ){
  5004. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  5005. }
  5006. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  5007. const char *zTerm; /* Buffer containing term */
  5008. int nTerm; /* Size of zTerm in bytes */
  5009. const u8 *pDoclist; /* Pointer to doclist for this term */
  5010. int nDoclist; /* Size of doclist in bytes */
  5011. /* Get the term and doclist for this entry. */
  5012. sqlite3Fts5HashScanEntry(pHash, &zTerm, &nTerm, &pDoclist, &nDoclist);
  5013. if( bSecureDelete==0 ){
  5014. fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
  5015. if( p->rc!=SQLITE_OK ) break;
  5016. assert( writer.bFirstRowidInPage==0 );
  5017. }
  5018. if( !bSecureDelete && pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  5019. /* The entire doclist will fit on the current leaf. */
  5020. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  5021. }else{
  5022. int bTermWritten = !bSecureDelete;
  5023. i64 iRowid = 0;
  5024. i64 iPrev = 0;
  5025. int iOff = 0;
  5026. /* The entire doclist will not fit on this leaf. The following
  5027. ** loop iterates through the poslists that make up the current
  5028. ** doclist. */
  5029. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  5030. u64 iDelta = 0;
  5031. iOff += fts5GetVarint(&pDoclist[iOff], &iDelta);
  5032. iRowid += iDelta;
  5033. /* If in secure delete mode, and if this entry in the poslist is
  5034. ** in fact a delete, then edit the existing segments directly
  5035. ** using fts5FlushSecureDelete(). */
  5036. if( bSecureDelete ){
  5037. if( eDetail==FTS5_DETAIL_NONE ){
  5038. if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
  5039. fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid);
  5040. iOff++;
  5041. if( iOff<nDoclist && pDoclist[iOff]==0x00 ){
  5042. iOff++;
  5043. nDoclist = 0;
  5044. }else{
  5045. continue;
  5046. }
  5047. }
  5048. }else if( (pDoclist[iOff] & 0x01) ){
  5049. fts5FlushSecureDelete(p, pStruct, zTerm, nTerm, iRowid);
  5050. if( p->rc!=SQLITE_OK || pDoclist[iOff]==0x01 ){
  5051. iOff++;
  5052. continue;
  5053. }
  5054. }
  5055. }
  5056. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  5057. fts5WriteAppendTerm(p, &writer, nTerm, (const u8*)zTerm);
  5058. bTermWritten = 1;
  5059. assert( p->rc!=SQLITE_OK || writer.bFirstRowidInPage==0 );
  5060. }
  5061. if( writer.bFirstRowidInPage ){
  5062. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  5063. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  5064. writer.bFirstRowidInPage = 0;
  5065. fts5WriteDlidxAppend(p, &writer, iRowid);
  5066. }else{
  5067. u64 iRowidDelta = (u64)iRowid - (u64)iPrev;
  5068. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowidDelta);
  5069. }
  5070. if( p->rc!=SQLITE_OK ) break;
  5071. assert( pBuf->n<=pBuf->nSpace );
  5072. iPrev = iRowid;
  5073. if( eDetail==FTS5_DETAIL_NONE ){
  5074. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  5075. pBuf->p[pBuf->n++] = 0;
  5076. iOff++;
  5077. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  5078. pBuf->p[pBuf->n++] = 0;
  5079. iOff++;
  5080. }
  5081. }
  5082. if( (pBuf->n + pPgidx->n)>=pgsz ){
  5083. fts5WriteFlushLeaf(p, &writer);
  5084. }
  5085. }else{
  5086. int bDel = 0;
  5087. int nPos = 0;
  5088. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDel);
  5089. if( bDel && bSecureDelete ){
  5090. fts5BufferAppendVarint(&p->rc, pBuf, nPos*2);
  5091. iOff += nCopy;
  5092. nCopy = nPos;
  5093. }else{
  5094. nCopy += nPos;
  5095. }
  5096. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  5097. /* The entire poslist will fit on the current leaf. So copy
  5098. ** it in one go. */
  5099. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  5100. }else{
  5101. /* The entire poslist will not fit on this leaf. So it needs
  5102. ** to be broken into sections. The only qualification being
  5103. ** that each varint must be stored contiguously. */
  5104. const u8 *pPoslist = &pDoclist[iOff];
  5105. int iPos = 0;
  5106. while( p->rc==SQLITE_OK ){
  5107. int nSpace = pgsz - pBuf->n - pPgidx->n;
  5108. int n = 0;
  5109. if( (nCopy - iPos)<=nSpace ){
  5110. n = nCopy - iPos;
  5111. }else{
  5112. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  5113. }
  5114. assert( n>0 );
  5115. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  5116. iPos += n;
  5117. if( (pBuf->n + pPgidx->n)>=pgsz ){
  5118. fts5WriteFlushLeaf(p, &writer);
  5119. }
  5120. if( iPos>=nCopy ) break;
  5121. }
  5122. }
  5123. iOff += nCopy;
  5124. }
  5125. }
  5126. }
  5127. /* TODO2: Doclist terminator written here. */
  5128. /* pBuf->p[pBuf->n++] = '\0'; */
  5129. assert( pBuf->n<=pBuf->nSpace );
  5130. if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
  5131. }
  5132. fts5WriteFinish(p, &writer, &pgnoLast);
  5133. assert( p->rc!=SQLITE_OK || bSecureDelete || pgnoLast>0 );
  5134. if( pgnoLast>0 ){
  5135. /* Update the Fts5Structure. It is written back to the database by the
  5136. ** fts5StructureRelease() call below. */
  5137. if( pStruct->nLevel==0 ){
  5138. fts5StructureAddLevel(&p->rc, &pStruct);
  5139. }
  5140. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  5141. if( p->rc==SQLITE_OK ){
  5142. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  5143. pSeg->iSegid = iSegid;
  5144. pSeg->pgnoFirst = 1;
  5145. pSeg->pgnoLast = pgnoLast;
  5146. if( pStruct->nOriginCntr>0 ){
  5147. pSeg->iOrigin1 = pStruct->nOriginCntr;
  5148. pSeg->iOrigin2 = pStruct->nOriginCntr;
  5149. pSeg->nEntry = p->nPendingRow;
  5150. pStruct->nOriginCntr++;
  5151. }
  5152. pStruct->nSegment++;
  5153. }
  5154. fts5StructurePromote(p, 0, pStruct);
  5155. }
  5156. }
  5157. }
  5158. fts5IndexAutomerge(p, &pStruct, pgnoLast + p->nContentlessDelete);
  5159. fts5IndexCrisismerge(p, &pStruct);
  5160. fts5StructureWrite(p, pStruct);
  5161. fts5StructureRelease(pStruct);
  5162. }
  5163. /*
  5164. ** Flush any data stored in the in-memory hash tables to the database.
  5165. */
  5166. static void fts5IndexFlush(Fts5Index *p){
  5167. /* Unless it is empty, flush the hash table to disk */
  5168. if( p->flushRc ){
  5169. p->rc = p->flushRc;
  5170. return;
  5171. }
  5172. if( p->nPendingData || p->nContentlessDelete ){
  5173. assert( p->pHash );
  5174. fts5FlushOneHash(p);
  5175. if( p->rc==SQLITE_OK ){
  5176. sqlite3Fts5HashClear(p->pHash);
  5177. p->nPendingData = 0;
  5178. p->nPendingRow = 0;
  5179. p->nContentlessDelete = 0;
  5180. }else if( p->nPendingData || p->nContentlessDelete ){
  5181. p->flushRc = p->rc;
  5182. }
  5183. }
  5184. }
  5185. static Fts5Structure *fts5IndexOptimizeStruct(
  5186. Fts5Index *p,
  5187. Fts5Structure *pStruct
  5188. ){
  5189. Fts5Structure *pNew = 0;
  5190. sqlite3_int64 nByte = sizeof(Fts5Structure);
  5191. int nSeg = pStruct->nSegment;
  5192. int i;
  5193. /* Figure out if this structure requires optimization. A structure does
  5194. ** not require optimization if either:
  5195. **
  5196. ** 1. it consists of fewer than two segments, or
  5197. ** 2. all segments are on the same level, or
  5198. ** 3. all segments except one are currently inputs to a merge operation.
  5199. **
  5200. ** In the first case, if there are no tombstone hash pages, return NULL. In
  5201. ** the second, increment the ref-count on *pStruct and return a copy of the
  5202. ** pointer to it.
  5203. */
  5204. if( nSeg==0 ) return 0;
  5205. for(i=0; i<pStruct->nLevel; i++){
  5206. int nThis = pStruct->aLevel[i].nSeg;
  5207. int nMerge = pStruct->aLevel[i].nMerge;
  5208. if( nThis>0 && (nThis==nSeg || (nThis==nSeg-1 && nMerge==nThis)) ){
  5209. if( nSeg==1 && nThis==1 && pStruct->aLevel[i].aSeg[0].nPgTombstone==0 ){
  5210. return 0;
  5211. }
  5212. fts5StructureRef(pStruct);
  5213. return pStruct;
  5214. }
  5215. assert( pStruct->aLevel[i].nMerge<=nThis );
  5216. }
  5217. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  5218. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  5219. if( pNew ){
  5220. Fts5StructureLevel *pLvl;
  5221. nByte = nSeg * sizeof(Fts5StructureSegment);
  5222. pNew->nLevel = MIN(pStruct->nLevel+1, FTS5_MAX_LEVEL);
  5223. pNew->nRef = 1;
  5224. pNew->nWriteCounter = pStruct->nWriteCounter;
  5225. pNew->nOriginCntr = pStruct->nOriginCntr;
  5226. pLvl = &pNew->aLevel[pNew->nLevel-1];
  5227. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  5228. if( pLvl->aSeg ){
  5229. int iLvl, iSeg;
  5230. int iSegOut = 0;
  5231. /* Iterate through all segments, from oldest to newest. Add them to
  5232. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  5233. ** segment in the data structure. */
  5234. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  5235. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  5236. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  5237. iSegOut++;
  5238. }
  5239. }
  5240. pNew->nSegment = pLvl->nSeg = nSeg;
  5241. }else{
  5242. sqlite3_free(pNew);
  5243. pNew = 0;
  5244. }
  5245. }
  5246. return pNew;
  5247. }
  5248. int sqlite3Fts5IndexOptimize(Fts5Index *p){
  5249. Fts5Structure *pStruct;
  5250. Fts5Structure *pNew = 0;
  5251. assert( p->rc==SQLITE_OK );
  5252. fts5IndexFlush(p);
  5253. assert( p->rc!=SQLITE_OK || p->nContentlessDelete==0 );
  5254. pStruct = fts5StructureRead(p);
  5255. assert( p->rc!=SQLITE_OK || pStruct!=0 );
  5256. fts5StructureInvalidate(p);
  5257. if( pStruct ){
  5258. pNew = fts5IndexOptimizeStruct(p, pStruct);
  5259. }
  5260. fts5StructureRelease(pStruct);
  5261. assert( pNew==0 || pNew->nSegment>0 );
  5262. if( pNew ){
  5263. int iLvl;
  5264. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  5265. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  5266. int nRem = FTS5_OPT_WORK_UNIT;
  5267. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  5268. }
  5269. fts5StructureWrite(p, pNew);
  5270. fts5StructureRelease(pNew);
  5271. }
  5272. return fts5IndexReturn(p);
  5273. }
  5274. /*
  5275. ** This is called to implement the special "VALUES('merge', $nMerge)"
  5276. ** INSERT command.
  5277. */
  5278. int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  5279. Fts5Structure *pStruct = 0;
  5280. fts5IndexFlush(p);
  5281. pStruct = fts5StructureRead(p);
  5282. if( pStruct ){
  5283. int nMin = p->pConfig->nUsermerge;
  5284. fts5StructureInvalidate(p);
  5285. if( nMerge<0 ){
  5286. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  5287. fts5StructureRelease(pStruct);
  5288. pStruct = pNew;
  5289. nMin = 1;
  5290. nMerge = nMerge*-1;
  5291. }
  5292. if( pStruct && pStruct->nLevel ){
  5293. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  5294. fts5StructureWrite(p, pStruct);
  5295. }
  5296. }
  5297. fts5StructureRelease(pStruct);
  5298. }
  5299. return fts5IndexReturn(p);
  5300. }
  5301. static void fts5AppendRowid(
  5302. Fts5Index *p,
  5303. u64 iDelta,
  5304. Fts5Iter *pUnused,
  5305. Fts5Buffer *pBuf
  5306. ){
  5307. UNUSED_PARAM(pUnused);
  5308. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  5309. }
  5310. static void fts5AppendPoslist(
  5311. Fts5Index *p,
  5312. u64 iDelta,
  5313. Fts5Iter *pMulti,
  5314. Fts5Buffer *pBuf
  5315. ){
  5316. int nData = pMulti->base.nData;
  5317. int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
  5318. assert( nData>0 );
  5319. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
  5320. fts5BufferSafeAppendVarint(pBuf, iDelta);
  5321. fts5BufferSafeAppendVarint(pBuf, nData*2);
  5322. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  5323. memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
  5324. }
  5325. }
  5326. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  5327. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  5328. assert( pIter->aPoslist || (p==0 && pIter->aPoslist==0) );
  5329. if( p>=pIter->aEof ){
  5330. pIter->aPoslist = 0;
  5331. }else{
  5332. i64 iDelta;
  5333. p += fts5GetVarint(p, (u64*)&iDelta);
  5334. pIter->iRowid += iDelta;
  5335. /* Read position list size */
  5336. if( p[0] & 0x80 ){
  5337. int nPos;
  5338. pIter->nSize = fts5GetVarint32(p, nPos);
  5339. pIter->nPoslist = (nPos>>1);
  5340. }else{
  5341. pIter->nPoslist = ((int)(p[0])) >> 1;
  5342. pIter->nSize = 1;
  5343. }
  5344. pIter->aPoslist = p;
  5345. if( &pIter->aPoslist[pIter->nPoslist]>pIter->aEof ){
  5346. pIter->aPoslist = 0;
  5347. }
  5348. }
  5349. }
  5350. static void fts5DoclistIterInit(
  5351. Fts5Buffer *pBuf,
  5352. Fts5DoclistIter *pIter
  5353. ){
  5354. memset(pIter, 0, sizeof(*pIter));
  5355. if( pBuf->n>0 ){
  5356. pIter->aPoslist = pBuf->p;
  5357. pIter->aEof = &pBuf->p[pBuf->n];
  5358. fts5DoclistIterNext(pIter);
  5359. }
  5360. }
  5361. #if 0
  5362. /*
  5363. ** Append a doclist to buffer pBuf.
  5364. **
  5365. ** This function assumes that space within the buffer has already been
  5366. ** allocated.
  5367. */
  5368. static void fts5MergeAppendDocid(
  5369. Fts5Buffer *pBuf, /* Buffer to write to */
  5370. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  5371. i64 iRowid /* Rowid to append */
  5372. ){
  5373. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  5374. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  5375. *piLastRowid = iRowid;
  5376. }
  5377. #endif
  5378. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  5379. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  5380. fts5BufferSafeAppendVarint((pBuf), (u64)(iRowid) - (u64)(iLastRowid)); \
  5381. (iLastRowid) = (iRowid); \
  5382. }
  5383. /*
  5384. ** Swap the contents of buffer *p1 with that of *p2.
  5385. */
  5386. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  5387. Fts5Buffer tmp = *p1;
  5388. *p1 = *p2;
  5389. *p2 = tmp;
  5390. }
  5391. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  5392. int i = *piOff;
  5393. if( i>=pBuf->n ){
  5394. *piOff = -1;
  5395. }else{
  5396. u64 iVal;
  5397. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  5398. *piRowid += iVal;
  5399. }
  5400. }
  5401. /*
  5402. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  5403. ** In this case the buffers consist of a delta-encoded list of rowids only.
  5404. */
  5405. static void fts5MergeRowidLists(
  5406. Fts5Index *p, /* FTS5 backend object */
  5407. Fts5Buffer *p1, /* First list to merge */
  5408. int nBuf, /* Number of entries in apBuf[] */
  5409. Fts5Buffer *aBuf /* Array of other lists to merge into p1 */
  5410. ){
  5411. int i1 = 0;
  5412. int i2 = 0;
  5413. i64 iRowid1 = 0;
  5414. i64 iRowid2 = 0;
  5415. i64 iOut = 0;
  5416. Fts5Buffer *p2 = &aBuf[0];
  5417. Fts5Buffer out;
  5418. (void)nBuf;
  5419. memset(&out, 0, sizeof(out));
  5420. assert( nBuf==1 );
  5421. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  5422. if( p->rc ) return;
  5423. fts5NextRowid(p1, &i1, &iRowid1);
  5424. fts5NextRowid(p2, &i2, &iRowid2);
  5425. while( i1>=0 || i2>=0 ){
  5426. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  5427. assert( iOut==0 || iRowid1>iOut );
  5428. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  5429. iOut = iRowid1;
  5430. fts5NextRowid(p1, &i1, &iRowid1);
  5431. }else{
  5432. assert( iOut==0 || iRowid2>iOut );
  5433. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  5434. iOut = iRowid2;
  5435. if( i1>=0 && iRowid1==iRowid2 ){
  5436. fts5NextRowid(p1, &i1, &iRowid1);
  5437. }
  5438. fts5NextRowid(p2, &i2, &iRowid2);
  5439. }
  5440. }
  5441. fts5BufferSwap(&out, p1);
  5442. fts5BufferFree(&out);
  5443. }
  5444. typedef struct PrefixMerger PrefixMerger;
  5445. struct PrefixMerger {
  5446. Fts5DoclistIter iter; /* Doclist iterator */
  5447. i64 iPos; /* For iterating through a position list */
  5448. int iOff;
  5449. u8 *aPos;
  5450. PrefixMerger *pNext; /* Next in docid/poslist order */
  5451. };
  5452. static void fts5PrefixMergerInsertByRowid(
  5453. PrefixMerger **ppHead,
  5454. PrefixMerger *p
  5455. ){
  5456. if( p->iter.aPoslist ){
  5457. PrefixMerger **pp = ppHead;
  5458. while( *pp && p->iter.iRowid>(*pp)->iter.iRowid ){
  5459. pp = &(*pp)->pNext;
  5460. }
  5461. p->pNext = *pp;
  5462. *pp = p;
  5463. }
  5464. }
  5465. static void fts5PrefixMergerInsertByPosition(
  5466. PrefixMerger **ppHead,
  5467. PrefixMerger *p
  5468. ){
  5469. if( p->iPos>=0 ){
  5470. PrefixMerger **pp = ppHead;
  5471. while( *pp && p->iPos>(*pp)->iPos ){
  5472. pp = &(*pp)->pNext;
  5473. }
  5474. p->pNext = *pp;
  5475. *pp = p;
  5476. }
  5477. }
  5478. /*
  5479. ** Array aBuf[] contains nBuf doclists. These are all merged in with the
  5480. ** doclist in buffer p1.
  5481. */
  5482. static void fts5MergePrefixLists(
  5483. Fts5Index *p, /* FTS5 backend object */
  5484. Fts5Buffer *p1, /* First list to merge */
  5485. int nBuf, /* Number of buffers in array aBuf[] */
  5486. Fts5Buffer *aBuf /* Other lists to merge in */
  5487. ){
  5488. #define fts5PrefixMergerNextPosition(p) \
  5489. sqlite3Fts5PoslistNext64((p)->aPos,(p)->iter.nPoslist,&(p)->iOff,&(p)->iPos)
  5490. #define FTS5_MERGE_NLIST 16
  5491. PrefixMerger aMerger[FTS5_MERGE_NLIST];
  5492. PrefixMerger *pHead = 0;
  5493. int i;
  5494. int nOut = 0;
  5495. Fts5Buffer out = {0, 0, 0};
  5496. Fts5Buffer tmp = {0, 0, 0};
  5497. i64 iLastRowid = 0;
  5498. /* Initialize a doclist-iterator for each input buffer. Arrange them in
  5499. ** a linked-list starting at pHead in ascending order of rowid. Avoid
  5500. ** linking any iterators already at EOF into the linked list at all. */
  5501. assert( nBuf+1<=(int)(sizeof(aMerger)/sizeof(aMerger[0])) );
  5502. memset(aMerger, 0, sizeof(PrefixMerger)*(nBuf+1));
  5503. pHead = &aMerger[nBuf];
  5504. fts5DoclistIterInit(p1, &pHead->iter);
  5505. for(i=0; i<nBuf; i++){
  5506. fts5DoclistIterInit(&aBuf[i], &aMerger[i].iter);
  5507. fts5PrefixMergerInsertByRowid(&pHead, &aMerger[i]);
  5508. nOut += aBuf[i].n;
  5509. }
  5510. if( nOut==0 ) return;
  5511. nOut += p1->n + 9 + 10*nBuf;
  5512. /* The maximum size of the output is equal to the sum of the
  5513. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  5514. ** first rowid in one input is a large negative number, and the first in
  5515. ** the other a non-negative number, the delta for the non-negative
  5516. ** number will be larger on disk than the literal integer value
  5517. ** was.
  5518. **
  5519. ** Or, if the input position-lists are corrupt, then the output might
  5520. ** include up to (nBuf+1) extra 10-byte positions created by interpreting -1
  5521. ** (the value PoslistNext64() uses for EOF) as a position and appending
  5522. ** it to the output. This can happen at most once for each input
  5523. ** position-list, hence (nBuf+1) 10 byte paddings. */
  5524. if( sqlite3Fts5BufferSize(&p->rc, &out, nOut) ) return;
  5525. while( pHead ){
  5526. fts5MergeAppendDocid(&out, iLastRowid, pHead->iter.iRowid);
  5527. if( pHead->pNext && iLastRowid==pHead->pNext->iter.iRowid ){
  5528. /* Merge data from two or more poslists */
  5529. i64 iPrev = 0;
  5530. int nTmp = FTS5_DATA_ZERO_PADDING;
  5531. int nMerge = 0;
  5532. PrefixMerger *pSave = pHead;
  5533. PrefixMerger *pThis = 0;
  5534. int nTail = 0;
  5535. pHead = 0;
  5536. while( pSave && pSave->iter.iRowid==iLastRowid ){
  5537. PrefixMerger *pNext = pSave->pNext;
  5538. pSave->iOff = 0;
  5539. pSave->iPos = 0;
  5540. pSave->aPos = &pSave->iter.aPoslist[pSave->iter.nSize];
  5541. fts5PrefixMergerNextPosition(pSave);
  5542. nTmp += pSave->iter.nPoslist + 10;
  5543. nMerge++;
  5544. fts5PrefixMergerInsertByPosition(&pHead, pSave);
  5545. pSave = pNext;
  5546. }
  5547. if( pHead==0 || pHead->pNext==0 ){
  5548. p->rc = FTS5_CORRUPT;
  5549. break;
  5550. }
  5551. /* See the earlier comment in this function for an explanation of why
  5552. ** corrupt input position lists might cause the output to consume
  5553. ** at most nMerge*10 bytes of unexpected space. */
  5554. if( sqlite3Fts5BufferSize(&p->rc, &tmp, nTmp+nMerge*10) ){
  5555. break;
  5556. }
  5557. fts5BufferZero(&tmp);
  5558. pThis = pHead;
  5559. pHead = pThis->pNext;
  5560. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
  5561. fts5PrefixMergerNextPosition(pThis);
  5562. fts5PrefixMergerInsertByPosition(&pHead, pThis);
  5563. while( pHead->pNext ){
  5564. pThis = pHead;
  5565. if( pThis->iPos!=iPrev ){
  5566. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pThis->iPos);
  5567. }
  5568. fts5PrefixMergerNextPosition(pThis);
  5569. pHead = pThis->pNext;
  5570. fts5PrefixMergerInsertByPosition(&pHead, pThis);
  5571. }
  5572. if( pHead->iPos!=iPrev ){
  5573. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, pHead->iPos);
  5574. }
  5575. nTail = pHead->iter.nPoslist - pHead->iOff;
  5576. /* WRITEPOSLISTSIZE */
  5577. assert_nc( tmp.n+nTail<=nTmp );
  5578. assert( tmp.n+nTail<=nTmp+nMerge*10 );
  5579. if( tmp.n+nTail>nTmp-FTS5_DATA_ZERO_PADDING ){
  5580. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  5581. break;
  5582. }
  5583. fts5BufferSafeAppendVarint(&out, (tmp.n+nTail) * 2);
  5584. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  5585. if( nTail>0 ){
  5586. fts5BufferSafeAppendBlob(&out, &pHead->aPos[pHead->iOff], nTail);
  5587. }
  5588. pHead = pSave;
  5589. for(i=0; i<nBuf+1; i++){
  5590. PrefixMerger *pX = &aMerger[i];
  5591. if( pX->iter.aPoslist && pX->iter.iRowid==iLastRowid ){
  5592. fts5DoclistIterNext(&pX->iter);
  5593. fts5PrefixMergerInsertByRowid(&pHead, pX);
  5594. }
  5595. }
  5596. }else{
  5597. /* Copy poslist from pHead to output */
  5598. PrefixMerger *pThis = pHead;
  5599. Fts5DoclistIter *pI = &pThis->iter;
  5600. fts5BufferSafeAppendBlob(&out, pI->aPoslist, pI->nPoslist+pI->nSize);
  5601. fts5DoclistIterNext(pI);
  5602. pHead = pThis->pNext;
  5603. fts5PrefixMergerInsertByRowid(&pHead, pThis);
  5604. }
  5605. }
  5606. fts5BufferFree(p1);
  5607. fts5BufferFree(&tmp);
  5608. memset(&out.p[out.n], 0, FTS5_DATA_ZERO_PADDING);
  5609. *p1 = out;
  5610. }
  5611. static void fts5SetupPrefixIter(
  5612. Fts5Index *p, /* Index to read from */
  5613. int bDesc, /* True for "ORDER BY rowid DESC" */
  5614. int iIdx, /* Index to scan for data */
  5615. u8 *pToken, /* Buffer containing prefix to match */
  5616. int nToken, /* Size of buffer pToken in bytes */
  5617. Fts5Colset *pColset, /* Restrict matches to these columns */
  5618. Fts5Iter **ppIter /* OUT: New iterator */
  5619. ){
  5620. Fts5Structure *pStruct;
  5621. Fts5Buffer *aBuf;
  5622. int nBuf = 32;
  5623. int nMerge = 1;
  5624. void (*xMerge)(Fts5Index*, Fts5Buffer*, int, Fts5Buffer*);
  5625. void (*xAppend)(Fts5Index*, u64, Fts5Iter*, Fts5Buffer*);
  5626. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  5627. xMerge = fts5MergeRowidLists;
  5628. xAppend = fts5AppendRowid;
  5629. }else{
  5630. nMerge = FTS5_MERGE_NLIST-1;
  5631. nBuf = nMerge*8; /* Sufficient to merge (16^8)==(2^32) lists */
  5632. xMerge = fts5MergePrefixLists;
  5633. xAppend = fts5AppendPoslist;
  5634. }
  5635. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  5636. pStruct = fts5StructureRead(p);
  5637. assert( p->rc!=SQLITE_OK || (aBuf && pStruct) );
  5638. if( p->rc==SQLITE_OK ){
  5639. const int flags = FTS5INDEX_QUERY_SCAN
  5640. | FTS5INDEX_QUERY_SKIPEMPTY
  5641. | FTS5INDEX_QUERY_NOOUTPUT;
  5642. int i;
  5643. i64 iLastRowid = 0;
  5644. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  5645. Fts5Data *pData;
  5646. Fts5Buffer doclist;
  5647. int bNewTerm = 1;
  5648. memset(&doclist, 0, sizeof(doclist));
  5649. /* If iIdx is non-zero, then it is the number of a prefix-index for
  5650. ** prefixes 1 character longer than the prefix being queried for. That
  5651. ** index contains all the doclists required, except for the one
  5652. ** corresponding to the prefix itself. That one is extracted from the
  5653. ** main term index here. */
  5654. if( iIdx!=0 ){
  5655. int dummy = 0;
  5656. const int f2 = FTS5INDEX_QUERY_SKIPEMPTY|FTS5INDEX_QUERY_NOOUTPUT;
  5657. pToken[0] = FTS5_MAIN_PREFIX;
  5658. fts5MultiIterNew(p, pStruct, f2, pColset, pToken, nToken, -1, 0, &p1);
  5659. fts5IterSetOutputCb(&p->rc, p1);
  5660. for(;
  5661. fts5MultiIterEof(p, p1)==0;
  5662. fts5MultiIterNext2(p, p1, &dummy)
  5663. ){
  5664. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  5665. p1->xSetOutputs(p1, pSeg);
  5666. if( p1->base.nData ){
  5667. xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
  5668. iLastRowid = p1->base.iRowid;
  5669. }
  5670. }
  5671. fts5MultiIterFree(p1);
  5672. }
  5673. pToken[0] = FTS5_MAIN_PREFIX + iIdx;
  5674. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  5675. fts5IterSetOutputCb(&p->rc, p1);
  5676. for( /* no-op */ ;
  5677. fts5MultiIterEof(p, p1)==0;
  5678. fts5MultiIterNext2(p, p1, &bNewTerm)
  5679. ){
  5680. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  5681. int nTerm = pSeg->term.n;
  5682. const u8 *pTerm = pSeg->term.p;
  5683. p1->xSetOutputs(p1, pSeg);
  5684. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  5685. if( bNewTerm ){
  5686. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  5687. }
  5688. if( p1->base.nData==0 ) continue;
  5689. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  5690. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  5691. int i1 = i*nMerge;
  5692. int iStore;
  5693. assert( i1+nMerge<=nBuf );
  5694. for(iStore=i1; iStore<i1+nMerge; iStore++){
  5695. if( aBuf[iStore].n==0 ){
  5696. fts5BufferSwap(&doclist, &aBuf[iStore]);
  5697. fts5BufferZero(&doclist);
  5698. break;
  5699. }
  5700. }
  5701. if( iStore==i1+nMerge ){
  5702. xMerge(p, &doclist, nMerge, &aBuf[i1]);
  5703. for(iStore=i1; iStore<i1+nMerge; iStore++){
  5704. fts5BufferZero(&aBuf[iStore]);
  5705. }
  5706. }
  5707. }
  5708. iLastRowid = 0;
  5709. }
  5710. xAppend(p, (u64)p1->base.iRowid-(u64)iLastRowid, p1, &doclist);
  5711. iLastRowid = p1->base.iRowid;
  5712. }
  5713. assert( (nBuf%nMerge)==0 );
  5714. for(i=0; i<nBuf; i+=nMerge){
  5715. int iFree;
  5716. if( p->rc==SQLITE_OK ){
  5717. xMerge(p, &doclist, nMerge, &aBuf[i]);
  5718. }
  5719. for(iFree=i; iFree<i+nMerge; iFree++){
  5720. fts5BufferFree(&aBuf[iFree]);
  5721. }
  5722. }
  5723. fts5MultiIterFree(p1);
  5724. pData = fts5IdxMalloc(p, sizeof(*pData)+doclist.n+FTS5_DATA_ZERO_PADDING);
  5725. if( pData ){
  5726. pData->p = (u8*)&pData[1];
  5727. pData->nn = pData->szLeaf = doclist.n;
  5728. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  5729. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  5730. }
  5731. fts5BufferFree(&doclist);
  5732. }
  5733. fts5StructureRelease(pStruct);
  5734. sqlite3_free(aBuf);
  5735. }
  5736. /*
  5737. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  5738. ** to the document with rowid iRowid.
  5739. */
  5740. int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  5741. assert( p->rc==SQLITE_OK );
  5742. /* Allocate the hash table if it has not already been allocated */
  5743. if( p->pHash==0 ){
  5744. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  5745. }
  5746. /* Flush the hash table to disk if required */
  5747. if( iRowid<p->iWriteRowid
  5748. || (iRowid==p->iWriteRowid && p->bDelete==0)
  5749. || (p->nPendingData > p->pConfig->nHashSize)
  5750. ){
  5751. fts5IndexFlush(p);
  5752. }
  5753. p->iWriteRowid = iRowid;
  5754. p->bDelete = bDelete;
  5755. if( bDelete==0 ){
  5756. p->nPendingRow++;
  5757. }
  5758. return fts5IndexReturn(p);
  5759. }
  5760. /*
  5761. ** Commit data to disk.
  5762. */
  5763. int sqlite3Fts5IndexSync(Fts5Index *p){
  5764. assert( p->rc==SQLITE_OK );
  5765. fts5IndexFlush(p);
  5766. sqlite3Fts5IndexCloseReader(p);
  5767. return fts5IndexReturn(p);
  5768. }
  5769. /*
  5770. ** Discard any data stored in the in-memory hash tables. Do not write it
  5771. ** to the database. Additionally, assume that the contents of the %_data
  5772. ** table may have changed on disk. So any in-memory caches of %_data
  5773. ** records must be invalidated.
  5774. */
  5775. int sqlite3Fts5IndexRollback(Fts5Index *p){
  5776. sqlite3Fts5IndexCloseReader(p);
  5777. fts5IndexDiscardData(p);
  5778. fts5StructureInvalidate(p);
  5779. /* assert( p->rc==SQLITE_OK ); */
  5780. return SQLITE_OK;
  5781. }
  5782. /*
  5783. ** The %_data table is completely empty when this function is called. This
  5784. ** function populates it with the initial structure objects for each index,
  5785. ** and the initial version of the "averages" record (a zero-byte blob).
  5786. */
  5787. int sqlite3Fts5IndexReinit(Fts5Index *p){
  5788. Fts5Structure s;
  5789. fts5StructureInvalidate(p);
  5790. fts5IndexDiscardData(p);
  5791. memset(&s, 0, sizeof(Fts5Structure));
  5792. if( p->pConfig->bContentlessDelete ){
  5793. s.nOriginCntr = 1;
  5794. }
  5795. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  5796. fts5StructureWrite(p, &s);
  5797. return fts5IndexReturn(p);
  5798. }
  5799. /*
  5800. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  5801. ** and initialize the underlying %_data table.
  5802. **
  5803. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  5804. ** Otherwise, set *pp to NULL and return an SQLite error code.
  5805. */
  5806. int sqlite3Fts5IndexOpen(
  5807. Fts5Config *pConfig,
  5808. int bCreate,
  5809. Fts5Index **pp,
  5810. char **pzErr
  5811. ){
  5812. int rc = SQLITE_OK;
  5813. Fts5Index *p; /* New object */
  5814. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  5815. if( rc==SQLITE_OK ){
  5816. p->pConfig = pConfig;
  5817. p->nWorkUnit = FTS5_WORK_UNIT;
  5818. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  5819. if( p->zDataTbl && bCreate ){
  5820. rc = sqlite3Fts5CreateTable(
  5821. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  5822. );
  5823. if( rc==SQLITE_OK ){
  5824. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  5825. "segid, term, pgno, PRIMARY KEY(segid, term)",
  5826. 1, pzErr
  5827. );
  5828. }
  5829. if( rc==SQLITE_OK ){
  5830. rc = sqlite3Fts5IndexReinit(p);
  5831. }
  5832. }
  5833. }
  5834. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  5835. if( rc ){
  5836. sqlite3Fts5IndexClose(p);
  5837. *pp = 0;
  5838. }
  5839. return rc;
  5840. }
  5841. /*
  5842. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  5843. */
  5844. int sqlite3Fts5IndexClose(Fts5Index *p){
  5845. int rc = SQLITE_OK;
  5846. if( p ){
  5847. assert( p->pReader==0 );
  5848. fts5StructureInvalidate(p);
  5849. sqlite3_finalize(p->pWriter);
  5850. sqlite3_finalize(p->pDeleter);
  5851. sqlite3_finalize(p->pIdxWriter);
  5852. sqlite3_finalize(p->pIdxDeleter);
  5853. sqlite3_finalize(p->pIdxSelect);
  5854. sqlite3_finalize(p->pIdxNextSelect);
  5855. sqlite3_finalize(p->pDataVersion);
  5856. sqlite3_finalize(p->pDeleteFromIdx);
  5857. sqlite3Fts5HashFree(p->pHash);
  5858. sqlite3_free(p->zDataTbl);
  5859. sqlite3_free(p);
  5860. }
  5861. return rc;
  5862. }
  5863. /*
  5864. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  5865. ** size. Return the number of bytes in the nChar character prefix of the
  5866. ** buffer, or 0 if there are less than nChar characters in total.
  5867. */
  5868. int sqlite3Fts5IndexCharlenToBytelen(
  5869. const char *p,
  5870. int nByte,
  5871. int nChar
  5872. ){
  5873. int n = 0;
  5874. int i;
  5875. for(i=0; i<nChar; i++){
  5876. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  5877. if( (unsigned char)p[n++]>=0xc0 ){
  5878. if( n>=nByte ) return 0;
  5879. while( (p[n] & 0xc0)==0x80 ){
  5880. n++;
  5881. if( n>=nByte ){
  5882. if( i+1==nChar ) break;
  5883. return 0;
  5884. }
  5885. }
  5886. }
  5887. }
  5888. return n;
  5889. }
  5890. /*
  5891. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  5892. ** unicode characters in the string.
  5893. */
  5894. static int fts5IndexCharlen(const char *pIn, int nIn){
  5895. int nChar = 0;
  5896. int i = 0;
  5897. while( i<nIn ){
  5898. if( (unsigned char)pIn[i++]>=0xc0 ){
  5899. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  5900. }
  5901. nChar++;
  5902. }
  5903. return nChar;
  5904. }
  5905. /*
  5906. ** Insert or remove data to or from the index. Each time a document is
  5907. ** added to or removed from the index, this function is called one or more
  5908. ** times.
  5909. **
  5910. ** For an insert, it must be called once for each token in the new document.
  5911. ** If the operation is a delete, it must be called (at least) once for each
  5912. ** unique token in the document with an iCol value less than zero. The iPos
  5913. ** argument is ignored for a delete.
  5914. */
  5915. int sqlite3Fts5IndexWrite(
  5916. Fts5Index *p, /* Index to write to */
  5917. int iCol, /* Column token appears in (-ve -> delete) */
  5918. int iPos, /* Position of token within column */
  5919. const char *pToken, int nToken /* Token to add or remove to or from index */
  5920. ){
  5921. int i; /* Used to iterate through indexes */
  5922. int rc = SQLITE_OK; /* Return code */
  5923. Fts5Config *pConfig = p->pConfig;
  5924. assert( p->rc==SQLITE_OK );
  5925. assert( (iCol<0)==p->bDelete );
  5926. /* Add the entry to the main terms index. */
  5927. rc = sqlite3Fts5HashWrite(
  5928. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  5929. );
  5930. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  5931. const int nChar = pConfig->aPrefix[i];
  5932. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  5933. if( nByte ){
  5934. rc = sqlite3Fts5HashWrite(p->pHash,
  5935. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  5936. nByte
  5937. );
  5938. }
  5939. }
  5940. return rc;
  5941. }
  5942. /*
  5943. ** pToken points to a buffer of size nToken bytes containing a search
  5944. ** term, including the index number at the start, used on a tokendata=1
  5945. ** table. This function returns true if the term in buffer pBuf matches
  5946. ** token pToken/nToken.
  5947. */
  5948. static int fts5IsTokendataPrefix(
  5949. Fts5Buffer *pBuf,
  5950. const u8 *pToken,
  5951. int nToken
  5952. ){
  5953. return (
  5954. pBuf->n>=nToken
  5955. && 0==memcmp(pBuf->p, pToken, nToken)
  5956. && (pBuf->n==nToken || pBuf->p[nToken]==0x00)
  5957. );
  5958. }
  5959. /*
  5960. ** Ensure the segment-iterator passed as the only argument points to EOF.
  5961. */
  5962. static void fts5SegIterSetEOF(Fts5SegIter *pSeg){
  5963. fts5DataRelease(pSeg->pLeaf);
  5964. pSeg->pLeaf = 0;
  5965. }
  5966. /*
  5967. ** Usually, a tokendata=1 iterator (struct Fts5TokenDataIter) accumulates an
  5968. ** array of these for each row it visits. Or, for an iterator used by an
  5969. ** "ORDER BY rank" query, it accumulates an array of these for the entire
  5970. ** query.
  5971. **
  5972. ** Each instance in the array indicates the iterator (and therefore term)
  5973. ** associated with position iPos of rowid iRowid. This is used by the
  5974. ** xInstToken() API.
  5975. */
  5976. struct Fts5TokenDataMap {
  5977. i64 iRowid; /* Row this token is located in */
  5978. i64 iPos; /* Position of token */
  5979. int iIter; /* Iterator token was read from */
  5980. };
  5981. /*
  5982. ** An object used to supplement Fts5Iter for tokendata=1 iterators.
  5983. */
  5984. struct Fts5TokenDataIter {
  5985. int nIter;
  5986. int nIterAlloc;
  5987. int nMap;
  5988. int nMapAlloc;
  5989. Fts5TokenDataMap *aMap;
  5990. Fts5PoslistReader *aPoslistReader;
  5991. int *aPoslistToIter;
  5992. Fts5Iter *apIter[1];
  5993. };
  5994. /*
  5995. ** This function appends iterator pAppend to Fts5TokenDataIter pIn and
  5996. ** returns the result.
  5997. */
  5998. static Fts5TokenDataIter *fts5AppendTokendataIter(
  5999. Fts5Index *p, /* Index object (for error code) */
  6000. Fts5TokenDataIter *pIn, /* Current Fts5TokenDataIter struct */
  6001. Fts5Iter *pAppend /* Append this iterator */
  6002. ){
  6003. Fts5TokenDataIter *pRet = pIn;
  6004. if( p->rc==SQLITE_OK ){
  6005. if( pIn==0 || pIn->nIter==pIn->nIterAlloc ){
  6006. int nAlloc = pIn ? pIn->nIterAlloc*2 : 16;
  6007. int nByte = nAlloc * sizeof(Fts5Iter*) + sizeof(Fts5TokenDataIter);
  6008. Fts5TokenDataIter *pNew = (Fts5TokenDataIter*)sqlite3_realloc(pIn, nByte);
  6009. if( pNew==0 ){
  6010. p->rc = SQLITE_NOMEM;
  6011. }else{
  6012. if( pIn==0 ) memset(pNew, 0, nByte);
  6013. pRet = pNew;
  6014. pNew->nIterAlloc = nAlloc;
  6015. }
  6016. }
  6017. }
  6018. if( p->rc ){
  6019. sqlite3Fts5IterClose((Fts5IndexIter*)pAppend);
  6020. }else{
  6021. pRet->apIter[pRet->nIter++] = pAppend;
  6022. }
  6023. assert( pRet==0 || pRet->nIter<=pRet->nIterAlloc );
  6024. return pRet;
  6025. }
  6026. /*
  6027. ** Delete an Fts5TokenDataIter structure and its contents.
  6028. */
  6029. static void fts5TokendataIterDelete(Fts5TokenDataIter *pSet){
  6030. if( pSet ){
  6031. int ii;
  6032. for(ii=0; ii<pSet->nIter; ii++){
  6033. fts5MultiIterFree(pSet->apIter[ii]);
  6034. }
  6035. sqlite3_free(pSet->aPoslistReader);
  6036. sqlite3_free(pSet->aMap);
  6037. sqlite3_free(pSet);
  6038. }
  6039. }
  6040. /*
  6041. ** Append a mapping to the token-map belonging to object pT.
  6042. */
  6043. static void fts5TokendataIterAppendMap(
  6044. Fts5Index *p,
  6045. Fts5TokenDataIter *pT,
  6046. int iIter,
  6047. i64 iRowid,
  6048. i64 iPos
  6049. ){
  6050. if( p->rc==SQLITE_OK ){
  6051. if( pT->nMap==pT->nMapAlloc ){
  6052. int nNew = pT->nMapAlloc ? pT->nMapAlloc*2 : 64;
  6053. int nByte = nNew * sizeof(Fts5TokenDataMap);
  6054. Fts5TokenDataMap *aNew;
  6055. aNew = (Fts5TokenDataMap*)sqlite3_realloc(pT->aMap, nByte);
  6056. if( aNew==0 ){
  6057. p->rc = SQLITE_NOMEM;
  6058. return;
  6059. }
  6060. pT->aMap = aNew;
  6061. pT->nMapAlloc = nNew;
  6062. }
  6063. pT->aMap[pT->nMap].iRowid = iRowid;
  6064. pT->aMap[pT->nMap].iPos = iPos;
  6065. pT->aMap[pT->nMap].iIter = iIter;
  6066. pT->nMap++;
  6067. }
  6068. }
  6069. /*
  6070. ** The iterator passed as the only argument must be a tokendata=1 iterator
  6071. ** (pIter->pTokenDataIter!=0). This function sets the iterator output
  6072. ** variables (pIter->base.*) according to the contents of the current
  6073. ** row.
  6074. */
  6075. static void fts5IterSetOutputsTokendata(Fts5Iter *pIter){
  6076. int ii;
  6077. int nHit = 0;
  6078. i64 iRowid = SMALLEST_INT64;
  6079. int iMin = 0;
  6080. Fts5TokenDataIter *pT = pIter->pTokenDataIter;
  6081. pIter->base.nData = 0;
  6082. pIter->base.pData = 0;
  6083. for(ii=0; ii<pT->nIter; ii++){
  6084. Fts5Iter *p = pT->apIter[ii];
  6085. if( p->base.bEof==0 ){
  6086. if( nHit==0 || p->base.iRowid<iRowid ){
  6087. iRowid = p->base.iRowid;
  6088. nHit = 1;
  6089. pIter->base.pData = p->base.pData;
  6090. pIter->base.nData = p->base.nData;
  6091. iMin = ii;
  6092. }else if( p->base.iRowid==iRowid ){
  6093. nHit++;
  6094. }
  6095. }
  6096. }
  6097. if( nHit==0 ){
  6098. pIter->base.bEof = 1;
  6099. }else{
  6100. int eDetail = pIter->pIndex->pConfig->eDetail;
  6101. pIter->base.bEof = 0;
  6102. pIter->base.iRowid = iRowid;
  6103. if( nHit==1 && eDetail==FTS5_DETAIL_FULL ){
  6104. fts5TokendataIterAppendMap(pIter->pIndex, pT, iMin, iRowid, -1);
  6105. }else
  6106. if( nHit>1 && eDetail!=FTS5_DETAIL_NONE ){
  6107. int nReader = 0;
  6108. int nByte = 0;
  6109. i64 iPrev = 0;
  6110. /* Allocate array of iterators if they are not already allocated. */
  6111. if( pT->aPoslistReader==0 ){
  6112. pT->aPoslistReader = (Fts5PoslistReader*)sqlite3Fts5MallocZero(
  6113. &pIter->pIndex->rc,
  6114. pT->nIter * (sizeof(Fts5PoslistReader) + sizeof(int))
  6115. );
  6116. if( pT->aPoslistReader==0 ) return;
  6117. pT->aPoslistToIter = (int*)&pT->aPoslistReader[pT->nIter];
  6118. }
  6119. /* Populate an iterator for each poslist that will be merged */
  6120. for(ii=0; ii<pT->nIter; ii++){
  6121. Fts5Iter *p = pT->apIter[ii];
  6122. if( iRowid==p->base.iRowid ){
  6123. pT->aPoslistToIter[nReader] = ii;
  6124. sqlite3Fts5PoslistReaderInit(
  6125. p->base.pData, p->base.nData, &pT->aPoslistReader[nReader++]
  6126. );
  6127. nByte += p->base.nData;
  6128. }
  6129. }
  6130. /* Ensure the output buffer is large enough */
  6131. if( fts5BufferGrow(&pIter->pIndex->rc, &pIter->poslist, nByte+nHit*10) ){
  6132. return;
  6133. }
  6134. /* Ensure the token-mapping is large enough */
  6135. if( eDetail==FTS5_DETAIL_FULL && pT->nMapAlloc<(pT->nMap + nByte) ){
  6136. int nNew = (pT->nMapAlloc + nByte) * 2;
  6137. Fts5TokenDataMap *aNew = (Fts5TokenDataMap*)sqlite3_realloc(
  6138. pT->aMap, nNew*sizeof(Fts5TokenDataMap)
  6139. );
  6140. if( aNew==0 ){
  6141. pIter->pIndex->rc = SQLITE_NOMEM;
  6142. return;
  6143. }
  6144. pT->aMap = aNew;
  6145. pT->nMapAlloc = nNew;
  6146. }
  6147. pIter->poslist.n = 0;
  6148. while( 1 ){
  6149. i64 iMinPos = LARGEST_INT64;
  6150. /* Find smallest position */
  6151. iMin = 0;
  6152. for(ii=0; ii<nReader; ii++){
  6153. Fts5PoslistReader *pReader = &pT->aPoslistReader[ii];
  6154. if( pReader->bEof==0 ){
  6155. if( pReader->iPos<iMinPos ){
  6156. iMinPos = pReader->iPos;
  6157. iMin = ii;
  6158. }
  6159. }
  6160. }
  6161. /* If all readers were at EOF, break out of the loop. */
  6162. if( iMinPos==LARGEST_INT64 ) break;
  6163. sqlite3Fts5PoslistSafeAppend(&pIter->poslist, &iPrev, iMinPos);
  6164. sqlite3Fts5PoslistReaderNext(&pT->aPoslistReader[iMin]);
  6165. if( eDetail==FTS5_DETAIL_FULL ){
  6166. pT->aMap[pT->nMap].iPos = iMinPos;
  6167. pT->aMap[pT->nMap].iIter = pT->aPoslistToIter[iMin];
  6168. pT->aMap[pT->nMap].iRowid = iRowid;
  6169. pT->nMap++;
  6170. }
  6171. }
  6172. pIter->base.pData = pIter->poslist.p;
  6173. pIter->base.nData = pIter->poslist.n;
  6174. }
  6175. }
  6176. }
  6177. /*
  6178. ** The iterator passed as the only argument must be a tokendata=1 iterator
  6179. ** (pIter->pTokenDataIter!=0). This function advances the iterator. If
  6180. ** argument bFrom is false, then the iterator is advanced to the next
  6181. ** entry. Or, if bFrom is true, it is advanced to the first entry with
  6182. ** a rowid of iFrom or greater.
  6183. */
  6184. static void fts5TokendataIterNext(Fts5Iter *pIter, int bFrom, i64 iFrom){
  6185. int ii;
  6186. Fts5TokenDataIter *pT = pIter->pTokenDataIter;
  6187. Fts5Index *pIndex = pIter->pIndex;
  6188. for(ii=0; ii<pT->nIter; ii++){
  6189. Fts5Iter *p = pT->apIter[ii];
  6190. if( p->base.bEof==0
  6191. && (p->base.iRowid==pIter->base.iRowid || (bFrom && p->base.iRowid<iFrom))
  6192. ){
  6193. fts5MultiIterNext(pIndex, p, bFrom, iFrom);
  6194. while( bFrom && p->base.bEof==0
  6195. && p->base.iRowid<iFrom
  6196. && pIndex->rc==SQLITE_OK
  6197. ){
  6198. fts5MultiIterNext(pIndex, p, 0, 0);
  6199. }
  6200. }
  6201. }
  6202. if( pIndex->rc==SQLITE_OK ){
  6203. fts5IterSetOutputsTokendata(pIter);
  6204. }
  6205. }
  6206. /*
  6207. ** If the segment-iterator passed as the first argument is at EOF, then
  6208. ** set pIter->term to a copy of buffer pTerm.
  6209. */
  6210. static void fts5TokendataSetTermIfEof(Fts5Iter *pIter, Fts5Buffer *pTerm){
  6211. if( pIter && pIter->aSeg[0].pLeaf==0 ){
  6212. fts5BufferSet(&pIter->pIndex->rc, &pIter->aSeg[0].term, pTerm->n, pTerm->p);
  6213. }
  6214. }
  6215. /*
  6216. ** This function sets up an iterator to use for a non-prefix query on a
  6217. ** tokendata=1 table.
  6218. */
  6219. static Fts5Iter *fts5SetupTokendataIter(
  6220. Fts5Index *p, /* FTS index to query */
  6221. const u8 *pToken, /* Buffer containing query term */
  6222. int nToken, /* Size of buffer pToken in bytes */
  6223. Fts5Colset *pColset /* Colset to filter on */
  6224. ){
  6225. Fts5Iter *pRet = 0;
  6226. Fts5TokenDataIter *pSet = 0;
  6227. Fts5Structure *pStruct = 0;
  6228. const int flags = FTS5INDEX_QUERY_SCANONETERM | FTS5INDEX_QUERY_SCAN;
  6229. Fts5Buffer bSeek = {0, 0, 0};
  6230. Fts5Buffer *pSmall = 0;
  6231. fts5IndexFlush(p);
  6232. pStruct = fts5StructureRead(p);
  6233. while( p->rc==SQLITE_OK ){
  6234. Fts5Iter *pPrev = pSet ? pSet->apIter[pSet->nIter-1] : 0;
  6235. Fts5Iter *pNew = 0;
  6236. Fts5SegIter *pNewIter = 0;
  6237. Fts5SegIter *pPrevIter = 0;
  6238. int iLvl, iSeg, ii;
  6239. pNew = fts5MultiIterAlloc(p, pStruct->nSegment);
  6240. if( pSmall ){
  6241. fts5BufferSet(&p->rc, &bSeek, pSmall->n, pSmall->p);
  6242. fts5BufferAppendBlob(&p->rc, &bSeek, 1, (const u8*)"\0");
  6243. }else{
  6244. fts5BufferSet(&p->rc, &bSeek, nToken, pToken);
  6245. }
  6246. if( p->rc ){
  6247. sqlite3Fts5IterClose((Fts5IndexIter*)pNew);
  6248. break;
  6249. }
  6250. pNewIter = &pNew->aSeg[0];
  6251. pPrevIter = (pPrev ? &pPrev->aSeg[0] : 0);
  6252. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  6253. for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
  6254. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  6255. int bDone = 0;
  6256. if( pPrevIter ){
  6257. if( fts5BufferCompare(pSmall, &pPrevIter->term) ){
  6258. memcpy(pNewIter, pPrevIter, sizeof(Fts5SegIter));
  6259. memset(pPrevIter, 0, sizeof(Fts5SegIter));
  6260. bDone = 1;
  6261. }else if( pPrevIter->iEndofDoclist>pPrevIter->pLeaf->szLeaf ){
  6262. fts5SegIterNextInit(p,(const char*)bSeek.p,bSeek.n-1,pSeg,pNewIter);
  6263. bDone = 1;
  6264. }
  6265. }
  6266. if( bDone==0 ){
  6267. fts5SegIterSeekInit(p, bSeek.p, bSeek.n, flags, pSeg, pNewIter);
  6268. }
  6269. if( pPrevIter ){
  6270. if( pPrevIter->pTombArray ){
  6271. pNewIter->pTombArray = pPrevIter->pTombArray;
  6272. pNewIter->pTombArray->nRef++;
  6273. }
  6274. }else{
  6275. fts5SegIterAllocTombstone(p, pNewIter);
  6276. }
  6277. pNewIter++;
  6278. if( pPrevIter ) pPrevIter++;
  6279. if( p->rc ) break;
  6280. }
  6281. }
  6282. fts5TokendataSetTermIfEof(pPrev, pSmall);
  6283. pNew->bSkipEmpty = 1;
  6284. pNew->pColset = pColset;
  6285. fts5IterSetOutputCb(&p->rc, pNew);
  6286. /* Loop through all segments in the new iterator. Find the smallest
  6287. ** term that any segment-iterator points to. Iterator pNew will be
  6288. ** used for this term. Also, set any iterator that points to a term that
  6289. ** does not match pToken/nToken to point to EOF */
  6290. pSmall = 0;
  6291. for(ii=0; ii<pNew->nSeg; ii++){
  6292. Fts5SegIter *pII = &pNew->aSeg[ii];
  6293. if( 0==fts5IsTokendataPrefix(&pII->term, pToken, nToken) ){
  6294. fts5SegIterSetEOF(pII);
  6295. }
  6296. if( pII->pLeaf && (!pSmall || fts5BufferCompare(pSmall, &pII->term)>0) ){
  6297. pSmall = &pII->term;
  6298. }
  6299. }
  6300. /* If pSmall is still NULL at this point, then the new iterator does
  6301. ** not point to any terms that match the query. So delete it and break
  6302. ** out of the loop - all required iterators have been collected. */
  6303. if( pSmall==0 ){
  6304. sqlite3Fts5IterClose((Fts5IndexIter*)pNew);
  6305. break;
  6306. }
  6307. /* Append this iterator to the set and continue. */
  6308. pSet = fts5AppendTokendataIter(p, pSet, pNew);
  6309. }
  6310. if( p->rc==SQLITE_OK && pSet ){
  6311. int ii;
  6312. for(ii=0; ii<pSet->nIter; ii++){
  6313. Fts5Iter *pIter = pSet->apIter[ii];
  6314. int iSeg;
  6315. for(iSeg=0; iSeg<pIter->nSeg; iSeg++){
  6316. pIter->aSeg[iSeg].flags |= FTS5_SEGITER_ONETERM;
  6317. }
  6318. fts5MultiIterFinishSetup(p, pIter);
  6319. }
  6320. }
  6321. if( p->rc==SQLITE_OK ){
  6322. pRet = fts5MultiIterAlloc(p, 0);
  6323. }
  6324. if( pRet ){
  6325. pRet->pTokenDataIter = pSet;
  6326. if( pSet ){
  6327. fts5IterSetOutputsTokendata(pRet);
  6328. }else{
  6329. pRet->base.bEof = 1;
  6330. }
  6331. }else{
  6332. fts5TokendataIterDelete(pSet);
  6333. }
  6334. fts5StructureRelease(pStruct);
  6335. fts5BufferFree(&bSeek);
  6336. return pRet;
  6337. }
  6338. /*
  6339. ** Open a new iterator to iterate though all rowid that match the
  6340. ** specified token or token prefix.
  6341. */
  6342. int sqlite3Fts5IndexQuery(
  6343. Fts5Index *p, /* FTS index to query */
  6344. const char *pToken, int nToken, /* Token (or prefix) to query for */
  6345. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  6346. Fts5Colset *pColset, /* Match these columns only */
  6347. Fts5IndexIter **ppIter /* OUT: New iterator object */
  6348. ){
  6349. Fts5Config *pConfig = p->pConfig;
  6350. Fts5Iter *pRet = 0;
  6351. Fts5Buffer buf = {0, 0, 0};
  6352. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  6353. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  6354. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  6355. int iIdx = 0; /* Index to search */
  6356. int iPrefixIdx = 0; /* +1 prefix index */
  6357. int bTokendata = pConfig->bTokendata;
  6358. if( nToken>0 ) memcpy(&buf.p[1], pToken, nToken);
  6359. if( flags & (FTS5INDEX_QUERY_NOTOKENDATA|FTS5INDEX_QUERY_SCAN) ){
  6360. bTokendata = 0;
  6361. }
  6362. /* Figure out which index to search and set iIdx accordingly. If this
  6363. ** is a prefix query for which there is no prefix index, set iIdx to
  6364. ** greater than pConfig->nPrefix to indicate that the query will be
  6365. ** satisfied by scanning multiple terms in the main index.
  6366. **
  6367. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  6368. ** prefix-query. Instead of using a prefix-index (if one exists),
  6369. ** evaluate the prefix query using the main FTS index. This is used
  6370. ** for internal sanity checking by the integrity-check in debug
  6371. ** mode only. */
  6372. #ifdef SQLITE_DEBUG
  6373. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  6374. assert( flags & FTS5INDEX_QUERY_PREFIX );
  6375. iIdx = 1+pConfig->nPrefix;
  6376. }else
  6377. #endif
  6378. if( flags & FTS5INDEX_QUERY_PREFIX ){
  6379. int nChar = fts5IndexCharlen(pToken, nToken);
  6380. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  6381. int nIdxChar = pConfig->aPrefix[iIdx-1];
  6382. if( nIdxChar==nChar ) break;
  6383. if( nIdxChar==nChar+1 ) iPrefixIdx = iIdx;
  6384. }
  6385. }
  6386. if( bTokendata && iIdx==0 ){
  6387. buf.p[0] = '0';
  6388. pRet = fts5SetupTokendataIter(p, buf.p, nToken+1, pColset);
  6389. }else if( iIdx<=pConfig->nPrefix ){
  6390. /* Straight index lookup */
  6391. Fts5Structure *pStruct = fts5StructureRead(p);
  6392. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  6393. if( pStruct ){
  6394. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  6395. pColset, buf.p, nToken+1, -1, 0, &pRet
  6396. );
  6397. fts5StructureRelease(pStruct);
  6398. }
  6399. }else{
  6400. /* Scan multiple terms in the main index */
  6401. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  6402. fts5SetupPrefixIter(p, bDesc, iPrefixIdx, buf.p, nToken+1, pColset,&pRet);
  6403. if( pRet==0 ){
  6404. assert( p->rc!=SQLITE_OK );
  6405. }else{
  6406. assert( pRet->pColset==0 );
  6407. fts5IterSetOutputCb(&p->rc, pRet);
  6408. if( p->rc==SQLITE_OK ){
  6409. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  6410. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  6411. }
  6412. }
  6413. }
  6414. if( p->rc ){
  6415. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  6416. pRet = 0;
  6417. sqlite3Fts5IndexCloseReader(p);
  6418. }
  6419. *ppIter = (Fts5IndexIter*)pRet;
  6420. sqlite3Fts5BufferFree(&buf);
  6421. }
  6422. return fts5IndexReturn(p);
  6423. }
  6424. /*
  6425. ** Return true if the iterator passed as the only argument is at EOF.
  6426. */
  6427. /*
  6428. ** Move to the next matching rowid.
  6429. */
  6430. int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  6431. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6432. assert( pIter->pIndex->rc==SQLITE_OK );
  6433. if( pIter->pTokenDataIter ){
  6434. fts5TokendataIterNext(pIter, 0, 0);
  6435. }else{
  6436. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  6437. }
  6438. return fts5IndexReturn(pIter->pIndex);
  6439. }
  6440. /*
  6441. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  6442. */
  6443. int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  6444. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6445. Fts5Index *p = pIter->pIndex;
  6446. assert( pIter->pIndex->rc==SQLITE_OK );
  6447. fts5MultiIterNext(p, pIter, 0, 0);
  6448. if( p->rc==SQLITE_OK ){
  6449. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  6450. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  6451. fts5DataRelease(pSeg->pLeaf);
  6452. pSeg->pLeaf = 0;
  6453. pIter->base.bEof = 1;
  6454. }
  6455. }
  6456. return fts5IndexReturn(pIter->pIndex);
  6457. }
  6458. /*
  6459. ** Move to the next matching rowid that occurs at or after iMatch. The
  6460. ** definition of "at or after" depends on whether this iterator iterates
  6461. ** in ascending or descending rowid order.
  6462. */
  6463. int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  6464. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6465. if( pIter->pTokenDataIter ){
  6466. fts5TokendataIterNext(pIter, 1, iMatch);
  6467. }else{
  6468. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  6469. }
  6470. return fts5IndexReturn(pIter->pIndex);
  6471. }
  6472. /*
  6473. ** Return the current term.
  6474. */
  6475. const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  6476. int n;
  6477. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  6478. assert_nc( z || n<=1 );
  6479. *pn = n-1;
  6480. return (z ? &z[1] : 0);
  6481. }
  6482. /*
  6483. ** This is used by xInstToken() to access the token at offset iOff, column
  6484. ** iCol of row iRowid. The token is returned via output variables *ppOut
  6485. ** and *pnOut. The iterator passed as the first argument must be a tokendata=1
  6486. ** iterator (pIter->pTokenDataIter!=0).
  6487. */
  6488. int sqlite3Fts5IterToken(
  6489. Fts5IndexIter *pIndexIter,
  6490. i64 iRowid,
  6491. int iCol,
  6492. int iOff,
  6493. const char **ppOut, int *pnOut
  6494. ){
  6495. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6496. Fts5TokenDataIter *pT = pIter->pTokenDataIter;
  6497. Fts5TokenDataMap *aMap = pT->aMap;
  6498. i64 iPos = (((i64)iCol)<<32) + iOff;
  6499. int i1 = 0;
  6500. int i2 = pT->nMap;
  6501. int iTest = 0;
  6502. while( i2>i1 ){
  6503. iTest = (i1 + i2) / 2;
  6504. if( aMap[iTest].iRowid<iRowid ){
  6505. i1 = iTest+1;
  6506. }else if( aMap[iTest].iRowid>iRowid ){
  6507. i2 = iTest;
  6508. }else{
  6509. if( aMap[iTest].iPos<iPos ){
  6510. if( aMap[iTest].iPos<0 ){
  6511. break;
  6512. }
  6513. i1 = iTest+1;
  6514. }else if( aMap[iTest].iPos>iPos ){
  6515. i2 = iTest;
  6516. }else{
  6517. break;
  6518. }
  6519. }
  6520. }
  6521. if( i2>i1 ){
  6522. Fts5Iter *pMap = pT->apIter[aMap[iTest].iIter];
  6523. *ppOut = (const char*)pMap->aSeg[0].term.p+1;
  6524. *pnOut = pMap->aSeg[0].term.n-1;
  6525. }
  6526. return SQLITE_OK;
  6527. }
  6528. /*
  6529. ** Clear any existing entries from the token-map associated with the
  6530. ** iterator passed as the only argument.
  6531. */
  6532. void sqlite3Fts5IndexIterClearTokendata(Fts5IndexIter *pIndexIter){
  6533. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6534. if( pIter && pIter->pTokenDataIter ){
  6535. pIter->pTokenDataIter->nMap = 0;
  6536. }
  6537. }
  6538. /*
  6539. ** Set a token-mapping for the iterator passed as the first argument. This
  6540. ** is used in detail=column or detail=none mode when a token is requested
  6541. ** using the xInstToken() API. In this case the caller tokenizers the
  6542. ** current row and configures the token-mapping via multiple calls to this
  6543. ** function.
  6544. */
  6545. int sqlite3Fts5IndexIterWriteTokendata(
  6546. Fts5IndexIter *pIndexIter,
  6547. const char *pToken, int nToken,
  6548. i64 iRowid, int iCol, int iOff
  6549. ){
  6550. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6551. Fts5TokenDataIter *pT = pIter->pTokenDataIter;
  6552. Fts5Index *p = pIter->pIndex;
  6553. int ii;
  6554. assert( p->pConfig->eDetail!=FTS5_DETAIL_FULL );
  6555. assert( pIter->pTokenDataIter );
  6556. for(ii=0; ii<pT->nIter; ii++){
  6557. Fts5Buffer *pTerm = &pT->apIter[ii]->aSeg[0].term;
  6558. if( nToken==pTerm->n-1 && memcmp(pToken, pTerm->p+1, nToken)==0 ) break;
  6559. }
  6560. if( ii<pT->nIter ){
  6561. fts5TokendataIterAppendMap(p, pT, ii, iRowid, (((i64)iCol)<<32) + iOff);
  6562. }
  6563. return fts5IndexReturn(p);
  6564. }
  6565. /*
  6566. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  6567. */
  6568. void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  6569. if( pIndexIter ){
  6570. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  6571. Fts5Index *pIndex = pIter->pIndex;
  6572. fts5TokendataIterDelete(pIter->pTokenDataIter);
  6573. fts5MultiIterFree(pIter);
  6574. sqlite3Fts5IndexCloseReader(pIndex);
  6575. }
  6576. }
  6577. /*
  6578. ** Read and decode the "averages" record from the database.
  6579. **
  6580. ** Parameter anSize must point to an array of size nCol, where nCol is
  6581. ** the number of user defined columns in the FTS table.
  6582. */
  6583. int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  6584. int nCol = p->pConfig->nCol;
  6585. Fts5Data *pData;
  6586. *pnRow = 0;
  6587. memset(anSize, 0, sizeof(i64) * nCol);
  6588. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  6589. if( p->rc==SQLITE_OK && pData->nn ){
  6590. int i = 0;
  6591. int iCol;
  6592. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  6593. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  6594. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  6595. }
  6596. }
  6597. fts5DataRelease(pData);
  6598. return fts5IndexReturn(p);
  6599. }
  6600. /*
  6601. ** Replace the current "averages" record with the contents of the buffer
  6602. ** supplied as the second argument.
  6603. */
  6604. int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  6605. assert( p->rc==SQLITE_OK );
  6606. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  6607. return fts5IndexReturn(p);
  6608. }
  6609. /*
  6610. ** Return the total number of blocks this module has read from the %_data
  6611. ** table since it was created.
  6612. */
  6613. int sqlite3Fts5IndexReads(Fts5Index *p){
  6614. return p->nRead;
  6615. }
  6616. /*
  6617. ** Set the 32-bit cookie value stored at the start of all structure
  6618. ** records to the value passed as the second argument.
  6619. **
  6620. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  6621. ** occurs.
  6622. */
  6623. int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  6624. int rc; /* Return code */
  6625. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  6626. u8 aCookie[4]; /* Binary representation of iNew */
  6627. sqlite3_blob *pBlob = 0;
  6628. assert( p->rc==SQLITE_OK );
  6629. sqlite3Fts5Put32(aCookie, iNew);
  6630. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  6631. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  6632. );
  6633. if( rc==SQLITE_OK ){
  6634. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  6635. rc = sqlite3_blob_close(pBlob);
  6636. }
  6637. return rc;
  6638. }
  6639. int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  6640. Fts5Structure *pStruct;
  6641. pStruct = fts5StructureRead(p);
  6642. fts5StructureRelease(pStruct);
  6643. return fts5IndexReturn(p);
  6644. }
  6645. /*
  6646. ** Retrieve the origin value that will be used for the segment currently
  6647. ** being accumulated in the in-memory hash table when it is flushed to
  6648. ** disk. If successful, SQLITE_OK is returned and (*piOrigin) set to
  6649. ** the queried value. Or, if an error occurs, an error code is returned
  6650. ** and the final value of (*piOrigin) is undefined.
  6651. */
  6652. int sqlite3Fts5IndexGetOrigin(Fts5Index *p, i64 *piOrigin){
  6653. Fts5Structure *pStruct;
  6654. pStruct = fts5StructureRead(p);
  6655. if( pStruct ){
  6656. *piOrigin = pStruct->nOriginCntr;
  6657. fts5StructureRelease(pStruct);
  6658. }
  6659. return fts5IndexReturn(p);
  6660. }
  6661. /*
  6662. ** Buffer pPg contains a page of a tombstone hash table - one of nPg pages
  6663. ** associated with the same segment. This function adds rowid iRowid to
  6664. ** the hash table. The caller is required to guarantee that there is at
  6665. ** least one free slot on the page.
  6666. **
  6667. ** If parameter bForce is false and the hash table is deemed to be full
  6668. ** (more than half of the slots are occupied), then non-zero is returned
  6669. ** and iRowid not inserted. Or, if bForce is true or if the hash table page
  6670. ** is not full, iRowid is inserted and zero returned.
  6671. */
  6672. static int fts5IndexTombstoneAddToPage(
  6673. Fts5Data *pPg,
  6674. int bForce,
  6675. int nPg,
  6676. u64 iRowid
  6677. ){
  6678. const int szKey = TOMBSTONE_KEYSIZE(pPg);
  6679. const int nSlot = TOMBSTONE_NSLOT(pPg);
  6680. const int nElem = fts5GetU32(&pPg->p[4]);
  6681. int iSlot = (iRowid / nPg) % nSlot;
  6682. int nCollide = nSlot;
  6683. if( szKey==4 && iRowid>0xFFFFFFFF ) return 2;
  6684. if( iRowid==0 ){
  6685. pPg->p[1] = 0x01;
  6686. return 0;
  6687. }
  6688. if( bForce==0 && nElem>=(nSlot/2) ){
  6689. return 1;
  6690. }
  6691. fts5PutU32(&pPg->p[4], nElem+1);
  6692. if( szKey==4 ){
  6693. u32 *aSlot = (u32*)&pPg->p[8];
  6694. while( aSlot[iSlot] ){
  6695. iSlot = (iSlot + 1) % nSlot;
  6696. if( nCollide--==0 ) return 0;
  6697. }
  6698. fts5PutU32((u8*)&aSlot[iSlot], (u32)iRowid);
  6699. }else{
  6700. u64 *aSlot = (u64*)&pPg->p[8];
  6701. while( aSlot[iSlot] ){
  6702. iSlot = (iSlot + 1) % nSlot;
  6703. if( nCollide--==0 ) return 0;
  6704. }
  6705. fts5PutU64((u8*)&aSlot[iSlot], iRowid);
  6706. }
  6707. return 0;
  6708. }
  6709. /*
  6710. ** This function attempts to build a new hash containing all the keys
  6711. ** currently in the tombstone hash table for segment pSeg. The new
  6712. ** hash will be stored in the nOut buffers passed in array apOut[].
  6713. ** All pages of the new hash use key-size szKey (4 or 8).
  6714. **
  6715. ** Return 0 if the hash is successfully rebuilt into the nOut pages.
  6716. ** Or non-zero if it is not (because one page became overfull). In this
  6717. ** case the caller should retry with a larger nOut parameter.
  6718. **
  6719. ** Parameter pData1 is page iPg1 of the hash table being rebuilt.
  6720. */
  6721. static int fts5IndexTombstoneRehash(
  6722. Fts5Index *p,
  6723. Fts5StructureSegment *pSeg, /* Segment to rebuild hash of */
  6724. Fts5Data *pData1, /* One page of current hash - or NULL */
  6725. int iPg1, /* Which page of the current hash is pData1 */
  6726. int szKey, /* 4 or 8, the keysize */
  6727. int nOut, /* Number of output pages */
  6728. Fts5Data **apOut /* Array of output hash pages */
  6729. ){
  6730. int ii;
  6731. int res = 0;
  6732. /* Initialize the headers of all the output pages */
  6733. for(ii=0; ii<nOut; ii++){
  6734. apOut[ii]->p[0] = szKey;
  6735. fts5PutU32(&apOut[ii]->p[4], 0);
  6736. }
  6737. /* Loop through the current pages of the hash table. */
  6738. for(ii=0; res==0 && ii<pSeg->nPgTombstone; ii++){
  6739. Fts5Data *pData = 0; /* Page ii of the current hash table */
  6740. Fts5Data *pFree = 0; /* Free this at the end of the loop */
  6741. if( iPg1==ii ){
  6742. pData = pData1;
  6743. }else{
  6744. pFree = pData = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii));
  6745. }
  6746. if( pData ){
  6747. int szKeyIn = TOMBSTONE_KEYSIZE(pData);
  6748. int nSlotIn = (pData->nn - 8) / szKeyIn;
  6749. int iIn;
  6750. for(iIn=0; iIn<nSlotIn; iIn++){
  6751. u64 iVal = 0;
  6752. /* Read the value from slot iIn of the input page into iVal. */
  6753. if( szKeyIn==4 ){
  6754. u32 *aSlot = (u32*)&pData->p[8];
  6755. if( aSlot[iIn] ) iVal = fts5GetU32((u8*)&aSlot[iIn]);
  6756. }else{
  6757. u64 *aSlot = (u64*)&pData->p[8];
  6758. if( aSlot[iIn] ) iVal = fts5GetU64((u8*)&aSlot[iIn]);
  6759. }
  6760. /* If iVal is not 0 at this point, insert it into the new hash table */
  6761. if( iVal ){
  6762. Fts5Data *pPg = apOut[(iVal % nOut)];
  6763. res = fts5IndexTombstoneAddToPage(pPg, 0, nOut, iVal);
  6764. if( res ) break;
  6765. }
  6766. }
  6767. /* If this is page 0 of the old hash, copy the rowid-0-flag from the
  6768. ** old hash to the new. */
  6769. if( ii==0 ){
  6770. apOut[0]->p[1] = pData->p[1];
  6771. }
  6772. }
  6773. fts5DataRelease(pFree);
  6774. }
  6775. return res;
  6776. }
  6777. /*
  6778. ** This is called to rebuild the hash table belonging to segment pSeg.
  6779. ** If parameter pData1 is not NULL, then one page of the existing hash table
  6780. ** has already been loaded - pData1, which is page iPg1. The key-size for
  6781. ** the new hash table is szKey (4 or 8).
  6782. **
  6783. ** If successful, the new hash table is not written to disk. Instead,
  6784. ** output parameter (*pnOut) is set to the number of pages in the new
  6785. ** hash table, and (*papOut) to point to an array of buffers containing
  6786. ** the new page data.
  6787. **
  6788. ** If an error occurs, an error code is left in the Fts5Index object and
  6789. ** both output parameters set to 0 before returning.
  6790. */
  6791. static void fts5IndexTombstoneRebuild(
  6792. Fts5Index *p,
  6793. Fts5StructureSegment *pSeg, /* Segment to rebuild hash of */
  6794. Fts5Data *pData1, /* One page of current hash - or NULL */
  6795. int iPg1, /* Which page of the current hash is pData1 */
  6796. int szKey, /* 4 or 8, the keysize */
  6797. int *pnOut, /* OUT: Number of output pages */
  6798. Fts5Data ***papOut /* OUT: Output hash pages */
  6799. ){
  6800. const int MINSLOT = 32;
  6801. int nSlotPerPage = MAX(MINSLOT, (p->pConfig->pgsz - 8) / szKey);
  6802. int nSlot = 0; /* Number of slots in each output page */
  6803. int nOut = 0;
  6804. /* Figure out how many output pages (nOut) and how many slots per
  6805. ** page (nSlot). There are three possibilities:
  6806. **
  6807. ** 1. The hash table does not yet exist. In this case the new hash
  6808. ** table will consist of a single page with MINSLOT slots.
  6809. **
  6810. ** 2. The hash table exists but is currently a single page. In this
  6811. ** case an attempt is made to grow the page to accommodate the new
  6812. ** entry. The page is allowed to grow up to nSlotPerPage (see above)
  6813. ** slots.
  6814. **
  6815. ** 3. The hash table already consists of more than one page, or of
  6816. ** a single page already so large that it cannot be grown. In this
  6817. ** case the new hash consists of (nPg*2+1) pages of nSlotPerPage
  6818. ** slots each, where nPg is the current number of pages in the
  6819. ** hash table.
  6820. */
  6821. if( pSeg->nPgTombstone==0 ){
  6822. /* Case 1. */
  6823. nOut = 1;
  6824. nSlot = MINSLOT;
  6825. }else if( pSeg->nPgTombstone==1 ){
  6826. /* Case 2. */
  6827. int nElem = (int)fts5GetU32(&pData1->p[4]);
  6828. assert( pData1 && iPg1==0 );
  6829. nOut = 1;
  6830. nSlot = MAX(nElem*4, MINSLOT);
  6831. if( nSlot>nSlotPerPage ) nOut = 0;
  6832. }
  6833. if( nOut==0 ){
  6834. /* Case 3. */
  6835. nOut = (pSeg->nPgTombstone * 2 + 1);
  6836. nSlot = nSlotPerPage;
  6837. }
  6838. /* Allocate the required array and output pages */
  6839. while( 1 ){
  6840. int res = 0;
  6841. int ii = 0;
  6842. int szPage = 0;
  6843. Fts5Data **apOut = 0;
  6844. /* Allocate space for the new hash table */
  6845. assert( nSlot>=MINSLOT );
  6846. apOut = (Fts5Data**)sqlite3Fts5MallocZero(&p->rc, sizeof(Fts5Data*) * nOut);
  6847. szPage = 8 + nSlot*szKey;
  6848. for(ii=0; ii<nOut; ii++){
  6849. Fts5Data *pNew = (Fts5Data*)sqlite3Fts5MallocZero(&p->rc,
  6850. sizeof(Fts5Data)+szPage
  6851. );
  6852. if( pNew ){
  6853. pNew->nn = szPage;
  6854. pNew->p = (u8*)&pNew[1];
  6855. apOut[ii] = pNew;
  6856. }
  6857. }
  6858. /* Rebuild the hash table. */
  6859. if( p->rc==SQLITE_OK ){
  6860. res = fts5IndexTombstoneRehash(p, pSeg, pData1, iPg1, szKey, nOut, apOut);
  6861. }
  6862. if( res==0 ){
  6863. if( p->rc ){
  6864. fts5IndexFreeArray(apOut, nOut);
  6865. apOut = 0;
  6866. nOut = 0;
  6867. }
  6868. *pnOut = nOut;
  6869. *papOut = apOut;
  6870. break;
  6871. }
  6872. /* If control flows to here, it was not possible to rebuild the hash
  6873. ** table. Free all buffers and then try again with more pages. */
  6874. assert( p->rc==SQLITE_OK );
  6875. fts5IndexFreeArray(apOut, nOut);
  6876. nSlot = nSlotPerPage;
  6877. nOut = nOut*2 + 1;
  6878. }
  6879. }
  6880. /*
  6881. ** Add a tombstone for rowid iRowid to segment pSeg.
  6882. */
  6883. static void fts5IndexTombstoneAdd(
  6884. Fts5Index *p,
  6885. Fts5StructureSegment *pSeg,
  6886. u64 iRowid
  6887. ){
  6888. Fts5Data *pPg = 0;
  6889. int iPg = -1;
  6890. int szKey = 0;
  6891. int nHash = 0;
  6892. Fts5Data **apHash = 0;
  6893. p->nContentlessDelete++;
  6894. if( pSeg->nPgTombstone>0 ){
  6895. iPg = iRowid % pSeg->nPgTombstone;
  6896. pPg = fts5DataRead(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg));
  6897. if( pPg==0 ){
  6898. assert( p->rc!=SQLITE_OK );
  6899. return;
  6900. }
  6901. if( 0==fts5IndexTombstoneAddToPage(pPg, 0, pSeg->nPgTombstone, iRowid) ){
  6902. fts5DataWrite(p, FTS5_TOMBSTONE_ROWID(pSeg->iSegid,iPg), pPg->p, pPg->nn);
  6903. fts5DataRelease(pPg);
  6904. return;
  6905. }
  6906. }
  6907. /* Have to rebuild the hash table. First figure out the key-size (4 or 8). */
  6908. szKey = pPg ? TOMBSTONE_KEYSIZE(pPg) : 4;
  6909. if( iRowid>0xFFFFFFFF ) szKey = 8;
  6910. /* Rebuild the hash table */
  6911. fts5IndexTombstoneRebuild(p, pSeg, pPg, iPg, szKey, &nHash, &apHash);
  6912. assert( p->rc==SQLITE_OK || (nHash==0 && apHash==0) );
  6913. /* If all has succeeded, write the new rowid into one of the new hash
  6914. ** table pages, then write them all out to disk. */
  6915. if( nHash ){
  6916. int ii = 0;
  6917. fts5IndexTombstoneAddToPage(apHash[iRowid % nHash], 1, nHash, iRowid);
  6918. for(ii=0; ii<nHash; ii++){
  6919. i64 iTombstoneRowid = FTS5_TOMBSTONE_ROWID(pSeg->iSegid, ii);
  6920. fts5DataWrite(p, iTombstoneRowid, apHash[ii]->p, apHash[ii]->nn);
  6921. }
  6922. pSeg->nPgTombstone = nHash;
  6923. fts5StructureWrite(p, p->pStruct);
  6924. }
  6925. fts5DataRelease(pPg);
  6926. fts5IndexFreeArray(apHash, nHash);
  6927. }
  6928. /*
  6929. ** Add iRowid to the tombstone list of the segment or segments that contain
  6930. ** rows from origin iOrigin. Return SQLITE_OK if successful, or an SQLite
  6931. ** error code otherwise.
  6932. */
  6933. int sqlite3Fts5IndexContentlessDelete(Fts5Index *p, i64 iOrigin, i64 iRowid){
  6934. Fts5Structure *pStruct;
  6935. pStruct = fts5StructureRead(p);
  6936. if( pStruct ){
  6937. int bFound = 0; /* True after pSeg->nEntryTombstone incr. */
  6938. int iLvl;
  6939. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  6940. int iSeg;
  6941. for(iSeg=pStruct->aLevel[iLvl].nSeg-1; iSeg>=0; iSeg--){
  6942. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  6943. if( pSeg->iOrigin1<=(u64)iOrigin && pSeg->iOrigin2>=(u64)iOrigin ){
  6944. if( bFound==0 ){
  6945. pSeg->nEntryTombstone++;
  6946. bFound = 1;
  6947. }
  6948. fts5IndexTombstoneAdd(p, pSeg, iRowid);
  6949. }
  6950. }
  6951. }
  6952. fts5StructureRelease(pStruct);
  6953. }
  6954. return fts5IndexReturn(p);
  6955. }
  6956. /*************************************************************************
  6957. **************************************************************************
  6958. ** Below this point is the implementation of the integrity-check
  6959. ** functionality.
  6960. */
  6961. /*
  6962. ** Return a simple checksum value based on the arguments.
  6963. */
  6964. u64 sqlite3Fts5IndexEntryCksum(
  6965. i64 iRowid,
  6966. int iCol,
  6967. int iPos,
  6968. int iIdx,
  6969. const char *pTerm,
  6970. int nTerm
  6971. ){
  6972. int i;
  6973. u64 ret = iRowid;
  6974. ret += (ret<<3) + iCol;
  6975. ret += (ret<<3) + iPos;
  6976. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  6977. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  6978. return ret;
  6979. }
  6980. #ifdef SQLITE_DEBUG
  6981. /*
  6982. ** This function is purely an internal test. It does not contribute to
  6983. ** FTS functionality, or even the integrity-check, in any way.
  6984. **
  6985. ** Instead, it tests that the same set of pgno/rowid combinations are
  6986. ** visited regardless of whether the doclist-index identified by parameters
  6987. ** iSegid/iLeaf is iterated in forwards or reverse order.
  6988. */
  6989. static void fts5TestDlidxReverse(
  6990. Fts5Index *p,
  6991. int iSegid, /* Segment id to load from */
  6992. int iLeaf /* Load doclist-index for this leaf */
  6993. ){
  6994. Fts5DlidxIter *pDlidx = 0;
  6995. u64 cksum1 = 13;
  6996. u64 cksum2 = 13;
  6997. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  6998. fts5DlidxIterEof(p, pDlidx)==0;
  6999. fts5DlidxIterNext(p, pDlidx)
  7000. ){
  7001. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  7002. int pgno = fts5DlidxIterPgno(pDlidx);
  7003. assert( pgno>iLeaf );
  7004. cksum1 += iRowid + ((i64)pgno<<32);
  7005. }
  7006. fts5DlidxIterFree(pDlidx);
  7007. pDlidx = 0;
  7008. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  7009. fts5DlidxIterEof(p, pDlidx)==0;
  7010. fts5DlidxIterPrev(p, pDlidx)
  7011. ){
  7012. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  7013. int pgno = fts5DlidxIterPgno(pDlidx);
  7014. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  7015. cksum2 += iRowid + ((i64)pgno<<32);
  7016. }
  7017. fts5DlidxIterFree(pDlidx);
  7018. pDlidx = 0;
  7019. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  7020. }
  7021. static int fts5QueryCksum(
  7022. Fts5Index *p, /* Fts5 index object */
  7023. int iIdx,
  7024. const char *z, /* Index key to query for */
  7025. int n, /* Size of index key in bytes */
  7026. int flags, /* Flags for Fts5IndexQuery */
  7027. u64 *pCksum /* IN/OUT: Checksum value */
  7028. ){
  7029. int eDetail = p->pConfig->eDetail;
  7030. u64 cksum = *pCksum;
  7031. Fts5IndexIter *pIter = 0;
  7032. int rc = sqlite3Fts5IndexQuery(
  7033. p, z, n, (flags | FTS5INDEX_QUERY_NOTOKENDATA), 0, &pIter
  7034. );
  7035. while( rc==SQLITE_OK && ALWAYS(pIter!=0) && 0==sqlite3Fts5IterEof(pIter) ){
  7036. i64 rowid = pIter->iRowid;
  7037. if( eDetail==FTS5_DETAIL_NONE ){
  7038. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  7039. }else{
  7040. Fts5PoslistReader sReader;
  7041. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  7042. sReader.bEof==0;
  7043. sqlite3Fts5PoslistReaderNext(&sReader)
  7044. ){
  7045. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  7046. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  7047. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  7048. }
  7049. }
  7050. if( rc==SQLITE_OK ){
  7051. rc = sqlite3Fts5IterNext(pIter);
  7052. }
  7053. }
  7054. sqlite3Fts5IterClose(pIter);
  7055. *pCksum = cksum;
  7056. return rc;
  7057. }
  7058. /*
  7059. ** Check if buffer z[], size n bytes, contains as series of valid utf-8
  7060. ** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
  7061. ** contain valid utf-8, return non-zero.
  7062. */
  7063. static int fts5TestUtf8(const char *z, int n){
  7064. int i = 0;
  7065. assert_nc( n>0 );
  7066. while( i<n ){
  7067. if( (z[i] & 0x80)==0x00 ){
  7068. i++;
  7069. }else
  7070. if( (z[i] & 0xE0)==0xC0 ){
  7071. if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
  7072. i += 2;
  7073. }else
  7074. if( (z[i] & 0xF0)==0xE0 ){
  7075. if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
  7076. i += 3;
  7077. }else
  7078. if( (z[i] & 0xF8)==0xF0 ){
  7079. if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
  7080. if( (z[i+2] & 0xC0)!=0x80 ) return 1;
  7081. i += 3;
  7082. }else{
  7083. return 1;
  7084. }
  7085. }
  7086. return 0;
  7087. }
  7088. /*
  7089. ** This function is also purely an internal test. It does not contribute to
  7090. ** FTS functionality, or even the integrity-check, in any way.
  7091. */
  7092. static void fts5TestTerm(
  7093. Fts5Index *p,
  7094. Fts5Buffer *pPrev, /* Previous term */
  7095. const char *z, int n, /* Possibly new term to test */
  7096. u64 expected,
  7097. u64 *pCksum
  7098. ){
  7099. int rc = p->rc;
  7100. if( pPrev->n==0 ){
  7101. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  7102. }else
  7103. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  7104. u64 cksum3 = *pCksum;
  7105. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  7106. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  7107. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  7108. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  7109. u64 ck1 = 0;
  7110. u64 ck2 = 0;
  7111. /* Check that the results returned for ASC and DESC queries are
  7112. ** the same. If not, call this corruption. */
  7113. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  7114. if( rc==SQLITE_OK ){
  7115. int f = flags|FTS5INDEX_QUERY_DESC;
  7116. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  7117. }
  7118. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  7119. /* If this is a prefix query, check that the results returned if the
  7120. ** the index is disabled are the same. In both ASC and DESC order.
  7121. **
  7122. ** This check may only be performed if the hash table is empty. This
  7123. ** is because the hash table only supports a single scan query at
  7124. ** a time, and the multi-iter loop from which this function is called
  7125. ** is already performing such a scan.
  7126. **
  7127. ** Also only do this if buffer zTerm contains nTerm bytes of valid
  7128. ** utf-8. Otherwise, the last part of the buffer contents might contain
  7129. ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
  7130. ** character stored in the main fts index, which will cause the
  7131. ** test to fail. */
  7132. if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
  7133. if( iIdx>0 && rc==SQLITE_OK ){
  7134. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  7135. ck2 = 0;
  7136. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  7137. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  7138. }
  7139. if( iIdx>0 && rc==SQLITE_OK ){
  7140. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  7141. ck2 = 0;
  7142. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  7143. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  7144. }
  7145. }
  7146. cksum3 ^= ck1;
  7147. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  7148. if( rc==SQLITE_OK && cksum3!=expected ){
  7149. rc = FTS5_CORRUPT;
  7150. }
  7151. *pCksum = cksum3;
  7152. }
  7153. p->rc = rc;
  7154. }
  7155. #else
  7156. # define fts5TestDlidxReverse(x,y,z)
  7157. # define fts5TestTerm(u,v,w,x,y,z)
  7158. #endif
  7159. /*
  7160. ** Check that:
  7161. **
  7162. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  7163. ** contain zero terms.
  7164. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  7165. ** contain zero rowids.
  7166. */
  7167. static void fts5IndexIntegrityCheckEmpty(
  7168. Fts5Index *p,
  7169. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  7170. int iFirst,
  7171. int iNoRowid,
  7172. int iLast
  7173. ){
  7174. int i;
  7175. /* Now check that the iter.nEmpty leaves following the current leaf
  7176. ** (a) exist and (b) contain no terms. */
  7177. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  7178. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  7179. if( pLeaf ){
  7180. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  7181. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  7182. }
  7183. fts5DataRelease(pLeaf);
  7184. }
  7185. }
  7186. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  7187. i64 iTermOff = 0;
  7188. int ii;
  7189. Fts5Buffer buf1 = {0,0,0};
  7190. Fts5Buffer buf2 = {0,0,0};
  7191. ii = pLeaf->szLeaf;
  7192. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  7193. int res;
  7194. i64 iOff;
  7195. int nIncr;
  7196. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  7197. iTermOff += nIncr;
  7198. iOff = iTermOff;
  7199. if( iOff>=pLeaf->szLeaf ){
  7200. p->rc = FTS5_CORRUPT;
  7201. }else if( iTermOff==nIncr ){
  7202. int nByte;
  7203. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  7204. if( (iOff+nByte)>pLeaf->szLeaf ){
  7205. p->rc = FTS5_CORRUPT;
  7206. }else{
  7207. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  7208. }
  7209. }else{
  7210. int nKeep, nByte;
  7211. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  7212. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  7213. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  7214. p->rc = FTS5_CORRUPT;
  7215. }else{
  7216. buf1.n = nKeep;
  7217. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  7218. }
  7219. if( p->rc==SQLITE_OK ){
  7220. res = fts5BufferCompare(&buf1, &buf2);
  7221. if( res<=0 ) p->rc = FTS5_CORRUPT;
  7222. }
  7223. }
  7224. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  7225. }
  7226. fts5BufferFree(&buf1);
  7227. fts5BufferFree(&buf2);
  7228. }
  7229. static void fts5IndexIntegrityCheckSegment(
  7230. Fts5Index *p, /* FTS5 backend object */
  7231. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  7232. ){
  7233. Fts5Config *pConfig = p->pConfig;
  7234. int bSecureDelete = (pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE);
  7235. sqlite3_stmt *pStmt = 0;
  7236. int rc2;
  7237. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  7238. int iDlidxPrevLeaf = pSeg->pgnoLast;
  7239. if( pSeg->pgnoFirst==0 ) return;
  7240. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  7241. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d "
  7242. "ORDER BY 1, 2",
  7243. pConfig->zDb, pConfig->zName, pSeg->iSegid
  7244. ));
  7245. /* Iterate through the b-tree hierarchy. */
  7246. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  7247. i64 iRow; /* Rowid for this leaf */
  7248. Fts5Data *pLeaf; /* Data for this leaf */
  7249. const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
  7250. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  7251. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  7252. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  7253. /* If the leaf in question has already been trimmed from the segment,
  7254. ** ignore this b-tree entry. Otherwise, load it into memory. */
  7255. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  7256. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  7257. pLeaf = fts5LeafRead(p, iRow);
  7258. if( pLeaf==0 ) break;
  7259. /* Check that the leaf contains at least one term, and that it is equal
  7260. ** to or larger than the split-key in zIdxTerm. Also check that if there
  7261. ** is also a rowid pointer within the leaf page header, it points to a
  7262. ** location before the term. */
  7263. if( pLeaf->nn<=pLeaf->szLeaf ){
  7264. if( nIdxTerm==0
  7265. && pConfig->iVersion==FTS5_CURRENT_VERSION_SECUREDELETE
  7266. && pLeaf->nn==pLeaf->szLeaf
  7267. && pLeaf->nn==4
  7268. ){
  7269. /* special case - the very first page in a segment keeps its %_idx
  7270. ** entry even if all the terms are removed from it by secure-delete
  7271. ** operations. */
  7272. }else{
  7273. p->rc = FTS5_CORRUPT;
  7274. }
  7275. }else{
  7276. int iOff; /* Offset of first term on leaf */
  7277. int iRowidOff; /* Offset of first rowid on leaf */
  7278. int nTerm; /* Size of term on leaf in bytes */
  7279. int res; /* Comparison of term and split-key */
  7280. iOff = fts5LeafFirstTermOff(pLeaf);
  7281. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  7282. if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
  7283. p->rc = FTS5_CORRUPT;
  7284. }else{
  7285. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  7286. res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  7287. if( res==0 ) res = nTerm - nIdxTerm;
  7288. if( res<0 ) p->rc = FTS5_CORRUPT;
  7289. }
  7290. fts5IntegrityCheckPgidx(p, pLeaf);
  7291. }
  7292. fts5DataRelease(pLeaf);
  7293. if( p->rc ) break;
  7294. /* Now check that the iter.nEmpty leaves following the current leaf
  7295. ** (a) exist and (b) contain no terms. */
  7296. fts5IndexIntegrityCheckEmpty(
  7297. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  7298. );
  7299. if( p->rc ) break;
  7300. /* If there is a doclist-index, check that it looks right. */
  7301. if( bIdxDlidx ){
  7302. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  7303. int iPrevLeaf = iIdxLeaf;
  7304. int iSegid = pSeg->iSegid;
  7305. int iPg = 0;
  7306. i64 iKey;
  7307. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  7308. fts5DlidxIterEof(p, pDlidx)==0;
  7309. fts5DlidxIterNext(p, pDlidx)
  7310. ){
  7311. /* Check any rowid-less pages that occur before the current leaf. */
  7312. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  7313. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  7314. pLeaf = fts5DataRead(p, iKey);
  7315. if( pLeaf ){
  7316. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  7317. fts5DataRelease(pLeaf);
  7318. }
  7319. }
  7320. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  7321. /* Check that the leaf page indicated by the iterator really does
  7322. ** contain the rowid suggested by the same. */
  7323. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  7324. pLeaf = fts5DataRead(p, iKey);
  7325. if( pLeaf ){
  7326. i64 iRowid;
  7327. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  7328. ASSERT_SZLEAF_OK(pLeaf);
  7329. if( iRowidOff>=pLeaf->szLeaf ){
  7330. p->rc = FTS5_CORRUPT;
  7331. }else if( bSecureDelete==0 || iRowidOff>0 ){
  7332. i64 iDlRowid = fts5DlidxIterRowid(pDlidx);
  7333. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  7334. if( iRowid<iDlRowid || (bSecureDelete==0 && iRowid!=iDlRowid) ){
  7335. p->rc = FTS5_CORRUPT;
  7336. }
  7337. }
  7338. fts5DataRelease(pLeaf);
  7339. }
  7340. }
  7341. iDlidxPrevLeaf = iPg;
  7342. fts5DlidxIterFree(pDlidx);
  7343. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  7344. }else{
  7345. iDlidxPrevLeaf = pSeg->pgnoLast;
  7346. /* TODO: Check there is no doclist index */
  7347. }
  7348. iIdxPrevLeaf = iIdxLeaf;
  7349. }
  7350. rc2 = sqlite3_finalize(pStmt);
  7351. if( p->rc==SQLITE_OK ) p->rc = rc2;
  7352. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  7353. #if 0
  7354. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  7355. p->rc = FTS5_CORRUPT;
  7356. }
  7357. #endif
  7358. }
  7359. /*
  7360. ** Run internal checks to ensure that the FTS index (a) is internally
  7361. ** consistent and (b) contains entries for which the XOR of the checksums
  7362. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  7363. **
  7364. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  7365. ** checksum does not match. Return SQLITE_OK if all checks pass without
  7366. ** error, or some other SQLite error code if another error (e.g. OOM)
  7367. ** occurs.
  7368. */
  7369. int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
  7370. int eDetail = p->pConfig->eDetail;
  7371. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  7372. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  7373. Fts5Iter *pIter; /* Used to iterate through entire index */
  7374. Fts5Structure *pStruct; /* Index structure */
  7375. int iLvl, iSeg;
  7376. #ifdef SQLITE_DEBUG
  7377. /* Used by extra internal tests only run if NDEBUG is not defined */
  7378. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  7379. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  7380. #endif
  7381. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  7382. /* Load the FTS index structure */
  7383. pStruct = fts5StructureRead(p);
  7384. if( pStruct==0 ){
  7385. assert( p->rc!=SQLITE_OK );
  7386. return fts5IndexReturn(p);
  7387. }
  7388. /* Check that the internal nodes of each segment match the leaves */
  7389. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  7390. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  7391. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  7392. fts5IndexIntegrityCheckSegment(p, pSeg);
  7393. }
  7394. }
  7395. /* The cksum argument passed to this function is a checksum calculated
  7396. ** based on all expected entries in the FTS index (including prefix index
  7397. ** entries). This block checks that a checksum calculated based on the
  7398. ** actual contents of FTS index is identical.
  7399. **
  7400. ** Two versions of the same checksum are calculated. The first (stack
  7401. ** variable cksum2) based on entries extracted from the full-text index
  7402. ** while doing a linear scan of each individual index in turn.
  7403. **
  7404. ** As each term visited by the linear scans, a separate query for the
  7405. ** same term is performed. cksum3 is calculated based on the entries
  7406. ** extracted by these queries.
  7407. */
  7408. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  7409. fts5MultiIterEof(p, pIter)==0;
  7410. fts5MultiIterNext(p, pIter, 0, 0)
  7411. ){
  7412. int n; /* Size of term in bytes */
  7413. i64 iPos = 0; /* Position read from poslist */
  7414. int iOff = 0; /* Offset within poslist */
  7415. i64 iRowid = fts5MultiIterRowid(pIter);
  7416. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  7417. /* If this is a new term, query for it. Update cksum3 with the results. */
  7418. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  7419. if( p->rc ) break;
  7420. if( eDetail==FTS5_DETAIL_NONE ){
  7421. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  7422. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  7423. }
  7424. }else{
  7425. poslist.n = 0;
  7426. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  7427. fts5BufferAppendBlob(&p->rc, &poslist, 4, (const u8*)"\0\0\0\0");
  7428. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  7429. int iCol = FTS5_POS2COLUMN(iPos);
  7430. int iTokOff = FTS5_POS2OFFSET(iPos);
  7431. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  7432. }
  7433. }
  7434. }
  7435. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  7436. fts5MultiIterFree(pIter);
  7437. if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  7438. fts5StructureRelease(pStruct);
  7439. #ifdef SQLITE_DEBUG
  7440. fts5BufferFree(&term);
  7441. #endif
  7442. fts5BufferFree(&poslist);
  7443. return fts5IndexReturn(p);
  7444. }
  7445. /*************************************************************************
  7446. **************************************************************************
  7447. ** Below this point is the implementation of the fts5_decode() scalar
  7448. ** function only.
  7449. */
  7450. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7451. /*
  7452. ** Decode a segment-data rowid from the %_data table. This function is
  7453. ** the opposite of macro FTS5_SEGMENT_ROWID().
  7454. */
  7455. static void fts5DecodeRowid(
  7456. i64 iRowid, /* Rowid from %_data table */
  7457. int *pbTombstone, /* OUT: Tombstone hash flag */
  7458. int *piSegid, /* OUT: Segment id */
  7459. int *pbDlidx, /* OUT: Dlidx flag */
  7460. int *piHeight, /* OUT: Height */
  7461. int *piPgno /* OUT: Page number */
  7462. ){
  7463. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  7464. iRowid >>= FTS5_DATA_PAGE_B;
  7465. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  7466. iRowid >>= FTS5_DATA_HEIGHT_B;
  7467. *pbDlidx = (int)(iRowid & 0x0001);
  7468. iRowid >>= FTS5_DATA_DLI_B;
  7469. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  7470. iRowid >>= FTS5_DATA_ID_B;
  7471. *pbTombstone = (int)(iRowid & 0x0001);
  7472. }
  7473. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7474. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7475. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  7476. int iSegid, iHeight, iPgno, bDlidx, bTomb; /* Rowid compenents */
  7477. fts5DecodeRowid(iKey, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
  7478. if( iSegid==0 ){
  7479. if( iKey==FTS5_AVERAGES_ROWID ){
  7480. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  7481. }else{
  7482. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  7483. }
  7484. }
  7485. else{
  7486. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%s%ssegid=%d h=%d pgno=%d}",
  7487. bDlidx ? "dlidx " : "",
  7488. bTomb ? "tombstone " : "",
  7489. iSegid, iHeight, iPgno
  7490. );
  7491. }
  7492. }
  7493. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7494. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7495. static void fts5DebugStructure(
  7496. int *pRc, /* IN/OUT: error code */
  7497. Fts5Buffer *pBuf,
  7498. Fts5Structure *p
  7499. ){
  7500. int iLvl, iSeg; /* Iterate through levels, segments */
  7501. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  7502. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  7503. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  7504. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  7505. );
  7506. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  7507. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  7508. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d",
  7509. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  7510. );
  7511. if( pSeg->iOrigin1>0 ){
  7512. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " origin=%lld..%lld",
  7513. pSeg->iOrigin1, pSeg->iOrigin2
  7514. );
  7515. }
  7516. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  7517. }
  7518. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  7519. }
  7520. }
  7521. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7522. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7523. /*
  7524. ** This is part of the fts5_decode() debugging aid.
  7525. **
  7526. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  7527. ** function appends a human-readable representation of the same object
  7528. ** to the buffer passed as the second argument.
  7529. */
  7530. static void fts5DecodeStructure(
  7531. int *pRc, /* IN/OUT: error code */
  7532. Fts5Buffer *pBuf,
  7533. const u8 *pBlob, int nBlob
  7534. ){
  7535. int rc; /* Return code */
  7536. Fts5Structure *p = 0; /* Decoded structure object */
  7537. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  7538. if( rc!=SQLITE_OK ){
  7539. *pRc = rc;
  7540. return;
  7541. }
  7542. fts5DebugStructure(pRc, pBuf, p);
  7543. fts5StructureRelease(p);
  7544. }
  7545. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7546. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7547. /*
  7548. ** This is part of the fts5_decode() debugging aid.
  7549. **
  7550. ** Arguments pBlob/nBlob contain an "averages" record. This function
  7551. ** appends a human-readable representation of record to the buffer passed
  7552. ** as the second argument.
  7553. */
  7554. static void fts5DecodeAverages(
  7555. int *pRc, /* IN/OUT: error code */
  7556. Fts5Buffer *pBuf,
  7557. const u8 *pBlob, int nBlob
  7558. ){
  7559. int i = 0;
  7560. const char *zSpace = "";
  7561. while( i<nBlob ){
  7562. u64 iVal;
  7563. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  7564. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  7565. zSpace = " ";
  7566. }
  7567. }
  7568. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7569. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7570. /*
  7571. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  7572. ** each varint and append its string representation to buffer pBuf. Return
  7573. ** after either the input buffer is exhausted or a 0 value is read.
  7574. **
  7575. ** The return value is the number of bytes read from the input buffer.
  7576. */
  7577. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  7578. int iOff = 0;
  7579. while( iOff<n ){
  7580. int iVal;
  7581. iOff += fts5GetVarint32(&a[iOff], iVal);
  7582. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  7583. }
  7584. return iOff;
  7585. }
  7586. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7587. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7588. /*
  7589. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  7590. ** may or may not finish within the buffer. This function appends a text
  7591. ** representation of the part of the doclist that is present to buffer
  7592. ** pBuf.
  7593. **
  7594. ** The return value is the number of bytes read from the input buffer.
  7595. */
  7596. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  7597. i64 iDocid = 0;
  7598. int iOff = 0;
  7599. if( n>0 ){
  7600. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  7601. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  7602. }
  7603. while( iOff<n ){
  7604. int nPos;
  7605. int bDel;
  7606. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  7607. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  7608. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  7609. if( iOff<n ){
  7610. i64 iDelta;
  7611. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  7612. iDocid += iDelta;
  7613. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  7614. }
  7615. }
  7616. return iOff;
  7617. }
  7618. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7619. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7620. /*
  7621. ** This function is part of the fts5_decode() debugging function. It is
  7622. ** only ever used with detail=none tables.
  7623. **
  7624. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  7625. ** tables. This function appends a human-readable version of that list to
  7626. ** buffer pBuf.
  7627. **
  7628. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  7629. ** no-op. If an OOM or other error occurs within this function, *pRc is
  7630. ** set to an SQLite error code before returning. The final state of buffer
  7631. ** pBuf is undefined in this case.
  7632. */
  7633. static void fts5DecodeRowidList(
  7634. int *pRc, /* IN/OUT: Error code */
  7635. Fts5Buffer *pBuf, /* Buffer to append text to */
  7636. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  7637. ){
  7638. int i = 0;
  7639. i64 iRowid = 0;
  7640. while( i<nData ){
  7641. const char *zApp = "";
  7642. u64 iVal;
  7643. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  7644. iRowid += iVal;
  7645. if( i<nData && pData[i]==0x00 ){
  7646. i++;
  7647. if( i<nData && pData[i]==0x00 ){
  7648. i++;
  7649. zApp = "+";
  7650. }else{
  7651. zApp = "*";
  7652. }
  7653. }
  7654. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  7655. }
  7656. }
  7657. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7658. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7659. static void fts5BufferAppendTerm(int *pRc, Fts5Buffer *pBuf, Fts5Buffer *pTerm){
  7660. int ii;
  7661. fts5BufferGrow(pRc, pBuf, pTerm->n*2 + 1);
  7662. if( *pRc==SQLITE_OK ){
  7663. for(ii=0; ii<pTerm->n; ii++){
  7664. if( pTerm->p[ii]==0x00 ){
  7665. pBuf->p[pBuf->n++] = '\\';
  7666. pBuf->p[pBuf->n++] = '0';
  7667. }else{
  7668. pBuf->p[pBuf->n++] = pTerm->p[ii];
  7669. }
  7670. }
  7671. pBuf->p[pBuf->n] = 0x00;
  7672. }
  7673. }
  7674. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7675. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7676. /*
  7677. ** The implementation of user-defined scalar function fts5_decode().
  7678. */
  7679. static void fts5DecodeFunction(
  7680. sqlite3_context *pCtx, /* Function call context */
  7681. int nArg, /* Number of args (always 2) */
  7682. sqlite3_value **apVal /* Function arguments */
  7683. ){
  7684. i64 iRowid; /* Rowid for record being decoded */
  7685. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  7686. int bTomb;
  7687. const u8 *aBlob; int n; /* Record to decode */
  7688. u8 *a = 0;
  7689. Fts5Buffer s; /* Build up text to return here */
  7690. int rc = SQLITE_OK; /* Return code */
  7691. sqlite3_int64 nSpace = 0;
  7692. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  7693. assert( nArg==2 );
  7694. UNUSED_PARAM(nArg);
  7695. memset(&s, 0, sizeof(Fts5Buffer));
  7696. iRowid = sqlite3_value_int64(apVal[0]);
  7697. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  7698. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  7699. ** buffer overreads even if the record is corrupt. */
  7700. n = sqlite3_value_bytes(apVal[1]);
  7701. aBlob = sqlite3_value_blob(apVal[1]);
  7702. nSpace = n + FTS5_DATA_ZERO_PADDING;
  7703. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  7704. if( a==0 ) goto decode_out;
  7705. if( n>0 ) memcpy(a, aBlob, n);
  7706. fts5DecodeRowid(iRowid, &bTomb, &iSegid, &bDlidx, &iHeight, &iPgno);
  7707. fts5DebugRowid(&rc, &s, iRowid);
  7708. if( bDlidx ){
  7709. Fts5Data dlidx;
  7710. Fts5DlidxLvl lvl;
  7711. dlidx.p = a;
  7712. dlidx.nn = n;
  7713. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  7714. lvl.pData = &dlidx;
  7715. lvl.iLeafPgno = iPgno;
  7716. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  7717. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  7718. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  7719. );
  7720. }
  7721. }else if( bTomb ){
  7722. u32 nElem = fts5GetU32(&a[4]);
  7723. int szKey = (aBlob[0]==4 || aBlob[0]==8) ? aBlob[0] : 8;
  7724. int nSlot = (n - 8) / szKey;
  7725. int ii;
  7726. sqlite3Fts5BufferAppendPrintf(&rc, &s, " nElem=%d", (int)nElem);
  7727. if( aBlob[1] ){
  7728. sqlite3Fts5BufferAppendPrintf(&rc, &s, " 0");
  7729. }
  7730. for(ii=0; ii<nSlot; ii++){
  7731. u64 iVal = 0;
  7732. if( szKey==4 ){
  7733. u32 *aSlot = (u32*)&aBlob[8];
  7734. if( aSlot[ii] ) iVal = fts5GetU32((u8*)&aSlot[ii]);
  7735. }else{
  7736. u64 *aSlot = (u64*)&aBlob[8];
  7737. if( aSlot[ii] ) iVal = fts5GetU64((u8*)&aSlot[ii]);
  7738. }
  7739. if( iVal!=0 ){
  7740. sqlite3Fts5BufferAppendPrintf(&rc, &s, " %lld", (i64)iVal);
  7741. }
  7742. }
  7743. }else if( iSegid==0 ){
  7744. if( iRowid==FTS5_AVERAGES_ROWID ){
  7745. fts5DecodeAverages(&rc, &s, a, n);
  7746. }else{
  7747. fts5DecodeStructure(&rc, &s, a, n);
  7748. }
  7749. }else if( eDetailNone ){
  7750. Fts5Buffer term; /* Current term read from page */
  7751. int szLeaf;
  7752. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  7753. int iTermOff;
  7754. int nKeep = 0;
  7755. int iOff;
  7756. memset(&term, 0, sizeof(Fts5Buffer));
  7757. /* Decode any entries that occur before the first term. */
  7758. if( szLeaf<n ){
  7759. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  7760. }else{
  7761. iTermOff = szLeaf;
  7762. }
  7763. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  7764. iOff = iTermOff;
  7765. while( iOff<szLeaf && rc==SQLITE_OK ){
  7766. int nAppend;
  7767. /* Read the term data for the next term*/
  7768. iOff += fts5GetVarint32(&a[iOff], nAppend);
  7769. term.n = nKeep;
  7770. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  7771. sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
  7772. fts5BufferAppendTerm(&rc, &s, &term);
  7773. iOff += nAppend;
  7774. /* Figure out where the doclist for this term ends */
  7775. if( iPgidxOff<n ){
  7776. int nIncr;
  7777. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  7778. iTermOff += nIncr;
  7779. }else{
  7780. iTermOff = szLeaf;
  7781. }
  7782. if( iTermOff>szLeaf ){
  7783. rc = FTS5_CORRUPT;
  7784. }else{
  7785. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  7786. }
  7787. iOff = iTermOff;
  7788. if( iOff<szLeaf ){
  7789. iOff += fts5GetVarint32(&a[iOff], nKeep);
  7790. }
  7791. }
  7792. fts5BufferFree(&term);
  7793. }else{
  7794. Fts5Buffer term; /* Current term read from page */
  7795. int szLeaf; /* Offset of pgidx in a[] */
  7796. int iPgidxOff;
  7797. int iPgidxPrev = 0; /* Previous value read from pgidx */
  7798. int iTermOff = 0;
  7799. int iRowidOff = 0;
  7800. int iOff;
  7801. int nDoclist;
  7802. memset(&term, 0, sizeof(Fts5Buffer));
  7803. if( n<4 ){
  7804. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  7805. goto decode_out;
  7806. }else{
  7807. iRowidOff = fts5GetU16(&a[0]);
  7808. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  7809. if( iPgidxOff<n ){
  7810. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  7811. }else if( iPgidxOff>n ){
  7812. rc = FTS5_CORRUPT;
  7813. goto decode_out;
  7814. }
  7815. }
  7816. /* Decode the position list tail at the start of the page */
  7817. if( iRowidOff!=0 ){
  7818. iOff = iRowidOff;
  7819. }else if( iTermOff!=0 ){
  7820. iOff = iTermOff;
  7821. }else{
  7822. iOff = szLeaf;
  7823. }
  7824. if( iOff>n ){
  7825. rc = FTS5_CORRUPT;
  7826. goto decode_out;
  7827. }
  7828. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  7829. /* Decode any more doclist data that appears on the page before the
  7830. ** first term. */
  7831. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  7832. if( nDoclist+iOff>n ){
  7833. rc = FTS5_CORRUPT;
  7834. goto decode_out;
  7835. }
  7836. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  7837. while( iPgidxOff<n && rc==SQLITE_OK ){
  7838. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  7839. int nByte; /* Bytes of data */
  7840. int iEnd;
  7841. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  7842. iPgidxPrev += nByte;
  7843. iOff = iPgidxPrev;
  7844. if( iPgidxOff<n ){
  7845. fts5GetVarint32(&a[iPgidxOff], nByte);
  7846. iEnd = iPgidxPrev + nByte;
  7847. }else{
  7848. iEnd = szLeaf;
  7849. }
  7850. if( iEnd>szLeaf ){
  7851. rc = FTS5_CORRUPT;
  7852. break;
  7853. }
  7854. if( bFirst==0 ){
  7855. iOff += fts5GetVarint32(&a[iOff], nByte);
  7856. if( nByte>term.n ){
  7857. rc = FTS5_CORRUPT;
  7858. break;
  7859. }
  7860. term.n = nByte;
  7861. }
  7862. iOff += fts5GetVarint32(&a[iOff], nByte);
  7863. if( iOff+nByte>n ){
  7864. rc = FTS5_CORRUPT;
  7865. break;
  7866. }
  7867. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  7868. iOff += nByte;
  7869. sqlite3Fts5BufferAppendPrintf(&rc, &s, " term=");
  7870. fts5BufferAppendTerm(&rc, &s, &term);
  7871. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  7872. }
  7873. fts5BufferFree(&term);
  7874. }
  7875. decode_out:
  7876. sqlite3_free(a);
  7877. if( rc==SQLITE_OK ){
  7878. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  7879. }else{
  7880. sqlite3_result_error_code(pCtx, rc);
  7881. }
  7882. fts5BufferFree(&s);
  7883. }
  7884. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7885. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7886. /*
  7887. ** The implementation of user-defined scalar function fts5_rowid().
  7888. */
  7889. static void fts5RowidFunction(
  7890. sqlite3_context *pCtx, /* Function call context */
  7891. int nArg, /* Number of args (always 2) */
  7892. sqlite3_value **apVal /* Function arguments */
  7893. ){
  7894. const char *zArg;
  7895. if( nArg==0 ){
  7896. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  7897. }else{
  7898. zArg = (const char*)sqlite3_value_text(apVal[0]);
  7899. if( 0==sqlite3_stricmp(zArg, "segment") ){
  7900. i64 iRowid;
  7901. int segid, pgno;
  7902. if( nArg!=3 ){
  7903. sqlite3_result_error(pCtx,
  7904. "should be: fts5_rowid('segment', segid, pgno))", -1
  7905. );
  7906. }else{
  7907. segid = sqlite3_value_int(apVal[1]);
  7908. pgno = sqlite3_value_int(apVal[2]);
  7909. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  7910. sqlite3_result_int64(pCtx, iRowid);
  7911. }
  7912. }else{
  7913. sqlite3_result_error(pCtx,
  7914. "first arg to fts5_rowid() must be 'segment'" , -1
  7915. );
  7916. }
  7917. }
  7918. }
  7919. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  7920. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  7921. typedef struct Fts5StructVtab Fts5StructVtab;
  7922. struct Fts5StructVtab {
  7923. sqlite3_vtab base;
  7924. };
  7925. typedef struct Fts5StructVcsr Fts5StructVcsr;
  7926. struct Fts5StructVcsr {
  7927. sqlite3_vtab_cursor base;
  7928. Fts5Structure *pStruct;
  7929. int iLevel;
  7930. int iSeg;
  7931. int iRowid;
  7932. };
  7933. /*
  7934. ** Create a new fts5_structure() table-valued function.
  7935. */
  7936. static int fts5structConnectMethod(
  7937. sqlite3 *db,
  7938. void *pAux,
  7939. int argc, const char *const*argv,
  7940. sqlite3_vtab **ppVtab,
  7941. char **pzErr
  7942. ){
  7943. Fts5StructVtab *pNew = 0;
  7944. int rc = SQLITE_OK;
  7945. rc = sqlite3_declare_vtab(db,
  7946. "CREATE TABLE xyz("
  7947. "level, segment, merge, segid, leaf1, leaf2, loc1, loc2, "
  7948. "npgtombstone, nentrytombstone, nentry, struct HIDDEN);"
  7949. );
  7950. if( rc==SQLITE_OK ){
  7951. pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
  7952. }
  7953. *ppVtab = (sqlite3_vtab*)pNew;
  7954. return rc;
  7955. }
  7956. /*
  7957. ** We must have a single struct=? constraint that will be passed through
  7958. ** into the xFilter method. If there is no valid struct=? constraint,
  7959. ** then return an SQLITE_CONSTRAINT error.
  7960. */
  7961. static int fts5structBestIndexMethod(
  7962. sqlite3_vtab *tab,
  7963. sqlite3_index_info *pIdxInfo
  7964. ){
  7965. int i;
  7966. int rc = SQLITE_CONSTRAINT;
  7967. struct sqlite3_index_constraint *p;
  7968. pIdxInfo->estimatedCost = (double)100;
  7969. pIdxInfo->estimatedRows = 100;
  7970. pIdxInfo->idxNum = 0;
  7971. for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
  7972. if( p->usable==0 ) continue;
  7973. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==11 ){
  7974. rc = SQLITE_OK;
  7975. pIdxInfo->aConstraintUsage[i].omit = 1;
  7976. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  7977. break;
  7978. }
  7979. }
  7980. return rc;
  7981. }
  7982. /*
  7983. ** This method is the destructor for bytecodevtab objects.
  7984. */
  7985. static int fts5structDisconnectMethod(sqlite3_vtab *pVtab){
  7986. Fts5StructVtab *p = (Fts5StructVtab*)pVtab;
  7987. sqlite3_free(p);
  7988. return SQLITE_OK;
  7989. }
  7990. /*
  7991. ** Constructor for a new bytecodevtab_cursor object.
  7992. */
  7993. static int fts5structOpenMethod(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  7994. int rc = SQLITE_OK;
  7995. Fts5StructVcsr *pNew = 0;
  7996. pNew = sqlite3Fts5MallocZero(&rc, sizeof(*pNew));
  7997. *ppCsr = (sqlite3_vtab_cursor*)pNew;
  7998. return SQLITE_OK;
  7999. }
  8000. /*
  8001. ** Destructor for a bytecodevtab_cursor.
  8002. */
  8003. static int fts5structCloseMethod(sqlite3_vtab_cursor *cur){
  8004. Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
  8005. fts5StructureRelease(pCsr->pStruct);
  8006. sqlite3_free(pCsr);
  8007. return SQLITE_OK;
  8008. }
  8009. /*
  8010. ** Advance a bytecodevtab_cursor to its next row of output.
  8011. */
  8012. static int fts5structNextMethod(sqlite3_vtab_cursor *cur){
  8013. Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
  8014. Fts5Structure *p = pCsr->pStruct;
  8015. assert( pCsr->pStruct );
  8016. pCsr->iSeg++;
  8017. pCsr->iRowid++;
  8018. while( pCsr->iLevel<p->nLevel && pCsr->iSeg>=p->aLevel[pCsr->iLevel].nSeg ){
  8019. pCsr->iLevel++;
  8020. pCsr->iSeg = 0;
  8021. }
  8022. if( pCsr->iLevel>=p->nLevel ){
  8023. fts5StructureRelease(pCsr->pStruct);
  8024. pCsr->pStruct = 0;
  8025. }
  8026. return SQLITE_OK;
  8027. }
  8028. /*
  8029. ** Return TRUE if the cursor has been moved off of the last
  8030. ** row of output.
  8031. */
  8032. static int fts5structEofMethod(sqlite3_vtab_cursor *cur){
  8033. Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
  8034. return pCsr->pStruct==0;
  8035. }
  8036. static int fts5structRowidMethod(
  8037. sqlite3_vtab_cursor *cur,
  8038. sqlite_int64 *piRowid
  8039. ){
  8040. Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
  8041. *piRowid = pCsr->iRowid;
  8042. return SQLITE_OK;
  8043. }
  8044. /*
  8045. ** Return values of columns for the row at which the bytecodevtab_cursor
  8046. ** is currently pointing.
  8047. */
  8048. static int fts5structColumnMethod(
  8049. sqlite3_vtab_cursor *cur, /* The cursor */
  8050. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  8051. int i /* Which column to return */
  8052. ){
  8053. Fts5StructVcsr *pCsr = (Fts5StructVcsr*)cur;
  8054. Fts5Structure *p = pCsr->pStruct;
  8055. Fts5StructureSegment *pSeg = &p->aLevel[pCsr->iLevel].aSeg[pCsr->iSeg];
  8056. switch( i ){
  8057. case 0: /* level */
  8058. sqlite3_result_int(ctx, pCsr->iLevel);
  8059. break;
  8060. case 1: /* segment */
  8061. sqlite3_result_int(ctx, pCsr->iSeg);
  8062. break;
  8063. case 2: /* merge */
  8064. sqlite3_result_int(ctx, pCsr->iSeg < p->aLevel[pCsr->iLevel].nMerge);
  8065. break;
  8066. case 3: /* segid */
  8067. sqlite3_result_int(ctx, pSeg->iSegid);
  8068. break;
  8069. case 4: /* leaf1 */
  8070. sqlite3_result_int(ctx, pSeg->pgnoFirst);
  8071. break;
  8072. case 5: /* leaf2 */
  8073. sqlite3_result_int(ctx, pSeg->pgnoLast);
  8074. break;
  8075. case 6: /* origin1 */
  8076. sqlite3_result_int64(ctx, pSeg->iOrigin1);
  8077. break;
  8078. case 7: /* origin2 */
  8079. sqlite3_result_int64(ctx, pSeg->iOrigin2);
  8080. break;
  8081. case 8: /* npgtombstone */
  8082. sqlite3_result_int(ctx, pSeg->nPgTombstone);
  8083. break;
  8084. case 9: /* nentrytombstone */
  8085. sqlite3_result_int64(ctx, pSeg->nEntryTombstone);
  8086. break;
  8087. case 10: /* nentry */
  8088. sqlite3_result_int64(ctx, pSeg->nEntry);
  8089. break;
  8090. }
  8091. return SQLITE_OK;
  8092. }
  8093. /*
  8094. ** Initialize a cursor.
  8095. **
  8096. ** idxNum==0 means show all subprograms
  8097. ** idxNum==1 means show only the main bytecode and omit subprograms.
  8098. */
  8099. static int fts5structFilterMethod(
  8100. sqlite3_vtab_cursor *pVtabCursor,
  8101. int idxNum, const char *idxStr,
  8102. int argc, sqlite3_value **argv
  8103. ){
  8104. Fts5StructVcsr *pCsr = (Fts5StructVcsr *)pVtabCursor;
  8105. int rc = SQLITE_OK;
  8106. const u8 *aBlob = 0;
  8107. int nBlob = 0;
  8108. assert( argc==1 );
  8109. fts5StructureRelease(pCsr->pStruct);
  8110. pCsr->pStruct = 0;
  8111. nBlob = sqlite3_value_bytes(argv[0]);
  8112. aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  8113. rc = fts5StructureDecode(aBlob, nBlob, 0, &pCsr->pStruct);
  8114. if( rc==SQLITE_OK ){
  8115. pCsr->iLevel = 0;
  8116. pCsr->iRowid = 0;
  8117. pCsr->iSeg = -1;
  8118. rc = fts5structNextMethod(pVtabCursor);
  8119. }
  8120. return rc;
  8121. }
  8122. #endif /* SQLITE_TEST || SQLITE_FTS5_DEBUG */
  8123. /*
  8124. ** This is called as part of registering the FTS5 module with database
  8125. ** connection db. It registers several user-defined scalar functions useful
  8126. ** with FTS5.
  8127. **
  8128. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  8129. ** SQLite error code is returned instead.
  8130. */
  8131. int sqlite3Fts5IndexInit(sqlite3 *db){
  8132. #if defined(SQLITE_TEST) || defined(SQLITE_FTS5_DEBUG)
  8133. int rc = sqlite3_create_function(
  8134. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  8135. );
  8136. if( rc==SQLITE_OK ){
  8137. rc = sqlite3_create_function(
  8138. db, "fts5_decode_none", 2,
  8139. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  8140. );
  8141. }
  8142. if( rc==SQLITE_OK ){
  8143. rc = sqlite3_create_function(
  8144. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  8145. );
  8146. }
  8147. if( rc==SQLITE_OK ){
  8148. static const sqlite3_module fts5structure_module = {
  8149. 0, /* iVersion */
  8150. 0, /* xCreate */
  8151. fts5structConnectMethod, /* xConnect */
  8152. fts5structBestIndexMethod, /* xBestIndex */
  8153. fts5structDisconnectMethod, /* xDisconnect */
  8154. 0, /* xDestroy */
  8155. fts5structOpenMethod, /* xOpen */
  8156. fts5structCloseMethod, /* xClose */
  8157. fts5structFilterMethod, /* xFilter */
  8158. fts5structNextMethod, /* xNext */
  8159. fts5structEofMethod, /* xEof */
  8160. fts5structColumnMethod, /* xColumn */
  8161. fts5structRowidMethod, /* xRowid */
  8162. 0, /* xUpdate */
  8163. 0, /* xBegin */
  8164. 0, /* xSync */
  8165. 0, /* xCommit */
  8166. 0, /* xRollback */
  8167. 0, /* xFindFunction */
  8168. 0, /* xRename */
  8169. 0, /* xSavepoint */
  8170. 0, /* xRelease */
  8171. 0, /* xRollbackTo */
  8172. 0, /* xShadowName */
  8173. 0 /* xIntegrity */
  8174. };
  8175. rc = sqlite3_create_module(db, "fts5_structure", &fts5structure_module, 0);
  8176. }
  8177. return rc;
  8178. #else
  8179. return SQLITE_OK;
  8180. UNUSED_PARAM(db);
  8181. #endif
  8182. }
  8183. int sqlite3Fts5IndexReset(Fts5Index *p){
  8184. assert( p->pStruct==0 || p->iStructVersion!=0 );
  8185. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  8186. fts5StructureInvalidate(p);
  8187. }
  8188. return fts5IndexReturn(p);
  8189. }