fts2.c 215 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860
  1. /* fts2 has a design flaw which can lead to database corruption (see
  2. ** below). It is recommended not to use it any longer, instead use
  3. ** fts3 (or higher). If you believe that your use of fts2 is safe,
  4. ** add -DSQLITE_ENABLE_BROKEN_FTS2=1 to your CFLAGS.
  5. */
  6. #if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)) \
  7. && !defined(SQLITE_ENABLE_BROKEN_FTS2)
  8. #error fts2 has a design flaw and has been deprecated.
  9. #endif
  10. /* The flaw is that fts2 uses the content table's unaliased rowid as
  11. ** the unique docid. fts2 embeds the rowid in the index it builds,
  12. ** and expects the rowid to not change. The SQLite VACUUM operation
  13. ** will renumber such rowids, thereby breaking fts2. If you are using
  14. ** fts2 in a system which has disabled VACUUM, then you can continue
  15. ** to use it safely. Note that PRAGMA auto_vacuum does NOT disable
  16. ** VACUUM, though systems using auto_vacuum are unlikely to invoke
  17. ** VACUUM.
  18. **
  19. ** Unlike fts1, which is safe across VACUUM if you never delete
  20. ** documents, fts2 has a second exposure to this flaw, in the segments
  21. ** table. So fts2 should be considered unsafe across VACUUM in all
  22. ** cases.
  23. */
  24. /*
  25. ** 2006 Oct 10
  26. **
  27. ** The author disclaims copyright to this source code. In place of
  28. ** a legal notice, here is a blessing:
  29. **
  30. ** May you do good and not evil.
  31. ** May you find forgiveness for yourself and forgive others.
  32. ** May you share freely, never taking more than you give.
  33. **
  34. ******************************************************************************
  35. **
  36. ** This is an SQLite module implementing full-text search.
  37. */
  38. /*
  39. ** The code in this file is only compiled if:
  40. **
  41. ** * The FTS2 module is being built as an extension
  42. ** (in which case SQLITE_CORE is not defined), or
  43. **
  44. ** * The FTS2 module is being built into the core of
  45. ** SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
  46. */
  47. /* TODO(shess) Consider exporting this comment to an HTML file or the
  48. ** wiki.
  49. */
  50. /* The full-text index is stored in a series of b+tree (-like)
  51. ** structures called segments which map terms to doclists. The
  52. ** structures are like b+trees in layout, but are constructed from the
  53. ** bottom up in optimal fashion and are not updatable. Since trees
  54. ** are built from the bottom up, things will be described from the
  55. ** bottom up.
  56. **
  57. **
  58. **** Varints ****
  59. ** The basic unit of encoding is a variable-length integer called a
  60. ** varint. We encode variable-length integers in little-endian order
  61. ** using seven bits * per byte as follows:
  62. **
  63. ** KEY:
  64. ** A = 0xxxxxxx 7 bits of data and one flag bit
  65. ** B = 1xxxxxxx 7 bits of data and one flag bit
  66. **
  67. ** 7 bits - A
  68. ** 14 bits - BA
  69. ** 21 bits - BBA
  70. ** and so on.
  71. **
  72. ** This is identical to how sqlite encodes varints (see util.c).
  73. **
  74. **
  75. **** Document lists ****
  76. ** A doclist (document list) holds a docid-sorted list of hits for a
  77. ** given term. Doclists hold docids, and can optionally associate
  78. ** token positions and offsets with docids.
  79. **
  80. ** A DL_POSITIONS_OFFSETS doclist is stored like this:
  81. **
  82. ** array {
  83. ** varint docid;
  84. ** array { (position list for column 0)
  85. ** varint position; (delta from previous position plus POS_BASE)
  86. ** varint startOffset; (delta from previous startOffset)
  87. ** varint endOffset; (delta from startOffset)
  88. ** }
  89. ** array {
  90. ** varint POS_COLUMN; (marks start of position list for new column)
  91. ** varint column; (index of new column)
  92. ** array {
  93. ** varint position; (delta from previous position plus POS_BASE)
  94. ** varint startOffset;(delta from previous startOffset)
  95. ** varint endOffset; (delta from startOffset)
  96. ** }
  97. ** }
  98. ** varint POS_END; (marks end of positions for this document.
  99. ** }
  100. **
  101. ** Here, array { X } means zero or more occurrences of X, adjacent in
  102. ** memory. A "position" is an index of a token in the token stream
  103. ** generated by the tokenizer, while an "offset" is a byte offset,
  104. ** both based at 0. Note that POS_END and POS_COLUMN occur in the
  105. ** same logical place as the position element, and act as sentinals
  106. ** ending a position list array.
  107. **
  108. ** A DL_POSITIONS doclist omits the startOffset and endOffset
  109. ** information. A DL_DOCIDS doclist omits both the position and
  110. ** offset information, becoming an array of varint-encoded docids.
  111. **
  112. ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
  113. ** the type. Due to how deletion is implemented in the segmentation
  114. ** system, on-disk doclists MUST store at least positions.
  115. **
  116. **
  117. **** Segment leaf nodes ****
  118. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  119. ** nodes are written using LeafWriter, and read using LeafReader (to
  120. ** iterate through a single leaf node's data) and LeavesReader (to
  121. ** iterate through a segment's entire leaf layer). Leaf nodes have
  122. ** the format:
  123. **
  124. ** varint iHeight; (height from leaf level, always 0)
  125. ** varint nTerm; (length of first term)
  126. ** char pTerm[nTerm]; (content of first term)
  127. ** varint nDoclist; (length of term's associated doclist)
  128. ** char pDoclist[nDoclist]; (content of doclist)
  129. ** array {
  130. ** (further terms are delta-encoded)
  131. ** varint nPrefix; (length of prefix shared with previous term)
  132. ** varint nSuffix; (length of unshared suffix)
  133. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  134. ** varint nDoclist; (length of term's associated doclist)
  135. ** char pDoclist[nDoclist]; (content of doclist)
  136. ** }
  137. **
  138. ** Here, array { X } means zero or more occurrences of X, adjacent in
  139. ** memory.
  140. **
  141. ** Leaf nodes are broken into blocks which are stored contiguously in
  142. ** the %_segments table in sorted order. This means that when the end
  143. ** of a node is reached, the next term is in the node with the next
  144. ** greater node id.
  145. **
  146. ** New data is spilled to a new leaf node when the current node
  147. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  148. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  149. ** node (a leaf node with a single term and doclist). The goal of
  150. ** these settings is to pack together groups of small doclists while
  151. ** making it efficient to directly access large doclists. The
  152. ** assumption is that large doclists represent terms which are more
  153. ** likely to be query targets.
  154. **
  155. ** TODO(shess) It may be useful for blocking decisions to be more
  156. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  157. ** node rather than splitting into 2k and .5k nodes. My intuition is
  158. ** that this might extend through 2x or 4x the pagesize.
  159. **
  160. **
  161. **** Segment interior nodes ****
  162. ** Segment interior nodes store blockids for subtree nodes and terms
  163. ** to describe what data is stored by the each subtree. Interior
  164. ** nodes are written using InteriorWriter, and read using
  165. ** InteriorReader. InteriorWriters are created as needed when
  166. ** SegmentWriter creates new leaf nodes, or when an interior node
  167. ** itself grows too big and must be split. The format of interior
  168. ** nodes:
  169. **
  170. ** varint iHeight; (height from leaf level, always >0)
  171. ** varint iBlockid; (block id of node's leftmost subtree)
  172. ** optional {
  173. ** varint nTerm; (length of first term)
  174. ** char pTerm[nTerm]; (content of first term)
  175. ** array {
  176. ** (further terms are delta-encoded)
  177. ** varint nPrefix; (length of shared prefix with previous term)
  178. ** varint nSuffix; (length of unshared suffix)
  179. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  180. ** }
  181. ** }
  182. **
  183. ** Here, optional { X } means an optional element, while array { X }
  184. ** means zero or more occurrences of X, adjacent in memory.
  185. **
  186. ** An interior node encodes n terms separating n+1 subtrees. The
  187. ** subtree blocks are contiguous, so only the first subtree's blockid
  188. ** is encoded. The subtree at iBlockid will contain all terms less
  189. ** than the first term encoded (or all terms if no term is encoded).
  190. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  191. ** than pTerm[i+1], the subtree for that term will be rooted at
  192. ** iBlockid+i. Interior nodes only store enough term data to
  193. ** distinguish adjacent children (if the rightmost term of the left
  194. ** child is "something", and the leftmost term of the right child is
  195. ** "wicked", only "w" is stored).
  196. **
  197. ** New data is spilled to a new interior node at the same height when
  198. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  199. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  200. ** interior nodes and making the tree too skinny. The interior nodes
  201. ** at a given height are naturally tracked by interior nodes at
  202. ** height+1, and so on.
  203. **
  204. **
  205. **** Segment directory ****
  206. ** The segment directory in table %_segdir stores meta-information for
  207. ** merging and deleting segments, and also the root node of the
  208. ** segment's tree.
  209. **
  210. ** The root node is the top node of the segment's tree after encoding
  211. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  212. ** This could be either a leaf node or an interior node. If the top
  213. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  214. ** and a new root interior node is generated (which should always fit
  215. ** within ROOT_MAX because it only needs space for 2 varints, the
  216. ** height and the blockid of the previous root).
  217. **
  218. ** The meta-information in the segment directory is:
  219. ** level - segment level (see below)
  220. ** idx - index within level
  221. ** - (level,idx uniquely identify a segment)
  222. ** start_block - first leaf node
  223. ** leaves_end_block - last leaf node
  224. ** end_block - last block (including interior nodes)
  225. ** root - contents of root node
  226. **
  227. ** If the root node is a leaf node, then start_block,
  228. ** leaves_end_block, and end_block are all 0.
  229. **
  230. **
  231. **** Segment merging ****
  232. ** To amortize update costs, segments are groups into levels and
  233. ** merged in matches. Each increase in level represents exponentially
  234. ** more documents.
  235. **
  236. ** New documents (actually, document updates) are tokenized and
  237. ** written individually (using LeafWriter) to a level 0 segment, with
  238. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  239. ** level 0 segments are merged into a single level 1 segment. Level 1
  240. ** is populated like level 0, and eventually MERGE_COUNT level 1
  241. ** segments are merged to a single level 2 segment (representing
  242. ** MERGE_COUNT^2 updates), and so on.
  243. **
  244. ** A segment merge traverses all segments at a given level in
  245. ** parallel, performing a straightforward sorted merge. Since segment
  246. ** leaf nodes are written in to the %_segments table in order, this
  247. ** merge traverses the underlying sqlite disk structures efficiently.
  248. ** After the merge, all segment blocks from the merged level are
  249. ** deleted.
  250. **
  251. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  252. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  253. ** very similar performance numbers to 16 on insertion, though they're
  254. ** a tiny bit slower (perhaps due to more overhead in merge-time
  255. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  256. ** 16, 2 about 66% slower than 16.
  257. **
  258. ** At query time, high MERGE_COUNT increases the number of segments
  259. ** which need to be scanned and merged. For instance, with 100k docs
  260. ** inserted:
  261. **
  262. ** MERGE_COUNT segments
  263. ** 16 25
  264. ** 8 12
  265. ** 4 10
  266. ** 2 6
  267. **
  268. ** This appears to have only a moderate impact on queries for very
  269. ** frequent terms (which are somewhat dominated by segment merge
  270. ** costs), and infrequent and non-existent terms still seem to be fast
  271. ** even with many segments.
  272. **
  273. ** TODO(shess) That said, it would be nice to have a better query-side
  274. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  275. ** optimizations to things like doclist merging will swing the sweet
  276. ** spot around.
  277. **
  278. **
  279. **
  280. **** Handling of deletions and updates ****
  281. ** Since we're using a segmented structure, with no docid-oriented
  282. ** index into the term index, we clearly cannot simply update the term
  283. ** index when a document is deleted or updated. For deletions, we
  284. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  285. ** we simply write the new doclist. Segment merges overwrite older
  286. ** data for a particular docid with newer data, so deletes or updates
  287. ** will eventually overtake the earlier data and knock it out. The
  288. ** query logic likewise merges doclists so that newer data knocks out
  289. ** older data.
  290. **
  291. ** TODO(shess) Provide a VACUUM type operation to clear out all
  292. ** deletions and duplications. This would basically be a forced merge
  293. ** into a single segment.
  294. */
  295. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)
  296. #if defined(SQLITE_ENABLE_FTS2) && !defined(SQLITE_CORE)
  297. # define SQLITE_CORE 1
  298. #endif
  299. #include <assert.h>
  300. #include <stdlib.h>
  301. #include <stdio.h>
  302. #include <string.h>
  303. #include "fts2.h"
  304. #include "fts2_hash.h"
  305. #include "fts2_tokenizer.h"
  306. #include "sqlite3.h"
  307. #include "sqlite3ext.h"
  308. SQLITE_EXTENSION_INIT1
  309. /* TODO(shess) MAN, this thing needs some refactoring. At minimum, it
  310. ** would be nice to order the file better, perhaps something along the
  311. ** lines of:
  312. **
  313. ** - utility functions
  314. ** - table setup functions
  315. ** - table update functions
  316. ** - table query functions
  317. **
  318. ** Put the query functions last because they're likely to reference
  319. ** typedefs or functions from the table update section.
  320. */
  321. #if 0
  322. # define TRACE(A) printf A; fflush(stdout)
  323. #else
  324. # define TRACE(A)
  325. #endif
  326. /* It is not safe to call isspace(), tolower(), or isalnum() on
  327. ** hi-bit-set characters. This is the same solution used in the
  328. ** tokenizer.
  329. */
  330. /* TODO(shess) The snippet-generation code should be using the
  331. ** tokenizer-generated tokens rather than doing its own local
  332. ** tokenization.
  333. */
  334. /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */
  335. static int safe_isspace(char c){
  336. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  337. }
  338. static int safe_tolower(char c){
  339. return (c>='A' && c<='Z') ? (c - 'A' + 'a') : c;
  340. }
  341. static int safe_isalnum(char c){
  342. return (c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z');
  343. }
  344. typedef enum DocListType {
  345. DL_DOCIDS, /* docids only */
  346. DL_POSITIONS, /* docids + positions */
  347. DL_POSITIONS_OFFSETS /* docids + positions + offsets */
  348. } DocListType;
  349. /*
  350. ** By default, only positions and not offsets are stored in the doclists.
  351. ** To change this so that offsets are stored too, compile with
  352. **
  353. ** -DDL_DEFAULT=DL_POSITIONS_OFFSETS
  354. **
  355. ** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted
  356. ** into (no deletes or updates).
  357. */
  358. #ifndef DL_DEFAULT
  359. # define DL_DEFAULT DL_POSITIONS
  360. #endif
  361. enum {
  362. POS_END = 0, /* end of this position list */
  363. POS_COLUMN, /* followed by new column number */
  364. POS_BASE
  365. };
  366. /* MERGE_COUNT controls how often we merge segments (see comment at
  367. ** top of file).
  368. */
  369. #define MERGE_COUNT 16
  370. /* utility functions */
  371. /* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single
  372. ** record to prevent errors of the form:
  373. **
  374. ** my_function(SomeType *b){
  375. ** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b)
  376. ** }
  377. */
  378. /* TODO(shess) Obvious candidates for a header file. */
  379. #define CLEAR(b) memset(b, '\0', sizeof(*(b)))
  380. #ifndef NDEBUG
  381. # define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b)))
  382. #else
  383. # define SCRAMBLE(b)
  384. #endif
  385. /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */
  386. #define VARINT_MAX 10
  387. /* Write a 64-bit variable-length integer to memory starting at p[0].
  388. * The length of data written will be between 1 and VARINT_MAX bytes.
  389. * The number of bytes written is returned. */
  390. static int putVarint(char *p, sqlite_int64 v){
  391. unsigned char *q = (unsigned char *) p;
  392. sqlite_uint64 vu = v;
  393. do{
  394. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  395. vu >>= 7;
  396. }while( vu!=0 );
  397. q[-1] &= 0x7f; /* turn off high bit in final byte */
  398. assert( q - (unsigned char *)p <= VARINT_MAX );
  399. return (int) (q - (unsigned char *)p);
  400. }
  401. /* Read a 64-bit variable-length integer from memory starting at p[0].
  402. * Return the number of bytes read, or 0 on error.
  403. * The value is stored in *v. */
  404. static int getVarint(const char *p, sqlite_int64 *v){
  405. const unsigned char *q = (const unsigned char *) p;
  406. sqlite_uint64 x = 0, y = 1;
  407. while( (*q & 0x80) == 0x80 ){
  408. x += y * (*q++ & 0x7f);
  409. y <<= 7;
  410. if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */
  411. assert( 0 );
  412. return 0;
  413. }
  414. }
  415. x += y * (*q++);
  416. *v = (sqlite_int64) x;
  417. return (int) (q - (unsigned char *)p);
  418. }
  419. static int getVarint32(const char *p, int *pi){
  420. sqlite_int64 i;
  421. int ret = getVarint(p, &i);
  422. *pi = (int) i;
  423. assert( *pi==i );
  424. return ret;
  425. }
  426. /*******************************************************************/
  427. /* DataBuffer is used to collect data into a buffer in piecemeal
  428. ** fashion. It implements the usual distinction between amount of
  429. ** data currently stored (nData) and buffer capacity (nCapacity).
  430. **
  431. ** dataBufferInit - create a buffer with given initial capacity.
  432. ** dataBufferReset - forget buffer's data, retaining capacity.
  433. ** dataBufferDestroy - free buffer's data.
  434. ** dataBufferSwap - swap contents of two buffers.
  435. ** dataBufferExpand - expand capacity without adding data.
  436. ** dataBufferAppend - append data.
  437. ** dataBufferAppend2 - append two pieces of data at once.
  438. ** dataBufferReplace - replace buffer's data.
  439. */
  440. typedef struct DataBuffer {
  441. char *pData; /* Pointer to malloc'ed buffer. */
  442. int nCapacity; /* Size of pData buffer. */
  443. int nData; /* End of data loaded into pData. */
  444. } DataBuffer;
  445. static void dataBufferInit(DataBuffer *pBuffer, int nCapacity){
  446. assert( nCapacity>=0 );
  447. pBuffer->nData = 0;
  448. pBuffer->nCapacity = nCapacity;
  449. pBuffer->pData = nCapacity==0 ? NULL : sqlite3_malloc(nCapacity);
  450. }
  451. static void dataBufferReset(DataBuffer *pBuffer){
  452. pBuffer->nData = 0;
  453. }
  454. static void dataBufferDestroy(DataBuffer *pBuffer){
  455. if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData);
  456. SCRAMBLE(pBuffer);
  457. }
  458. static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){
  459. DataBuffer tmp = *pBuffer1;
  460. *pBuffer1 = *pBuffer2;
  461. *pBuffer2 = tmp;
  462. }
  463. static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){
  464. assert( nAddCapacity>0 );
  465. /* TODO(shess) Consider expanding more aggressively. Note that the
  466. ** underlying malloc implementation may take care of such things for
  467. ** us already.
  468. */
  469. if( pBuffer->nData+nAddCapacity>pBuffer->nCapacity ){
  470. pBuffer->nCapacity = pBuffer->nData+nAddCapacity;
  471. pBuffer->pData = sqlite3_realloc(pBuffer->pData, pBuffer->nCapacity);
  472. }
  473. }
  474. static void dataBufferAppend(DataBuffer *pBuffer,
  475. const char *pSource, int nSource){
  476. assert( nSource>0 && pSource!=NULL );
  477. dataBufferExpand(pBuffer, nSource);
  478. memcpy(pBuffer->pData+pBuffer->nData, pSource, nSource);
  479. pBuffer->nData += nSource;
  480. }
  481. static void dataBufferAppend2(DataBuffer *pBuffer,
  482. const char *pSource1, int nSource1,
  483. const char *pSource2, int nSource2){
  484. assert( nSource1>0 && pSource1!=NULL );
  485. assert( nSource2>0 && pSource2!=NULL );
  486. dataBufferExpand(pBuffer, nSource1+nSource2);
  487. memcpy(pBuffer->pData+pBuffer->nData, pSource1, nSource1);
  488. memcpy(pBuffer->pData+pBuffer->nData+nSource1, pSource2, nSource2);
  489. pBuffer->nData += nSource1+nSource2;
  490. }
  491. static void dataBufferReplace(DataBuffer *pBuffer,
  492. const char *pSource, int nSource){
  493. dataBufferReset(pBuffer);
  494. dataBufferAppend(pBuffer, pSource, nSource);
  495. }
  496. /* StringBuffer is a null-terminated version of DataBuffer. */
  497. typedef struct StringBuffer {
  498. DataBuffer b; /* Includes null terminator. */
  499. } StringBuffer;
  500. static void initStringBuffer(StringBuffer *sb){
  501. dataBufferInit(&sb->b, 100);
  502. dataBufferReplace(&sb->b, "", 1);
  503. }
  504. static int stringBufferLength(StringBuffer *sb){
  505. return sb->b.nData-1;
  506. }
  507. static char *stringBufferData(StringBuffer *sb){
  508. return sb->b.pData;
  509. }
  510. static void stringBufferDestroy(StringBuffer *sb){
  511. dataBufferDestroy(&sb->b);
  512. }
  513. static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){
  514. assert( sb->b.nData>0 );
  515. if( nFrom>0 ){
  516. sb->b.nData--;
  517. dataBufferAppend2(&sb->b, zFrom, nFrom, "", 1);
  518. }
  519. }
  520. static void append(StringBuffer *sb, const char *zFrom){
  521. nappend(sb, zFrom, strlen(zFrom));
  522. }
  523. /* Append a list of strings separated by commas. */
  524. static void appendList(StringBuffer *sb, int nString, char **azString){
  525. int i;
  526. for(i=0; i<nString; ++i){
  527. if( i>0 ) append(sb, ", ");
  528. append(sb, azString[i]);
  529. }
  530. }
  531. static int endsInWhiteSpace(StringBuffer *p){
  532. return stringBufferLength(p)>0 &&
  533. safe_isspace(stringBufferData(p)[stringBufferLength(p)-1]);
  534. }
  535. /* If the StringBuffer ends in something other than white space, add a
  536. ** single space character to the end.
  537. */
  538. static void appendWhiteSpace(StringBuffer *p){
  539. if( stringBufferLength(p)==0 ) return;
  540. if( !endsInWhiteSpace(p) ) append(p, " ");
  541. }
  542. /* Remove white space from the end of the StringBuffer */
  543. static void trimWhiteSpace(StringBuffer *p){
  544. while( endsInWhiteSpace(p) ){
  545. p->b.pData[--p->b.nData-1] = '\0';
  546. }
  547. }
  548. /*******************************************************************/
  549. /* DLReader is used to read document elements from a doclist. The
  550. ** current docid is cached, so dlrDocid() is fast. DLReader does not
  551. ** own the doclist buffer.
  552. **
  553. ** dlrAtEnd - true if there's no more data to read.
  554. ** dlrDocid - docid of current document.
  555. ** dlrDocData - doclist data for current document (including docid).
  556. ** dlrDocDataBytes - length of same.
  557. ** dlrAllDataBytes - length of all remaining data.
  558. ** dlrPosData - position data for current document.
  559. ** dlrPosDataLen - length of pos data for current document (incl POS_END).
  560. ** dlrStep - step to current document.
  561. ** dlrInit - initial for doclist of given type against given data.
  562. ** dlrDestroy - clean up.
  563. **
  564. ** Expected usage is something like:
  565. **
  566. ** DLReader reader;
  567. ** dlrInit(&reader, pData, nData);
  568. ** while( !dlrAtEnd(&reader) ){
  569. ** // calls to dlrDocid() and kin.
  570. ** dlrStep(&reader);
  571. ** }
  572. ** dlrDestroy(&reader);
  573. */
  574. typedef struct DLReader {
  575. DocListType iType;
  576. const char *pData;
  577. int nData;
  578. sqlite_int64 iDocid;
  579. int nElement;
  580. } DLReader;
  581. static int dlrAtEnd(DLReader *pReader){
  582. assert( pReader->nData>=0 );
  583. return pReader->nData==0;
  584. }
  585. static sqlite_int64 dlrDocid(DLReader *pReader){
  586. assert( !dlrAtEnd(pReader) );
  587. return pReader->iDocid;
  588. }
  589. static const char *dlrDocData(DLReader *pReader){
  590. assert( !dlrAtEnd(pReader) );
  591. return pReader->pData;
  592. }
  593. static int dlrDocDataBytes(DLReader *pReader){
  594. assert( !dlrAtEnd(pReader) );
  595. return pReader->nElement;
  596. }
  597. static int dlrAllDataBytes(DLReader *pReader){
  598. assert( !dlrAtEnd(pReader) );
  599. return pReader->nData;
  600. }
  601. /* TODO(shess) Consider adding a field to track iDocid varint length
  602. ** to make these two functions faster. This might matter (a tiny bit)
  603. ** for queries.
  604. */
  605. static const char *dlrPosData(DLReader *pReader){
  606. sqlite_int64 iDummy;
  607. int n = getVarint(pReader->pData, &iDummy);
  608. assert( !dlrAtEnd(pReader) );
  609. return pReader->pData+n;
  610. }
  611. static int dlrPosDataLen(DLReader *pReader){
  612. sqlite_int64 iDummy;
  613. int n = getVarint(pReader->pData, &iDummy);
  614. assert( !dlrAtEnd(pReader) );
  615. return pReader->nElement-n;
  616. }
  617. static void dlrStep(DLReader *pReader){
  618. assert( !dlrAtEnd(pReader) );
  619. /* Skip past current doclist element. */
  620. assert( pReader->nElement<=pReader->nData );
  621. pReader->pData += pReader->nElement;
  622. pReader->nData -= pReader->nElement;
  623. /* If there is more data, read the next doclist element. */
  624. if( pReader->nData!=0 ){
  625. sqlite_int64 iDocidDelta;
  626. int iDummy, n = getVarint(pReader->pData, &iDocidDelta);
  627. pReader->iDocid += iDocidDelta;
  628. if( pReader->iType>=DL_POSITIONS ){
  629. assert( n<pReader->nData );
  630. while( 1 ){
  631. n += getVarint32(pReader->pData+n, &iDummy);
  632. assert( n<=pReader->nData );
  633. if( iDummy==POS_END ) break;
  634. if( iDummy==POS_COLUMN ){
  635. n += getVarint32(pReader->pData+n, &iDummy);
  636. assert( n<pReader->nData );
  637. }else if( pReader->iType==DL_POSITIONS_OFFSETS ){
  638. n += getVarint32(pReader->pData+n, &iDummy);
  639. n += getVarint32(pReader->pData+n, &iDummy);
  640. assert( n<pReader->nData );
  641. }
  642. }
  643. }
  644. pReader->nElement = n;
  645. assert( pReader->nElement<=pReader->nData );
  646. }
  647. }
  648. static void dlrInit(DLReader *pReader, DocListType iType,
  649. const char *pData, int nData){
  650. assert( pData!=NULL && nData!=0 );
  651. pReader->iType = iType;
  652. pReader->pData = pData;
  653. pReader->nData = nData;
  654. pReader->nElement = 0;
  655. pReader->iDocid = 0;
  656. /* Load the first element's data. There must be a first element. */
  657. dlrStep(pReader);
  658. }
  659. static void dlrDestroy(DLReader *pReader){
  660. SCRAMBLE(pReader);
  661. }
  662. #ifndef NDEBUG
  663. /* Verify that the doclist can be validly decoded. Also returns the
  664. ** last docid found because it is convenient in other assertions for
  665. ** DLWriter.
  666. */
  667. static void docListValidate(DocListType iType, const char *pData, int nData,
  668. sqlite_int64 *pLastDocid){
  669. sqlite_int64 iPrevDocid = 0;
  670. assert( nData>0 );
  671. assert( pData!=0 );
  672. assert( pData+nData>pData );
  673. while( nData!=0 ){
  674. sqlite_int64 iDocidDelta;
  675. int n = getVarint(pData, &iDocidDelta);
  676. iPrevDocid += iDocidDelta;
  677. if( iType>DL_DOCIDS ){
  678. int iDummy;
  679. while( 1 ){
  680. n += getVarint32(pData+n, &iDummy);
  681. if( iDummy==POS_END ) break;
  682. if( iDummy==POS_COLUMN ){
  683. n += getVarint32(pData+n, &iDummy);
  684. }else if( iType>DL_POSITIONS ){
  685. n += getVarint32(pData+n, &iDummy);
  686. n += getVarint32(pData+n, &iDummy);
  687. }
  688. assert( n<=nData );
  689. }
  690. }
  691. assert( n<=nData );
  692. pData += n;
  693. nData -= n;
  694. }
  695. if( pLastDocid ) *pLastDocid = iPrevDocid;
  696. }
  697. #define ASSERT_VALID_DOCLIST(i, p, n, o) docListValidate(i, p, n, o)
  698. #else
  699. #define ASSERT_VALID_DOCLIST(i, p, n, o) assert( 1 )
  700. #endif
  701. /*******************************************************************/
  702. /* DLWriter is used to write doclist data to a DataBuffer. DLWriter
  703. ** always appends to the buffer and does not own it.
  704. **
  705. ** dlwInit - initialize to write a given type doclistto a buffer.
  706. ** dlwDestroy - clear the writer's memory. Does not free buffer.
  707. ** dlwAppend - append raw doclist data to buffer.
  708. ** dlwCopy - copy next doclist from reader to writer.
  709. ** dlwAdd - construct doclist element and append to buffer.
  710. ** Only apply dlwAdd() to DL_DOCIDS doclists (else use PLWriter).
  711. */
  712. typedef struct DLWriter {
  713. DocListType iType;
  714. DataBuffer *b;
  715. sqlite_int64 iPrevDocid;
  716. #ifndef NDEBUG
  717. int has_iPrevDocid;
  718. #endif
  719. } DLWriter;
  720. static void dlwInit(DLWriter *pWriter, DocListType iType, DataBuffer *b){
  721. pWriter->b = b;
  722. pWriter->iType = iType;
  723. pWriter->iPrevDocid = 0;
  724. #ifndef NDEBUG
  725. pWriter->has_iPrevDocid = 0;
  726. #endif
  727. }
  728. static void dlwDestroy(DLWriter *pWriter){
  729. SCRAMBLE(pWriter);
  730. }
  731. /* iFirstDocid is the first docid in the doclist in pData. It is
  732. ** needed because pData may point within a larger doclist, in which
  733. ** case the first item would be delta-encoded.
  734. **
  735. ** iLastDocid is the final docid in the doclist in pData. It is
  736. ** needed to create the new iPrevDocid for future delta-encoding. The
  737. ** code could decode the passed doclist to recreate iLastDocid, but
  738. ** the only current user (docListMerge) already has decoded this
  739. ** information.
  740. */
  741. /* TODO(shess) This has become just a helper for docListMerge.
  742. ** Consider a refactor to make this cleaner.
  743. */
  744. static void dlwAppend(DLWriter *pWriter,
  745. const char *pData, int nData,
  746. sqlite_int64 iFirstDocid, sqlite_int64 iLastDocid){
  747. sqlite_int64 iDocid = 0;
  748. char c[VARINT_MAX];
  749. int nFirstOld, nFirstNew; /* Old and new varint len of first docid. */
  750. #ifndef NDEBUG
  751. sqlite_int64 iLastDocidDelta;
  752. #endif
  753. /* Recode the initial docid as delta from iPrevDocid. */
  754. nFirstOld = getVarint(pData, &iDocid);
  755. assert( nFirstOld<nData || (nFirstOld==nData && pWriter->iType==DL_DOCIDS) );
  756. nFirstNew = putVarint(c, iFirstDocid-pWriter->iPrevDocid);
  757. /* Verify that the incoming doclist is valid AND that it ends with
  758. ** the expected docid. This is essential because we'll trust this
  759. ** docid in future delta-encoding.
  760. */
  761. ASSERT_VALID_DOCLIST(pWriter->iType, pData, nData, &iLastDocidDelta);
  762. assert( iLastDocid==iFirstDocid-iDocid+iLastDocidDelta );
  763. /* Append recoded initial docid and everything else. Rest of docids
  764. ** should have been delta-encoded from previous initial docid.
  765. */
  766. if( nFirstOld<nData ){
  767. dataBufferAppend2(pWriter->b, c, nFirstNew,
  768. pData+nFirstOld, nData-nFirstOld);
  769. }else{
  770. dataBufferAppend(pWriter->b, c, nFirstNew);
  771. }
  772. pWriter->iPrevDocid = iLastDocid;
  773. }
  774. static void dlwCopy(DLWriter *pWriter, DLReader *pReader){
  775. dlwAppend(pWriter, dlrDocData(pReader), dlrDocDataBytes(pReader),
  776. dlrDocid(pReader), dlrDocid(pReader));
  777. }
  778. static void dlwAdd(DLWriter *pWriter, sqlite_int64 iDocid){
  779. char c[VARINT_MAX];
  780. int n = putVarint(c, iDocid-pWriter->iPrevDocid);
  781. /* Docids must ascend. */
  782. assert( !pWriter->has_iPrevDocid || iDocid>pWriter->iPrevDocid );
  783. assert( pWriter->iType==DL_DOCIDS );
  784. dataBufferAppend(pWriter->b, c, n);
  785. pWriter->iPrevDocid = iDocid;
  786. #ifndef NDEBUG
  787. pWriter->has_iPrevDocid = 1;
  788. #endif
  789. }
  790. /*******************************************************************/
  791. /* PLReader is used to read data from a document's position list. As
  792. ** the caller steps through the list, data is cached so that varints
  793. ** only need to be decoded once.
  794. **
  795. ** plrInit, plrDestroy - create/destroy a reader.
  796. ** plrColumn, plrPosition, plrStartOffset, plrEndOffset - accessors
  797. ** plrAtEnd - at end of stream, only call plrDestroy once true.
  798. ** plrStep - step to the next element.
  799. */
  800. typedef struct PLReader {
  801. /* These refer to the next position's data. nData will reach 0 when
  802. ** reading the last position, so plrStep() signals EOF by setting
  803. ** pData to NULL.
  804. */
  805. const char *pData;
  806. int nData;
  807. DocListType iType;
  808. int iColumn; /* the last column read */
  809. int iPosition; /* the last position read */
  810. int iStartOffset; /* the last start offset read */
  811. int iEndOffset; /* the last end offset read */
  812. } PLReader;
  813. static int plrAtEnd(PLReader *pReader){
  814. return pReader->pData==NULL;
  815. }
  816. static int plrColumn(PLReader *pReader){
  817. assert( !plrAtEnd(pReader) );
  818. return pReader->iColumn;
  819. }
  820. static int plrPosition(PLReader *pReader){
  821. assert( !plrAtEnd(pReader) );
  822. return pReader->iPosition;
  823. }
  824. static int plrStartOffset(PLReader *pReader){
  825. assert( !plrAtEnd(pReader) );
  826. return pReader->iStartOffset;
  827. }
  828. static int plrEndOffset(PLReader *pReader){
  829. assert( !plrAtEnd(pReader) );
  830. return pReader->iEndOffset;
  831. }
  832. static void plrStep(PLReader *pReader){
  833. int i, n;
  834. assert( !plrAtEnd(pReader) );
  835. if( pReader->nData==0 ){
  836. pReader->pData = NULL;
  837. return;
  838. }
  839. n = getVarint32(pReader->pData, &i);
  840. if( i==POS_COLUMN ){
  841. n += getVarint32(pReader->pData+n, &pReader->iColumn);
  842. pReader->iPosition = 0;
  843. pReader->iStartOffset = 0;
  844. n += getVarint32(pReader->pData+n, &i);
  845. }
  846. /* Should never see adjacent column changes. */
  847. assert( i!=POS_COLUMN );
  848. if( i==POS_END ){
  849. pReader->nData = 0;
  850. pReader->pData = NULL;
  851. return;
  852. }
  853. pReader->iPosition += i-POS_BASE;
  854. if( pReader->iType==DL_POSITIONS_OFFSETS ){
  855. n += getVarint32(pReader->pData+n, &i);
  856. pReader->iStartOffset += i;
  857. n += getVarint32(pReader->pData+n, &i);
  858. pReader->iEndOffset = pReader->iStartOffset+i;
  859. }
  860. assert( n<=pReader->nData );
  861. pReader->pData += n;
  862. pReader->nData -= n;
  863. }
  864. static void plrInit(PLReader *pReader, DLReader *pDLReader){
  865. pReader->pData = dlrPosData(pDLReader);
  866. pReader->nData = dlrPosDataLen(pDLReader);
  867. pReader->iType = pDLReader->iType;
  868. pReader->iColumn = 0;
  869. pReader->iPosition = 0;
  870. pReader->iStartOffset = 0;
  871. pReader->iEndOffset = 0;
  872. plrStep(pReader);
  873. }
  874. static void plrDestroy(PLReader *pReader){
  875. SCRAMBLE(pReader);
  876. }
  877. /*******************************************************************/
  878. /* PLWriter is used in constructing a document's position list. As a
  879. ** convenience, if iType is DL_DOCIDS, PLWriter becomes a no-op.
  880. ** PLWriter writes to the associated DLWriter's buffer.
  881. **
  882. ** plwInit - init for writing a document's poslist.
  883. ** plwDestroy - clear a writer.
  884. ** plwAdd - append position and offset information.
  885. ** plwCopy - copy next position's data from reader to writer.
  886. ** plwTerminate - add any necessary doclist terminator.
  887. **
  888. ** Calling plwAdd() after plwTerminate() may result in a corrupt
  889. ** doclist.
  890. */
  891. /* TODO(shess) Until we've written the second item, we can cache the
  892. ** first item's information. Then we'd have three states:
  893. **
  894. ** - initialized with docid, no positions.
  895. ** - docid and one position.
  896. ** - docid and multiple positions.
  897. **
  898. ** Only the last state needs to actually write to dlw->b, which would
  899. ** be an improvement in the DLCollector case.
  900. */
  901. typedef struct PLWriter {
  902. DLWriter *dlw;
  903. int iColumn; /* the last column written */
  904. int iPos; /* the last position written */
  905. int iOffset; /* the last start offset written */
  906. } PLWriter;
  907. /* TODO(shess) In the case where the parent is reading these values
  908. ** from a PLReader, we could optimize to a copy if that PLReader has
  909. ** the same type as pWriter.
  910. */
  911. static void plwAdd(PLWriter *pWriter, int iColumn, int iPos,
  912. int iStartOffset, int iEndOffset){
  913. /* Worst-case space for POS_COLUMN, iColumn, iPosDelta,
  914. ** iStartOffsetDelta, and iEndOffsetDelta.
  915. */
  916. char c[5*VARINT_MAX];
  917. int n = 0;
  918. /* Ban plwAdd() after plwTerminate(). */
  919. assert( pWriter->iPos!=-1 );
  920. if( pWriter->dlw->iType==DL_DOCIDS ) return;
  921. if( iColumn!=pWriter->iColumn ){
  922. n += putVarint(c+n, POS_COLUMN);
  923. n += putVarint(c+n, iColumn);
  924. pWriter->iColumn = iColumn;
  925. pWriter->iPos = 0;
  926. pWriter->iOffset = 0;
  927. }
  928. assert( iPos>=pWriter->iPos );
  929. n += putVarint(c+n, POS_BASE+(iPos-pWriter->iPos));
  930. pWriter->iPos = iPos;
  931. if( pWriter->dlw->iType==DL_POSITIONS_OFFSETS ){
  932. assert( iStartOffset>=pWriter->iOffset );
  933. n += putVarint(c+n, iStartOffset-pWriter->iOffset);
  934. pWriter->iOffset = iStartOffset;
  935. assert( iEndOffset>=iStartOffset );
  936. n += putVarint(c+n, iEndOffset-iStartOffset);
  937. }
  938. dataBufferAppend(pWriter->dlw->b, c, n);
  939. }
  940. static void plwCopy(PLWriter *pWriter, PLReader *pReader){
  941. plwAdd(pWriter, plrColumn(pReader), plrPosition(pReader),
  942. plrStartOffset(pReader), plrEndOffset(pReader));
  943. }
  944. static void plwInit(PLWriter *pWriter, DLWriter *dlw, sqlite_int64 iDocid){
  945. char c[VARINT_MAX];
  946. int n;
  947. pWriter->dlw = dlw;
  948. /* Docids must ascend. */
  949. assert( !pWriter->dlw->has_iPrevDocid || iDocid>pWriter->dlw->iPrevDocid );
  950. n = putVarint(c, iDocid-pWriter->dlw->iPrevDocid);
  951. dataBufferAppend(pWriter->dlw->b, c, n);
  952. pWriter->dlw->iPrevDocid = iDocid;
  953. #ifndef NDEBUG
  954. pWriter->dlw->has_iPrevDocid = 1;
  955. #endif
  956. pWriter->iColumn = 0;
  957. pWriter->iPos = 0;
  958. pWriter->iOffset = 0;
  959. }
  960. /* TODO(shess) Should plwDestroy() also terminate the doclist? But
  961. ** then plwDestroy() would no longer be just a destructor, it would
  962. ** also be doing work, which isn't consistent with the overall idiom.
  963. ** Another option would be for plwAdd() to always append any necessary
  964. ** terminator, so that the output is always correct. But that would
  965. ** add incremental work to the common case with the only benefit being
  966. ** API elegance. Punt for now.
  967. */
  968. static void plwTerminate(PLWriter *pWriter){
  969. if( pWriter->dlw->iType>DL_DOCIDS ){
  970. char c[VARINT_MAX];
  971. int n = putVarint(c, POS_END);
  972. dataBufferAppend(pWriter->dlw->b, c, n);
  973. }
  974. #ifndef NDEBUG
  975. /* Mark as terminated for assert in plwAdd(). */
  976. pWriter->iPos = -1;
  977. #endif
  978. }
  979. static void plwDestroy(PLWriter *pWriter){
  980. SCRAMBLE(pWriter);
  981. }
  982. /*******************************************************************/
  983. /* DLCollector wraps PLWriter and DLWriter to provide a
  984. ** dynamically-allocated doclist area to use during tokenization.
  985. **
  986. ** dlcNew - malloc up and initialize a collector.
  987. ** dlcDelete - destroy a collector and all contained items.
  988. ** dlcAddPos - append position and offset information.
  989. ** dlcAddDoclist - add the collected doclist to the given buffer.
  990. ** dlcNext - terminate the current document and open another.
  991. */
  992. typedef struct DLCollector {
  993. DataBuffer b;
  994. DLWriter dlw;
  995. PLWriter plw;
  996. } DLCollector;
  997. /* TODO(shess) This could also be done by calling plwTerminate() and
  998. ** dataBufferAppend(). I tried that, expecting nominal performance
  999. ** differences, but it seemed to pretty reliably be worth 1% to code
  1000. ** it this way. I suspect it is the incremental malloc overhead (some
  1001. ** percentage of the plwTerminate() calls will cause a realloc), so
  1002. ** this might be worth revisiting if the DataBuffer implementation
  1003. ** changes.
  1004. */
  1005. static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){
  1006. if( pCollector->dlw.iType>DL_DOCIDS ){
  1007. char c[VARINT_MAX];
  1008. int n = putVarint(c, POS_END);
  1009. dataBufferAppend2(b, pCollector->b.pData, pCollector->b.nData, c, n);
  1010. }else{
  1011. dataBufferAppend(b, pCollector->b.pData, pCollector->b.nData);
  1012. }
  1013. }
  1014. static void dlcNext(DLCollector *pCollector, sqlite_int64 iDocid){
  1015. plwTerminate(&pCollector->plw);
  1016. plwDestroy(&pCollector->plw);
  1017. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  1018. }
  1019. static void dlcAddPos(DLCollector *pCollector, int iColumn, int iPos,
  1020. int iStartOffset, int iEndOffset){
  1021. plwAdd(&pCollector->plw, iColumn, iPos, iStartOffset, iEndOffset);
  1022. }
  1023. static DLCollector *dlcNew(sqlite_int64 iDocid, DocListType iType){
  1024. DLCollector *pCollector = sqlite3_malloc(sizeof(DLCollector));
  1025. dataBufferInit(&pCollector->b, 0);
  1026. dlwInit(&pCollector->dlw, iType, &pCollector->b);
  1027. plwInit(&pCollector->plw, &pCollector->dlw, iDocid);
  1028. return pCollector;
  1029. }
  1030. static void dlcDelete(DLCollector *pCollector){
  1031. plwDestroy(&pCollector->plw);
  1032. dlwDestroy(&pCollector->dlw);
  1033. dataBufferDestroy(&pCollector->b);
  1034. SCRAMBLE(pCollector);
  1035. sqlite3_free(pCollector);
  1036. }
  1037. /* Copy the doclist data of iType in pData/nData into *out, trimming
  1038. ** unnecessary data as we go. Only columns matching iColumn are
  1039. ** copied, all columns copied if iColumn is -1. Elements with no
  1040. ** matching columns are dropped. The output is an iOutType doclist.
  1041. */
  1042. /* NOTE(shess) This code is only valid after all doclists are merged.
  1043. ** If this is run before merges, then doclist items which represent
  1044. ** deletion will be trimmed, and will thus not effect a deletion
  1045. ** during the merge.
  1046. */
  1047. static void docListTrim(DocListType iType, const char *pData, int nData,
  1048. int iColumn, DocListType iOutType, DataBuffer *out){
  1049. DLReader dlReader;
  1050. DLWriter dlWriter;
  1051. assert( iOutType<=iType );
  1052. dlrInit(&dlReader, iType, pData, nData);
  1053. dlwInit(&dlWriter, iOutType, out);
  1054. while( !dlrAtEnd(&dlReader) ){
  1055. PLReader plReader;
  1056. PLWriter plWriter;
  1057. int match = 0;
  1058. plrInit(&plReader, &dlReader);
  1059. while( !plrAtEnd(&plReader) ){
  1060. if( iColumn==-1 || plrColumn(&plReader)==iColumn ){
  1061. if( !match ){
  1062. plwInit(&plWriter, &dlWriter, dlrDocid(&dlReader));
  1063. match = 1;
  1064. }
  1065. plwAdd(&plWriter, plrColumn(&plReader), plrPosition(&plReader),
  1066. plrStartOffset(&plReader), plrEndOffset(&plReader));
  1067. }
  1068. plrStep(&plReader);
  1069. }
  1070. if( match ){
  1071. plwTerminate(&plWriter);
  1072. plwDestroy(&plWriter);
  1073. }
  1074. plrDestroy(&plReader);
  1075. dlrStep(&dlReader);
  1076. }
  1077. dlwDestroy(&dlWriter);
  1078. dlrDestroy(&dlReader);
  1079. }
  1080. /* Used by docListMerge() to keep doclists in the ascending order by
  1081. ** docid, then ascending order by age (so the newest comes first).
  1082. */
  1083. typedef struct OrderedDLReader {
  1084. DLReader *pReader;
  1085. /* TODO(shess) If we assume that docListMerge pReaders is ordered by
  1086. ** age (which we do), then we could use pReader comparisons to break
  1087. ** ties.
  1088. */
  1089. int idx;
  1090. } OrderedDLReader;
  1091. /* Order eof to end, then by docid asc, idx desc. */
  1092. static int orderedDLReaderCmp(OrderedDLReader *r1, OrderedDLReader *r2){
  1093. if( dlrAtEnd(r1->pReader) ){
  1094. if( dlrAtEnd(r2->pReader) ) return 0; /* Both atEnd(). */
  1095. return 1; /* Only r1 atEnd(). */
  1096. }
  1097. if( dlrAtEnd(r2->pReader) ) return -1; /* Only r2 atEnd(). */
  1098. if( dlrDocid(r1->pReader)<dlrDocid(r2->pReader) ) return -1;
  1099. if( dlrDocid(r1->pReader)>dlrDocid(r2->pReader) ) return 1;
  1100. /* Descending on idx. */
  1101. return r2->idx-r1->idx;
  1102. }
  1103. /* Bubble p[0] to appropriate place in p[1..n-1]. Assumes that
  1104. ** p[1..n-1] is already sorted.
  1105. */
  1106. /* TODO(shess) Is this frequent enough to warrant a binary search?
  1107. ** Before implementing that, instrument the code to check. In most
  1108. ** current usage, I expect that p[0] will be less than p[1] a very
  1109. ** high proportion of the time.
  1110. */
  1111. static void orderedDLReaderReorder(OrderedDLReader *p, int n){
  1112. while( n>1 && orderedDLReaderCmp(p, p+1)>0 ){
  1113. OrderedDLReader tmp = p[0];
  1114. p[0] = p[1];
  1115. p[1] = tmp;
  1116. n--;
  1117. p++;
  1118. }
  1119. }
  1120. /* Given an array of doclist readers, merge their doclist elements
  1121. ** into out in sorted order (by docid), dropping elements from older
  1122. ** readers when there is a duplicate docid. pReaders is assumed to be
  1123. ** ordered by age, oldest first.
  1124. */
  1125. /* TODO(shess) nReaders must be <= MERGE_COUNT. This should probably
  1126. ** be fixed.
  1127. */
  1128. static void docListMerge(DataBuffer *out,
  1129. DLReader *pReaders, int nReaders){
  1130. OrderedDLReader readers[MERGE_COUNT];
  1131. DLWriter writer;
  1132. int i, n;
  1133. const char *pStart = 0;
  1134. int nStart = 0;
  1135. sqlite_int64 iFirstDocid = 0, iLastDocid = 0;
  1136. assert( nReaders>0 );
  1137. if( nReaders==1 ){
  1138. dataBufferAppend(out, dlrDocData(pReaders), dlrAllDataBytes(pReaders));
  1139. return;
  1140. }
  1141. assert( nReaders<=MERGE_COUNT );
  1142. n = 0;
  1143. for(i=0; i<nReaders; i++){
  1144. assert( pReaders[i].iType==pReaders[0].iType );
  1145. readers[i].pReader = pReaders+i;
  1146. readers[i].idx = i;
  1147. n += dlrAllDataBytes(&pReaders[i]);
  1148. }
  1149. /* Conservatively size output to sum of inputs. Output should end
  1150. ** up strictly smaller than input.
  1151. */
  1152. dataBufferExpand(out, n);
  1153. /* Get the readers into sorted order. */
  1154. while( i-->0 ){
  1155. orderedDLReaderReorder(readers+i, nReaders-i);
  1156. }
  1157. dlwInit(&writer, pReaders[0].iType, out);
  1158. while( !dlrAtEnd(readers[0].pReader) ){
  1159. sqlite_int64 iDocid = dlrDocid(readers[0].pReader);
  1160. /* If this is a continuation of the current buffer to copy, extend
  1161. ** that buffer. memcpy() seems to be more efficient if it has a
  1162. ** lots of data to copy.
  1163. */
  1164. if( dlrDocData(readers[0].pReader)==pStart+nStart ){
  1165. nStart += dlrDocDataBytes(readers[0].pReader);
  1166. }else{
  1167. if( pStart!=0 ){
  1168. dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  1169. }
  1170. pStart = dlrDocData(readers[0].pReader);
  1171. nStart = dlrDocDataBytes(readers[0].pReader);
  1172. iFirstDocid = iDocid;
  1173. }
  1174. iLastDocid = iDocid;
  1175. dlrStep(readers[0].pReader);
  1176. /* Drop all of the older elements with the same docid. */
  1177. for(i=1; i<nReaders &&
  1178. !dlrAtEnd(readers[i].pReader) &&
  1179. dlrDocid(readers[i].pReader)==iDocid; i++){
  1180. dlrStep(readers[i].pReader);
  1181. }
  1182. /* Get the readers back into order. */
  1183. while( i-->0 ){
  1184. orderedDLReaderReorder(readers+i, nReaders-i);
  1185. }
  1186. }
  1187. /* Copy over any remaining elements. */
  1188. if( nStart>0 ) dlwAppend(&writer, pStart, nStart, iFirstDocid, iLastDocid);
  1189. dlwDestroy(&writer);
  1190. }
  1191. /* Helper function for posListUnion(). Compares the current position
  1192. ** between left and right, returning as standard C idiom of <0 if
  1193. ** left<right, >0 if left>right, and 0 if left==right. "End" always
  1194. ** compares greater.
  1195. */
  1196. static int posListCmp(PLReader *pLeft, PLReader *pRight){
  1197. assert( pLeft->iType==pRight->iType );
  1198. if( pLeft->iType==DL_DOCIDS ) return 0;
  1199. if( plrAtEnd(pLeft) ) return plrAtEnd(pRight) ? 0 : 1;
  1200. if( plrAtEnd(pRight) ) return -1;
  1201. if( plrColumn(pLeft)<plrColumn(pRight) ) return -1;
  1202. if( plrColumn(pLeft)>plrColumn(pRight) ) return 1;
  1203. if( plrPosition(pLeft)<plrPosition(pRight) ) return -1;
  1204. if( plrPosition(pLeft)>plrPosition(pRight) ) return 1;
  1205. if( pLeft->iType==DL_POSITIONS ) return 0;
  1206. if( plrStartOffset(pLeft)<plrStartOffset(pRight) ) return -1;
  1207. if( plrStartOffset(pLeft)>plrStartOffset(pRight) ) return 1;
  1208. if( plrEndOffset(pLeft)<plrEndOffset(pRight) ) return -1;
  1209. if( plrEndOffset(pLeft)>plrEndOffset(pRight) ) return 1;
  1210. return 0;
  1211. }
  1212. /* Write the union of position lists in pLeft and pRight to pOut.
  1213. ** "Union" in this case meaning "All unique position tuples". Should
  1214. ** work with any doclist type, though both inputs and the output
  1215. ** should be the same type.
  1216. */
  1217. static void posListUnion(DLReader *pLeft, DLReader *pRight, DLWriter *pOut){
  1218. PLReader left, right;
  1219. PLWriter writer;
  1220. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  1221. assert( pLeft->iType==pRight->iType );
  1222. assert( pLeft->iType==pOut->iType );
  1223. plrInit(&left, pLeft);
  1224. plrInit(&right, pRight);
  1225. plwInit(&writer, pOut, dlrDocid(pLeft));
  1226. while( !plrAtEnd(&left) || !plrAtEnd(&right) ){
  1227. int c = posListCmp(&left, &right);
  1228. if( c<0 ){
  1229. plwCopy(&writer, &left);
  1230. plrStep(&left);
  1231. }else if( c>0 ){
  1232. plwCopy(&writer, &right);
  1233. plrStep(&right);
  1234. }else{
  1235. plwCopy(&writer, &left);
  1236. plrStep(&left);
  1237. plrStep(&right);
  1238. }
  1239. }
  1240. plwTerminate(&writer);
  1241. plwDestroy(&writer);
  1242. plrDestroy(&left);
  1243. plrDestroy(&right);
  1244. }
  1245. /* Write the union of doclists in pLeft and pRight to pOut. For
  1246. ** docids in common between the inputs, the union of the position
  1247. ** lists is written. Inputs and outputs are always type DL_DEFAULT.
  1248. */
  1249. static void docListUnion(
  1250. const char *pLeft, int nLeft,
  1251. const char *pRight, int nRight,
  1252. DataBuffer *pOut /* Write the combined doclist here */
  1253. ){
  1254. DLReader left, right;
  1255. DLWriter writer;
  1256. if( nLeft==0 ){
  1257. if( nRight!=0) dataBufferAppend(pOut, pRight, nRight);
  1258. return;
  1259. }
  1260. if( nRight==0 ){
  1261. dataBufferAppend(pOut, pLeft, nLeft);
  1262. return;
  1263. }
  1264. dlrInit(&left, DL_DEFAULT, pLeft, nLeft);
  1265. dlrInit(&right, DL_DEFAULT, pRight, nRight);
  1266. dlwInit(&writer, DL_DEFAULT, pOut);
  1267. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  1268. if( dlrAtEnd(&right) ){
  1269. dlwCopy(&writer, &left);
  1270. dlrStep(&left);
  1271. }else if( dlrAtEnd(&left) ){
  1272. dlwCopy(&writer, &right);
  1273. dlrStep(&right);
  1274. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  1275. dlwCopy(&writer, &left);
  1276. dlrStep(&left);
  1277. }else if( dlrDocid(&left)>dlrDocid(&right) ){
  1278. dlwCopy(&writer, &right);
  1279. dlrStep(&right);
  1280. }else{
  1281. posListUnion(&left, &right, &writer);
  1282. dlrStep(&left);
  1283. dlrStep(&right);
  1284. }
  1285. }
  1286. dlrDestroy(&left);
  1287. dlrDestroy(&right);
  1288. dlwDestroy(&writer);
  1289. }
  1290. /* pLeft and pRight are DLReaders positioned to the same docid.
  1291. **
  1292. ** If there are no instances in pLeft or pRight where the position
  1293. ** of pLeft is one less than the position of pRight, then this
  1294. ** routine adds nothing to pOut.
  1295. **
  1296. ** If there are one or more instances where positions from pLeft
  1297. ** are exactly one less than positions from pRight, then add a new
  1298. ** document record to pOut. If pOut wants to hold positions, then
  1299. ** include the positions from pRight that are one more than a
  1300. ** position in pLeft. In other words: pRight.iPos==pLeft.iPos+1.
  1301. */
  1302. static void posListPhraseMerge(DLReader *pLeft, DLReader *pRight,
  1303. DLWriter *pOut){
  1304. PLReader left, right;
  1305. PLWriter writer;
  1306. int match = 0;
  1307. assert( dlrDocid(pLeft)==dlrDocid(pRight) );
  1308. assert( pOut->iType!=DL_POSITIONS_OFFSETS );
  1309. plrInit(&left, pLeft);
  1310. plrInit(&right, pRight);
  1311. while( !plrAtEnd(&left) && !plrAtEnd(&right) ){
  1312. if( plrColumn(&left)<plrColumn(&right) ){
  1313. plrStep(&left);
  1314. }else if( plrColumn(&left)>plrColumn(&right) ){
  1315. plrStep(&right);
  1316. }else if( plrPosition(&left)+1<plrPosition(&right) ){
  1317. plrStep(&left);
  1318. }else if( plrPosition(&left)+1>plrPosition(&right) ){
  1319. plrStep(&right);
  1320. }else{
  1321. if( !match ){
  1322. plwInit(&writer, pOut, dlrDocid(pLeft));
  1323. match = 1;
  1324. }
  1325. plwAdd(&writer, plrColumn(&right), plrPosition(&right), 0, 0);
  1326. plrStep(&left);
  1327. plrStep(&right);
  1328. }
  1329. }
  1330. if( match ){
  1331. plwTerminate(&writer);
  1332. plwDestroy(&writer);
  1333. }
  1334. plrDestroy(&left);
  1335. plrDestroy(&right);
  1336. }
  1337. /* We have two doclists with positions: pLeft and pRight.
  1338. ** Write the phrase intersection of these two doclists into pOut.
  1339. **
  1340. ** A phrase intersection means that two documents only match
  1341. ** if pLeft.iPos+1==pRight.iPos.
  1342. **
  1343. ** iType controls the type of data written to pOut. If iType is
  1344. ** DL_POSITIONS, the positions are those from pRight.
  1345. */
  1346. static void docListPhraseMerge(
  1347. const char *pLeft, int nLeft,
  1348. const char *pRight, int nRight,
  1349. DocListType iType,
  1350. DataBuffer *pOut /* Write the combined doclist here */
  1351. ){
  1352. DLReader left, right;
  1353. DLWriter writer;
  1354. if( nLeft==0 || nRight==0 ) return;
  1355. assert( iType!=DL_POSITIONS_OFFSETS );
  1356. dlrInit(&left, DL_POSITIONS, pLeft, nLeft);
  1357. dlrInit(&right, DL_POSITIONS, pRight, nRight);
  1358. dlwInit(&writer, iType, pOut);
  1359. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  1360. if( dlrDocid(&left)<dlrDocid(&right) ){
  1361. dlrStep(&left);
  1362. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  1363. dlrStep(&right);
  1364. }else{
  1365. posListPhraseMerge(&left, &right, &writer);
  1366. dlrStep(&left);
  1367. dlrStep(&right);
  1368. }
  1369. }
  1370. dlrDestroy(&left);
  1371. dlrDestroy(&right);
  1372. dlwDestroy(&writer);
  1373. }
  1374. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  1375. ** Write the intersection of these two doclists into pOut as a
  1376. ** DL_DOCIDS doclist.
  1377. */
  1378. static void docListAndMerge(
  1379. const char *pLeft, int nLeft,
  1380. const char *pRight, int nRight,
  1381. DataBuffer *pOut /* Write the combined doclist here */
  1382. ){
  1383. DLReader left, right;
  1384. DLWriter writer;
  1385. if( nLeft==0 || nRight==0 ) return;
  1386. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  1387. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  1388. dlwInit(&writer, DL_DOCIDS, pOut);
  1389. while( !dlrAtEnd(&left) && !dlrAtEnd(&right) ){
  1390. if( dlrDocid(&left)<dlrDocid(&right) ){
  1391. dlrStep(&left);
  1392. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  1393. dlrStep(&right);
  1394. }else{
  1395. dlwAdd(&writer, dlrDocid(&left));
  1396. dlrStep(&left);
  1397. dlrStep(&right);
  1398. }
  1399. }
  1400. dlrDestroy(&left);
  1401. dlrDestroy(&right);
  1402. dlwDestroy(&writer);
  1403. }
  1404. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  1405. ** Write the union of these two doclists into pOut as a
  1406. ** DL_DOCIDS doclist.
  1407. */
  1408. static void docListOrMerge(
  1409. const char *pLeft, int nLeft,
  1410. const char *pRight, int nRight,
  1411. DataBuffer *pOut /* Write the combined doclist here */
  1412. ){
  1413. DLReader left, right;
  1414. DLWriter writer;
  1415. if( nLeft==0 ){
  1416. if( nRight!=0 ) dataBufferAppend(pOut, pRight, nRight);
  1417. return;
  1418. }
  1419. if( nRight==0 ){
  1420. dataBufferAppend(pOut, pLeft, nLeft);
  1421. return;
  1422. }
  1423. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  1424. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  1425. dlwInit(&writer, DL_DOCIDS, pOut);
  1426. while( !dlrAtEnd(&left) || !dlrAtEnd(&right) ){
  1427. if( dlrAtEnd(&right) ){
  1428. dlwAdd(&writer, dlrDocid(&left));
  1429. dlrStep(&left);
  1430. }else if( dlrAtEnd(&left) ){
  1431. dlwAdd(&writer, dlrDocid(&right));
  1432. dlrStep(&right);
  1433. }else if( dlrDocid(&left)<dlrDocid(&right) ){
  1434. dlwAdd(&writer, dlrDocid(&left));
  1435. dlrStep(&left);
  1436. }else if( dlrDocid(&right)<dlrDocid(&left) ){
  1437. dlwAdd(&writer, dlrDocid(&right));
  1438. dlrStep(&right);
  1439. }else{
  1440. dlwAdd(&writer, dlrDocid(&left));
  1441. dlrStep(&left);
  1442. dlrStep(&right);
  1443. }
  1444. }
  1445. dlrDestroy(&left);
  1446. dlrDestroy(&right);
  1447. dlwDestroy(&writer);
  1448. }
  1449. /* We have two DL_DOCIDS doclists: pLeft and pRight.
  1450. ** Write into pOut as DL_DOCIDS doclist containing all documents that
  1451. ** occur in pLeft but not in pRight.
  1452. */
  1453. static void docListExceptMerge(
  1454. const char *pLeft, int nLeft,
  1455. const char *pRight, int nRight,
  1456. DataBuffer *pOut /* Write the combined doclist here */
  1457. ){
  1458. DLReader left, right;
  1459. DLWriter writer;
  1460. if( nLeft==0 ) return;
  1461. if( nRight==0 ){
  1462. dataBufferAppend(pOut, pLeft, nLeft);
  1463. return;
  1464. }
  1465. dlrInit(&left, DL_DOCIDS, pLeft, nLeft);
  1466. dlrInit(&right, DL_DOCIDS, pRight, nRight);
  1467. dlwInit(&writer, DL_DOCIDS, pOut);
  1468. while( !dlrAtEnd(&left) ){
  1469. while( !dlrAtEnd(&right) && dlrDocid(&right)<dlrDocid(&left) ){
  1470. dlrStep(&right);
  1471. }
  1472. if( dlrAtEnd(&right) || dlrDocid(&left)<dlrDocid(&right) ){
  1473. dlwAdd(&writer, dlrDocid(&left));
  1474. }
  1475. dlrStep(&left);
  1476. }
  1477. dlrDestroy(&left);
  1478. dlrDestroy(&right);
  1479. dlwDestroy(&writer);
  1480. }
  1481. static char *string_dup_n(const char *s, int n){
  1482. char *str = sqlite3_malloc(n + 1);
  1483. memcpy(str, s, n);
  1484. str[n] = '\0';
  1485. return str;
  1486. }
  1487. /* Duplicate a string; the caller must free() the returned string.
  1488. * (We don't use strdup() since it is not part of the standard C library and
  1489. * may not be available everywhere.) */
  1490. static char *string_dup(const char *s){
  1491. return string_dup_n(s, strlen(s));
  1492. }
  1493. /* Format a string, replacing each occurrence of the % character with
  1494. * zDb.zName. This may be more convenient than sqlite_mprintf()
  1495. * when one string is used repeatedly in a format string.
  1496. * The caller must free() the returned string. */
  1497. static char *string_format(const char *zFormat,
  1498. const char *zDb, const char *zName){
  1499. const char *p;
  1500. size_t len = 0;
  1501. size_t nDb = strlen(zDb);
  1502. size_t nName = strlen(zName);
  1503. size_t nFullTableName = nDb+1+nName;
  1504. char *result;
  1505. char *r;
  1506. /* first compute length needed */
  1507. for(p = zFormat ; *p ; ++p){
  1508. len += (*p=='%' ? nFullTableName : 1);
  1509. }
  1510. len += 1; /* for null terminator */
  1511. r = result = sqlite3_malloc(len);
  1512. for(p = zFormat; *p; ++p){
  1513. if( *p=='%' ){
  1514. memcpy(r, zDb, nDb);
  1515. r += nDb;
  1516. *r++ = '.';
  1517. memcpy(r, zName, nName);
  1518. r += nName;
  1519. } else {
  1520. *r++ = *p;
  1521. }
  1522. }
  1523. *r++ = '\0';
  1524. assert( r == result + len );
  1525. return result;
  1526. }
  1527. static int sql_exec(sqlite3 *db, const char *zDb, const char *zName,
  1528. const char *zFormat){
  1529. char *zCommand = string_format(zFormat, zDb, zName);
  1530. int rc;
  1531. TRACE(("FTS2 sql: %s\n", zCommand));
  1532. rc = sqlite3_exec(db, zCommand, NULL, 0, NULL);
  1533. sqlite3_free(zCommand);
  1534. return rc;
  1535. }
  1536. static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName,
  1537. sqlite3_stmt **ppStmt, const char *zFormat){
  1538. char *zCommand = string_format(zFormat, zDb, zName);
  1539. int rc;
  1540. TRACE(("FTS2 prepare: %s\n", zCommand));
  1541. rc = sqlite3_prepare_v2(db, zCommand, -1, ppStmt, NULL);
  1542. sqlite3_free(zCommand);
  1543. return rc;
  1544. }
  1545. /* end utility functions */
  1546. /* Forward reference */
  1547. typedef struct fulltext_vtab fulltext_vtab;
  1548. /* A single term in a query is represented by an instances of
  1549. ** the following structure.
  1550. */
  1551. typedef struct QueryTerm {
  1552. short int nPhrase; /* How many following terms are part of the same phrase */
  1553. short int iPhrase; /* This is the i-th term of a phrase. */
  1554. short int iColumn; /* Column of the index that must match this term */
  1555. signed char isOr; /* this term is preceded by "OR" */
  1556. signed char isNot; /* this term is preceded by "-" */
  1557. signed char isPrefix; /* this term is followed by "*" */
  1558. char *pTerm; /* text of the term. '\000' terminated. malloced */
  1559. int nTerm; /* Number of bytes in pTerm[] */
  1560. } QueryTerm;
  1561. /* A query string is parsed into a Query structure.
  1562. *
  1563. * We could, in theory, allow query strings to be complicated
  1564. * nested expressions with precedence determined by parentheses.
  1565. * But none of the major search engines do this. (Perhaps the
  1566. * feeling is that an parenthesized expression is two complex of
  1567. * an idea for the average user to grasp.) Taking our lead from
  1568. * the major search engines, we will allow queries to be a list
  1569. * of terms (with an implied AND operator) or phrases in double-quotes,
  1570. * with a single optional "-" before each non-phrase term to designate
  1571. * negation and an optional OR connector.
  1572. *
  1573. * OR binds more tightly than the implied AND, which is what the
  1574. * major search engines seem to do. So, for example:
  1575. *
  1576. * [one two OR three] ==> one AND (two OR three)
  1577. * [one OR two three] ==> (one OR two) AND three
  1578. *
  1579. * A "-" before a term matches all entries that lack that term.
  1580. * The "-" must occur immediately before the term with in intervening
  1581. * space. This is how the search engines do it.
  1582. *
  1583. * A NOT term cannot be the right-hand operand of an OR. If this
  1584. * occurs in the query string, the NOT is ignored:
  1585. *
  1586. * [one OR -two] ==> one OR two
  1587. *
  1588. */
  1589. typedef struct Query {
  1590. fulltext_vtab *pFts; /* The full text index */
  1591. int nTerms; /* Number of terms in the query */
  1592. QueryTerm *pTerms; /* Array of terms. Space obtained from malloc() */
  1593. int nextIsOr; /* Set the isOr flag on the next inserted term */
  1594. int nextColumn; /* Next word parsed must be in this column */
  1595. int dfltColumn; /* The default column */
  1596. } Query;
  1597. /*
  1598. ** An instance of the following structure keeps track of generated
  1599. ** matching-word offset information and snippets.
  1600. */
  1601. typedef struct Snippet {
  1602. int nMatch; /* Total number of matches */
  1603. int nAlloc; /* Space allocated for aMatch[] */
  1604. struct snippetMatch { /* One entry for each matching term */
  1605. char snStatus; /* Status flag for use while constructing snippets */
  1606. short int iCol; /* The column that contains the match */
  1607. short int iTerm; /* The index in Query.pTerms[] of the matching term */
  1608. short int nByte; /* Number of bytes in the term */
  1609. int iStart; /* The offset to the first character of the term */
  1610. } *aMatch; /* Points to space obtained from malloc */
  1611. char *zOffset; /* Text rendering of aMatch[] */
  1612. int nOffset; /* strlen(zOffset) */
  1613. char *zSnippet; /* Snippet text */
  1614. int nSnippet; /* strlen(zSnippet) */
  1615. } Snippet;
  1616. typedef enum QueryType {
  1617. QUERY_GENERIC, /* table scan */
  1618. QUERY_ROWID, /* lookup by rowid */
  1619. QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/
  1620. } QueryType;
  1621. typedef enum fulltext_statement {
  1622. CONTENT_INSERT_STMT,
  1623. CONTENT_SELECT_STMT,
  1624. CONTENT_UPDATE_STMT,
  1625. CONTENT_DELETE_STMT,
  1626. CONTENT_EXISTS_STMT,
  1627. BLOCK_INSERT_STMT,
  1628. BLOCK_SELECT_STMT,
  1629. BLOCK_DELETE_STMT,
  1630. BLOCK_DELETE_ALL_STMT,
  1631. SEGDIR_MAX_INDEX_STMT,
  1632. SEGDIR_SET_STMT,
  1633. SEGDIR_SELECT_LEVEL_STMT,
  1634. SEGDIR_SPAN_STMT,
  1635. SEGDIR_DELETE_STMT,
  1636. SEGDIR_SELECT_SEGMENT_STMT,
  1637. SEGDIR_SELECT_ALL_STMT,
  1638. SEGDIR_DELETE_ALL_STMT,
  1639. SEGDIR_COUNT_STMT,
  1640. MAX_STMT /* Always at end! */
  1641. } fulltext_statement;
  1642. /* These must exactly match the enum above. */
  1643. /* TODO(shess): Is there some risk that a statement will be used in two
  1644. ** cursors at once, e.g. if a query joins a virtual table to itself?
  1645. ** If so perhaps we should move some of these to the cursor object.
  1646. */
  1647. static const char *const fulltext_zStatement[MAX_STMT] = {
  1648. /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */
  1649. /* CONTENT_SELECT */ "select * from %_content where rowid = ?",
  1650. /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */
  1651. /* CONTENT_DELETE */ "delete from %_content where rowid = ?",
  1652. /* CONTENT_EXISTS */ "select rowid from %_content limit 1",
  1653. /* BLOCK_INSERT */ "insert into %_segments values (?)",
  1654. /* BLOCK_SELECT */ "select block from %_segments where rowid = ?",
  1655. /* BLOCK_DELETE */ "delete from %_segments where rowid between ? and ?",
  1656. /* BLOCK_DELETE_ALL */ "delete from %_segments",
  1657. /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?",
  1658. /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)",
  1659. /* SEGDIR_SELECT_LEVEL */
  1660. "select start_block, leaves_end_block, root from %_segdir "
  1661. " where level = ? order by idx",
  1662. /* SEGDIR_SPAN */
  1663. "select min(start_block), max(end_block) from %_segdir "
  1664. " where level = ? and start_block <> 0",
  1665. /* SEGDIR_DELETE */ "delete from %_segdir where level = ?",
  1666. /* NOTE(shess): The first three results of the following two
  1667. ** statements must match.
  1668. */
  1669. /* SEGDIR_SELECT_SEGMENT */
  1670. "select start_block, leaves_end_block, root from %_segdir "
  1671. " where level = ? and idx = ?",
  1672. /* SEGDIR_SELECT_ALL */
  1673. "select start_block, leaves_end_block, root from %_segdir "
  1674. " order by level desc, idx asc",
  1675. /* SEGDIR_DELETE_ALL */ "delete from %_segdir",
  1676. /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir",
  1677. };
  1678. /*
  1679. ** A connection to a fulltext index is an instance of the following
  1680. ** structure. The xCreate and xConnect methods create an instance
  1681. ** of this structure and xDestroy and xDisconnect free that instance.
  1682. ** All other methods receive a pointer to the structure as one of their
  1683. ** arguments.
  1684. */
  1685. struct fulltext_vtab {
  1686. sqlite3_vtab base; /* Base class used by SQLite core */
  1687. sqlite3 *db; /* The database connection */
  1688. const char *zDb; /* logical database name */
  1689. const char *zName; /* virtual table name */
  1690. int nColumn; /* number of columns in virtual table */
  1691. char **azColumn; /* column names. malloced */
  1692. char **azContentColumn; /* column names in content table; malloced */
  1693. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  1694. /* Precompiled statements which we keep as long as the table is
  1695. ** open.
  1696. */
  1697. sqlite3_stmt *pFulltextStatements[MAX_STMT];
  1698. /* Precompiled statements used for segment merges. We run a
  1699. ** separate select across the leaf level of each tree being merged.
  1700. */
  1701. sqlite3_stmt *pLeafSelectStmts[MERGE_COUNT];
  1702. /* The statement used to prepare pLeafSelectStmts. */
  1703. #define LEAF_SELECT \
  1704. "select block from %_segments where rowid between ? and ? order by rowid"
  1705. /* These buffer pending index updates during transactions.
  1706. ** nPendingData estimates the memory size of the pending data. It
  1707. ** doesn't include the hash-bucket overhead, nor any malloc
  1708. ** overhead. When nPendingData exceeds kPendingThreshold, the
  1709. ** buffer is flushed even before the transaction closes.
  1710. ** pendingTerms stores the data, and is only valid when nPendingData
  1711. ** is >=0 (nPendingData<0 means pendingTerms has not been
  1712. ** initialized). iPrevDocid is the last docid written, used to make
  1713. ** certain we're inserting in sorted order.
  1714. */
  1715. int nPendingData;
  1716. #define kPendingThreshold (1*1024*1024)
  1717. sqlite_int64 iPrevDocid;
  1718. fts2Hash pendingTerms;
  1719. };
  1720. /*
  1721. ** When the core wants to do a query, it create a cursor using a
  1722. ** call to xOpen. This structure is an instance of a cursor. It
  1723. ** is destroyed by xClose.
  1724. */
  1725. typedef struct fulltext_cursor {
  1726. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  1727. QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */
  1728. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  1729. int eof; /* True if at End Of Results */
  1730. Query q; /* Parsed query string */
  1731. Snippet snippet; /* Cached snippet for the current row */
  1732. int iColumn; /* Column being searched */
  1733. DataBuffer result; /* Doclist results from fulltextQuery */
  1734. DLReader reader; /* Result reader if result not empty */
  1735. } fulltext_cursor;
  1736. static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  1737. return (fulltext_vtab *) c->base.pVtab;
  1738. }
  1739. static const sqlite3_module fts2Module; /* forward declaration */
  1740. /* Return a dynamically generated statement of the form
  1741. * insert into %_content (rowid, ...) values (?, ...)
  1742. */
  1743. static const char *contentInsertStatement(fulltext_vtab *v){
  1744. StringBuffer sb;
  1745. int i;
  1746. initStringBuffer(&sb);
  1747. append(&sb, "insert into %_content (rowid, ");
  1748. appendList(&sb, v->nColumn, v->azContentColumn);
  1749. append(&sb, ") values (?");
  1750. for(i=0; i<v->nColumn; ++i)
  1751. append(&sb, ", ?");
  1752. append(&sb, ")");
  1753. return stringBufferData(&sb);
  1754. }
  1755. /* Return a dynamically generated statement of the form
  1756. * update %_content set [col_0] = ?, [col_1] = ?, ...
  1757. * where rowid = ?
  1758. */
  1759. static const char *contentUpdateStatement(fulltext_vtab *v){
  1760. StringBuffer sb;
  1761. int i;
  1762. initStringBuffer(&sb);
  1763. append(&sb, "update %_content set ");
  1764. for(i=0; i<v->nColumn; ++i) {
  1765. if( i>0 ){
  1766. append(&sb, ", ");
  1767. }
  1768. append(&sb, v->azContentColumn[i]);
  1769. append(&sb, " = ?");
  1770. }
  1771. append(&sb, " where rowid = ?");
  1772. return stringBufferData(&sb);
  1773. }
  1774. /* Puts a freshly-prepared statement determined by iStmt in *ppStmt.
  1775. ** If the indicated statement has never been prepared, it is prepared
  1776. ** and cached, otherwise the cached version is reset.
  1777. */
  1778. static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt,
  1779. sqlite3_stmt **ppStmt){
  1780. assert( iStmt<MAX_STMT );
  1781. if( v->pFulltextStatements[iStmt]==NULL ){
  1782. const char *zStmt;
  1783. int rc;
  1784. switch( iStmt ){
  1785. case CONTENT_INSERT_STMT:
  1786. zStmt = contentInsertStatement(v); break;
  1787. case CONTENT_UPDATE_STMT:
  1788. zStmt = contentUpdateStatement(v); break;
  1789. default:
  1790. zStmt = fulltext_zStatement[iStmt];
  1791. }
  1792. rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt],
  1793. zStmt);
  1794. if( zStmt != fulltext_zStatement[iStmt]) sqlite3_free((void *) zStmt);
  1795. if( rc!=SQLITE_OK ) return rc;
  1796. } else {
  1797. int rc = sqlite3_reset(v->pFulltextStatements[iStmt]);
  1798. if( rc!=SQLITE_OK ) return rc;
  1799. }
  1800. *ppStmt = v->pFulltextStatements[iStmt];
  1801. return SQLITE_OK;
  1802. }
  1803. /* Like sqlite3_step(), but convert SQLITE_DONE to SQLITE_OK and
  1804. ** SQLITE_ROW to SQLITE_ERROR. Useful for statements like UPDATE,
  1805. ** where we expect no results.
  1806. */
  1807. static int sql_single_step(sqlite3_stmt *s){
  1808. int rc = sqlite3_step(s);
  1809. return (rc==SQLITE_DONE) ? SQLITE_OK : rc;
  1810. }
  1811. /* Like sql_get_statement(), but for special replicated LEAF_SELECT
  1812. ** statements. idx -1 is a special case for an uncached version of
  1813. ** the statement (used in the optimize implementation).
  1814. */
  1815. /* TODO(shess) Write version for generic statements and then share
  1816. ** that between the cached-statement functions.
  1817. */
  1818. static int sql_get_leaf_statement(fulltext_vtab *v, int idx,
  1819. sqlite3_stmt **ppStmt){
  1820. assert( idx>=-1 && idx<MERGE_COUNT );
  1821. if( idx==-1 ){
  1822. return sql_prepare(v->db, v->zDb, v->zName, ppStmt, LEAF_SELECT);
  1823. }else if( v->pLeafSelectStmts[idx]==NULL ){
  1824. int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx],
  1825. LEAF_SELECT);
  1826. if( rc!=SQLITE_OK ) return rc;
  1827. }else{
  1828. int rc = sqlite3_reset(v->pLeafSelectStmts[idx]);
  1829. if( rc!=SQLITE_OK ) return rc;
  1830. }
  1831. *ppStmt = v->pLeafSelectStmts[idx];
  1832. return SQLITE_OK;
  1833. }
  1834. /* insert into %_content (rowid, ...) values ([rowid], [pValues]) */
  1835. static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
  1836. sqlite3_value **pValues){
  1837. sqlite3_stmt *s;
  1838. int i;
  1839. int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s);
  1840. if( rc!=SQLITE_OK ) return rc;
  1841. rc = sqlite3_bind_value(s, 1, rowid);
  1842. if( rc!=SQLITE_OK ) return rc;
  1843. for(i=0; i<v->nColumn; ++i){
  1844. rc = sqlite3_bind_value(s, 2+i, pValues[i]);
  1845. if( rc!=SQLITE_OK ) return rc;
  1846. }
  1847. return sql_single_step(s);
  1848. }
  1849. /* update %_content set col0 = pValues[0], col1 = pValues[1], ...
  1850. * where rowid = [iRowid] */
  1851. static int content_update(fulltext_vtab *v, sqlite3_value **pValues,
  1852. sqlite_int64 iRowid){
  1853. sqlite3_stmt *s;
  1854. int i;
  1855. int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s);
  1856. if( rc!=SQLITE_OK ) return rc;
  1857. for(i=0; i<v->nColumn; ++i){
  1858. rc = sqlite3_bind_value(s, 1+i, pValues[i]);
  1859. if( rc!=SQLITE_OK ) return rc;
  1860. }
  1861. rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid);
  1862. if( rc!=SQLITE_OK ) return rc;
  1863. return sql_single_step(s);
  1864. }
  1865. static void freeStringArray(int nString, const char **pString){
  1866. int i;
  1867. for (i=0 ; i < nString ; ++i) {
  1868. if( pString[i]!=NULL ) sqlite3_free((void *) pString[i]);
  1869. }
  1870. sqlite3_free((void *) pString);
  1871. }
  1872. /* select * from %_content where rowid = [iRow]
  1873. * The caller must delete the returned array and all strings in it.
  1874. * null fields will be NULL in the returned array.
  1875. *
  1876. * TODO: Perhaps we should return pointer/length strings here for consistency
  1877. * with other code which uses pointer/length. */
  1878. static int content_select(fulltext_vtab *v, sqlite_int64 iRow,
  1879. const char ***pValues){
  1880. sqlite3_stmt *s;
  1881. const char **values;
  1882. int i;
  1883. int rc;
  1884. *pValues = NULL;
  1885. rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s);
  1886. if( rc!=SQLITE_OK ) return rc;
  1887. rc = sqlite3_bind_int64(s, 1, iRow);
  1888. if( rc!=SQLITE_OK ) return rc;
  1889. rc = sqlite3_step(s);
  1890. if( rc!=SQLITE_ROW ) return rc;
  1891. values = (const char **) sqlite3_malloc(v->nColumn * sizeof(const char *));
  1892. for(i=0; i<v->nColumn; ++i){
  1893. if( sqlite3_column_type(s, i)==SQLITE_NULL ){
  1894. values[i] = NULL;
  1895. }else{
  1896. values[i] = string_dup((char*)sqlite3_column_text(s, i));
  1897. }
  1898. }
  1899. /* We expect only one row. We must execute another sqlite3_step()
  1900. * to complete the iteration; otherwise the table will remain locked. */
  1901. rc = sqlite3_step(s);
  1902. if( rc==SQLITE_DONE ){
  1903. *pValues = values;
  1904. return SQLITE_OK;
  1905. }
  1906. freeStringArray(v->nColumn, values);
  1907. return rc;
  1908. }
  1909. /* delete from %_content where rowid = [iRow ] */
  1910. static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){
  1911. sqlite3_stmt *s;
  1912. int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s);
  1913. if( rc!=SQLITE_OK ) return rc;
  1914. rc = sqlite3_bind_int64(s, 1, iRow);
  1915. if( rc!=SQLITE_OK ) return rc;
  1916. return sql_single_step(s);
  1917. }
  1918. /* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if
  1919. ** no rows exist, and any error in case of failure.
  1920. */
  1921. static int content_exists(fulltext_vtab *v){
  1922. sqlite3_stmt *s;
  1923. int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s);
  1924. if( rc!=SQLITE_OK ) return rc;
  1925. rc = sqlite3_step(s);
  1926. if( rc!=SQLITE_ROW ) return rc;
  1927. /* We expect only one row. We must execute another sqlite3_step()
  1928. * to complete the iteration; otherwise the table will remain locked. */
  1929. rc = sqlite3_step(s);
  1930. if( rc==SQLITE_DONE ) return SQLITE_ROW;
  1931. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  1932. return rc;
  1933. }
  1934. /* insert into %_segments values ([pData])
  1935. ** returns assigned rowid in *piBlockid
  1936. */
  1937. static int block_insert(fulltext_vtab *v, const char *pData, int nData,
  1938. sqlite_int64 *piBlockid){
  1939. sqlite3_stmt *s;
  1940. int rc = sql_get_statement(v, BLOCK_INSERT_STMT, &s);
  1941. if( rc!=SQLITE_OK ) return rc;
  1942. rc = sqlite3_bind_blob(s, 1, pData, nData, SQLITE_STATIC);
  1943. if( rc!=SQLITE_OK ) return rc;
  1944. rc = sqlite3_step(s);
  1945. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  1946. if( rc!=SQLITE_DONE ) return rc;
  1947. *piBlockid = sqlite3_last_insert_rowid(v->db);
  1948. return SQLITE_OK;
  1949. }
  1950. /* delete from %_segments
  1951. ** where rowid between [iStartBlockid] and [iEndBlockid]
  1952. **
  1953. ** Deletes the range of blocks, inclusive, used to delete the blocks
  1954. ** which form a segment.
  1955. */
  1956. static int block_delete(fulltext_vtab *v,
  1957. sqlite_int64 iStartBlockid, sqlite_int64 iEndBlockid){
  1958. sqlite3_stmt *s;
  1959. int rc = sql_get_statement(v, BLOCK_DELETE_STMT, &s);
  1960. if( rc!=SQLITE_OK ) return rc;
  1961. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  1962. if( rc!=SQLITE_OK ) return rc;
  1963. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  1964. if( rc!=SQLITE_OK ) return rc;
  1965. return sql_single_step(s);
  1966. }
  1967. /* Returns SQLITE_ROW with *pidx set to the maximum segment idx found
  1968. ** at iLevel. Returns SQLITE_DONE if there are no segments at
  1969. ** iLevel. Otherwise returns an error.
  1970. */
  1971. static int segdir_max_index(fulltext_vtab *v, int iLevel, int *pidx){
  1972. sqlite3_stmt *s;
  1973. int rc = sql_get_statement(v, SEGDIR_MAX_INDEX_STMT, &s);
  1974. if( rc!=SQLITE_OK ) return rc;
  1975. rc = sqlite3_bind_int(s, 1, iLevel);
  1976. if( rc!=SQLITE_OK ) return rc;
  1977. rc = sqlite3_step(s);
  1978. /* Should always get at least one row due to how max() works. */
  1979. if( rc==SQLITE_DONE ) return SQLITE_DONE;
  1980. if( rc!=SQLITE_ROW ) return rc;
  1981. /* NULL means that there were no inputs to max(). */
  1982. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  1983. rc = sqlite3_step(s);
  1984. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  1985. return rc;
  1986. }
  1987. *pidx = sqlite3_column_int(s, 0);
  1988. /* We expect only one row. We must execute another sqlite3_step()
  1989. * to complete the iteration; otherwise the table will remain locked. */
  1990. rc = sqlite3_step(s);
  1991. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  1992. if( rc!=SQLITE_DONE ) return rc;
  1993. return SQLITE_ROW;
  1994. }
  1995. /* insert into %_segdir values (
  1996. ** [iLevel], [idx],
  1997. ** [iStartBlockid], [iLeavesEndBlockid], [iEndBlockid],
  1998. ** [pRootData]
  1999. ** )
  2000. */
  2001. static int segdir_set(fulltext_vtab *v, int iLevel, int idx,
  2002. sqlite_int64 iStartBlockid,
  2003. sqlite_int64 iLeavesEndBlockid,
  2004. sqlite_int64 iEndBlockid,
  2005. const char *pRootData, int nRootData){
  2006. sqlite3_stmt *s;
  2007. int rc = sql_get_statement(v, SEGDIR_SET_STMT, &s);
  2008. if( rc!=SQLITE_OK ) return rc;
  2009. rc = sqlite3_bind_int(s, 1, iLevel);
  2010. if( rc!=SQLITE_OK ) return rc;
  2011. rc = sqlite3_bind_int(s, 2, idx);
  2012. if( rc!=SQLITE_OK ) return rc;
  2013. rc = sqlite3_bind_int64(s, 3, iStartBlockid);
  2014. if( rc!=SQLITE_OK ) return rc;
  2015. rc = sqlite3_bind_int64(s, 4, iLeavesEndBlockid);
  2016. if( rc!=SQLITE_OK ) return rc;
  2017. rc = sqlite3_bind_int64(s, 5, iEndBlockid);
  2018. if( rc!=SQLITE_OK ) return rc;
  2019. rc = sqlite3_bind_blob(s, 6, pRootData, nRootData, SQLITE_STATIC);
  2020. if( rc!=SQLITE_OK ) return rc;
  2021. return sql_single_step(s);
  2022. }
  2023. /* Queries %_segdir for the block span of the segments in level
  2024. ** iLevel. Returns SQLITE_DONE if there are no blocks for iLevel,
  2025. ** SQLITE_ROW if there are blocks, else an error.
  2026. */
  2027. static int segdir_span(fulltext_vtab *v, int iLevel,
  2028. sqlite_int64 *piStartBlockid,
  2029. sqlite_int64 *piEndBlockid){
  2030. sqlite3_stmt *s;
  2031. int rc = sql_get_statement(v, SEGDIR_SPAN_STMT, &s);
  2032. if( rc!=SQLITE_OK ) return rc;
  2033. rc = sqlite3_bind_int(s, 1, iLevel);
  2034. if( rc!=SQLITE_OK ) return rc;
  2035. rc = sqlite3_step(s);
  2036. if( rc==SQLITE_DONE ) return SQLITE_DONE; /* Should never happen */
  2037. if( rc!=SQLITE_ROW ) return rc;
  2038. /* This happens if all segments at this level are entirely inline. */
  2039. if( SQLITE_NULL==sqlite3_column_type(s, 0) ){
  2040. /* We expect only one row. We must execute another sqlite3_step()
  2041. * to complete the iteration; otherwise the table will remain locked. */
  2042. int rc2 = sqlite3_step(s);
  2043. if( rc2==SQLITE_ROW ) return SQLITE_ERROR;
  2044. return rc2;
  2045. }
  2046. *piStartBlockid = sqlite3_column_int64(s, 0);
  2047. *piEndBlockid = sqlite3_column_int64(s, 1);
  2048. /* We expect only one row. We must execute another sqlite3_step()
  2049. * to complete the iteration; otherwise the table will remain locked. */
  2050. rc = sqlite3_step(s);
  2051. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  2052. if( rc!=SQLITE_DONE ) return rc;
  2053. return SQLITE_ROW;
  2054. }
  2055. /* Delete the segment blocks and segment directory records for all
  2056. ** segments at iLevel.
  2057. */
  2058. static int segdir_delete(fulltext_vtab *v, int iLevel){
  2059. sqlite3_stmt *s;
  2060. sqlite_int64 iStartBlockid, iEndBlockid;
  2061. int rc = segdir_span(v, iLevel, &iStartBlockid, &iEndBlockid);
  2062. if( rc!=SQLITE_ROW && rc!=SQLITE_DONE ) return rc;
  2063. if( rc==SQLITE_ROW ){
  2064. rc = block_delete(v, iStartBlockid, iEndBlockid);
  2065. if( rc!=SQLITE_OK ) return rc;
  2066. }
  2067. /* Delete the segment directory itself. */
  2068. rc = sql_get_statement(v, SEGDIR_DELETE_STMT, &s);
  2069. if( rc!=SQLITE_OK ) return rc;
  2070. rc = sqlite3_bind_int64(s, 1, iLevel);
  2071. if( rc!=SQLITE_OK ) return rc;
  2072. return sql_single_step(s);
  2073. }
  2074. /* Delete entire fts index, SQLITE_OK on success, relevant error on
  2075. ** failure.
  2076. */
  2077. static int segdir_delete_all(fulltext_vtab *v){
  2078. sqlite3_stmt *s;
  2079. int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s);
  2080. if( rc!=SQLITE_OK ) return rc;
  2081. rc = sql_single_step(s);
  2082. if( rc!=SQLITE_OK ) return rc;
  2083. rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s);
  2084. if( rc!=SQLITE_OK ) return rc;
  2085. return sql_single_step(s);
  2086. }
  2087. /* Returns SQLITE_OK with *pnSegments set to the number of entries in
  2088. ** %_segdir and *piMaxLevel set to the highest level which has a
  2089. ** segment. Otherwise returns the SQLite error which caused failure.
  2090. */
  2091. static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){
  2092. sqlite3_stmt *s;
  2093. int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s);
  2094. if( rc!=SQLITE_OK ) return rc;
  2095. rc = sqlite3_step(s);
  2096. /* TODO(shess): This case should not be possible? Should stronger
  2097. ** measures be taken if it happens?
  2098. */
  2099. if( rc==SQLITE_DONE ){
  2100. *pnSegments = 0;
  2101. *piMaxLevel = 0;
  2102. return SQLITE_OK;
  2103. }
  2104. if( rc!=SQLITE_ROW ) return rc;
  2105. *pnSegments = sqlite3_column_int(s, 0);
  2106. *piMaxLevel = sqlite3_column_int(s, 1);
  2107. /* We expect only one row. We must execute another sqlite3_step()
  2108. * to complete the iteration; otherwise the table will remain locked. */
  2109. rc = sqlite3_step(s);
  2110. if( rc==SQLITE_DONE ) return SQLITE_OK;
  2111. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  2112. return rc;
  2113. }
  2114. /* TODO(shess) clearPendingTerms() is far down the file because
  2115. ** writeZeroSegment() is far down the file because LeafWriter is far
  2116. ** down the file. Consider refactoring the code to move the non-vtab
  2117. ** code above the vtab code so that we don't need this forward
  2118. ** reference.
  2119. */
  2120. static int clearPendingTerms(fulltext_vtab *v);
  2121. /*
  2122. ** Free the memory used to contain a fulltext_vtab structure.
  2123. */
  2124. static void fulltext_vtab_destroy(fulltext_vtab *v){
  2125. int iStmt, i;
  2126. TRACE(("FTS2 Destroy %p\n", v));
  2127. for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){
  2128. if( v->pFulltextStatements[iStmt]!=NULL ){
  2129. sqlite3_finalize(v->pFulltextStatements[iStmt]);
  2130. v->pFulltextStatements[iStmt] = NULL;
  2131. }
  2132. }
  2133. for( i=0; i<MERGE_COUNT; i++ ){
  2134. if( v->pLeafSelectStmts[i]!=NULL ){
  2135. sqlite3_finalize(v->pLeafSelectStmts[i]);
  2136. v->pLeafSelectStmts[i] = NULL;
  2137. }
  2138. }
  2139. if( v->pTokenizer!=NULL ){
  2140. v->pTokenizer->pModule->xDestroy(v->pTokenizer);
  2141. v->pTokenizer = NULL;
  2142. }
  2143. clearPendingTerms(v);
  2144. sqlite3_free(v->azColumn);
  2145. for(i = 0; i < v->nColumn; ++i) {
  2146. sqlite3_free(v->azContentColumn[i]);
  2147. }
  2148. sqlite3_free(v->azContentColumn);
  2149. sqlite3_free(v);
  2150. }
  2151. /*
  2152. ** Token types for parsing the arguments to xConnect or xCreate.
  2153. */
  2154. #define TOKEN_EOF 0 /* End of file */
  2155. #define TOKEN_SPACE 1 /* Any kind of whitespace */
  2156. #define TOKEN_ID 2 /* An identifier */
  2157. #define TOKEN_STRING 3 /* A string literal */
  2158. #define TOKEN_PUNCT 4 /* A single punctuation character */
  2159. /*
  2160. ** If X is a character that can be used in an identifier then
  2161. ** IdChar(X) will be true. Otherwise it is false.
  2162. **
  2163. ** For ASCII, any character with the high-order bit set is
  2164. ** allowed in an identifier. For 7-bit characters,
  2165. ** sqlite3IsIdChar[X] must be 1.
  2166. **
  2167. ** Ticket #1066. the SQL standard does not allow '$' in the
  2168. ** middle of identfiers. But many SQL implementations do.
  2169. ** SQLite will allow '$' in identifiers for compatibility.
  2170. ** But the feature is undocumented.
  2171. */
  2172. static const char isIdChar[] = {
  2173. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  2174. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  2175. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  2176. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  2177. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  2178. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  2179. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  2180. };
  2181. #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20]))
  2182. /*
  2183. ** Return the length of the token that begins at z[0].
  2184. ** Store the token type in *tokenType before returning.
  2185. */
  2186. static int getToken(const char *z, int *tokenType){
  2187. int i, c;
  2188. switch( *z ){
  2189. case 0: {
  2190. *tokenType = TOKEN_EOF;
  2191. return 0;
  2192. }
  2193. case ' ': case '\t': case '\n': case '\f': case '\r': {
  2194. for(i=1; safe_isspace(z[i]); i++){}
  2195. *tokenType = TOKEN_SPACE;
  2196. return i;
  2197. }
  2198. case '`':
  2199. case '\'':
  2200. case '"': {
  2201. int delim = z[0];
  2202. for(i=1; (c=z[i])!=0; i++){
  2203. if( c==delim ){
  2204. if( z[i+1]==delim ){
  2205. i++;
  2206. }else{
  2207. break;
  2208. }
  2209. }
  2210. }
  2211. *tokenType = TOKEN_STRING;
  2212. return i + (c!=0);
  2213. }
  2214. case '[': {
  2215. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  2216. *tokenType = TOKEN_ID;
  2217. return i;
  2218. }
  2219. default: {
  2220. if( !IdChar(*z) ){
  2221. break;
  2222. }
  2223. for(i=1; IdChar(z[i]); i++){}
  2224. *tokenType = TOKEN_ID;
  2225. return i;
  2226. }
  2227. }
  2228. *tokenType = TOKEN_PUNCT;
  2229. return 1;
  2230. }
  2231. /*
  2232. ** A token extracted from a string is an instance of the following
  2233. ** structure.
  2234. */
  2235. typedef struct Token {
  2236. const char *z; /* Pointer to token text. Not '\000' terminated */
  2237. short int n; /* Length of the token text in bytes. */
  2238. } Token;
  2239. /*
  2240. ** Given a input string (which is really one of the argv[] parameters
  2241. ** passed into xConnect or xCreate) split the string up into tokens.
  2242. ** Return an array of pointers to '\000' terminated strings, one string
  2243. ** for each non-whitespace token.
  2244. **
  2245. ** The returned array is terminated by a single NULL pointer.
  2246. **
  2247. ** Space to hold the returned array is obtained from a single
  2248. ** malloc and should be freed by passing the return value to free().
  2249. ** The individual strings within the token list are all a part of
  2250. ** the single memory allocation and will all be freed at once.
  2251. */
  2252. static char **tokenizeString(const char *z, int *pnToken){
  2253. int nToken = 0;
  2254. Token *aToken = sqlite3_malloc( strlen(z) * sizeof(aToken[0]) );
  2255. int n = 1;
  2256. int e, i;
  2257. int totalSize = 0;
  2258. char **azToken;
  2259. char *zCopy;
  2260. while( n>0 ){
  2261. n = getToken(z, &e);
  2262. if( e!=TOKEN_SPACE ){
  2263. aToken[nToken].z = z;
  2264. aToken[nToken].n = n;
  2265. nToken++;
  2266. totalSize += n+1;
  2267. }
  2268. z += n;
  2269. }
  2270. azToken = (char**)sqlite3_malloc( nToken*sizeof(char*) + totalSize );
  2271. zCopy = (char*)&azToken[nToken];
  2272. nToken--;
  2273. for(i=0; i<nToken; i++){
  2274. azToken[i] = zCopy;
  2275. n = aToken[i].n;
  2276. memcpy(zCopy, aToken[i].z, n);
  2277. zCopy[n] = 0;
  2278. zCopy += n+1;
  2279. }
  2280. azToken[nToken] = 0;
  2281. sqlite3_free(aToken);
  2282. *pnToken = nToken;
  2283. return azToken;
  2284. }
  2285. /*
  2286. ** Convert an SQL-style quoted string into a normal string by removing
  2287. ** the quote characters. The conversion is done in-place. If the
  2288. ** input does not begin with a quote character, then this routine
  2289. ** is a no-op.
  2290. **
  2291. ** Examples:
  2292. **
  2293. ** "abc" becomes abc
  2294. ** 'xyz' becomes xyz
  2295. ** [pqr] becomes pqr
  2296. ** `mno` becomes mno
  2297. */
  2298. static void dequoteString(char *z){
  2299. int quote;
  2300. int i, j;
  2301. if( z==0 ) return;
  2302. quote = z[0];
  2303. switch( quote ){
  2304. case '\'': break;
  2305. case '"': break;
  2306. case '`': break; /* For MySQL compatibility */
  2307. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  2308. default: return;
  2309. }
  2310. for(i=1, j=0; z[i]; i++){
  2311. if( z[i]==quote ){
  2312. if( z[i+1]==quote ){
  2313. z[j++] = quote;
  2314. i++;
  2315. }else{
  2316. z[j++] = 0;
  2317. break;
  2318. }
  2319. }else{
  2320. z[j++] = z[i];
  2321. }
  2322. }
  2323. }
  2324. /*
  2325. ** The input azIn is a NULL-terminated list of tokens. Remove the first
  2326. ** token and all punctuation tokens. Remove the quotes from
  2327. ** around string literal tokens.
  2328. **
  2329. ** Example:
  2330. **
  2331. ** input: tokenize chinese ( 'simplifed' , 'mixed' )
  2332. ** output: chinese simplifed mixed
  2333. **
  2334. ** Another example:
  2335. **
  2336. ** input: delimiters ( '[' , ']' , '...' )
  2337. ** output: [ ] ...
  2338. */
  2339. static void tokenListToIdList(char **azIn){
  2340. int i, j;
  2341. if( azIn ){
  2342. for(i=0, j=-1; azIn[i]; i++){
  2343. if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){
  2344. dequoteString(azIn[i]);
  2345. if( j>=0 ){
  2346. azIn[j] = azIn[i];
  2347. }
  2348. j++;
  2349. }
  2350. }
  2351. azIn[j] = 0;
  2352. }
  2353. }
  2354. /*
  2355. ** Find the first alphanumeric token in the string zIn. Null-terminate
  2356. ** this token. Remove any quotation marks. And return a pointer to
  2357. ** the result.
  2358. */
  2359. static char *firstToken(char *zIn, char **pzTail){
  2360. int n, ttype;
  2361. while(1){
  2362. n = getToken(zIn, &ttype);
  2363. if( ttype==TOKEN_SPACE ){
  2364. zIn += n;
  2365. }else if( ttype==TOKEN_EOF ){
  2366. *pzTail = zIn;
  2367. return 0;
  2368. }else{
  2369. zIn[n] = 0;
  2370. *pzTail = &zIn[1];
  2371. dequoteString(zIn);
  2372. return zIn;
  2373. }
  2374. }
  2375. /*NOTREACHED*/
  2376. }
  2377. /* Return true if...
  2378. **
  2379. ** * s begins with the string t, ignoring case
  2380. ** * s is longer than t
  2381. ** * The first character of s beyond t is not a alphanumeric
  2382. **
  2383. ** Ignore leading space in *s.
  2384. **
  2385. ** To put it another way, return true if the first token of
  2386. ** s[] is t[].
  2387. */
  2388. static int startsWith(const char *s, const char *t){
  2389. while( safe_isspace(*s) ){ s++; }
  2390. while( *t ){
  2391. if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0;
  2392. }
  2393. return *s!='_' && !safe_isalnum(*s);
  2394. }
  2395. /*
  2396. ** An instance of this structure defines the "spec" of a
  2397. ** full text index. This structure is populated by parseSpec
  2398. ** and use by fulltextConnect and fulltextCreate.
  2399. */
  2400. typedef struct TableSpec {
  2401. const char *zDb; /* Logical database name */
  2402. const char *zName; /* Name of the full-text index */
  2403. int nColumn; /* Number of columns to be indexed */
  2404. char **azColumn; /* Original names of columns to be indexed */
  2405. char **azContentColumn; /* Column names for %_content */
  2406. char **azTokenizer; /* Name of tokenizer and its arguments */
  2407. } TableSpec;
  2408. /*
  2409. ** Reclaim all of the memory used by a TableSpec
  2410. */
  2411. static void clearTableSpec(TableSpec *p) {
  2412. sqlite3_free(p->azColumn);
  2413. sqlite3_free(p->azContentColumn);
  2414. sqlite3_free(p->azTokenizer);
  2415. }
  2416. /* Parse a CREATE VIRTUAL TABLE statement, which looks like this:
  2417. *
  2418. * CREATE VIRTUAL TABLE email
  2419. * USING fts2(subject, body, tokenize mytokenizer(myarg))
  2420. *
  2421. * We return parsed information in a TableSpec structure.
  2422. *
  2423. */
  2424. static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv,
  2425. char**pzErr){
  2426. int i, n;
  2427. char *z, *zDummy;
  2428. char **azArg;
  2429. const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */
  2430. assert( argc>=3 );
  2431. /* Current interface:
  2432. ** argv[0] - module name
  2433. ** argv[1] - database name
  2434. ** argv[2] - table name
  2435. ** argv[3..] - columns, optionally followed by tokenizer specification
  2436. ** and snippet delimiters specification.
  2437. */
  2438. /* Make a copy of the complete argv[][] array in a single allocation.
  2439. ** The argv[][] array is read-only and transient. We can write to the
  2440. ** copy in order to modify things and the copy is persistent.
  2441. */
  2442. CLEAR(pSpec);
  2443. for(i=n=0; i<argc; i++){
  2444. n += strlen(argv[i]) + 1;
  2445. }
  2446. azArg = sqlite3_malloc( sizeof(char*)*argc + n );
  2447. if( azArg==0 ){
  2448. return SQLITE_NOMEM;
  2449. }
  2450. z = (char*)&azArg[argc];
  2451. for(i=0; i<argc; i++){
  2452. azArg[i] = z;
  2453. strcpy(z, argv[i]);
  2454. z += strlen(z)+1;
  2455. }
  2456. /* Identify the column names and the tokenizer and delimiter arguments
  2457. ** in the argv[][] array.
  2458. */
  2459. pSpec->zDb = azArg[1];
  2460. pSpec->zName = azArg[2];
  2461. pSpec->nColumn = 0;
  2462. pSpec->azColumn = azArg;
  2463. zTokenizer = "tokenize simple";
  2464. for(i=3; i<argc; ++i){
  2465. if( startsWith(azArg[i],"tokenize") ){
  2466. zTokenizer = azArg[i];
  2467. }else{
  2468. z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy);
  2469. pSpec->nColumn++;
  2470. }
  2471. }
  2472. if( pSpec->nColumn==0 ){
  2473. azArg[0] = "content";
  2474. pSpec->nColumn = 1;
  2475. }
  2476. /*
  2477. ** Construct the list of content column names.
  2478. **
  2479. ** Each content column name will be of the form cNNAAAA
  2480. ** where NN is the column number and AAAA is the sanitized
  2481. ** column name. "sanitized" means that special characters are
  2482. ** converted to "_". The cNN prefix guarantees that all column
  2483. ** names are unique.
  2484. **
  2485. ** The AAAA suffix is not strictly necessary. It is included
  2486. ** for the convenience of people who might examine the generated
  2487. ** %_content table and wonder what the columns are used for.
  2488. */
  2489. pSpec->azContentColumn = sqlite3_malloc( pSpec->nColumn * sizeof(char *) );
  2490. if( pSpec->azContentColumn==0 ){
  2491. clearTableSpec(pSpec);
  2492. return SQLITE_NOMEM;
  2493. }
  2494. for(i=0; i<pSpec->nColumn; i++){
  2495. char *p;
  2496. pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]);
  2497. for (p = pSpec->azContentColumn[i]; *p ; ++p) {
  2498. if( !safe_isalnum(*p) ) *p = '_';
  2499. }
  2500. }
  2501. /*
  2502. ** Parse the tokenizer specification string.
  2503. */
  2504. pSpec->azTokenizer = tokenizeString(zTokenizer, &n);
  2505. tokenListToIdList(pSpec->azTokenizer);
  2506. return SQLITE_OK;
  2507. }
  2508. /*
  2509. ** Generate a CREATE TABLE statement that describes the schema of
  2510. ** the virtual table. Return a pointer to this schema string.
  2511. **
  2512. ** Space is obtained from sqlite3_mprintf() and should be freed
  2513. ** using sqlite3_free().
  2514. */
  2515. static char *fulltextSchema(
  2516. int nColumn, /* Number of columns */
  2517. const char *const* azColumn, /* List of columns */
  2518. const char *zTableName /* Name of the table */
  2519. ){
  2520. int i;
  2521. char *zSchema, *zNext;
  2522. const char *zSep = "(";
  2523. zSchema = sqlite3_mprintf("CREATE TABLE x");
  2524. for(i=0; i<nColumn; i++){
  2525. zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]);
  2526. sqlite3_free(zSchema);
  2527. zSchema = zNext;
  2528. zSep = ",";
  2529. }
  2530. zNext = sqlite3_mprintf("%s,%Q)", zSchema, zTableName);
  2531. sqlite3_free(zSchema);
  2532. return zNext;
  2533. }
  2534. /*
  2535. ** Build a new sqlite3_vtab structure that will describe the
  2536. ** fulltext index defined by spec.
  2537. */
  2538. static int constructVtab(
  2539. sqlite3 *db, /* The SQLite database connection */
  2540. fts2Hash *pHash, /* Hash table containing tokenizers */
  2541. TableSpec *spec, /* Parsed spec information from parseSpec() */
  2542. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  2543. char **pzErr /* Write any error message here */
  2544. ){
  2545. int rc;
  2546. int n;
  2547. fulltext_vtab *v = 0;
  2548. const sqlite3_tokenizer_module *m = NULL;
  2549. char *schema;
  2550. char const *zTok; /* Name of tokenizer to use for this fts table */
  2551. int nTok; /* Length of zTok, including nul terminator */
  2552. v = (fulltext_vtab *) sqlite3_malloc(sizeof(fulltext_vtab));
  2553. if( v==0 ) return SQLITE_NOMEM;
  2554. CLEAR(v);
  2555. /* sqlite will initialize v->base */
  2556. v->db = db;
  2557. v->zDb = spec->zDb; /* Freed when azColumn is freed */
  2558. v->zName = spec->zName; /* Freed when azColumn is freed */
  2559. v->nColumn = spec->nColumn;
  2560. v->azContentColumn = spec->azContentColumn;
  2561. spec->azContentColumn = 0;
  2562. v->azColumn = spec->azColumn;
  2563. spec->azColumn = 0;
  2564. if( spec->azTokenizer==0 ){
  2565. return SQLITE_NOMEM;
  2566. }
  2567. zTok = spec->azTokenizer[0];
  2568. if( !zTok ){
  2569. zTok = "simple";
  2570. }
  2571. nTok = strlen(zTok)+1;
  2572. m = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zTok, nTok);
  2573. if( !m ){
  2574. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
  2575. rc = SQLITE_ERROR;
  2576. goto err;
  2577. }
  2578. for(n=0; spec->azTokenizer[n]; n++){}
  2579. if( n ){
  2580. rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
  2581. &v->pTokenizer);
  2582. }else{
  2583. rc = m->xCreate(0, 0, &v->pTokenizer);
  2584. }
  2585. if( rc!=SQLITE_OK ) goto err;
  2586. v->pTokenizer->pModule = m;
  2587. /* TODO: verify the existence of backing tables foo_content, foo_term */
  2588. schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn,
  2589. spec->zName);
  2590. rc = sqlite3_declare_vtab(db, schema);
  2591. sqlite3_free(schema);
  2592. if( rc!=SQLITE_OK ) goto err;
  2593. memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements));
  2594. /* Indicate that the buffer is not live. */
  2595. v->nPendingData = -1;
  2596. *ppVTab = &v->base;
  2597. TRACE(("FTS2 Connect %p\n", v));
  2598. return rc;
  2599. err:
  2600. fulltext_vtab_destroy(v);
  2601. return rc;
  2602. }
  2603. static int fulltextConnect(
  2604. sqlite3 *db,
  2605. void *pAux,
  2606. int argc, const char *const*argv,
  2607. sqlite3_vtab **ppVTab,
  2608. char **pzErr
  2609. ){
  2610. TableSpec spec;
  2611. int rc = parseSpec(&spec, argc, argv, pzErr);
  2612. if( rc!=SQLITE_OK ) return rc;
  2613. rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
  2614. clearTableSpec(&spec);
  2615. return rc;
  2616. }
  2617. /* The %_content table holds the text of each document, with
  2618. ** the rowid used as the docid.
  2619. */
  2620. /* TODO(shess) This comment needs elaboration to match the updated
  2621. ** code. Work it into the top-of-file comment at that time.
  2622. */
  2623. static int fulltextCreate(sqlite3 *db, void *pAux,
  2624. int argc, const char * const *argv,
  2625. sqlite3_vtab **ppVTab, char **pzErr){
  2626. int rc;
  2627. TableSpec spec;
  2628. StringBuffer schema;
  2629. TRACE(("FTS2 Create\n"));
  2630. rc = parseSpec(&spec, argc, argv, pzErr);
  2631. if( rc!=SQLITE_OK ) return rc;
  2632. initStringBuffer(&schema);
  2633. append(&schema, "CREATE TABLE %_content(");
  2634. appendList(&schema, spec.nColumn, spec.azContentColumn);
  2635. append(&schema, ")");
  2636. rc = sql_exec(db, spec.zDb, spec.zName, stringBufferData(&schema));
  2637. stringBufferDestroy(&schema);
  2638. if( rc!=SQLITE_OK ) goto out;
  2639. rc = sql_exec(db, spec.zDb, spec.zName,
  2640. "create table %_segments(block blob);");
  2641. if( rc!=SQLITE_OK ) goto out;
  2642. rc = sql_exec(db, spec.zDb, spec.zName,
  2643. "create table %_segdir("
  2644. " level integer,"
  2645. " idx integer,"
  2646. " start_block integer,"
  2647. " leaves_end_block integer,"
  2648. " end_block integer,"
  2649. " root blob,"
  2650. " primary key(level, idx)"
  2651. ");");
  2652. if( rc!=SQLITE_OK ) goto out;
  2653. rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
  2654. out:
  2655. clearTableSpec(&spec);
  2656. return rc;
  2657. }
  2658. /* Decide how to handle an SQL query. */
  2659. static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  2660. int i;
  2661. TRACE(("FTS2 BestIndex\n"));
  2662. for(i=0; i<pInfo->nConstraint; ++i){
  2663. const struct sqlite3_index_constraint *pConstraint;
  2664. pConstraint = &pInfo->aConstraint[i];
  2665. if( pConstraint->usable ) {
  2666. if( pConstraint->iColumn==-1 &&
  2667. pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  2668. pInfo->idxNum = QUERY_ROWID; /* lookup by rowid */
  2669. TRACE(("FTS2 QUERY_ROWID\n"));
  2670. } else if( pConstraint->iColumn>=0 &&
  2671. pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  2672. /* full-text search */
  2673. pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn;
  2674. TRACE(("FTS2 QUERY_FULLTEXT %d\n", pConstraint->iColumn));
  2675. } else continue;
  2676. pInfo->aConstraintUsage[i].argvIndex = 1;
  2677. pInfo->aConstraintUsage[i].omit = 1;
  2678. /* An arbitrary value for now.
  2679. * TODO: Perhaps rowid matches should be considered cheaper than
  2680. * full-text searches. */
  2681. pInfo->estimatedCost = 1.0;
  2682. return SQLITE_OK;
  2683. }
  2684. }
  2685. pInfo->idxNum = QUERY_GENERIC;
  2686. return SQLITE_OK;
  2687. }
  2688. static int fulltextDisconnect(sqlite3_vtab *pVTab){
  2689. TRACE(("FTS2 Disconnect %p\n", pVTab));
  2690. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  2691. return SQLITE_OK;
  2692. }
  2693. static int fulltextDestroy(sqlite3_vtab *pVTab){
  2694. fulltext_vtab *v = (fulltext_vtab *)pVTab;
  2695. int rc;
  2696. TRACE(("FTS2 Destroy %p\n", pVTab));
  2697. rc = sql_exec(v->db, v->zDb, v->zName,
  2698. "drop table if exists %_content;"
  2699. "drop table if exists %_segments;"
  2700. "drop table if exists %_segdir;"
  2701. );
  2702. if( rc!=SQLITE_OK ) return rc;
  2703. fulltext_vtab_destroy((fulltext_vtab *)pVTab);
  2704. return SQLITE_OK;
  2705. }
  2706. static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  2707. fulltext_cursor *c;
  2708. c = (fulltext_cursor *) sqlite3_malloc(sizeof(fulltext_cursor));
  2709. if( c ){
  2710. memset(c, 0, sizeof(fulltext_cursor));
  2711. /* sqlite will initialize c->base */
  2712. *ppCursor = &c->base;
  2713. TRACE(("FTS2 Open %p: %p\n", pVTab, c));
  2714. return SQLITE_OK;
  2715. }else{
  2716. return SQLITE_NOMEM;
  2717. }
  2718. }
  2719. /* Free all of the dynamically allocated memory held by *q
  2720. */
  2721. static void queryClear(Query *q){
  2722. int i;
  2723. for(i = 0; i < q->nTerms; ++i){
  2724. sqlite3_free(q->pTerms[i].pTerm);
  2725. }
  2726. sqlite3_free(q->pTerms);
  2727. CLEAR(q);
  2728. }
  2729. /* Free all of the dynamically allocated memory held by the
  2730. ** Snippet
  2731. */
  2732. static void snippetClear(Snippet *p){
  2733. sqlite3_free(p->aMatch);
  2734. sqlite3_free(p->zOffset);
  2735. sqlite3_free(p->zSnippet);
  2736. CLEAR(p);
  2737. }
  2738. /*
  2739. ** Append a single entry to the p->aMatch[] log.
  2740. */
  2741. static void snippetAppendMatch(
  2742. Snippet *p, /* Append the entry to this snippet */
  2743. int iCol, int iTerm, /* The column and query term */
  2744. int iStart, int nByte /* Offset and size of the match */
  2745. ){
  2746. int i;
  2747. struct snippetMatch *pMatch;
  2748. if( p->nMatch+1>=p->nAlloc ){
  2749. p->nAlloc = p->nAlloc*2 + 10;
  2750. p->aMatch = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
  2751. if( p->aMatch==0 ){
  2752. p->nMatch = 0;
  2753. p->nAlloc = 0;
  2754. return;
  2755. }
  2756. }
  2757. i = p->nMatch++;
  2758. pMatch = &p->aMatch[i];
  2759. pMatch->iCol = iCol;
  2760. pMatch->iTerm = iTerm;
  2761. pMatch->iStart = iStart;
  2762. pMatch->nByte = nByte;
  2763. }
  2764. /*
  2765. ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
  2766. */
  2767. #define FTS2_ROTOR_SZ (32)
  2768. #define FTS2_ROTOR_MASK (FTS2_ROTOR_SZ-1)
  2769. /*
  2770. ** Add entries to pSnippet->aMatch[] for every match that occurs against
  2771. ** document zDoc[0..nDoc-1] which is stored in column iColumn.
  2772. */
  2773. static void snippetOffsetsOfColumn(
  2774. Query *pQuery,
  2775. Snippet *pSnippet,
  2776. int iColumn,
  2777. const char *zDoc,
  2778. int nDoc
  2779. ){
  2780. const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */
  2781. sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */
  2782. sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */
  2783. fulltext_vtab *pVtab; /* The full text index */
  2784. int nColumn; /* Number of columns in the index */
  2785. const QueryTerm *aTerm; /* Query string terms */
  2786. int nTerm; /* Number of query string terms */
  2787. int i, j; /* Loop counters */
  2788. int rc; /* Return code */
  2789. unsigned int match, prevMatch; /* Phrase search bitmasks */
  2790. const char *zToken; /* Next token from the tokenizer */
  2791. int nToken; /* Size of zToken */
  2792. int iBegin, iEnd, iPos; /* Offsets of beginning and end */
  2793. /* The following variables keep a circular buffer of the last
  2794. ** few tokens */
  2795. unsigned int iRotor = 0; /* Index of current token */
  2796. int iRotorBegin[FTS2_ROTOR_SZ]; /* Beginning offset of token */
  2797. int iRotorLen[FTS2_ROTOR_SZ]; /* Length of token */
  2798. pVtab = pQuery->pFts;
  2799. nColumn = pVtab->nColumn;
  2800. pTokenizer = pVtab->pTokenizer;
  2801. pTModule = pTokenizer->pModule;
  2802. rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
  2803. if( rc ) return;
  2804. pTCursor->pTokenizer = pTokenizer;
  2805. aTerm = pQuery->pTerms;
  2806. nTerm = pQuery->nTerms;
  2807. if( nTerm>=FTS2_ROTOR_SZ ){
  2808. nTerm = FTS2_ROTOR_SZ - 1;
  2809. }
  2810. prevMatch = 0;
  2811. while(1){
  2812. rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
  2813. if( rc ) break;
  2814. iRotorBegin[iRotor&FTS2_ROTOR_MASK] = iBegin;
  2815. iRotorLen[iRotor&FTS2_ROTOR_MASK] = iEnd-iBegin;
  2816. match = 0;
  2817. for(i=0; i<nTerm; i++){
  2818. int iCol;
  2819. iCol = aTerm[i].iColumn;
  2820. if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
  2821. if( aTerm[i].nTerm>nToken ) continue;
  2822. if( !aTerm[i].isPrefix && aTerm[i].nTerm<nToken ) continue;
  2823. assert( aTerm[i].nTerm<=nToken );
  2824. if( memcmp(aTerm[i].pTerm, zToken, aTerm[i].nTerm) ) continue;
  2825. if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue;
  2826. match |= 1<<i;
  2827. if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){
  2828. for(j=aTerm[i].iPhrase-1; j>=0; j--){
  2829. int k = (iRotor-j) & FTS2_ROTOR_MASK;
  2830. snippetAppendMatch(pSnippet, iColumn, i-j,
  2831. iRotorBegin[k], iRotorLen[k]);
  2832. }
  2833. }
  2834. }
  2835. prevMatch = match<<1;
  2836. iRotor++;
  2837. }
  2838. pTModule->xClose(pTCursor);
  2839. }
  2840. /*
  2841. ** Compute all offsets for the current row of the query.
  2842. ** If the offsets have already been computed, this routine is a no-op.
  2843. */
  2844. static void snippetAllOffsets(fulltext_cursor *p){
  2845. int nColumn;
  2846. int iColumn, i;
  2847. int iFirst, iLast;
  2848. fulltext_vtab *pFts;
  2849. if( p->snippet.nMatch ) return;
  2850. if( p->q.nTerms==0 ) return;
  2851. pFts = p->q.pFts;
  2852. nColumn = pFts->nColumn;
  2853. iColumn = (p->iCursorType - QUERY_FULLTEXT);
  2854. if( iColumn<0 || iColumn>=nColumn ){
  2855. iFirst = 0;
  2856. iLast = nColumn-1;
  2857. }else{
  2858. iFirst = iColumn;
  2859. iLast = iColumn;
  2860. }
  2861. for(i=iFirst; i<=iLast; i++){
  2862. const char *zDoc;
  2863. int nDoc;
  2864. zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1);
  2865. nDoc = sqlite3_column_bytes(p->pStmt, i+1);
  2866. snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc);
  2867. }
  2868. }
  2869. /*
  2870. ** Convert the information in the aMatch[] array of the snippet
  2871. ** into the string zOffset[0..nOffset-1].
  2872. */
  2873. static void snippetOffsetText(Snippet *p){
  2874. int i;
  2875. int cnt = 0;
  2876. StringBuffer sb;
  2877. char zBuf[200];
  2878. if( p->zOffset ) return;
  2879. initStringBuffer(&sb);
  2880. for(i=0; i<p->nMatch; i++){
  2881. struct snippetMatch *pMatch = &p->aMatch[i];
  2882. zBuf[0] = ' ';
  2883. sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
  2884. pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
  2885. append(&sb, zBuf);
  2886. cnt++;
  2887. }
  2888. p->zOffset = stringBufferData(&sb);
  2889. p->nOffset = stringBufferLength(&sb);
  2890. }
  2891. /*
  2892. ** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set
  2893. ** of matching words some of which might be in zDoc. zDoc is column
  2894. ** number iCol.
  2895. **
  2896. ** iBreak is suggested spot in zDoc where we could begin or end an
  2897. ** excerpt. Return a value similar to iBreak but possibly adjusted
  2898. ** to be a little left or right so that the break point is better.
  2899. */
  2900. static int wordBoundary(
  2901. int iBreak, /* The suggested break point */
  2902. const char *zDoc, /* Document text */
  2903. int nDoc, /* Number of bytes in zDoc[] */
  2904. struct snippetMatch *aMatch, /* Matching words */
  2905. int nMatch, /* Number of entries in aMatch[] */
  2906. int iCol /* The column number for zDoc[] */
  2907. ){
  2908. int i;
  2909. if( iBreak<=10 ){
  2910. return 0;
  2911. }
  2912. if( iBreak>=nDoc-10 ){
  2913. return nDoc;
  2914. }
  2915. for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){}
  2916. while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
  2917. if( i<nMatch ){
  2918. if( aMatch[i].iStart<iBreak+10 ){
  2919. return aMatch[i].iStart;
  2920. }
  2921. if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
  2922. return aMatch[i-1].iStart;
  2923. }
  2924. }
  2925. for(i=1; i<=10; i++){
  2926. if( safe_isspace(zDoc[iBreak-i]) ){
  2927. return iBreak - i + 1;
  2928. }
  2929. if( safe_isspace(zDoc[iBreak+i]) ){
  2930. return iBreak + i + 1;
  2931. }
  2932. }
  2933. return iBreak;
  2934. }
  2935. /*
  2936. ** Allowed values for Snippet.aMatch[].snStatus
  2937. */
  2938. #define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */
  2939. #define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */
  2940. /*
  2941. ** Generate the text of a snippet.
  2942. */
  2943. static void snippetText(
  2944. fulltext_cursor *pCursor, /* The cursor we need the snippet for */
  2945. const char *zStartMark, /* Markup to appear before each match */
  2946. const char *zEndMark, /* Markup to appear after each match */
  2947. const char *zEllipsis /* Ellipsis mark */
  2948. ){
  2949. int i, j;
  2950. struct snippetMatch *aMatch;
  2951. int nMatch;
  2952. int nDesired;
  2953. StringBuffer sb;
  2954. int tailCol;
  2955. int tailOffset;
  2956. int iCol;
  2957. int nDoc;
  2958. const char *zDoc;
  2959. int iStart, iEnd;
  2960. int tailEllipsis = 0;
  2961. int iMatch;
  2962. sqlite3_free(pCursor->snippet.zSnippet);
  2963. pCursor->snippet.zSnippet = 0;
  2964. aMatch = pCursor->snippet.aMatch;
  2965. nMatch = pCursor->snippet.nMatch;
  2966. initStringBuffer(&sb);
  2967. for(i=0; i<nMatch; i++){
  2968. aMatch[i].snStatus = SNIPPET_IGNORE;
  2969. }
  2970. nDesired = 0;
  2971. for(i=0; i<pCursor->q.nTerms; i++){
  2972. for(j=0; j<nMatch; j++){
  2973. if( aMatch[j].iTerm==i ){
  2974. aMatch[j].snStatus = SNIPPET_DESIRED;
  2975. nDesired++;
  2976. break;
  2977. }
  2978. }
  2979. }
  2980. iMatch = 0;
  2981. tailCol = -1;
  2982. tailOffset = 0;
  2983. for(i=0; i<nMatch && nDesired>0; i++){
  2984. if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
  2985. nDesired--;
  2986. iCol = aMatch[i].iCol;
  2987. zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
  2988. nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
  2989. iStart = aMatch[i].iStart - 40;
  2990. iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
  2991. if( iStart<=10 ){
  2992. iStart = 0;
  2993. }
  2994. if( iCol==tailCol && iStart<=tailOffset+20 ){
  2995. iStart = tailOffset;
  2996. }
  2997. if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
  2998. trimWhiteSpace(&sb);
  2999. appendWhiteSpace(&sb);
  3000. append(&sb, zEllipsis);
  3001. appendWhiteSpace(&sb);
  3002. }
  3003. iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
  3004. iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
  3005. if( iEnd>=nDoc-10 ){
  3006. iEnd = nDoc;
  3007. tailEllipsis = 0;
  3008. }else{
  3009. tailEllipsis = 1;
  3010. }
  3011. while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
  3012. while( iStart<iEnd ){
  3013. while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
  3014. && aMatch[iMatch].iCol<=iCol ){
  3015. iMatch++;
  3016. }
  3017. if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
  3018. && aMatch[iMatch].iCol==iCol ){
  3019. nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
  3020. iStart = aMatch[iMatch].iStart;
  3021. append(&sb, zStartMark);
  3022. nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
  3023. append(&sb, zEndMark);
  3024. iStart += aMatch[iMatch].nByte;
  3025. for(j=iMatch+1; j<nMatch; j++){
  3026. if( aMatch[j].iTerm==aMatch[iMatch].iTerm
  3027. && aMatch[j].snStatus==SNIPPET_DESIRED ){
  3028. nDesired--;
  3029. aMatch[j].snStatus = SNIPPET_IGNORE;
  3030. }
  3031. }
  3032. }else{
  3033. nappend(&sb, &zDoc[iStart], iEnd - iStart);
  3034. iStart = iEnd;
  3035. }
  3036. }
  3037. tailCol = iCol;
  3038. tailOffset = iEnd;
  3039. }
  3040. trimWhiteSpace(&sb);
  3041. if( tailEllipsis ){
  3042. appendWhiteSpace(&sb);
  3043. append(&sb, zEllipsis);
  3044. }
  3045. pCursor->snippet.zSnippet = stringBufferData(&sb);
  3046. pCursor->snippet.nSnippet = stringBufferLength(&sb);
  3047. }
  3048. /*
  3049. ** Close the cursor. For additional information see the documentation
  3050. ** on the xClose method of the virtual table interface.
  3051. */
  3052. static int fulltextClose(sqlite3_vtab_cursor *pCursor){
  3053. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3054. TRACE(("FTS2 Close %p\n", c));
  3055. sqlite3_finalize(c->pStmt);
  3056. queryClear(&c->q);
  3057. snippetClear(&c->snippet);
  3058. if( c->result.nData!=0 ) dlrDestroy(&c->reader);
  3059. dataBufferDestroy(&c->result);
  3060. sqlite3_free(c);
  3061. return SQLITE_OK;
  3062. }
  3063. static int fulltextNext(sqlite3_vtab_cursor *pCursor){
  3064. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3065. int rc;
  3066. TRACE(("FTS2 Next %p\n", pCursor));
  3067. snippetClear(&c->snippet);
  3068. if( c->iCursorType < QUERY_FULLTEXT ){
  3069. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  3070. rc = sqlite3_step(c->pStmt);
  3071. switch( rc ){
  3072. case SQLITE_ROW:
  3073. c->eof = 0;
  3074. return SQLITE_OK;
  3075. case SQLITE_DONE:
  3076. c->eof = 1;
  3077. return SQLITE_OK;
  3078. default:
  3079. c->eof = 1;
  3080. return rc;
  3081. }
  3082. } else { /* full-text query */
  3083. rc = sqlite3_reset(c->pStmt);
  3084. if( rc!=SQLITE_OK ) return rc;
  3085. if( c->result.nData==0 || dlrAtEnd(&c->reader) ){
  3086. c->eof = 1;
  3087. return SQLITE_OK;
  3088. }
  3089. rc = sqlite3_bind_int64(c->pStmt, 1, dlrDocid(&c->reader));
  3090. dlrStep(&c->reader);
  3091. if( rc!=SQLITE_OK ) return rc;
  3092. /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */
  3093. rc = sqlite3_step(c->pStmt);
  3094. if( rc==SQLITE_ROW ){ /* the case we expect */
  3095. c->eof = 0;
  3096. return SQLITE_OK;
  3097. }
  3098. /* an error occurred; abort */
  3099. return rc==SQLITE_DONE ? SQLITE_ERROR : rc;
  3100. }
  3101. }
  3102. /* TODO(shess) If we pushed LeafReader to the top of the file, or to
  3103. ** another file, term_select() could be pushed above
  3104. ** docListOfTerm().
  3105. */
  3106. static int termSelect(fulltext_vtab *v, int iColumn,
  3107. const char *pTerm, int nTerm, int isPrefix,
  3108. DocListType iType, DataBuffer *out);
  3109. /* Return a DocList corresponding to the query term *pTerm. If *pTerm
  3110. ** is the first term of a phrase query, go ahead and evaluate the phrase
  3111. ** query and return the doclist for the entire phrase query.
  3112. **
  3113. ** The resulting DL_DOCIDS doclist is stored in pResult, which is
  3114. ** overwritten.
  3115. */
  3116. static int docListOfTerm(
  3117. fulltext_vtab *v, /* The full text index */
  3118. int iColumn, /* column to restrict to. No restriction if >=nColumn */
  3119. QueryTerm *pQTerm, /* Term we are looking for, or 1st term of a phrase */
  3120. DataBuffer *pResult /* Write the result here */
  3121. ){
  3122. DataBuffer left, right, new;
  3123. int i, rc;
  3124. /* No phrase search if no position info. */
  3125. assert( pQTerm->nPhrase==0 || DL_DEFAULT!=DL_DOCIDS );
  3126. /* This code should never be called with buffered updates. */
  3127. assert( v->nPendingData<0 );
  3128. dataBufferInit(&left, 0);
  3129. rc = termSelect(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pQTerm->isPrefix,
  3130. 0<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &left);
  3131. if( rc ) return rc;
  3132. for(i=1; i<=pQTerm->nPhrase && left.nData>0; i++){
  3133. dataBufferInit(&right, 0);
  3134. rc = termSelect(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm,
  3135. pQTerm[i].isPrefix, DL_POSITIONS, &right);
  3136. if( rc ){
  3137. dataBufferDestroy(&left);
  3138. return rc;
  3139. }
  3140. dataBufferInit(&new, 0);
  3141. docListPhraseMerge(left.pData, left.nData, right.pData, right.nData,
  3142. i<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS, &new);
  3143. dataBufferDestroy(&left);
  3144. dataBufferDestroy(&right);
  3145. left = new;
  3146. }
  3147. *pResult = left;
  3148. return SQLITE_OK;
  3149. }
  3150. /* Add a new term pTerm[0..nTerm-1] to the query *q.
  3151. */
  3152. static void queryAdd(Query *q, const char *pTerm, int nTerm){
  3153. QueryTerm *t;
  3154. ++q->nTerms;
  3155. q->pTerms = sqlite3_realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0]));
  3156. if( q->pTerms==0 ){
  3157. q->nTerms = 0;
  3158. return;
  3159. }
  3160. t = &q->pTerms[q->nTerms - 1];
  3161. CLEAR(t);
  3162. t->pTerm = sqlite3_malloc(nTerm+1);
  3163. memcpy(t->pTerm, pTerm, nTerm);
  3164. t->pTerm[nTerm] = 0;
  3165. t->nTerm = nTerm;
  3166. t->isOr = q->nextIsOr;
  3167. t->isPrefix = 0;
  3168. q->nextIsOr = 0;
  3169. t->iColumn = q->nextColumn;
  3170. q->nextColumn = q->dfltColumn;
  3171. }
  3172. /*
  3173. ** Check to see if the string zToken[0...nToken-1] matches any
  3174. ** column name in the virtual table. If it does,
  3175. ** return the zero-indexed column number. If not, return -1.
  3176. */
  3177. static int checkColumnSpecifier(
  3178. fulltext_vtab *pVtab, /* The virtual table */
  3179. const char *zToken, /* Text of the token */
  3180. int nToken /* Number of characters in the token */
  3181. ){
  3182. int i;
  3183. for(i=0; i<pVtab->nColumn; i++){
  3184. if( memcmp(pVtab->azColumn[i], zToken, nToken)==0
  3185. && pVtab->azColumn[i][nToken]==0 ){
  3186. return i;
  3187. }
  3188. }
  3189. return -1;
  3190. }
  3191. /*
  3192. ** Parse the text at pSegment[0..nSegment-1]. Add additional terms
  3193. ** to the query being assemblied in pQuery.
  3194. **
  3195. ** inPhrase is true if pSegment[0..nSegement-1] is contained within
  3196. ** double-quotes. If inPhrase is true, then the first term
  3197. ** is marked with the number of terms in the phrase less one and
  3198. ** OR and "-" syntax is ignored. If inPhrase is false, then every
  3199. ** term found is marked with nPhrase=0 and OR and "-" syntax is significant.
  3200. */
  3201. static int tokenizeSegment(
  3202. sqlite3_tokenizer *pTokenizer, /* The tokenizer to use */
  3203. const char *pSegment, int nSegment, /* Query expression being parsed */
  3204. int inPhrase, /* True if within "..." */
  3205. Query *pQuery /* Append results here */
  3206. ){
  3207. const sqlite3_tokenizer_module *pModule = pTokenizer->pModule;
  3208. sqlite3_tokenizer_cursor *pCursor;
  3209. int firstIndex = pQuery->nTerms;
  3210. int iCol;
  3211. int nTerm = 1;
  3212. int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor);
  3213. if( rc!=SQLITE_OK ) return rc;
  3214. pCursor->pTokenizer = pTokenizer;
  3215. while( 1 ){
  3216. const char *pToken;
  3217. int nToken, iBegin, iEnd, iPos;
  3218. rc = pModule->xNext(pCursor,
  3219. &pToken, &nToken,
  3220. &iBegin, &iEnd, &iPos);
  3221. if( rc!=SQLITE_OK ) break;
  3222. if( !inPhrase &&
  3223. pSegment[iEnd]==':' &&
  3224. (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){
  3225. pQuery->nextColumn = iCol;
  3226. continue;
  3227. }
  3228. if( !inPhrase && pQuery->nTerms>0 && nToken==2
  3229. && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){
  3230. pQuery->nextIsOr = 1;
  3231. continue;
  3232. }
  3233. queryAdd(pQuery, pToken, nToken);
  3234. if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){
  3235. pQuery->pTerms[pQuery->nTerms-1].isNot = 1;
  3236. }
  3237. if( iEnd<nSegment && pSegment[iEnd]=='*' ){
  3238. pQuery->pTerms[pQuery->nTerms-1].isPrefix = 1;
  3239. }
  3240. pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm;
  3241. if( inPhrase ){
  3242. nTerm++;
  3243. }
  3244. }
  3245. if( inPhrase && pQuery->nTerms>firstIndex ){
  3246. pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1;
  3247. }
  3248. return pModule->xClose(pCursor);
  3249. }
  3250. /* Parse a query string, yielding a Query object pQuery.
  3251. **
  3252. ** The calling function will need to queryClear() to clean up
  3253. ** the dynamically allocated memory held by pQuery.
  3254. */
  3255. static int parseQuery(
  3256. fulltext_vtab *v, /* The fulltext index */
  3257. const char *zInput, /* Input text of the query string */
  3258. int nInput, /* Size of the input text */
  3259. int dfltColumn, /* Default column of the index to match against */
  3260. Query *pQuery /* Write the parse results here. */
  3261. ){
  3262. int iInput, inPhrase = 0;
  3263. if( zInput==0 ) nInput = 0;
  3264. if( nInput<0 ) nInput = strlen(zInput);
  3265. pQuery->nTerms = 0;
  3266. pQuery->pTerms = NULL;
  3267. pQuery->nextIsOr = 0;
  3268. pQuery->nextColumn = dfltColumn;
  3269. pQuery->dfltColumn = dfltColumn;
  3270. pQuery->pFts = v;
  3271. for(iInput=0; iInput<nInput; ++iInput){
  3272. int i;
  3273. for(i=iInput; i<nInput && zInput[i]!='"'; ++i){}
  3274. if( i>iInput ){
  3275. tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase,
  3276. pQuery);
  3277. }
  3278. iInput = i;
  3279. if( i<nInput ){
  3280. assert( zInput[i]=='"' );
  3281. inPhrase = !inPhrase;
  3282. }
  3283. }
  3284. if( inPhrase ){
  3285. /* unmatched quote */
  3286. queryClear(pQuery);
  3287. return SQLITE_ERROR;
  3288. }
  3289. return SQLITE_OK;
  3290. }
  3291. /* TODO(shess) Refactor the code to remove this forward decl. */
  3292. static int flushPendingTerms(fulltext_vtab *v);
  3293. /* Perform a full-text query using the search expression in
  3294. ** zInput[0..nInput-1]. Return a list of matching documents
  3295. ** in pResult.
  3296. **
  3297. ** Queries must match column iColumn. Or if iColumn>=nColumn
  3298. ** they are allowed to match against any column.
  3299. */
  3300. static int fulltextQuery(
  3301. fulltext_vtab *v, /* The full text index */
  3302. int iColumn, /* Match against this column by default */
  3303. const char *zInput, /* The query string */
  3304. int nInput, /* Number of bytes in zInput[] */
  3305. DataBuffer *pResult, /* Write the result doclist here */
  3306. Query *pQuery /* Put parsed query string here */
  3307. ){
  3308. int i, iNext, rc;
  3309. DataBuffer left, right, or, new;
  3310. int nNot = 0;
  3311. QueryTerm *aTerm;
  3312. /* TODO(shess) Instead of flushing pendingTerms, we could query for
  3313. ** the relevant term and merge the doclist into what we receive from
  3314. ** the database. Wait and see if this is a common issue, first.
  3315. **
  3316. ** A good reason not to flush is to not generate update-related
  3317. ** error codes from here.
  3318. */
  3319. /* Flush any buffered updates before executing the query. */
  3320. rc = flushPendingTerms(v);
  3321. if( rc!=SQLITE_OK ) return rc;
  3322. /* TODO(shess) I think that the queryClear() calls below are not
  3323. ** necessary, because fulltextClose() already clears the query.
  3324. */
  3325. rc = parseQuery(v, zInput, nInput, iColumn, pQuery);
  3326. if( rc!=SQLITE_OK ) return rc;
  3327. /* Empty or NULL queries return no results. */
  3328. if( pQuery->nTerms==0 ){
  3329. dataBufferInit(pResult, 0);
  3330. return SQLITE_OK;
  3331. }
  3332. /* Merge AND terms. */
  3333. /* TODO(shess) I think we can early-exit if( i>nNot && left.nData==0 ). */
  3334. aTerm = pQuery->pTerms;
  3335. for(i = 0; i<pQuery->nTerms; i=iNext){
  3336. if( aTerm[i].isNot ){
  3337. /* Handle all NOT terms in a separate pass */
  3338. nNot++;
  3339. iNext = i + aTerm[i].nPhrase+1;
  3340. continue;
  3341. }
  3342. iNext = i + aTerm[i].nPhrase + 1;
  3343. rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
  3344. if( rc ){
  3345. if( i!=nNot ) dataBufferDestroy(&left);
  3346. queryClear(pQuery);
  3347. return rc;
  3348. }
  3349. while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){
  3350. rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &or);
  3351. iNext += aTerm[iNext].nPhrase + 1;
  3352. if( rc ){
  3353. if( i!=nNot ) dataBufferDestroy(&left);
  3354. dataBufferDestroy(&right);
  3355. queryClear(pQuery);
  3356. return rc;
  3357. }
  3358. dataBufferInit(&new, 0);
  3359. docListOrMerge(right.pData, right.nData, or.pData, or.nData, &new);
  3360. dataBufferDestroy(&right);
  3361. dataBufferDestroy(&or);
  3362. right = new;
  3363. }
  3364. if( i==nNot ){ /* first term processed. */
  3365. left = right;
  3366. }else{
  3367. dataBufferInit(&new, 0);
  3368. docListAndMerge(left.pData, left.nData, right.pData, right.nData, &new);
  3369. dataBufferDestroy(&right);
  3370. dataBufferDestroy(&left);
  3371. left = new;
  3372. }
  3373. }
  3374. if( nNot==pQuery->nTerms ){
  3375. /* We do not yet know how to handle a query of only NOT terms */
  3376. return SQLITE_ERROR;
  3377. }
  3378. /* Do the EXCEPT terms */
  3379. for(i=0; i<pQuery->nTerms; i += aTerm[i].nPhrase + 1){
  3380. if( !aTerm[i].isNot ) continue;
  3381. rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &right);
  3382. if( rc ){
  3383. queryClear(pQuery);
  3384. dataBufferDestroy(&left);
  3385. return rc;
  3386. }
  3387. dataBufferInit(&new, 0);
  3388. docListExceptMerge(left.pData, left.nData, right.pData, right.nData, &new);
  3389. dataBufferDestroy(&right);
  3390. dataBufferDestroy(&left);
  3391. left = new;
  3392. }
  3393. *pResult = left;
  3394. return rc;
  3395. }
  3396. /*
  3397. ** This is the xFilter interface for the virtual table. See
  3398. ** the virtual table xFilter method documentation for additional
  3399. ** information.
  3400. **
  3401. ** If idxNum==QUERY_GENERIC then do a full table scan against
  3402. ** the %_content table.
  3403. **
  3404. ** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry
  3405. ** in the %_content table.
  3406. **
  3407. ** If idxNum>=QUERY_FULLTEXT then use the full text index. The
  3408. ** column on the left-hand side of the MATCH operator is column
  3409. ** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand
  3410. ** side of the MATCH operator.
  3411. */
  3412. /* TODO(shess) Upgrade the cursor initialization and destruction to
  3413. ** account for fulltextFilter() being called multiple times on the
  3414. ** same cursor. The current solution is very fragile. Apply fix to
  3415. ** fts2 as appropriate.
  3416. */
  3417. static int fulltextFilter(
  3418. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  3419. int idxNum, const char *idxStr, /* Which indexing scheme to use */
  3420. int argc, sqlite3_value **argv /* Arguments for the indexing scheme */
  3421. ){
  3422. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3423. fulltext_vtab *v = cursor_vtab(c);
  3424. int rc;
  3425. TRACE(("FTS2 Filter %p\n",pCursor));
  3426. /* If the cursor has a statement that was not prepared according to
  3427. ** idxNum, clear it. I believe all calls to fulltextFilter with a
  3428. ** given cursor will have the same idxNum , but in this case it's
  3429. ** easy to be safe.
  3430. */
  3431. if( c->pStmt && c->iCursorType!=idxNum ){
  3432. sqlite3_finalize(c->pStmt);
  3433. c->pStmt = NULL;
  3434. }
  3435. /* Get a fresh statement appropriate to idxNum. */
  3436. /* TODO(shess): Add a prepared-statement cache in the vt structure.
  3437. ** The cache must handle multiple open cursors. Easier to cache the
  3438. ** statement variants at the vt to reduce malloc/realloc/free here.
  3439. ** Or we could have a StringBuffer variant which allowed stack
  3440. ** construction for small values.
  3441. */
  3442. if( !c->pStmt ){
  3443. char *zSql = sqlite3_mprintf("select rowid, * from %%_content %s",
  3444. idxNum==QUERY_GENERIC ? "" : "where rowid=?");
  3445. rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql);
  3446. sqlite3_free(zSql);
  3447. if( rc!=SQLITE_OK ) return rc;
  3448. c->iCursorType = idxNum;
  3449. }else{
  3450. sqlite3_reset(c->pStmt);
  3451. assert( c->iCursorType==idxNum );
  3452. }
  3453. switch( idxNum ){
  3454. case QUERY_GENERIC:
  3455. break;
  3456. case QUERY_ROWID:
  3457. rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0]));
  3458. if( rc!=SQLITE_OK ) return rc;
  3459. break;
  3460. default: /* full-text search */
  3461. {
  3462. const char *zQuery = (const char *)sqlite3_value_text(argv[0]);
  3463. assert( idxNum<=QUERY_FULLTEXT+v->nColumn);
  3464. assert( argc==1 );
  3465. queryClear(&c->q);
  3466. if( c->result.nData!=0 ){
  3467. /* This case happens if the same cursor is used repeatedly. */
  3468. dlrDestroy(&c->reader);
  3469. dataBufferReset(&c->result);
  3470. }else{
  3471. dataBufferInit(&c->result, 0);
  3472. }
  3473. rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &c->result, &c->q);
  3474. if( rc!=SQLITE_OK ) return rc;
  3475. if( c->result.nData!=0 ){
  3476. dlrInit(&c->reader, DL_DOCIDS, c->result.pData, c->result.nData);
  3477. }
  3478. break;
  3479. }
  3480. }
  3481. return fulltextNext(pCursor);
  3482. }
  3483. /* This is the xEof method of the virtual table. The SQLite core
  3484. ** calls this routine to find out if it has reached the end of
  3485. ** a query's results set.
  3486. */
  3487. static int fulltextEof(sqlite3_vtab_cursor *pCursor){
  3488. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3489. return c->eof;
  3490. }
  3491. /* This is the xColumn method of the virtual table. The SQLite
  3492. ** core calls this method during a query when it needs the value
  3493. ** of a column from the virtual table. This method needs to use
  3494. ** one of the sqlite3_result_*() routines to store the requested
  3495. ** value back in the pContext.
  3496. */
  3497. static int fulltextColumn(sqlite3_vtab_cursor *pCursor,
  3498. sqlite3_context *pContext, int idxCol){
  3499. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3500. fulltext_vtab *v = cursor_vtab(c);
  3501. if( idxCol<v->nColumn ){
  3502. sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1);
  3503. sqlite3_result_value(pContext, pVal);
  3504. }else if( idxCol==v->nColumn ){
  3505. /* The extra column whose name is the same as the table.
  3506. ** Return a blob which is a pointer to the cursor
  3507. */
  3508. sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT);
  3509. }
  3510. return SQLITE_OK;
  3511. }
  3512. /* This is the xRowid method. The SQLite core calls this routine to
  3513. ** retrive the rowid for the current row of the result set. The
  3514. ** rowid should be written to *pRowid.
  3515. */
  3516. static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  3517. fulltext_cursor *c = (fulltext_cursor *) pCursor;
  3518. *pRowid = sqlite3_column_int64(c->pStmt, 0);
  3519. return SQLITE_OK;
  3520. }
  3521. /* Add all terms in [zText] to pendingTerms table. If [iColumn] > 0,
  3522. ** we also store positions and offsets in the hash table using that
  3523. ** column number.
  3524. */
  3525. static int buildTerms(fulltext_vtab *v, sqlite_int64 iDocid,
  3526. const char *zText, int iColumn){
  3527. sqlite3_tokenizer *pTokenizer = v->pTokenizer;
  3528. sqlite3_tokenizer_cursor *pCursor;
  3529. const char *pToken;
  3530. int nTokenBytes;
  3531. int iStartOffset, iEndOffset, iPosition;
  3532. int rc;
  3533. rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor);
  3534. if( rc!=SQLITE_OK ) return rc;
  3535. pCursor->pTokenizer = pTokenizer;
  3536. while( SQLITE_OK==(rc=pTokenizer->pModule->xNext(pCursor,
  3537. &pToken, &nTokenBytes,
  3538. &iStartOffset, &iEndOffset,
  3539. &iPosition)) ){
  3540. DLCollector *p;
  3541. int nData; /* Size of doclist before our update. */
  3542. /* Positions can't be negative; we use -1 as a terminator
  3543. * internally. Token can't be NULL or empty. */
  3544. if( iPosition<0 || pToken == NULL || nTokenBytes == 0 ){
  3545. rc = SQLITE_ERROR;
  3546. break;
  3547. }
  3548. p = fts2HashFind(&v->pendingTerms, pToken, nTokenBytes);
  3549. if( p==NULL ){
  3550. nData = 0;
  3551. p = dlcNew(iDocid, DL_DEFAULT);
  3552. fts2HashInsert(&v->pendingTerms, pToken, nTokenBytes, p);
  3553. /* Overhead for our hash table entry, the key, and the value. */
  3554. v->nPendingData += sizeof(struct fts2HashElem)+sizeof(*p)+nTokenBytes;
  3555. }else{
  3556. nData = p->b.nData;
  3557. if( p->dlw.iPrevDocid!=iDocid ) dlcNext(p, iDocid);
  3558. }
  3559. if( iColumn>=0 ){
  3560. dlcAddPos(p, iColumn, iPosition, iStartOffset, iEndOffset);
  3561. }
  3562. /* Accumulate data added by dlcNew or dlcNext, and dlcAddPos. */
  3563. v->nPendingData += p->b.nData-nData;
  3564. }
  3565. /* TODO(shess) Check return? Should this be able to cause errors at
  3566. ** this point? Actually, same question about sqlite3_finalize(),
  3567. ** though one could argue that failure there means that the data is
  3568. ** not durable. *ponder*
  3569. */
  3570. pTokenizer->pModule->xClose(pCursor);
  3571. if( SQLITE_DONE == rc ) return SQLITE_OK;
  3572. return rc;
  3573. }
  3574. /* Add doclists for all terms in [pValues] to pendingTerms table. */
  3575. static int insertTerms(fulltext_vtab *v, sqlite_int64 iRowid,
  3576. sqlite3_value **pValues){
  3577. int i;
  3578. for(i = 0; i < v->nColumn ; ++i){
  3579. char *zText = (char*)sqlite3_value_text(pValues[i]);
  3580. int rc = buildTerms(v, iRowid, zText, i);
  3581. if( rc!=SQLITE_OK ) return rc;
  3582. }
  3583. return SQLITE_OK;
  3584. }
  3585. /* Add empty doclists for all terms in the given row's content to
  3586. ** pendingTerms.
  3587. */
  3588. static int deleteTerms(fulltext_vtab *v, sqlite_int64 iRowid){
  3589. const char **pValues;
  3590. int i, rc;
  3591. /* TODO(shess) Should we allow such tables at all? */
  3592. if( DL_DEFAULT==DL_DOCIDS ) return SQLITE_ERROR;
  3593. rc = content_select(v, iRowid, &pValues);
  3594. if( rc!=SQLITE_OK ) return rc;
  3595. for(i = 0 ; i < v->nColumn; ++i) {
  3596. rc = buildTerms(v, iRowid, pValues[i], -1);
  3597. if( rc!=SQLITE_OK ) break;
  3598. }
  3599. freeStringArray(v->nColumn, pValues);
  3600. return SQLITE_OK;
  3601. }
  3602. /* TODO(shess) Refactor the code to remove this forward decl. */
  3603. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid);
  3604. /* Insert a row into the %_content table; set *piRowid to be the ID of the
  3605. ** new row. Add doclists for terms to pendingTerms.
  3606. */
  3607. static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid,
  3608. sqlite3_value **pValues, sqlite_int64 *piRowid){
  3609. int rc;
  3610. rc = content_insert(v, pRequestRowid, pValues); /* execute an SQL INSERT */
  3611. if( rc!=SQLITE_OK ) return rc;
  3612. *piRowid = sqlite3_last_insert_rowid(v->db);
  3613. rc = initPendingTerms(v, *piRowid);
  3614. if( rc!=SQLITE_OK ) return rc;
  3615. return insertTerms(v, *piRowid, pValues);
  3616. }
  3617. /* Delete a row from the %_content table; add empty doclists for terms
  3618. ** to pendingTerms.
  3619. */
  3620. static int index_delete(fulltext_vtab *v, sqlite_int64 iRow){
  3621. int rc = initPendingTerms(v, iRow);
  3622. if( rc!=SQLITE_OK ) return rc;
  3623. rc = deleteTerms(v, iRow);
  3624. if( rc!=SQLITE_OK ) return rc;
  3625. return content_delete(v, iRow); /* execute an SQL DELETE */
  3626. }
  3627. /* Update a row in the %_content table; add delete doclists to
  3628. ** pendingTerms for old terms not in the new data, add insert doclists
  3629. ** to pendingTerms for terms in the new data.
  3630. */
  3631. static int index_update(fulltext_vtab *v, sqlite_int64 iRow,
  3632. sqlite3_value **pValues){
  3633. int rc = initPendingTerms(v, iRow);
  3634. if( rc!=SQLITE_OK ) return rc;
  3635. /* Generate an empty doclist for each term that previously appeared in this
  3636. * row. */
  3637. rc = deleteTerms(v, iRow);
  3638. if( rc!=SQLITE_OK ) return rc;
  3639. rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */
  3640. if( rc!=SQLITE_OK ) return rc;
  3641. /* Now add positions for terms which appear in the updated row. */
  3642. return insertTerms(v, iRow, pValues);
  3643. }
  3644. /*******************************************************************/
  3645. /* InteriorWriter is used to collect terms and block references into
  3646. ** interior nodes in %_segments. See commentary at top of file for
  3647. ** format.
  3648. */
  3649. /* How large interior nodes can grow. */
  3650. #define INTERIOR_MAX 2048
  3651. /* Minimum number of terms per interior node (except the root). This
  3652. ** prevents large terms from making the tree too skinny - must be >0
  3653. ** so that the tree always makes progress. Note that the min tree
  3654. ** fanout will be INTERIOR_MIN_TERMS+1.
  3655. */
  3656. #define INTERIOR_MIN_TERMS 7
  3657. #if INTERIOR_MIN_TERMS<1
  3658. # error INTERIOR_MIN_TERMS must be greater than 0.
  3659. #endif
  3660. /* ROOT_MAX controls how much data is stored inline in the segment
  3661. ** directory.
  3662. */
  3663. /* TODO(shess) Push ROOT_MAX down to whoever is writing things. It's
  3664. ** only here so that interiorWriterRootInfo() and leafWriterRootInfo()
  3665. ** can both see it, but if the caller passed it in, we wouldn't even
  3666. ** need a define.
  3667. */
  3668. #define ROOT_MAX 1024
  3669. #if ROOT_MAX<VARINT_MAX*2
  3670. # error ROOT_MAX must have enough space for a header.
  3671. #endif
  3672. /* InteriorBlock stores a linked-list of interior blocks while a lower
  3673. ** layer is being constructed.
  3674. */
  3675. typedef struct InteriorBlock {
  3676. DataBuffer term; /* Leftmost term in block's subtree. */
  3677. DataBuffer data; /* Accumulated data for the block. */
  3678. struct InteriorBlock *next;
  3679. } InteriorBlock;
  3680. static InteriorBlock *interiorBlockNew(int iHeight, sqlite_int64 iChildBlock,
  3681. const char *pTerm, int nTerm){
  3682. InteriorBlock *block = sqlite3_malloc(sizeof(InteriorBlock));
  3683. char c[VARINT_MAX+VARINT_MAX];
  3684. int n;
  3685. if( block ){
  3686. memset(block, 0, sizeof(*block));
  3687. dataBufferInit(&block->term, 0);
  3688. dataBufferReplace(&block->term, pTerm, nTerm);
  3689. n = putVarint(c, iHeight);
  3690. n += putVarint(c+n, iChildBlock);
  3691. dataBufferInit(&block->data, INTERIOR_MAX);
  3692. dataBufferReplace(&block->data, c, n);
  3693. }
  3694. return block;
  3695. }
  3696. #ifndef NDEBUG
  3697. /* Verify that the data is readable as an interior node. */
  3698. static void interiorBlockValidate(InteriorBlock *pBlock){
  3699. const char *pData = pBlock->data.pData;
  3700. int nData = pBlock->data.nData;
  3701. int n, iDummy;
  3702. sqlite_int64 iBlockid;
  3703. assert( nData>0 );
  3704. assert( pData!=0 );
  3705. assert( pData+nData>pData );
  3706. /* Must lead with height of node as a varint(n), n>0 */
  3707. n = getVarint32(pData, &iDummy);
  3708. assert( n>0 );
  3709. assert( iDummy>0 );
  3710. assert( n<nData );
  3711. pData += n;
  3712. nData -= n;
  3713. /* Must contain iBlockid. */
  3714. n = getVarint(pData, &iBlockid);
  3715. assert( n>0 );
  3716. assert( n<=nData );
  3717. pData += n;
  3718. nData -= n;
  3719. /* Zero or more terms of positive length */
  3720. if( nData!=0 ){
  3721. /* First term is not delta-encoded. */
  3722. n = getVarint32(pData, &iDummy);
  3723. assert( n>0 );
  3724. assert( iDummy>0 );
  3725. assert( n+iDummy>0);
  3726. assert( n+iDummy<=nData );
  3727. pData += n+iDummy;
  3728. nData -= n+iDummy;
  3729. /* Following terms delta-encoded. */
  3730. while( nData!=0 ){
  3731. /* Length of shared prefix. */
  3732. n = getVarint32(pData, &iDummy);
  3733. assert( n>0 );
  3734. assert( iDummy>=0 );
  3735. assert( n<nData );
  3736. pData += n;
  3737. nData -= n;
  3738. /* Length and data of distinct suffix. */
  3739. n = getVarint32(pData, &iDummy);
  3740. assert( n>0 );
  3741. assert( iDummy>0 );
  3742. assert( n+iDummy>0);
  3743. assert( n+iDummy<=nData );
  3744. pData += n+iDummy;
  3745. nData -= n+iDummy;
  3746. }
  3747. }
  3748. }
  3749. #define ASSERT_VALID_INTERIOR_BLOCK(x) interiorBlockValidate(x)
  3750. #else
  3751. #define ASSERT_VALID_INTERIOR_BLOCK(x) assert( 1 )
  3752. #endif
  3753. typedef struct InteriorWriter {
  3754. int iHeight; /* from 0 at leaves. */
  3755. InteriorBlock *first, *last;
  3756. struct InteriorWriter *parentWriter;
  3757. DataBuffer term; /* Last term written to block "last". */
  3758. sqlite_int64 iOpeningChildBlock; /* First child block in block "last". */
  3759. #ifndef NDEBUG
  3760. sqlite_int64 iLastChildBlock; /* for consistency checks. */
  3761. #endif
  3762. } InteriorWriter;
  3763. /* Initialize an interior node where pTerm[nTerm] marks the leftmost
  3764. ** term in the tree. iChildBlock is the leftmost child block at the
  3765. ** next level down the tree.
  3766. */
  3767. static void interiorWriterInit(int iHeight, const char *pTerm, int nTerm,
  3768. sqlite_int64 iChildBlock,
  3769. InteriorWriter *pWriter){
  3770. InteriorBlock *block;
  3771. assert( iHeight>0 );
  3772. CLEAR(pWriter);
  3773. pWriter->iHeight = iHeight;
  3774. pWriter->iOpeningChildBlock = iChildBlock;
  3775. #ifndef NDEBUG
  3776. pWriter->iLastChildBlock = iChildBlock;
  3777. #endif
  3778. block = interiorBlockNew(iHeight, iChildBlock, pTerm, nTerm);
  3779. pWriter->last = pWriter->first = block;
  3780. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  3781. dataBufferInit(&pWriter->term, 0);
  3782. }
  3783. /* Append the child node rooted at iChildBlock to the interior node,
  3784. ** with pTerm[nTerm] as the leftmost term in iChildBlock's subtree.
  3785. */
  3786. static void interiorWriterAppend(InteriorWriter *pWriter,
  3787. const char *pTerm, int nTerm,
  3788. sqlite_int64 iChildBlock){
  3789. char c[VARINT_MAX+VARINT_MAX];
  3790. int n, nPrefix = 0;
  3791. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  3792. /* The first term written into an interior node is actually
  3793. ** associated with the second child added (the first child was added
  3794. ** in interiorWriterInit, or in the if clause at the bottom of this
  3795. ** function). That term gets encoded straight up, with nPrefix left
  3796. ** at 0.
  3797. */
  3798. if( pWriter->term.nData==0 ){
  3799. n = putVarint(c, nTerm);
  3800. }else{
  3801. while( nPrefix<pWriter->term.nData &&
  3802. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  3803. nPrefix++;
  3804. }
  3805. n = putVarint(c, nPrefix);
  3806. n += putVarint(c+n, nTerm-nPrefix);
  3807. }
  3808. #ifndef NDEBUG
  3809. pWriter->iLastChildBlock++;
  3810. #endif
  3811. assert( pWriter->iLastChildBlock==iChildBlock );
  3812. /* Overflow to a new block if the new term makes the current block
  3813. ** too big, and the current block already has enough terms.
  3814. */
  3815. if( pWriter->last->data.nData+n+nTerm-nPrefix>INTERIOR_MAX &&
  3816. iChildBlock-pWriter->iOpeningChildBlock>INTERIOR_MIN_TERMS ){
  3817. pWriter->last->next = interiorBlockNew(pWriter->iHeight, iChildBlock,
  3818. pTerm, nTerm);
  3819. pWriter->last = pWriter->last->next;
  3820. pWriter->iOpeningChildBlock = iChildBlock;
  3821. dataBufferReset(&pWriter->term);
  3822. }else{
  3823. dataBufferAppend2(&pWriter->last->data, c, n,
  3824. pTerm+nPrefix, nTerm-nPrefix);
  3825. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  3826. }
  3827. ASSERT_VALID_INTERIOR_BLOCK(pWriter->last);
  3828. }
  3829. /* Free the space used by pWriter, including the linked-list of
  3830. ** InteriorBlocks, and parentWriter, if present.
  3831. */
  3832. static int interiorWriterDestroy(InteriorWriter *pWriter){
  3833. InteriorBlock *block = pWriter->first;
  3834. while( block!=NULL ){
  3835. InteriorBlock *b = block;
  3836. block = block->next;
  3837. dataBufferDestroy(&b->term);
  3838. dataBufferDestroy(&b->data);
  3839. sqlite3_free(b);
  3840. }
  3841. if( pWriter->parentWriter!=NULL ){
  3842. interiorWriterDestroy(pWriter->parentWriter);
  3843. sqlite3_free(pWriter->parentWriter);
  3844. }
  3845. dataBufferDestroy(&pWriter->term);
  3846. SCRAMBLE(pWriter);
  3847. return SQLITE_OK;
  3848. }
  3849. /* If pWriter can fit entirely in ROOT_MAX, return it as the root info
  3850. ** directly, leaving *piEndBlockid unchanged. Otherwise, flush
  3851. ** pWriter to %_segments, building a new layer of interior nodes, and
  3852. ** recursively ask for their root into.
  3853. */
  3854. static int interiorWriterRootInfo(fulltext_vtab *v, InteriorWriter *pWriter,
  3855. char **ppRootInfo, int *pnRootInfo,
  3856. sqlite_int64 *piEndBlockid){
  3857. InteriorBlock *block = pWriter->first;
  3858. sqlite_int64 iBlockid = 0;
  3859. int rc;
  3860. /* If we can fit the segment inline */
  3861. if( block==pWriter->last && block->data.nData<ROOT_MAX ){
  3862. *ppRootInfo = block->data.pData;
  3863. *pnRootInfo = block->data.nData;
  3864. return SQLITE_OK;
  3865. }
  3866. /* Flush the first block to %_segments, and create a new level of
  3867. ** interior node.
  3868. */
  3869. ASSERT_VALID_INTERIOR_BLOCK(block);
  3870. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  3871. if( rc!=SQLITE_OK ) return rc;
  3872. *piEndBlockid = iBlockid;
  3873. pWriter->parentWriter = sqlite3_malloc(sizeof(*pWriter->parentWriter));
  3874. interiorWriterInit(pWriter->iHeight+1,
  3875. block->term.pData, block->term.nData,
  3876. iBlockid, pWriter->parentWriter);
  3877. /* Flush additional blocks and append to the higher interior
  3878. ** node.
  3879. */
  3880. for(block=block->next; block!=NULL; block=block->next){
  3881. ASSERT_VALID_INTERIOR_BLOCK(block);
  3882. rc = block_insert(v, block->data.pData, block->data.nData, &iBlockid);
  3883. if( rc!=SQLITE_OK ) return rc;
  3884. *piEndBlockid = iBlockid;
  3885. interiorWriterAppend(pWriter->parentWriter,
  3886. block->term.pData, block->term.nData, iBlockid);
  3887. }
  3888. /* Parent node gets the chance to be the root. */
  3889. return interiorWriterRootInfo(v, pWriter->parentWriter,
  3890. ppRootInfo, pnRootInfo, piEndBlockid);
  3891. }
  3892. /****************************************************************/
  3893. /* InteriorReader is used to read off the data from an interior node
  3894. ** (see comment at top of file for the format).
  3895. */
  3896. typedef struct InteriorReader {
  3897. const char *pData;
  3898. int nData;
  3899. DataBuffer term; /* previous term, for decoding term delta. */
  3900. sqlite_int64 iBlockid;
  3901. } InteriorReader;
  3902. static void interiorReaderDestroy(InteriorReader *pReader){
  3903. dataBufferDestroy(&pReader->term);
  3904. SCRAMBLE(pReader);
  3905. }
  3906. /* TODO(shess) The assertions are great, but what if we're in NDEBUG
  3907. ** and the blob is empty or otherwise contains suspect data?
  3908. */
  3909. static void interiorReaderInit(const char *pData, int nData,
  3910. InteriorReader *pReader){
  3911. int n, nTerm;
  3912. /* Require at least the leading flag byte */
  3913. assert( nData>0 );
  3914. assert( pData[0]!='\0' );
  3915. CLEAR(pReader);
  3916. /* Decode the base blockid, and set the cursor to the first term. */
  3917. n = getVarint(pData+1, &pReader->iBlockid);
  3918. assert( 1+n<=nData );
  3919. pReader->pData = pData+1+n;
  3920. pReader->nData = nData-(1+n);
  3921. /* A single-child interior node (such as when a leaf node was too
  3922. ** large for the segment directory) won't have any terms.
  3923. ** Otherwise, decode the first term.
  3924. */
  3925. if( pReader->nData==0 ){
  3926. dataBufferInit(&pReader->term, 0);
  3927. }else{
  3928. n = getVarint32(pReader->pData, &nTerm);
  3929. dataBufferInit(&pReader->term, nTerm);
  3930. dataBufferReplace(&pReader->term, pReader->pData+n, nTerm);
  3931. assert( n+nTerm<=pReader->nData );
  3932. pReader->pData += n+nTerm;
  3933. pReader->nData -= n+nTerm;
  3934. }
  3935. }
  3936. static int interiorReaderAtEnd(InteriorReader *pReader){
  3937. return pReader->term.nData==0;
  3938. }
  3939. static sqlite_int64 interiorReaderCurrentBlockid(InteriorReader *pReader){
  3940. return pReader->iBlockid;
  3941. }
  3942. static int interiorReaderTermBytes(InteriorReader *pReader){
  3943. assert( !interiorReaderAtEnd(pReader) );
  3944. return pReader->term.nData;
  3945. }
  3946. static const char *interiorReaderTerm(InteriorReader *pReader){
  3947. assert( !interiorReaderAtEnd(pReader) );
  3948. return pReader->term.pData;
  3949. }
  3950. /* Step forward to the next term in the node. */
  3951. static void interiorReaderStep(InteriorReader *pReader){
  3952. assert( !interiorReaderAtEnd(pReader) );
  3953. /* If the last term has been read, signal eof, else construct the
  3954. ** next term.
  3955. */
  3956. if( pReader->nData==0 ){
  3957. dataBufferReset(&pReader->term);
  3958. }else{
  3959. int n, nPrefix, nSuffix;
  3960. n = getVarint32(pReader->pData, &nPrefix);
  3961. n += getVarint32(pReader->pData+n, &nSuffix);
  3962. /* Truncate the current term and append suffix data. */
  3963. pReader->term.nData = nPrefix;
  3964. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  3965. assert( n+nSuffix<=pReader->nData );
  3966. pReader->pData += n+nSuffix;
  3967. pReader->nData -= n+nSuffix;
  3968. }
  3969. pReader->iBlockid++;
  3970. }
  3971. /* Compare the current term to pTerm[nTerm], returning strcmp-style
  3972. ** results. If isPrefix, equality means equal through nTerm bytes.
  3973. */
  3974. static int interiorReaderTermCmp(InteriorReader *pReader,
  3975. const char *pTerm, int nTerm, int isPrefix){
  3976. const char *pReaderTerm = interiorReaderTerm(pReader);
  3977. int nReaderTerm = interiorReaderTermBytes(pReader);
  3978. int c, n = nReaderTerm<nTerm ? nReaderTerm : nTerm;
  3979. if( n==0 ){
  3980. if( nReaderTerm>0 ) return -1;
  3981. if( nTerm>0 ) return 1;
  3982. return 0;
  3983. }
  3984. c = memcmp(pReaderTerm, pTerm, n);
  3985. if( c!=0 ) return c;
  3986. if( isPrefix && n==nTerm ) return 0;
  3987. return nReaderTerm - nTerm;
  3988. }
  3989. /****************************************************************/
  3990. /* LeafWriter is used to collect terms and associated doclist data
  3991. ** into leaf blocks in %_segments (see top of file for format info).
  3992. ** Expected usage is:
  3993. **
  3994. ** LeafWriter writer;
  3995. ** leafWriterInit(0, 0, &writer);
  3996. ** while( sorted_terms_left_to_process ){
  3997. ** // data is doclist data for that term.
  3998. ** rc = leafWriterStep(v, &writer, pTerm, nTerm, pData, nData);
  3999. ** if( rc!=SQLITE_OK ) goto err;
  4000. ** }
  4001. ** rc = leafWriterFinalize(v, &writer);
  4002. **err:
  4003. ** leafWriterDestroy(&writer);
  4004. ** return rc;
  4005. **
  4006. ** leafWriterStep() may write a collected leaf out to %_segments.
  4007. ** leafWriterFinalize() finishes writing any buffered data and stores
  4008. ** a root node in %_segdir. leafWriterDestroy() frees all buffers and
  4009. ** InteriorWriters allocated as part of writing this segment.
  4010. **
  4011. ** TODO(shess) Document leafWriterStepMerge().
  4012. */
  4013. /* Put terms with data this big in their own block. */
  4014. #define STANDALONE_MIN 1024
  4015. /* Keep leaf blocks below this size. */
  4016. #define LEAF_MAX 2048
  4017. typedef struct LeafWriter {
  4018. int iLevel;
  4019. int idx;
  4020. sqlite_int64 iStartBlockid; /* needed to create the root info */
  4021. sqlite_int64 iEndBlockid; /* when we're done writing. */
  4022. DataBuffer term; /* previous encoded term */
  4023. DataBuffer data; /* encoding buffer */
  4024. /* bytes of first term in the current node which distinguishes that
  4025. ** term from the last term of the previous node.
  4026. */
  4027. int nTermDistinct;
  4028. InteriorWriter parentWriter; /* if we overflow */
  4029. int has_parent;
  4030. } LeafWriter;
  4031. static void leafWriterInit(int iLevel, int idx, LeafWriter *pWriter){
  4032. CLEAR(pWriter);
  4033. pWriter->iLevel = iLevel;
  4034. pWriter->idx = idx;
  4035. dataBufferInit(&pWriter->term, 32);
  4036. /* Start out with a reasonably sized block, though it can grow. */
  4037. dataBufferInit(&pWriter->data, LEAF_MAX);
  4038. }
  4039. #ifndef NDEBUG
  4040. /* Verify that the data is readable as a leaf node. */
  4041. static void leafNodeValidate(const char *pData, int nData){
  4042. int n, iDummy;
  4043. if( nData==0 ) return;
  4044. assert( nData>0 );
  4045. assert( pData!=0 );
  4046. assert( pData+nData>pData );
  4047. /* Must lead with a varint(0) */
  4048. n = getVarint32(pData, &iDummy);
  4049. assert( iDummy==0 );
  4050. assert( n>0 );
  4051. assert( n<nData );
  4052. pData += n;
  4053. nData -= n;
  4054. /* Leading term length and data must fit in buffer. */
  4055. n = getVarint32(pData, &iDummy);
  4056. assert( n>0 );
  4057. assert( iDummy>0 );
  4058. assert( n+iDummy>0 );
  4059. assert( n+iDummy<nData );
  4060. pData += n+iDummy;
  4061. nData -= n+iDummy;
  4062. /* Leading term's doclist length and data must fit. */
  4063. n = getVarint32(pData, &iDummy);
  4064. assert( n>0 );
  4065. assert( iDummy>0 );
  4066. assert( n+iDummy>0 );
  4067. assert( n+iDummy<=nData );
  4068. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  4069. pData += n+iDummy;
  4070. nData -= n+iDummy;
  4071. /* Verify that trailing terms and doclists also are readable. */
  4072. while( nData!=0 ){
  4073. n = getVarint32(pData, &iDummy);
  4074. assert( n>0 );
  4075. assert( iDummy>=0 );
  4076. assert( n<nData );
  4077. pData += n;
  4078. nData -= n;
  4079. n = getVarint32(pData, &iDummy);
  4080. assert( n>0 );
  4081. assert( iDummy>0 );
  4082. assert( n+iDummy>0 );
  4083. assert( n+iDummy<nData );
  4084. pData += n+iDummy;
  4085. nData -= n+iDummy;
  4086. n = getVarint32(pData, &iDummy);
  4087. assert( n>0 );
  4088. assert( iDummy>0 );
  4089. assert( n+iDummy>0 );
  4090. assert( n+iDummy<=nData );
  4091. ASSERT_VALID_DOCLIST(DL_DEFAULT, pData+n, iDummy, NULL);
  4092. pData += n+iDummy;
  4093. nData -= n+iDummy;
  4094. }
  4095. }
  4096. #define ASSERT_VALID_LEAF_NODE(p, n) leafNodeValidate(p, n)
  4097. #else
  4098. #define ASSERT_VALID_LEAF_NODE(p, n) assert( 1 )
  4099. #endif
  4100. /* Flush the current leaf node to %_segments, and adding the resulting
  4101. ** blockid and the starting term to the interior node which will
  4102. ** contain it.
  4103. */
  4104. static int leafWriterInternalFlush(fulltext_vtab *v, LeafWriter *pWriter,
  4105. int iData, int nData){
  4106. sqlite_int64 iBlockid = 0;
  4107. const char *pStartingTerm;
  4108. int nStartingTerm, rc, n;
  4109. /* Must have the leading varint(0) flag, plus at least some
  4110. ** valid-looking data.
  4111. */
  4112. assert( nData>2 );
  4113. assert( iData>=0 );
  4114. assert( iData+nData<=pWriter->data.nData );
  4115. ASSERT_VALID_LEAF_NODE(pWriter->data.pData+iData, nData);
  4116. rc = block_insert(v, pWriter->data.pData+iData, nData, &iBlockid);
  4117. if( rc!=SQLITE_OK ) return rc;
  4118. assert( iBlockid!=0 );
  4119. /* Reconstruct the first term in the leaf for purposes of building
  4120. ** the interior node.
  4121. */
  4122. n = getVarint32(pWriter->data.pData+iData+1, &nStartingTerm);
  4123. pStartingTerm = pWriter->data.pData+iData+1+n;
  4124. assert( pWriter->data.nData>iData+1+n+nStartingTerm );
  4125. assert( pWriter->nTermDistinct>0 );
  4126. assert( pWriter->nTermDistinct<=nStartingTerm );
  4127. nStartingTerm = pWriter->nTermDistinct;
  4128. if( pWriter->has_parent ){
  4129. interiorWriterAppend(&pWriter->parentWriter,
  4130. pStartingTerm, nStartingTerm, iBlockid);
  4131. }else{
  4132. interiorWriterInit(1, pStartingTerm, nStartingTerm, iBlockid,
  4133. &pWriter->parentWriter);
  4134. pWriter->has_parent = 1;
  4135. }
  4136. /* Track the span of this segment's leaf nodes. */
  4137. if( pWriter->iEndBlockid==0 ){
  4138. pWriter->iEndBlockid = pWriter->iStartBlockid = iBlockid;
  4139. }else{
  4140. pWriter->iEndBlockid++;
  4141. assert( iBlockid==pWriter->iEndBlockid );
  4142. }
  4143. return SQLITE_OK;
  4144. }
  4145. static int leafWriterFlush(fulltext_vtab *v, LeafWriter *pWriter){
  4146. int rc = leafWriterInternalFlush(v, pWriter, 0, pWriter->data.nData);
  4147. if( rc!=SQLITE_OK ) return rc;
  4148. /* Re-initialize the output buffer. */
  4149. dataBufferReset(&pWriter->data);
  4150. return SQLITE_OK;
  4151. }
  4152. /* Fetch the root info for the segment. If the entire leaf fits
  4153. ** within ROOT_MAX, then it will be returned directly, otherwise it
  4154. ** will be flushed and the root info will be returned from the
  4155. ** interior node. *piEndBlockid is set to the blockid of the last
  4156. ** interior or leaf node written to disk (0 if none are written at
  4157. ** all).
  4158. */
  4159. static int leafWriterRootInfo(fulltext_vtab *v, LeafWriter *pWriter,
  4160. char **ppRootInfo, int *pnRootInfo,
  4161. sqlite_int64 *piEndBlockid){
  4162. /* we can fit the segment entirely inline */
  4163. if( !pWriter->has_parent && pWriter->data.nData<ROOT_MAX ){
  4164. *ppRootInfo = pWriter->data.pData;
  4165. *pnRootInfo = pWriter->data.nData;
  4166. *piEndBlockid = 0;
  4167. return SQLITE_OK;
  4168. }
  4169. /* Flush remaining leaf data. */
  4170. if( pWriter->data.nData>0 ){
  4171. int rc = leafWriterFlush(v, pWriter);
  4172. if( rc!=SQLITE_OK ) return rc;
  4173. }
  4174. /* We must have flushed a leaf at some point. */
  4175. assert( pWriter->has_parent );
  4176. /* Tenatively set the end leaf blockid as the end blockid. If the
  4177. ** interior node can be returned inline, this will be the final
  4178. ** blockid, otherwise it will be overwritten by
  4179. ** interiorWriterRootInfo().
  4180. */
  4181. *piEndBlockid = pWriter->iEndBlockid;
  4182. return interiorWriterRootInfo(v, &pWriter->parentWriter,
  4183. ppRootInfo, pnRootInfo, piEndBlockid);
  4184. }
  4185. /* Collect the rootInfo data and store it into the segment directory.
  4186. ** This has the effect of flushing the segment's leaf data to
  4187. ** %_segments, and also flushing any interior nodes to %_segments.
  4188. */
  4189. static int leafWriterFinalize(fulltext_vtab *v, LeafWriter *pWriter){
  4190. sqlite_int64 iEndBlockid;
  4191. char *pRootInfo;
  4192. int rc, nRootInfo;
  4193. rc = leafWriterRootInfo(v, pWriter, &pRootInfo, &nRootInfo, &iEndBlockid);
  4194. if( rc!=SQLITE_OK ) return rc;
  4195. /* Don't bother storing an entirely empty segment. */
  4196. if( iEndBlockid==0 && nRootInfo==0 ) return SQLITE_OK;
  4197. return segdir_set(v, pWriter->iLevel, pWriter->idx,
  4198. pWriter->iStartBlockid, pWriter->iEndBlockid,
  4199. iEndBlockid, pRootInfo, nRootInfo);
  4200. }
  4201. static void leafWriterDestroy(LeafWriter *pWriter){
  4202. if( pWriter->has_parent ) interiorWriterDestroy(&pWriter->parentWriter);
  4203. dataBufferDestroy(&pWriter->term);
  4204. dataBufferDestroy(&pWriter->data);
  4205. }
  4206. /* Encode a term into the leafWriter, delta-encoding as appropriate.
  4207. ** Returns the length of the new term which distinguishes it from the
  4208. ** previous term, which can be used to set nTermDistinct when a node
  4209. ** boundary is crossed.
  4210. */
  4211. static int leafWriterEncodeTerm(LeafWriter *pWriter,
  4212. const char *pTerm, int nTerm){
  4213. char c[VARINT_MAX+VARINT_MAX];
  4214. int n, nPrefix = 0;
  4215. assert( nTerm>0 );
  4216. while( nPrefix<pWriter->term.nData &&
  4217. pTerm[nPrefix]==pWriter->term.pData[nPrefix] ){
  4218. nPrefix++;
  4219. /* Failing this implies that the terms weren't in order. */
  4220. assert( nPrefix<nTerm );
  4221. }
  4222. if( pWriter->data.nData==0 ){
  4223. /* Encode the node header and leading term as:
  4224. ** varint(0)
  4225. ** varint(nTerm)
  4226. ** char pTerm[nTerm]
  4227. */
  4228. n = putVarint(c, '\0');
  4229. n += putVarint(c+n, nTerm);
  4230. dataBufferAppend2(&pWriter->data, c, n, pTerm, nTerm);
  4231. }else{
  4232. /* Delta-encode the term as:
  4233. ** varint(nPrefix)
  4234. ** varint(nSuffix)
  4235. ** char pTermSuffix[nSuffix]
  4236. */
  4237. n = putVarint(c, nPrefix);
  4238. n += putVarint(c+n, nTerm-nPrefix);
  4239. dataBufferAppend2(&pWriter->data, c, n, pTerm+nPrefix, nTerm-nPrefix);
  4240. }
  4241. dataBufferReplace(&pWriter->term, pTerm, nTerm);
  4242. return nPrefix+1;
  4243. }
  4244. /* Used to avoid a memmove when a large amount of doclist data is in
  4245. ** the buffer. This constructs a node and term header before
  4246. ** iDoclistData and flushes the resulting complete node using
  4247. ** leafWriterInternalFlush().
  4248. */
  4249. static int leafWriterInlineFlush(fulltext_vtab *v, LeafWriter *pWriter,
  4250. const char *pTerm, int nTerm,
  4251. int iDoclistData){
  4252. char c[VARINT_MAX+VARINT_MAX];
  4253. int iData, n = putVarint(c, 0);
  4254. n += putVarint(c+n, nTerm);
  4255. /* There should always be room for the header. Even if pTerm shared
  4256. ** a substantial prefix with the previous term, the entire prefix
  4257. ** could be constructed from earlier data in the doclist, so there
  4258. ** should be room.
  4259. */
  4260. assert( iDoclistData>=n+nTerm );
  4261. iData = iDoclistData-(n+nTerm);
  4262. memcpy(pWriter->data.pData+iData, c, n);
  4263. memcpy(pWriter->data.pData+iData+n, pTerm, nTerm);
  4264. return leafWriterInternalFlush(v, pWriter, iData, pWriter->data.nData-iData);
  4265. }
  4266. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  4267. ** %_segments.
  4268. */
  4269. static int leafWriterStepMerge(fulltext_vtab *v, LeafWriter *pWriter,
  4270. const char *pTerm, int nTerm,
  4271. DLReader *pReaders, int nReaders){
  4272. char c[VARINT_MAX+VARINT_MAX];
  4273. int iTermData = pWriter->data.nData, iDoclistData;
  4274. int i, nData, n, nActualData, nActual, rc, nTermDistinct;
  4275. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  4276. nTermDistinct = leafWriterEncodeTerm(pWriter, pTerm, nTerm);
  4277. /* Remember nTermDistinct if opening a new node. */
  4278. if( iTermData==0 ) pWriter->nTermDistinct = nTermDistinct;
  4279. iDoclistData = pWriter->data.nData;
  4280. /* Estimate the length of the merged doclist so we can leave space
  4281. ** to encode it.
  4282. */
  4283. for(i=0, nData=0; i<nReaders; i++){
  4284. nData += dlrAllDataBytes(&pReaders[i]);
  4285. }
  4286. n = putVarint(c, nData);
  4287. dataBufferAppend(&pWriter->data, c, n);
  4288. docListMerge(&pWriter->data, pReaders, nReaders);
  4289. ASSERT_VALID_DOCLIST(DL_DEFAULT,
  4290. pWriter->data.pData+iDoclistData+n,
  4291. pWriter->data.nData-iDoclistData-n, NULL);
  4292. /* The actual amount of doclist data at this point could be smaller
  4293. ** than the length we encoded. Additionally, the space required to
  4294. ** encode this length could be smaller. For small doclists, this is
  4295. ** not a big deal, we can just use memmove() to adjust things.
  4296. */
  4297. nActualData = pWriter->data.nData-(iDoclistData+n);
  4298. nActual = putVarint(c, nActualData);
  4299. assert( nActualData<=nData );
  4300. assert( nActual<=n );
  4301. /* If the new doclist is big enough for force a standalone leaf
  4302. ** node, we can immediately flush it inline without doing the
  4303. ** memmove().
  4304. */
  4305. /* TODO(shess) This test matches leafWriterStep(), which does this
  4306. ** test before it knows the cost to varint-encode the term and
  4307. ** doclist lengths. At some point, change to
  4308. ** pWriter->data.nData-iTermData>STANDALONE_MIN.
  4309. */
  4310. if( nTerm+nActualData>STANDALONE_MIN ){
  4311. /* Push leaf node from before this term. */
  4312. if( iTermData>0 ){
  4313. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  4314. if( rc!=SQLITE_OK ) return rc;
  4315. pWriter->nTermDistinct = nTermDistinct;
  4316. }
  4317. /* Fix the encoded doclist length. */
  4318. iDoclistData += n - nActual;
  4319. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  4320. /* Push the standalone leaf node. */
  4321. rc = leafWriterInlineFlush(v, pWriter, pTerm, nTerm, iDoclistData);
  4322. if( rc!=SQLITE_OK ) return rc;
  4323. /* Leave the node empty. */
  4324. dataBufferReset(&pWriter->data);
  4325. return rc;
  4326. }
  4327. /* At this point, we know that the doclist was small, so do the
  4328. ** memmove if indicated.
  4329. */
  4330. if( nActual<n ){
  4331. memmove(pWriter->data.pData+iDoclistData+nActual,
  4332. pWriter->data.pData+iDoclistData+n,
  4333. pWriter->data.nData-(iDoclistData+n));
  4334. pWriter->data.nData -= n-nActual;
  4335. }
  4336. /* Replace written length with actual length. */
  4337. memcpy(pWriter->data.pData+iDoclistData, c, nActual);
  4338. /* If the node is too large, break things up. */
  4339. /* TODO(shess) This test matches leafWriterStep(), which does this
  4340. ** test before it knows the cost to varint-encode the term and
  4341. ** doclist lengths. At some point, change to
  4342. ** pWriter->data.nData>LEAF_MAX.
  4343. */
  4344. if( iTermData+nTerm+nActualData>LEAF_MAX ){
  4345. /* Flush out the leading data as a node */
  4346. rc = leafWriterInternalFlush(v, pWriter, 0, iTermData);
  4347. if( rc!=SQLITE_OK ) return rc;
  4348. pWriter->nTermDistinct = nTermDistinct;
  4349. /* Rebuild header using the current term */
  4350. n = putVarint(pWriter->data.pData, 0);
  4351. n += putVarint(pWriter->data.pData+n, nTerm);
  4352. memcpy(pWriter->data.pData+n, pTerm, nTerm);
  4353. n += nTerm;
  4354. /* There should always be room, because the previous encoding
  4355. ** included all data necessary to construct the term.
  4356. */
  4357. assert( n<iDoclistData );
  4358. /* So long as STANDALONE_MIN is half or less of LEAF_MAX, the
  4359. ** following memcpy() is safe (as opposed to needing a memmove).
  4360. */
  4361. assert( 2*STANDALONE_MIN<=LEAF_MAX );
  4362. assert( n+pWriter->data.nData-iDoclistData<iDoclistData );
  4363. memcpy(pWriter->data.pData+n,
  4364. pWriter->data.pData+iDoclistData,
  4365. pWriter->data.nData-iDoclistData);
  4366. pWriter->data.nData -= iDoclistData-n;
  4367. }
  4368. ASSERT_VALID_LEAF_NODE(pWriter->data.pData, pWriter->data.nData);
  4369. return SQLITE_OK;
  4370. }
  4371. /* Push pTerm[nTerm] along with the doclist data to the leaf layer of
  4372. ** %_segments.
  4373. */
  4374. /* TODO(shess) Revise writeZeroSegment() so that doclists are
  4375. ** constructed directly in pWriter->data.
  4376. */
  4377. static int leafWriterStep(fulltext_vtab *v, LeafWriter *pWriter,
  4378. const char *pTerm, int nTerm,
  4379. const char *pData, int nData){
  4380. int rc;
  4381. DLReader reader;
  4382. dlrInit(&reader, DL_DEFAULT, pData, nData);
  4383. rc = leafWriterStepMerge(v, pWriter, pTerm, nTerm, &reader, 1);
  4384. dlrDestroy(&reader);
  4385. return rc;
  4386. }
  4387. /****************************************************************/
  4388. /* LeafReader is used to iterate over an individual leaf node. */
  4389. typedef struct LeafReader {
  4390. DataBuffer term; /* copy of current term. */
  4391. const char *pData; /* data for current term. */
  4392. int nData;
  4393. } LeafReader;
  4394. static void leafReaderDestroy(LeafReader *pReader){
  4395. dataBufferDestroy(&pReader->term);
  4396. SCRAMBLE(pReader);
  4397. }
  4398. static int leafReaderAtEnd(LeafReader *pReader){
  4399. return pReader->nData<=0;
  4400. }
  4401. /* Access the current term. */
  4402. static int leafReaderTermBytes(LeafReader *pReader){
  4403. return pReader->term.nData;
  4404. }
  4405. static const char *leafReaderTerm(LeafReader *pReader){
  4406. assert( pReader->term.nData>0 );
  4407. return pReader->term.pData;
  4408. }
  4409. /* Access the doclist data for the current term. */
  4410. static int leafReaderDataBytes(LeafReader *pReader){
  4411. int nData;
  4412. assert( pReader->term.nData>0 );
  4413. getVarint32(pReader->pData, &nData);
  4414. return nData;
  4415. }
  4416. static const char *leafReaderData(LeafReader *pReader){
  4417. int n, nData;
  4418. assert( pReader->term.nData>0 );
  4419. n = getVarint32(pReader->pData, &nData);
  4420. return pReader->pData+n;
  4421. }
  4422. static void leafReaderInit(const char *pData, int nData,
  4423. LeafReader *pReader){
  4424. int nTerm, n;
  4425. assert( nData>0 );
  4426. assert( pData[0]=='\0' );
  4427. CLEAR(pReader);
  4428. /* Read the first term, skipping the header byte. */
  4429. n = getVarint32(pData+1, &nTerm);
  4430. dataBufferInit(&pReader->term, nTerm);
  4431. dataBufferReplace(&pReader->term, pData+1+n, nTerm);
  4432. /* Position after the first term. */
  4433. assert( 1+n+nTerm<nData );
  4434. pReader->pData = pData+1+n+nTerm;
  4435. pReader->nData = nData-1-n-nTerm;
  4436. }
  4437. /* Step the reader forward to the next term. */
  4438. static void leafReaderStep(LeafReader *pReader){
  4439. int n, nData, nPrefix, nSuffix;
  4440. assert( !leafReaderAtEnd(pReader) );
  4441. /* Skip previous entry's data block. */
  4442. n = getVarint32(pReader->pData, &nData);
  4443. assert( n+nData<=pReader->nData );
  4444. pReader->pData += n+nData;
  4445. pReader->nData -= n+nData;
  4446. if( !leafReaderAtEnd(pReader) ){
  4447. /* Construct the new term using a prefix from the old term plus a
  4448. ** suffix from the leaf data.
  4449. */
  4450. n = getVarint32(pReader->pData, &nPrefix);
  4451. n += getVarint32(pReader->pData+n, &nSuffix);
  4452. assert( n+nSuffix<pReader->nData );
  4453. pReader->term.nData = nPrefix;
  4454. dataBufferAppend(&pReader->term, pReader->pData+n, nSuffix);
  4455. pReader->pData += n+nSuffix;
  4456. pReader->nData -= n+nSuffix;
  4457. }
  4458. }
  4459. /* strcmp-style comparison of pReader's current term against pTerm.
  4460. ** If isPrefix, equality means equal through nTerm bytes.
  4461. */
  4462. static int leafReaderTermCmp(LeafReader *pReader,
  4463. const char *pTerm, int nTerm, int isPrefix){
  4464. int c, n = pReader->term.nData<nTerm ? pReader->term.nData : nTerm;
  4465. if( n==0 ){
  4466. if( pReader->term.nData>0 ) return -1;
  4467. if(nTerm>0 ) return 1;
  4468. return 0;
  4469. }
  4470. c = memcmp(pReader->term.pData, pTerm, n);
  4471. if( c!=0 ) return c;
  4472. if( isPrefix && n==nTerm ) return 0;
  4473. return pReader->term.nData - nTerm;
  4474. }
  4475. /****************************************************************/
  4476. /* LeavesReader wraps LeafReader to allow iterating over the entire
  4477. ** leaf layer of the tree.
  4478. */
  4479. typedef struct LeavesReader {
  4480. int idx; /* Index within the segment. */
  4481. sqlite3_stmt *pStmt; /* Statement we're streaming leaves from. */
  4482. int eof; /* we've seen SQLITE_DONE from pStmt. */
  4483. LeafReader leafReader; /* reader for the current leaf. */
  4484. DataBuffer rootData; /* root data for inline. */
  4485. } LeavesReader;
  4486. /* Access the current term. */
  4487. static int leavesReaderTermBytes(LeavesReader *pReader){
  4488. assert( !pReader->eof );
  4489. return leafReaderTermBytes(&pReader->leafReader);
  4490. }
  4491. static const char *leavesReaderTerm(LeavesReader *pReader){
  4492. assert( !pReader->eof );
  4493. return leafReaderTerm(&pReader->leafReader);
  4494. }
  4495. /* Access the doclist data for the current term. */
  4496. static int leavesReaderDataBytes(LeavesReader *pReader){
  4497. assert( !pReader->eof );
  4498. return leafReaderDataBytes(&pReader->leafReader);
  4499. }
  4500. static const char *leavesReaderData(LeavesReader *pReader){
  4501. assert( !pReader->eof );
  4502. return leafReaderData(&pReader->leafReader);
  4503. }
  4504. static int leavesReaderAtEnd(LeavesReader *pReader){
  4505. return pReader->eof;
  4506. }
  4507. /* loadSegmentLeaves() may not read all the way to SQLITE_DONE, thus
  4508. ** leaving the statement handle open, which locks the table.
  4509. */
  4510. /* TODO(shess) This "solution" is not satisfactory. Really, there
  4511. ** should be check-in function for all statement handles which
  4512. ** arranges to call sqlite3_reset(). This most likely will require
  4513. ** modification to control flow all over the place, though, so for now
  4514. ** just punt.
  4515. **
  4516. ** Note the current system assumes that segment merges will run to
  4517. ** completion, which is why this particular probably hasn't arisen in
  4518. ** this case. Probably a brittle assumption.
  4519. */
  4520. static int leavesReaderReset(LeavesReader *pReader){
  4521. return sqlite3_reset(pReader->pStmt);
  4522. }
  4523. static void leavesReaderDestroy(LeavesReader *pReader){
  4524. /* If idx is -1, that means we're using a non-cached statement
  4525. ** handle in the optimize() case, so we need to release it.
  4526. */
  4527. if( pReader->pStmt!=NULL && pReader->idx==-1 ){
  4528. sqlite3_finalize(pReader->pStmt);
  4529. }
  4530. leafReaderDestroy(&pReader->leafReader);
  4531. dataBufferDestroy(&pReader->rootData);
  4532. SCRAMBLE(pReader);
  4533. }
  4534. /* Initialize pReader with the given root data (if iStartBlockid==0
  4535. ** the leaf data was entirely contained in the root), or from the
  4536. ** stream of blocks between iStartBlockid and iEndBlockid, inclusive.
  4537. */
  4538. static int leavesReaderInit(fulltext_vtab *v,
  4539. int idx,
  4540. sqlite_int64 iStartBlockid,
  4541. sqlite_int64 iEndBlockid,
  4542. const char *pRootData, int nRootData,
  4543. LeavesReader *pReader){
  4544. CLEAR(pReader);
  4545. pReader->idx = idx;
  4546. dataBufferInit(&pReader->rootData, 0);
  4547. if( iStartBlockid==0 ){
  4548. /* Entire leaf level fit in root data. */
  4549. dataBufferReplace(&pReader->rootData, pRootData, nRootData);
  4550. leafReaderInit(pReader->rootData.pData, pReader->rootData.nData,
  4551. &pReader->leafReader);
  4552. }else{
  4553. sqlite3_stmt *s;
  4554. int rc = sql_get_leaf_statement(v, idx, &s);
  4555. if( rc!=SQLITE_OK ) return rc;
  4556. rc = sqlite3_bind_int64(s, 1, iStartBlockid);
  4557. if( rc!=SQLITE_OK ) return rc;
  4558. rc = sqlite3_bind_int64(s, 2, iEndBlockid);
  4559. if( rc!=SQLITE_OK ) return rc;
  4560. rc = sqlite3_step(s);
  4561. if( rc==SQLITE_DONE ){
  4562. pReader->eof = 1;
  4563. return SQLITE_OK;
  4564. }
  4565. if( rc!=SQLITE_ROW ) return rc;
  4566. pReader->pStmt = s;
  4567. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  4568. sqlite3_column_bytes(pReader->pStmt, 0),
  4569. &pReader->leafReader);
  4570. }
  4571. return SQLITE_OK;
  4572. }
  4573. /* Step the current leaf forward to the next term. If we reach the
  4574. ** end of the current leaf, step forward to the next leaf block.
  4575. */
  4576. static int leavesReaderStep(fulltext_vtab *v, LeavesReader *pReader){
  4577. assert( !leavesReaderAtEnd(pReader) );
  4578. leafReaderStep(&pReader->leafReader);
  4579. if( leafReaderAtEnd(&pReader->leafReader) ){
  4580. int rc;
  4581. if( pReader->rootData.pData ){
  4582. pReader->eof = 1;
  4583. return SQLITE_OK;
  4584. }
  4585. rc = sqlite3_step(pReader->pStmt);
  4586. if( rc!=SQLITE_ROW ){
  4587. pReader->eof = 1;
  4588. return rc==SQLITE_DONE ? SQLITE_OK : rc;
  4589. }
  4590. leafReaderDestroy(&pReader->leafReader);
  4591. leafReaderInit(sqlite3_column_blob(pReader->pStmt, 0),
  4592. sqlite3_column_bytes(pReader->pStmt, 0),
  4593. &pReader->leafReader);
  4594. }
  4595. return SQLITE_OK;
  4596. }
  4597. /* Order LeavesReaders by their term, ignoring idx. Readers at eof
  4598. ** always sort to the end.
  4599. */
  4600. static int leavesReaderTermCmp(LeavesReader *lr1, LeavesReader *lr2){
  4601. if( leavesReaderAtEnd(lr1) ){
  4602. if( leavesReaderAtEnd(lr2) ) return 0;
  4603. return 1;
  4604. }
  4605. if( leavesReaderAtEnd(lr2) ) return -1;
  4606. return leafReaderTermCmp(&lr1->leafReader,
  4607. leavesReaderTerm(lr2), leavesReaderTermBytes(lr2),
  4608. 0);
  4609. }
  4610. /* Similar to leavesReaderTermCmp(), with additional ordering by idx
  4611. ** so that older segments sort before newer segments.
  4612. */
  4613. static int leavesReaderCmp(LeavesReader *lr1, LeavesReader *lr2){
  4614. int c = leavesReaderTermCmp(lr1, lr2);
  4615. if( c!=0 ) return c;
  4616. return lr1->idx-lr2->idx;
  4617. }
  4618. /* Assume that pLr[1]..pLr[nLr] are sorted. Bubble pLr[0] into its
  4619. ** sorted position.
  4620. */
  4621. static void leavesReaderReorder(LeavesReader *pLr, int nLr){
  4622. while( nLr>1 && leavesReaderCmp(pLr, pLr+1)>0 ){
  4623. LeavesReader tmp = pLr[0];
  4624. pLr[0] = pLr[1];
  4625. pLr[1] = tmp;
  4626. nLr--;
  4627. pLr++;
  4628. }
  4629. }
  4630. /* Initializes pReaders with the segments from level iLevel, returning
  4631. ** the number of segments in *piReaders. Leaves pReaders in sorted
  4632. ** order.
  4633. */
  4634. static int leavesReadersInit(fulltext_vtab *v, int iLevel,
  4635. LeavesReader *pReaders, int *piReaders){
  4636. sqlite3_stmt *s;
  4637. int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s);
  4638. if( rc!=SQLITE_OK ) return rc;
  4639. rc = sqlite3_bind_int(s, 1, iLevel);
  4640. if( rc!=SQLITE_OK ) return rc;
  4641. i = 0;
  4642. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  4643. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  4644. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  4645. const char *pRootData = sqlite3_column_blob(s, 2);
  4646. int nRootData = sqlite3_column_bytes(s, 2);
  4647. assert( i<MERGE_COUNT );
  4648. rc = leavesReaderInit(v, i, iStart, iEnd, pRootData, nRootData,
  4649. &pReaders[i]);
  4650. if( rc!=SQLITE_OK ) break;
  4651. i++;
  4652. }
  4653. if( rc!=SQLITE_DONE ){
  4654. while( i-->0 ){
  4655. leavesReaderDestroy(&pReaders[i]);
  4656. }
  4657. return rc;
  4658. }
  4659. *piReaders = i;
  4660. /* Leave our results sorted by term, then age. */
  4661. while( i-- ){
  4662. leavesReaderReorder(pReaders+i, *piReaders-i);
  4663. }
  4664. return SQLITE_OK;
  4665. }
  4666. /* Merge doclists from pReaders[nReaders] into a single doclist, which
  4667. ** is written to pWriter. Assumes pReaders is ordered oldest to
  4668. ** newest.
  4669. */
  4670. /* TODO(shess) Consider putting this inline in segmentMerge(). */
  4671. static int leavesReadersMerge(fulltext_vtab *v,
  4672. LeavesReader *pReaders, int nReaders,
  4673. LeafWriter *pWriter){
  4674. DLReader dlReaders[MERGE_COUNT];
  4675. const char *pTerm = leavesReaderTerm(pReaders);
  4676. int i, nTerm = leavesReaderTermBytes(pReaders);
  4677. assert( nReaders<=MERGE_COUNT );
  4678. for(i=0; i<nReaders; i++){
  4679. dlrInit(&dlReaders[i], DL_DEFAULT,
  4680. leavesReaderData(pReaders+i),
  4681. leavesReaderDataBytes(pReaders+i));
  4682. }
  4683. return leafWriterStepMerge(v, pWriter, pTerm, nTerm, dlReaders, nReaders);
  4684. }
  4685. /* Forward ref due to mutual recursion with segdirNextIndex(). */
  4686. static int segmentMerge(fulltext_vtab *v, int iLevel);
  4687. /* Put the next available index at iLevel into *pidx. If iLevel
  4688. ** already has MERGE_COUNT segments, they are merged to a higher
  4689. ** level to make room.
  4690. */
  4691. static int segdirNextIndex(fulltext_vtab *v, int iLevel, int *pidx){
  4692. int rc = segdir_max_index(v, iLevel, pidx);
  4693. if( rc==SQLITE_DONE ){ /* No segments at iLevel. */
  4694. *pidx = 0;
  4695. }else if( rc==SQLITE_ROW ){
  4696. if( *pidx==(MERGE_COUNT-1) ){
  4697. rc = segmentMerge(v, iLevel);
  4698. if( rc!=SQLITE_OK ) return rc;
  4699. *pidx = 0;
  4700. }else{
  4701. (*pidx)++;
  4702. }
  4703. }else{
  4704. return rc;
  4705. }
  4706. return SQLITE_OK;
  4707. }
  4708. /* Merge MERGE_COUNT segments at iLevel into a new segment at
  4709. ** iLevel+1. If iLevel+1 is already full of segments, those will be
  4710. ** merged to make room.
  4711. */
  4712. static int segmentMerge(fulltext_vtab *v, int iLevel){
  4713. LeafWriter writer;
  4714. LeavesReader lrs[MERGE_COUNT];
  4715. int i, rc, idx = 0;
  4716. /* Determine the next available segment index at the next level,
  4717. ** merging as necessary.
  4718. */
  4719. rc = segdirNextIndex(v, iLevel+1, &idx);
  4720. if( rc!=SQLITE_OK ) return rc;
  4721. /* TODO(shess) This assumes that we'll always see exactly
  4722. ** MERGE_COUNT segments to merge at a given level. That will be
  4723. ** broken if we allow the developer to request preemptive or
  4724. ** deferred merging.
  4725. */
  4726. memset(&lrs, '\0', sizeof(lrs));
  4727. rc = leavesReadersInit(v, iLevel, lrs, &i);
  4728. if( rc!=SQLITE_OK ) return rc;
  4729. assert( i==MERGE_COUNT );
  4730. leafWriterInit(iLevel+1, idx, &writer);
  4731. /* Since leavesReaderReorder() pushes readers at eof to the end,
  4732. ** when the first reader is empty, all will be empty.
  4733. */
  4734. while( !leavesReaderAtEnd(lrs) ){
  4735. /* Figure out how many readers share their next term. */
  4736. for(i=1; i<MERGE_COUNT && !leavesReaderAtEnd(lrs+i); i++){
  4737. if( 0!=leavesReaderTermCmp(lrs, lrs+i) ) break;
  4738. }
  4739. rc = leavesReadersMerge(v, lrs, i, &writer);
  4740. if( rc!=SQLITE_OK ) goto err;
  4741. /* Step forward those that were merged. */
  4742. while( i-->0 ){
  4743. rc = leavesReaderStep(v, lrs+i);
  4744. if( rc!=SQLITE_OK ) goto err;
  4745. /* Reorder by term, then by age. */
  4746. leavesReaderReorder(lrs+i, MERGE_COUNT-i);
  4747. }
  4748. }
  4749. for(i=0; i<MERGE_COUNT; i++){
  4750. leavesReaderDestroy(&lrs[i]);
  4751. }
  4752. rc = leafWriterFinalize(v, &writer);
  4753. leafWriterDestroy(&writer);
  4754. if( rc!=SQLITE_OK ) return rc;
  4755. /* Delete the merged segment data. */
  4756. return segdir_delete(v, iLevel);
  4757. err:
  4758. for(i=0; i<MERGE_COUNT; i++){
  4759. leavesReaderDestroy(&lrs[i]);
  4760. }
  4761. leafWriterDestroy(&writer);
  4762. return rc;
  4763. }
  4764. /* Accumulate the union of *acc and *pData into *acc. */
  4765. static void docListAccumulateUnion(DataBuffer *acc,
  4766. const char *pData, int nData) {
  4767. DataBuffer tmp = *acc;
  4768. dataBufferInit(acc, tmp.nData+nData);
  4769. docListUnion(tmp.pData, tmp.nData, pData, nData, acc);
  4770. dataBufferDestroy(&tmp);
  4771. }
  4772. /* TODO(shess) It might be interesting to explore different merge
  4773. ** strategies, here. For instance, since this is a sorted merge, we
  4774. ** could easily merge many doclists in parallel. With some
  4775. ** comprehension of the storage format, we could merge all of the
  4776. ** doclists within a leaf node directly from the leaf node's storage.
  4777. ** It may be worthwhile to merge smaller doclists before larger
  4778. ** doclists, since they can be traversed more quickly - but the
  4779. ** results may have less overlap, making them more expensive in a
  4780. ** different way.
  4781. */
  4782. /* Scan pReader for pTerm/nTerm, and merge the term's doclist over
  4783. ** *out (any doclists with duplicate docids overwrite those in *out).
  4784. ** Internal function for loadSegmentLeaf().
  4785. */
  4786. static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader,
  4787. const char *pTerm, int nTerm, int isPrefix,
  4788. DataBuffer *out){
  4789. /* doclist data is accumulated into pBuffers similar to how one does
  4790. ** increment in binary arithmetic. If index 0 is empty, the data is
  4791. ** stored there. If there is data there, it is merged and the
  4792. ** results carried into position 1, with further merge-and-carry
  4793. ** until an empty position is found.
  4794. */
  4795. DataBuffer *pBuffers = NULL;
  4796. int nBuffers = 0, nMaxBuffers = 0, rc;
  4797. assert( nTerm>0 );
  4798. for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader);
  4799. rc=leavesReaderStep(v, pReader)){
  4800. /* TODO(shess) Really want leavesReaderTermCmp(), but that name is
  4801. ** already taken to compare the terms of two LeavesReaders. Think
  4802. ** on a better name. [Meanwhile, break encapsulation rather than
  4803. ** use a confusing name.]
  4804. */
  4805. int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix);
  4806. if( c>0 ) break; /* Past any possible matches. */
  4807. if( c==0 ){
  4808. const char *pData = leavesReaderData(pReader);
  4809. int iBuffer, nData = leavesReaderDataBytes(pReader);
  4810. /* Find the first empty buffer. */
  4811. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  4812. if( 0==pBuffers[iBuffer].nData ) break;
  4813. }
  4814. /* Out of buffers, add an empty one. */
  4815. if( iBuffer==nBuffers ){
  4816. if( nBuffers==nMaxBuffers ){
  4817. DataBuffer *p;
  4818. nMaxBuffers += 20;
  4819. /* Manual realloc so we can handle NULL appropriately. */
  4820. p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers));
  4821. if( p==NULL ){
  4822. rc = SQLITE_NOMEM;
  4823. break;
  4824. }
  4825. if( nBuffers>0 ){
  4826. assert(pBuffers!=NULL);
  4827. memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers));
  4828. sqlite3_free(pBuffers);
  4829. }
  4830. pBuffers = p;
  4831. }
  4832. dataBufferInit(&(pBuffers[nBuffers]), 0);
  4833. nBuffers++;
  4834. }
  4835. /* At this point, must have an empty at iBuffer. */
  4836. assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0);
  4837. /* If empty was first buffer, no need for merge logic. */
  4838. if( iBuffer==0 ){
  4839. dataBufferReplace(&(pBuffers[0]), pData, nData);
  4840. }else{
  4841. /* pAcc is the empty buffer the merged data will end up in. */
  4842. DataBuffer *pAcc = &(pBuffers[iBuffer]);
  4843. DataBuffer *p = &(pBuffers[0]);
  4844. /* Handle position 0 specially to avoid need to prime pAcc
  4845. ** with pData/nData.
  4846. */
  4847. dataBufferSwap(p, pAcc);
  4848. docListAccumulateUnion(pAcc, pData, nData);
  4849. /* Accumulate remaining doclists into pAcc. */
  4850. for(++p; p<pAcc; ++p){
  4851. docListAccumulateUnion(pAcc, p->pData, p->nData);
  4852. /* dataBufferReset() could allow a large doclist to blow up
  4853. ** our memory requirements.
  4854. */
  4855. if( p->nCapacity<1024 ){
  4856. dataBufferReset(p);
  4857. }else{
  4858. dataBufferDestroy(p);
  4859. dataBufferInit(p, 0);
  4860. }
  4861. }
  4862. }
  4863. }
  4864. }
  4865. /* Union all the doclists together into *out. */
  4866. /* TODO(shess) What if *out is big? Sigh. */
  4867. if( rc==SQLITE_OK && nBuffers>0 ){
  4868. int iBuffer;
  4869. for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){
  4870. if( pBuffers[iBuffer].nData>0 ){
  4871. if( out->nData==0 ){
  4872. dataBufferSwap(out, &(pBuffers[iBuffer]));
  4873. }else{
  4874. docListAccumulateUnion(out, pBuffers[iBuffer].pData,
  4875. pBuffers[iBuffer].nData);
  4876. }
  4877. }
  4878. }
  4879. }
  4880. while( nBuffers-- ){
  4881. dataBufferDestroy(&(pBuffers[nBuffers]));
  4882. }
  4883. if( pBuffers!=NULL ) sqlite3_free(pBuffers);
  4884. return rc;
  4885. }
  4886. /* Call loadSegmentLeavesInt() with pData/nData as input. */
  4887. static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData,
  4888. const char *pTerm, int nTerm, int isPrefix,
  4889. DataBuffer *out){
  4890. LeavesReader reader;
  4891. int rc;
  4892. assert( nData>1 );
  4893. assert( *pData=='\0' );
  4894. rc = leavesReaderInit(v, 0, 0, 0, pData, nData, &reader);
  4895. if( rc!=SQLITE_OK ) return rc;
  4896. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  4897. leavesReaderReset(&reader);
  4898. leavesReaderDestroy(&reader);
  4899. return rc;
  4900. }
  4901. /* Call loadSegmentLeavesInt() with the leaf nodes from iStartLeaf to
  4902. ** iEndLeaf (inclusive) as input, and merge the resulting doclist into
  4903. ** out.
  4904. */
  4905. static int loadSegmentLeaves(fulltext_vtab *v,
  4906. sqlite_int64 iStartLeaf, sqlite_int64 iEndLeaf,
  4907. const char *pTerm, int nTerm, int isPrefix,
  4908. DataBuffer *out){
  4909. int rc;
  4910. LeavesReader reader;
  4911. assert( iStartLeaf<=iEndLeaf );
  4912. rc = leavesReaderInit(v, 0, iStartLeaf, iEndLeaf, NULL, 0, &reader);
  4913. if( rc!=SQLITE_OK ) return rc;
  4914. rc = loadSegmentLeavesInt(v, &reader, pTerm, nTerm, isPrefix, out);
  4915. leavesReaderReset(&reader);
  4916. leavesReaderDestroy(&reader);
  4917. return rc;
  4918. }
  4919. /* Taking pData/nData as an interior node, find the sequence of child
  4920. ** nodes which could include pTerm/nTerm/isPrefix. Note that the
  4921. ** interior node terms logically come between the blocks, so there is
  4922. ** one more blockid than there are terms (that block contains terms >=
  4923. ** the last interior-node term).
  4924. */
  4925. /* TODO(shess) The calling code may already know that the end child is
  4926. ** not worth calculating, because the end may be in a later sibling
  4927. ** node. Consider whether breaking symmetry is worthwhile. I suspect
  4928. ** it is not worthwhile.
  4929. */
  4930. static void getChildrenContaining(const char *pData, int nData,
  4931. const char *pTerm, int nTerm, int isPrefix,
  4932. sqlite_int64 *piStartChild,
  4933. sqlite_int64 *piEndChild){
  4934. InteriorReader reader;
  4935. assert( nData>1 );
  4936. assert( *pData!='\0' );
  4937. interiorReaderInit(pData, nData, &reader);
  4938. /* Scan for the first child which could contain pTerm/nTerm. */
  4939. while( !interiorReaderAtEnd(&reader) ){
  4940. if( interiorReaderTermCmp(&reader, pTerm, nTerm, 0)>0 ) break;
  4941. interiorReaderStep(&reader);
  4942. }
  4943. *piStartChild = interiorReaderCurrentBlockid(&reader);
  4944. /* Keep scanning to find a term greater than our term, using prefix
  4945. ** comparison if indicated. If isPrefix is false, this will be the
  4946. ** same blockid as the starting block.
  4947. */
  4948. while( !interiorReaderAtEnd(&reader) ){
  4949. if( interiorReaderTermCmp(&reader, pTerm, nTerm, isPrefix)>0 ) break;
  4950. interiorReaderStep(&reader);
  4951. }
  4952. *piEndChild = interiorReaderCurrentBlockid(&reader);
  4953. interiorReaderDestroy(&reader);
  4954. /* Children must ascend, and if !prefix, both must be the same. */
  4955. assert( *piEndChild>=*piStartChild );
  4956. assert( isPrefix || *piStartChild==*piEndChild );
  4957. }
  4958. /* Read block at iBlockid and pass it with other params to
  4959. ** getChildrenContaining().
  4960. */
  4961. static int loadAndGetChildrenContaining(
  4962. fulltext_vtab *v,
  4963. sqlite_int64 iBlockid,
  4964. const char *pTerm, int nTerm, int isPrefix,
  4965. sqlite_int64 *piStartChild, sqlite_int64 *piEndChild
  4966. ){
  4967. sqlite3_stmt *s = NULL;
  4968. int rc;
  4969. assert( iBlockid!=0 );
  4970. assert( pTerm!=NULL );
  4971. assert( nTerm!=0 ); /* TODO(shess) Why not allow this? */
  4972. assert( piStartChild!=NULL );
  4973. assert( piEndChild!=NULL );
  4974. rc = sql_get_statement(v, BLOCK_SELECT_STMT, &s);
  4975. if( rc!=SQLITE_OK ) return rc;
  4976. rc = sqlite3_bind_int64(s, 1, iBlockid);
  4977. if( rc!=SQLITE_OK ) return rc;
  4978. rc = sqlite3_step(s);
  4979. if( rc==SQLITE_DONE ) return SQLITE_ERROR;
  4980. if( rc!=SQLITE_ROW ) return rc;
  4981. getChildrenContaining(sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0),
  4982. pTerm, nTerm, isPrefix, piStartChild, piEndChild);
  4983. /* We expect only one row. We must execute another sqlite3_step()
  4984. * to complete the iteration; otherwise the table will remain
  4985. * locked. */
  4986. rc = sqlite3_step(s);
  4987. if( rc==SQLITE_ROW ) return SQLITE_ERROR;
  4988. if( rc!=SQLITE_DONE ) return rc;
  4989. return SQLITE_OK;
  4990. }
  4991. /* Traverse the tree represented by pData[nData] looking for
  4992. ** pTerm[nTerm], placing its doclist into *out. This is internal to
  4993. ** loadSegment() to make error-handling cleaner.
  4994. */
  4995. static int loadSegmentInt(fulltext_vtab *v, const char *pData, int nData,
  4996. sqlite_int64 iLeavesEnd,
  4997. const char *pTerm, int nTerm, int isPrefix,
  4998. DataBuffer *out){
  4999. /* Special case where root is a leaf. */
  5000. if( *pData=='\0' ){
  5001. return loadSegmentLeaf(v, pData, nData, pTerm, nTerm, isPrefix, out);
  5002. }else{
  5003. int rc;
  5004. sqlite_int64 iStartChild, iEndChild;
  5005. /* Process pData as an interior node, then loop down the tree
  5006. ** until we find the set of leaf nodes to scan for the term.
  5007. */
  5008. getChildrenContaining(pData, nData, pTerm, nTerm, isPrefix,
  5009. &iStartChild, &iEndChild);
  5010. while( iStartChild>iLeavesEnd ){
  5011. sqlite_int64 iNextStart, iNextEnd;
  5012. rc = loadAndGetChildrenContaining(v, iStartChild, pTerm, nTerm, isPrefix,
  5013. &iNextStart, &iNextEnd);
  5014. if( rc!=SQLITE_OK ) return rc;
  5015. /* If we've branched, follow the end branch, too. */
  5016. if( iStartChild!=iEndChild ){
  5017. sqlite_int64 iDummy;
  5018. rc = loadAndGetChildrenContaining(v, iEndChild, pTerm, nTerm, isPrefix,
  5019. &iDummy, &iNextEnd);
  5020. if( rc!=SQLITE_OK ) return rc;
  5021. }
  5022. assert( iNextStart<=iNextEnd );
  5023. iStartChild = iNextStart;
  5024. iEndChild = iNextEnd;
  5025. }
  5026. assert( iStartChild<=iLeavesEnd );
  5027. assert( iEndChild<=iLeavesEnd );
  5028. /* Scan through the leaf segments for doclists. */
  5029. return loadSegmentLeaves(v, iStartChild, iEndChild,
  5030. pTerm, nTerm, isPrefix, out);
  5031. }
  5032. }
  5033. /* Call loadSegmentInt() to collect the doclist for pTerm/nTerm, then
  5034. ** merge its doclist over *out (any duplicate doclists read from the
  5035. ** segment rooted at pData will overwrite those in *out).
  5036. */
  5037. /* TODO(shess) Consider changing this to determine the depth of the
  5038. ** leaves using either the first characters of interior nodes (when
  5039. ** ==1, we're one level above the leaves), or the first character of
  5040. ** the root (which will describe the height of the tree directly).
  5041. ** Either feels somewhat tricky to me.
  5042. */
  5043. /* TODO(shess) The current merge is likely to be slow for large
  5044. ** doclists (though it should process from newest/smallest to
  5045. ** oldest/largest, so it may not be that bad). It might be useful to
  5046. ** modify things to allow for N-way merging. This could either be
  5047. ** within a segment, with pairwise merges across segments, or across
  5048. ** all segments at once.
  5049. */
  5050. static int loadSegment(fulltext_vtab *v, const char *pData, int nData,
  5051. sqlite_int64 iLeavesEnd,
  5052. const char *pTerm, int nTerm, int isPrefix,
  5053. DataBuffer *out){
  5054. DataBuffer result;
  5055. int rc;
  5056. assert( nData>1 );
  5057. /* This code should never be called with buffered updates. */
  5058. assert( v->nPendingData<0 );
  5059. dataBufferInit(&result, 0);
  5060. rc = loadSegmentInt(v, pData, nData, iLeavesEnd,
  5061. pTerm, nTerm, isPrefix, &result);
  5062. if( rc==SQLITE_OK && result.nData>0 ){
  5063. if( out->nData==0 ){
  5064. DataBuffer tmp = *out;
  5065. *out = result;
  5066. result = tmp;
  5067. }else{
  5068. DataBuffer merged;
  5069. DLReader readers[2];
  5070. dlrInit(&readers[0], DL_DEFAULT, out->pData, out->nData);
  5071. dlrInit(&readers[1], DL_DEFAULT, result.pData, result.nData);
  5072. dataBufferInit(&merged, out->nData+result.nData);
  5073. docListMerge(&merged, readers, 2);
  5074. dataBufferDestroy(out);
  5075. *out = merged;
  5076. dlrDestroy(&readers[0]);
  5077. dlrDestroy(&readers[1]);
  5078. }
  5079. }
  5080. dataBufferDestroy(&result);
  5081. return rc;
  5082. }
  5083. /* Scan the database and merge together the posting lists for the term
  5084. ** into *out.
  5085. */
  5086. static int termSelect(fulltext_vtab *v, int iColumn,
  5087. const char *pTerm, int nTerm, int isPrefix,
  5088. DocListType iType, DataBuffer *out){
  5089. DataBuffer doclist;
  5090. sqlite3_stmt *s;
  5091. int rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  5092. if( rc!=SQLITE_OK ) return rc;
  5093. /* This code should never be called with buffered updates. */
  5094. assert( v->nPendingData<0 );
  5095. dataBufferInit(&doclist, 0);
  5096. /* Traverse the segments from oldest to newest so that newer doclist
  5097. ** elements for given docids overwrite older elements.
  5098. */
  5099. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  5100. const char *pData = sqlite3_column_blob(s, 2);
  5101. const int nData = sqlite3_column_bytes(s, 2);
  5102. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  5103. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix,
  5104. &doclist);
  5105. if( rc!=SQLITE_OK ) goto err;
  5106. }
  5107. if( rc==SQLITE_DONE ){
  5108. if( doclist.nData!=0 ){
  5109. /* TODO(shess) The old term_select_all() code applied the column
  5110. ** restrict as we merged segments, leading to smaller buffers.
  5111. ** This is probably worthwhile to bring back, once the new storage
  5112. ** system is checked in.
  5113. */
  5114. if( iColumn==v->nColumn) iColumn = -1;
  5115. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  5116. iColumn, iType, out);
  5117. }
  5118. rc = SQLITE_OK;
  5119. }
  5120. err:
  5121. dataBufferDestroy(&doclist);
  5122. return rc;
  5123. }
  5124. /****************************************************************/
  5125. /* Used to hold hashtable data for sorting. */
  5126. typedef struct TermData {
  5127. const char *pTerm;
  5128. int nTerm;
  5129. DLCollector *pCollector;
  5130. } TermData;
  5131. /* Orders TermData elements in strcmp fashion ( <0 for less-than, 0
  5132. ** for equal, >0 for greater-than).
  5133. */
  5134. static int termDataCmp(const void *av, const void *bv){
  5135. const TermData *a = (const TermData *)av;
  5136. const TermData *b = (const TermData *)bv;
  5137. int n = a->nTerm<b->nTerm ? a->nTerm : b->nTerm;
  5138. int c = memcmp(a->pTerm, b->pTerm, n);
  5139. if( c!=0 ) return c;
  5140. return a->nTerm-b->nTerm;
  5141. }
  5142. /* Order pTerms data by term, then write a new level 0 segment using
  5143. ** LeafWriter.
  5144. */
  5145. static int writeZeroSegment(fulltext_vtab *v, fts2Hash *pTerms){
  5146. fts2HashElem *e;
  5147. int idx, rc, i, n;
  5148. TermData *pData;
  5149. LeafWriter writer;
  5150. DataBuffer dl;
  5151. /* Determine the next index at level 0, merging as necessary. */
  5152. rc = segdirNextIndex(v, 0, &idx);
  5153. if( rc!=SQLITE_OK ) return rc;
  5154. n = fts2HashCount(pTerms);
  5155. pData = sqlite3_malloc(n*sizeof(TermData));
  5156. for(i = 0, e = fts2HashFirst(pTerms); e; i++, e = fts2HashNext(e)){
  5157. assert( i<n );
  5158. pData[i].pTerm = fts2HashKey(e);
  5159. pData[i].nTerm = fts2HashKeysize(e);
  5160. pData[i].pCollector = fts2HashData(e);
  5161. }
  5162. assert( i==n );
  5163. /* TODO(shess) Should we allow user-defined collation sequences,
  5164. ** here? I think we only need that once we support prefix searches.
  5165. */
  5166. if( n>1 ) qsort(pData, n, sizeof(*pData), termDataCmp);
  5167. /* TODO(shess) Refactor so that we can write directly to the segment
  5168. ** DataBuffer, as happens for segment merges.
  5169. */
  5170. leafWriterInit(0, idx, &writer);
  5171. dataBufferInit(&dl, 0);
  5172. for(i=0; i<n; i++){
  5173. dataBufferReset(&dl);
  5174. dlcAddDoclist(pData[i].pCollector, &dl);
  5175. rc = leafWriterStep(v, &writer,
  5176. pData[i].pTerm, pData[i].nTerm, dl.pData, dl.nData);
  5177. if( rc!=SQLITE_OK ) goto err;
  5178. }
  5179. rc = leafWriterFinalize(v, &writer);
  5180. err:
  5181. dataBufferDestroy(&dl);
  5182. sqlite3_free(pData);
  5183. leafWriterDestroy(&writer);
  5184. return rc;
  5185. }
  5186. /* If pendingTerms has data, free it. */
  5187. static int clearPendingTerms(fulltext_vtab *v){
  5188. if( v->nPendingData>=0 ){
  5189. fts2HashElem *e;
  5190. for(e=fts2HashFirst(&v->pendingTerms); e; e=fts2HashNext(e)){
  5191. dlcDelete(fts2HashData(e));
  5192. }
  5193. fts2HashClear(&v->pendingTerms);
  5194. v->nPendingData = -1;
  5195. }
  5196. return SQLITE_OK;
  5197. }
  5198. /* If pendingTerms has data, flush it to a level-zero segment, and
  5199. ** free it.
  5200. */
  5201. static int flushPendingTerms(fulltext_vtab *v){
  5202. if( v->nPendingData>=0 ){
  5203. int rc = writeZeroSegment(v, &v->pendingTerms);
  5204. if( rc==SQLITE_OK ) clearPendingTerms(v);
  5205. return rc;
  5206. }
  5207. return SQLITE_OK;
  5208. }
  5209. /* If pendingTerms is "too big", or docid is out of order, flush it.
  5210. ** Regardless, be certain that pendingTerms is initialized for use.
  5211. */
  5212. static int initPendingTerms(fulltext_vtab *v, sqlite_int64 iDocid){
  5213. /* TODO(shess) Explore whether partially flushing the buffer on
  5214. ** forced-flush would provide better performance. I suspect that if
  5215. ** we ordered the doclists by size and flushed the largest until the
  5216. ** buffer was half empty, that would let the less frequent terms
  5217. ** generate longer doclists.
  5218. */
  5219. if( iDocid<=v->iPrevDocid || v->nPendingData>kPendingThreshold ){
  5220. int rc = flushPendingTerms(v);
  5221. if( rc!=SQLITE_OK ) return rc;
  5222. }
  5223. if( v->nPendingData<0 ){
  5224. fts2HashInit(&v->pendingTerms, FTS2_HASH_STRING, 1);
  5225. v->nPendingData = 0;
  5226. }
  5227. v->iPrevDocid = iDocid;
  5228. return SQLITE_OK;
  5229. }
  5230. /* This function implements the xUpdate callback; it is the top-level entry
  5231. * point for inserting, deleting or updating a row in a full-text table. */
  5232. static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg,
  5233. sqlite_int64 *pRowid){
  5234. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  5235. int rc;
  5236. TRACE(("FTS2 Update %p\n", pVtab));
  5237. if( nArg<2 ){
  5238. rc = index_delete(v, sqlite3_value_int64(ppArg[0]));
  5239. if( rc==SQLITE_OK ){
  5240. /* If we just deleted the last row in the table, clear out the
  5241. ** index data.
  5242. */
  5243. rc = content_exists(v);
  5244. if( rc==SQLITE_ROW ){
  5245. rc = SQLITE_OK;
  5246. }else if( rc==SQLITE_DONE ){
  5247. /* Clear the pending terms so we don't flush a useless level-0
  5248. ** segment when the transaction closes.
  5249. */
  5250. rc = clearPendingTerms(v);
  5251. if( rc==SQLITE_OK ){
  5252. rc = segdir_delete_all(v);
  5253. }
  5254. }
  5255. }
  5256. } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){
  5257. /* An update:
  5258. * ppArg[0] = old rowid
  5259. * ppArg[1] = new rowid
  5260. * ppArg[2..2+v->nColumn-1] = values
  5261. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  5262. */
  5263. sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]);
  5264. if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER ||
  5265. sqlite3_value_int64(ppArg[1]) != rowid ){
  5266. rc = SQLITE_ERROR; /* we don't allow changing the rowid */
  5267. } else {
  5268. assert( nArg==2+v->nColumn+1);
  5269. rc = index_update(v, rowid, &ppArg[2]);
  5270. }
  5271. } else {
  5272. /* An insert:
  5273. * ppArg[1] = requested rowid
  5274. * ppArg[2..2+v->nColumn-1] = values
  5275. * ppArg[2+v->nColumn] = value for magic column (we ignore this)
  5276. */
  5277. assert( nArg==2+v->nColumn+1);
  5278. rc = index_insert(v, ppArg[1], &ppArg[2], pRowid);
  5279. }
  5280. return rc;
  5281. }
  5282. static int fulltextSync(sqlite3_vtab *pVtab){
  5283. TRACE(("FTS2 xSync()\n"));
  5284. return flushPendingTerms((fulltext_vtab *)pVtab);
  5285. }
  5286. static int fulltextBegin(sqlite3_vtab *pVtab){
  5287. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  5288. TRACE(("FTS2 xBegin()\n"));
  5289. /* Any buffered updates should have been cleared by the previous
  5290. ** transaction.
  5291. */
  5292. assert( v->nPendingData<0 );
  5293. return clearPendingTerms(v);
  5294. }
  5295. static int fulltextCommit(sqlite3_vtab *pVtab){
  5296. fulltext_vtab *v = (fulltext_vtab *) pVtab;
  5297. TRACE(("FTS2 xCommit()\n"));
  5298. /* Buffered updates should have been cleared by fulltextSync(). */
  5299. assert( v->nPendingData<0 );
  5300. return clearPendingTerms(v);
  5301. }
  5302. static int fulltextRollback(sqlite3_vtab *pVtab){
  5303. TRACE(("FTS2 xRollback()\n"));
  5304. return clearPendingTerms((fulltext_vtab *)pVtab);
  5305. }
  5306. /*
  5307. ** Implementation of the snippet() function for FTS2
  5308. */
  5309. static void snippetFunc(
  5310. sqlite3_context *pContext,
  5311. int argc,
  5312. sqlite3_value **argv
  5313. ){
  5314. fulltext_cursor *pCursor;
  5315. if( argc<1 ) return;
  5316. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  5317. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  5318. sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1);
  5319. }else{
  5320. const char *zStart = "<b>";
  5321. const char *zEnd = "</b>";
  5322. const char *zEllipsis = "<b>...</b>";
  5323. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  5324. if( argc>=2 ){
  5325. zStart = (const char*)sqlite3_value_text(argv[1]);
  5326. if( argc>=3 ){
  5327. zEnd = (const char*)sqlite3_value_text(argv[2]);
  5328. if( argc>=4 ){
  5329. zEllipsis = (const char*)sqlite3_value_text(argv[3]);
  5330. }
  5331. }
  5332. }
  5333. snippetAllOffsets(pCursor);
  5334. snippetText(pCursor, zStart, zEnd, zEllipsis);
  5335. sqlite3_result_text(pContext, pCursor->snippet.zSnippet,
  5336. pCursor->snippet.nSnippet, SQLITE_STATIC);
  5337. }
  5338. }
  5339. /*
  5340. ** Implementation of the offsets() function for FTS2
  5341. */
  5342. static void snippetOffsetsFunc(
  5343. sqlite3_context *pContext,
  5344. int argc,
  5345. sqlite3_value **argv
  5346. ){
  5347. fulltext_cursor *pCursor;
  5348. if( argc<1 ) return;
  5349. if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  5350. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  5351. sqlite3_result_error(pContext, "illegal first argument to offsets",-1);
  5352. }else{
  5353. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  5354. snippetAllOffsets(pCursor);
  5355. snippetOffsetText(&pCursor->snippet);
  5356. sqlite3_result_text(pContext,
  5357. pCursor->snippet.zOffset, pCursor->snippet.nOffset,
  5358. SQLITE_STATIC);
  5359. }
  5360. }
  5361. /* OptLeavesReader is nearly identical to LeavesReader, except that
  5362. ** where LeavesReader is geared towards the merging of complete
  5363. ** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader
  5364. ** is geared towards implementation of the optimize() function, and
  5365. ** can merge all segments simultaneously. This version may be
  5366. ** somewhat less efficient than LeavesReader because it merges into an
  5367. ** accumulator rather than doing an N-way merge, but since segment
  5368. ** size grows exponentially (so segment count logrithmically) this is
  5369. ** probably not an immediate problem.
  5370. */
  5371. /* TODO(shess): Prove that assertion, or extend the merge code to
  5372. ** merge tree fashion (like the prefix-searching code does).
  5373. */
  5374. /* TODO(shess): OptLeavesReader and LeavesReader could probably be
  5375. ** merged with little or no loss of performance for LeavesReader. The
  5376. ** merged code would need to handle >MERGE_COUNT segments, and would
  5377. ** also need to be able to optionally optimize away deletes.
  5378. */
  5379. typedef struct OptLeavesReader {
  5380. /* Segment number, to order readers by age. */
  5381. int segment;
  5382. LeavesReader reader;
  5383. } OptLeavesReader;
  5384. static int optLeavesReaderAtEnd(OptLeavesReader *pReader){
  5385. return leavesReaderAtEnd(&pReader->reader);
  5386. }
  5387. static int optLeavesReaderTermBytes(OptLeavesReader *pReader){
  5388. return leavesReaderTermBytes(&pReader->reader);
  5389. }
  5390. static const char *optLeavesReaderData(OptLeavesReader *pReader){
  5391. return leavesReaderData(&pReader->reader);
  5392. }
  5393. static int optLeavesReaderDataBytes(OptLeavesReader *pReader){
  5394. return leavesReaderDataBytes(&pReader->reader);
  5395. }
  5396. static const char *optLeavesReaderTerm(OptLeavesReader *pReader){
  5397. return leavesReaderTerm(&pReader->reader);
  5398. }
  5399. static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){
  5400. return leavesReaderStep(v, &pReader->reader);
  5401. }
  5402. static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  5403. return leavesReaderTermCmp(&lr1->reader, &lr2->reader);
  5404. }
  5405. /* Order by term ascending, segment ascending (oldest to newest), with
  5406. ** exhausted readers to the end.
  5407. */
  5408. static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){
  5409. int c = optLeavesReaderTermCmp(lr1, lr2);
  5410. if( c!=0 ) return c;
  5411. return lr1->segment-lr2->segment;
  5412. }
  5413. /* Bubble pLr[0] to appropriate place in pLr[1..nLr-1]. Assumes that
  5414. ** pLr[1..nLr-1] is already sorted.
  5415. */
  5416. static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){
  5417. while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){
  5418. OptLeavesReader tmp = pLr[0];
  5419. pLr[0] = pLr[1];
  5420. pLr[1] = tmp;
  5421. nLr--;
  5422. pLr++;
  5423. }
  5424. }
  5425. /* optimize() helper function. Put the readers in order and iterate
  5426. ** through them, merging doclists for matching terms into pWriter.
  5427. ** Returns SQLITE_OK on success, or the SQLite error code which
  5428. ** prevented success.
  5429. */
  5430. static int optimizeInternal(fulltext_vtab *v,
  5431. OptLeavesReader *readers, int nReaders,
  5432. LeafWriter *pWriter){
  5433. int i, rc = SQLITE_OK;
  5434. DataBuffer doclist, merged, tmp;
  5435. /* Order the readers. */
  5436. i = nReaders;
  5437. while( i-- > 0 ){
  5438. optLeavesReaderReorder(&readers[i], nReaders-i);
  5439. }
  5440. dataBufferInit(&doclist, LEAF_MAX);
  5441. dataBufferInit(&merged, LEAF_MAX);
  5442. /* Exhausted readers bubble to the end, so when the first reader is
  5443. ** at eof, all are at eof.
  5444. */
  5445. while( !optLeavesReaderAtEnd(&readers[0]) ){
  5446. /* Figure out how many readers share the next term. */
  5447. for(i=1; i<nReaders && !optLeavesReaderAtEnd(&readers[i]); i++){
  5448. if( 0!=optLeavesReaderTermCmp(&readers[0], &readers[i]) ) break;
  5449. }
  5450. /* Special-case for no merge. */
  5451. if( i==1 ){
  5452. /* Trim deletions from the doclist. */
  5453. dataBufferReset(&merged);
  5454. docListTrim(DL_DEFAULT,
  5455. optLeavesReaderData(&readers[0]),
  5456. optLeavesReaderDataBytes(&readers[0]),
  5457. -1, DL_DEFAULT, &merged);
  5458. }else{
  5459. DLReader dlReaders[MERGE_COUNT];
  5460. int iReader, nReaders;
  5461. /* Prime the pipeline with the first reader's doclist. After
  5462. ** one pass index 0 will reference the accumulated doclist.
  5463. */
  5464. dlrInit(&dlReaders[0], DL_DEFAULT,
  5465. optLeavesReaderData(&readers[0]),
  5466. optLeavesReaderDataBytes(&readers[0]));
  5467. iReader = 1;
  5468. assert( iReader<i ); /* Must execute the loop at least once. */
  5469. while( iReader<i ){
  5470. /* Merge 16 inputs per pass. */
  5471. for( nReaders=1; iReader<i && nReaders<MERGE_COUNT;
  5472. iReader++, nReaders++ ){
  5473. dlrInit(&dlReaders[nReaders], DL_DEFAULT,
  5474. optLeavesReaderData(&readers[iReader]),
  5475. optLeavesReaderDataBytes(&readers[iReader]));
  5476. }
  5477. /* Merge doclists and swap result into accumulator. */
  5478. dataBufferReset(&merged);
  5479. docListMerge(&merged, dlReaders, nReaders);
  5480. tmp = merged;
  5481. merged = doclist;
  5482. doclist = tmp;
  5483. while( nReaders-- > 0 ){
  5484. dlrDestroy(&dlReaders[nReaders]);
  5485. }
  5486. /* Accumulated doclist to reader 0 for next pass. */
  5487. dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData);
  5488. }
  5489. /* Destroy reader that was left in the pipeline. */
  5490. dlrDestroy(&dlReaders[0]);
  5491. /* Trim deletions from the doclist. */
  5492. dataBufferReset(&merged);
  5493. docListTrim(DL_DEFAULT, doclist.pData, doclist.nData,
  5494. -1, DL_DEFAULT, &merged);
  5495. }
  5496. /* Only pass doclists with hits (skip if all hits deleted). */
  5497. if( merged.nData>0 ){
  5498. rc = leafWriterStep(v, pWriter,
  5499. optLeavesReaderTerm(&readers[0]),
  5500. optLeavesReaderTermBytes(&readers[0]),
  5501. merged.pData, merged.nData);
  5502. if( rc!=SQLITE_OK ) goto err;
  5503. }
  5504. /* Step merged readers to next term and reorder. */
  5505. while( i-- > 0 ){
  5506. rc = optLeavesReaderStep(v, &readers[i]);
  5507. if( rc!=SQLITE_OK ) goto err;
  5508. optLeavesReaderReorder(&readers[i], nReaders-i);
  5509. }
  5510. }
  5511. err:
  5512. dataBufferDestroy(&doclist);
  5513. dataBufferDestroy(&merged);
  5514. return rc;
  5515. }
  5516. /* Implement optimize() function for FTS3. optimize(t) merges all
  5517. ** segments in the fts index into a single segment. 't' is the magic
  5518. ** table-named column.
  5519. */
  5520. static void optimizeFunc(sqlite3_context *pContext,
  5521. int argc, sqlite3_value **argv){
  5522. fulltext_cursor *pCursor;
  5523. if( argc>1 ){
  5524. sqlite3_result_error(pContext, "excess arguments to optimize()",-1);
  5525. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  5526. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  5527. sqlite3_result_error(pContext, "illegal first argument to optimize",-1);
  5528. }else{
  5529. fulltext_vtab *v;
  5530. int i, rc, iMaxLevel;
  5531. OptLeavesReader *readers;
  5532. int nReaders;
  5533. LeafWriter writer;
  5534. sqlite3_stmt *s;
  5535. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  5536. v = cursor_vtab(pCursor);
  5537. /* Flush any buffered updates before optimizing. */
  5538. rc = flushPendingTerms(v);
  5539. if( rc!=SQLITE_OK ) goto err;
  5540. rc = segdir_count(v, &nReaders, &iMaxLevel);
  5541. if( rc!=SQLITE_OK ) goto err;
  5542. if( nReaders==0 || nReaders==1 ){
  5543. sqlite3_result_text(pContext, "Index already optimal", -1,
  5544. SQLITE_STATIC);
  5545. return;
  5546. }
  5547. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  5548. if( rc!=SQLITE_OK ) goto err;
  5549. readers = sqlite3_malloc(nReaders*sizeof(readers[0]));
  5550. if( readers==NULL ) goto err;
  5551. /* Note that there will already be a segment at this position
  5552. ** until we call segdir_delete() on iMaxLevel.
  5553. */
  5554. leafWriterInit(iMaxLevel, 0, &writer);
  5555. i = 0;
  5556. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  5557. sqlite_int64 iStart = sqlite3_column_int64(s, 0);
  5558. sqlite_int64 iEnd = sqlite3_column_int64(s, 1);
  5559. const char *pRootData = sqlite3_column_blob(s, 2);
  5560. int nRootData = sqlite3_column_bytes(s, 2);
  5561. assert( i<nReaders );
  5562. rc = leavesReaderInit(v, -1, iStart, iEnd, pRootData, nRootData,
  5563. &readers[i].reader);
  5564. if( rc!=SQLITE_OK ) break;
  5565. readers[i].segment = i;
  5566. i++;
  5567. }
  5568. /* If we managed to successfully read them all, optimize them. */
  5569. if( rc==SQLITE_DONE ){
  5570. assert( i==nReaders );
  5571. rc = optimizeInternal(v, readers, nReaders, &writer);
  5572. }
  5573. while( i-- > 0 ){
  5574. leavesReaderDestroy(&readers[i].reader);
  5575. }
  5576. sqlite3_free(readers);
  5577. /* If we've successfully gotten to here, delete the old segments
  5578. ** and flush the interior structure of the new segment.
  5579. */
  5580. if( rc==SQLITE_OK ){
  5581. for( i=0; i<=iMaxLevel; i++ ){
  5582. rc = segdir_delete(v, i);
  5583. if( rc!=SQLITE_OK ) break;
  5584. }
  5585. if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer);
  5586. }
  5587. leafWriterDestroy(&writer);
  5588. if( rc!=SQLITE_OK ) goto err;
  5589. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  5590. return;
  5591. /* TODO(shess): Error-handling needs to be improved along the
  5592. ** lines of the dump_ functions.
  5593. */
  5594. err:
  5595. {
  5596. char buf[512];
  5597. sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s",
  5598. sqlite3_errmsg(sqlite3_context_db_handle(pContext)));
  5599. sqlite3_result_error(pContext, buf, -1);
  5600. }
  5601. }
  5602. }
  5603. #ifdef SQLITE_TEST
  5604. /* Generate an error of the form "<prefix>: <msg>". If msg is NULL,
  5605. ** pull the error from the context's db handle.
  5606. */
  5607. static void generateError(sqlite3_context *pContext,
  5608. const char *prefix, const char *msg){
  5609. char buf[512];
  5610. if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext));
  5611. sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg);
  5612. sqlite3_result_error(pContext, buf, -1);
  5613. }
  5614. /* Helper function to collect the set of terms in the segment into
  5615. ** pTerms. The segment is defined by the leaf nodes between
  5616. ** iStartBlockid and iEndBlockid, inclusive, or by the contents of
  5617. ** pRootData if iStartBlockid is 0 (in which case the entire segment
  5618. ** fit in a leaf).
  5619. */
  5620. static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s,
  5621. fts2Hash *pTerms){
  5622. const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0);
  5623. const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1);
  5624. const char *pRootData = sqlite3_column_blob(s, 2);
  5625. const int nRootData = sqlite3_column_bytes(s, 2);
  5626. LeavesReader reader;
  5627. int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid,
  5628. pRootData, nRootData, &reader);
  5629. if( rc!=SQLITE_OK ) return rc;
  5630. while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){
  5631. const char *pTerm = leavesReaderTerm(&reader);
  5632. const int nTerm = leavesReaderTermBytes(&reader);
  5633. void *oldValue = sqlite3Fts2HashFind(pTerms, pTerm, nTerm);
  5634. void *newValue = (void *)((char *)oldValue+1);
  5635. /* From the comment before sqlite3Fts2HashInsert in fts2_hash.c,
  5636. ** the data value passed is returned in case of malloc failure.
  5637. */
  5638. if( newValue==sqlite3Fts2HashInsert(pTerms, pTerm, nTerm, newValue) ){
  5639. rc = SQLITE_NOMEM;
  5640. }else{
  5641. rc = leavesReaderStep(v, &reader);
  5642. }
  5643. }
  5644. leavesReaderDestroy(&reader);
  5645. return rc;
  5646. }
  5647. /* Helper function to build the result string for dump_terms(). */
  5648. static int generateTermsResult(sqlite3_context *pContext, fts2Hash *pTerms){
  5649. int iTerm, nTerms, nResultBytes, iByte;
  5650. char *result;
  5651. TermData *pData;
  5652. fts2HashElem *e;
  5653. /* Iterate pTerms to generate an array of terms in pData for
  5654. ** sorting.
  5655. */
  5656. nTerms = fts2HashCount(pTerms);
  5657. assert( nTerms>0 );
  5658. pData = sqlite3_malloc(nTerms*sizeof(TermData));
  5659. if( pData==NULL ) return SQLITE_NOMEM;
  5660. nResultBytes = 0;
  5661. for(iTerm = 0, e = fts2HashFirst(pTerms); e; iTerm++, e = fts2HashNext(e)){
  5662. nResultBytes += fts2HashKeysize(e)+1; /* Term plus trailing space */
  5663. assert( iTerm<nTerms );
  5664. pData[iTerm].pTerm = fts2HashKey(e);
  5665. pData[iTerm].nTerm = fts2HashKeysize(e);
  5666. pData[iTerm].pCollector = fts2HashData(e); /* unused */
  5667. }
  5668. assert( iTerm==nTerms );
  5669. assert( nResultBytes>0 ); /* nTerms>0, nResultsBytes must be, too. */
  5670. result = sqlite3_malloc(nResultBytes);
  5671. if( result==NULL ){
  5672. sqlite3_free(pData);
  5673. return SQLITE_NOMEM;
  5674. }
  5675. if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp);
  5676. /* Read the terms in order to build the result. */
  5677. iByte = 0;
  5678. for(iTerm=0; iTerm<nTerms; ++iTerm){
  5679. memcpy(result+iByte, pData[iTerm].pTerm, pData[iTerm].nTerm);
  5680. iByte += pData[iTerm].nTerm;
  5681. result[iByte++] = ' ';
  5682. }
  5683. assert( iByte==nResultBytes );
  5684. assert( result[nResultBytes-1]==' ' );
  5685. result[nResultBytes-1] = '\0';
  5686. /* Passes away ownership of result. */
  5687. sqlite3_result_text(pContext, result, nResultBytes-1, sqlite3_free);
  5688. sqlite3_free(pData);
  5689. return SQLITE_OK;
  5690. }
  5691. /* Implements dump_terms() for use in inspecting the fts2 index from
  5692. ** tests. TEXT result containing the ordered list of terms joined by
  5693. ** spaces. dump_terms(t, level, idx) dumps the terms for the segment
  5694. ** specified by level, idx (in %_segdir), while dump_terms(t) dumps
  5695. ** all terms in the index. In both cases t is the fts table's magic
  5696. ** table-named column.
  5697. */
  5698. static void dumpTermsFunc(
  5699. sqlite3_context *pContext,
  5700. int argc, sqlite3_value **argv
  5701. ){
  5702. fulltext_cursor *pCursor;
  5703. if( argc!=3 && argc!=1 ){
  5704. generateError(pContext, "dump_terms", "incorrect arguments");
  5705. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  5706. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  5707. generateError(pContext, "dump_terms", "illegal first argument");
  5708. }else{
  5709. fulltext_vtab *v;
  5710. fts2Hash terms;
  5711. sqlite3_stmt *s = NULL;
  5712. int rc;
  5713. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  5714. v = cursor_vtab(pCursor);
  5715. /* If passed only the cursor column, get all segments. Otherwise
  5716. ** get the segment described by the following two arguments.
  5717. */
  5718. if( argc==1 ){
  5719. rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s);
  5720. }else{
  5721. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  5722. if( rc==SQLITE_OK ){
  5723. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[1]));
  5724. if( rc==SQLITE_OK ){
  5725. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[2]));
  5726. }
  5727. }
  5728. }
  5729. if( rc!=SQLITE_OK ){
  5730. generateError(pContext, "dump_terms", NULL);
  5731. return;
  5732. }
  5733. /* Collect the terms for each segment. */
  5734. sqlite3Fts2HashInit(&terms, FTS2_HASH_STRING, 1);
  5735. while( (rc = sqlite3_step(s))==SQLITE_ROW ){
  5736. rc = collectSegmentTerms(v, s, &terms);
  5737. if( rc!=SQLITE_OK ) break;
  5738. }
  5739. if( rc!=SQLITE_DONE ){
  5740. sqlite3_reset(s);
  5741. generateError(pContext, "dump_terms", NULL);
  5742. }else{
  5743. const int nTerms = fts2HashCount(&terms);
  5744. if( nTerms>0 ){
  5745. rc = generateTermsResult(pContext, &terms);
  5746. if( rc==SQLITE_NOMEM ){
  5747. generateError(pContext, "dump_terms", "out of memory");
  5748. }else{
  5749. assert( rc==SQLITE_OK );
  5750. }
  5751. }else if( argc==3 ){
  5752. /* The specific segment asked for could not be found. */
  5753. generateError(pContext, "dump_terms", "segment not found");
  5754. }else{
  5755. /* No segments found. */
  5756. /* TODO(shess): It should be impossible to reach this. This
  5757. ** case can only happen for an empty table, in which case
  5758. ** SQLite has no rows to call this function on.
  5759. */
  5760. sqlite3_result_null(pContext);
  5761. }
  5762. }
  5763. sqlite3Fts2HashClear(&terms);
  5764. }
  5765. }
  5766. /* Expand the DL_DEFAULT doclist in pData into a text result in
  5767. ** pContext.
  5768. */
  5769. static void createDoclistResult(sqlite3_context *pContext,
  5770. const char *pData, int nData){
  5771. DataBuffer dump;
  5772. DLReader dlReader;
  5773. assert( pData!=NULL && nData>0 );
  5774. dataBufferInit(&dump, 0);
  5775. dlrInit(&dlReader, DL_DEFAULT, pData, nData);
  5776. for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){
  5777. char buf[256];
  5778. PLReader plReader;
  5779. plrInit(&plReader, &dlReader);
  5780. if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){
  5781. sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader));
  5782. dataBufferAppend(&dump, buf, strlen(buf));
  5783. }else{
  5784. int iColumn = plrColumn(&plReader);
  5785. sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[",
  5786. dlrDocid(&dlReader), iColumn);
  5787. dataBufferAppend(&dump, buf, strlen(buf));
  5788. for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){
  5789. if( plrColumn(&plReader)!=iColumn ){
  5790. iColumn = plrColumn(&plReader);
  5791. sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn);
  5792. assert( dump.nData>0 );
  5793. dump.nData--; /* Overwrite trailing space. */
  5794. assert( dump.pData[dump.nData]==' ');
  5795. dataBufferAppend(&dump, buf, strlen(buf));
  5796. }
  5797. if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){
  5798. sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ",
  5799. plrPosition(&plReader),
  5800. plrStartOffset(&plReader), plrEndOffset(&plReader));
  5801. }else if( DL_DEFAULT==DL_POSITIONS ){
  5802. sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader));
  5803. }else{
  5804. assert( NULL=="Unhandled DL_DEFAULT value");
  5805. }
  5806. dataBufferAppend(&dump, buf, strlen(buf));
  5807. }
  5808. plrDestroy(&plReader);
  5809. assert( dump.nData>0 );
  5810. dump.nData--; /* Overwrite trailing space. */
  5811. assert( dump.pData[dump.nData]==' ');
  5812. dataBufferAppend(&dump, "]] ", 3);
  5813. }
  5814. }
  5815. dlrDestroy(&dlReader);
  5816. assert( dump.nData>0 );
  5817. dump.nData--; /* Overwrite trailing space. */
  5818. assert( dump.pData[dump.nData]==' ');
  5819. dump.pData[dump.nData] = '\0';
  5820. assert( dump.nData>0 );
  5821. /* Passes ownership of dump's buffer to pContext. */
  5822. sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free);
  5823. dump.pData = NULL;
  5824. dump.nData = dump.nCapacity = 0;
  5825. }
  5826. /* Implements dump_doclist() for use in inspecting the fts2 index from
  5827. ** tests. TEXT result containing a string representation of the
  5828. ** doclist for the indicated term. dump_doclist(t, term, level, idx)
  5829. ** dumps the doclist for term from the segment specified by level, idx
  5830. ** (in %_segdir), while dump_doclist(t, term) dumps the logical
  5831. ** doclist for the term across all segments. The per-segment doclist
  5832. ** can contain deletions, while the full-index doclist will not
  5833. ** (deletions are omitted).
  5834. **
  5835. ** Result formats differ with the setting of DL_DEFAULTS. Examples:
  5836. **
  5837. ** DL_DOCIDS: [1] [3] [7]
  5838. ** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]]
  5839. ** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]]
  5840. **
  5841. ** In each case the number after the outer '[' is the docid. In the
  5842. ** latter two cases, the number before the inner '[' is the column
  5843. ** associated with the values within. For DL_POSITIONS the numbers
  5844. ** within are the positions, for DL_POSITIONS_OFFSETS they are the
  5845. ** position, the start offset, and the end offset.
  5846. */
  5847. static void dumpDoclistFunc(
  5848. sqlite3_context *pContext,
  5849. int argc, sqlite3_value **argv
  5850. ){
  5851. fulltext_cursor *pCursor;
  5852. if( argc!=2 && argc!=4 ){
  5853. generateError(pContext, "dump_doclist", "incorrect arguments");
  5854. }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB ||
  5855. sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){
  5856. generateError(pContext, "dump_doclist", "illegal first argument");
  5857. }else if( sqlite3_value_text(argv[1])==NULL ||
  5858. sqlite3_value_text(argv[1])[0]=='\0' ){
  5859. generateError(pContext, "dump_doclist", "empty second argument");
  5860. }else{
  5861. const char *pTerm = (const char *)sqlite3_value_text(argv[1]);
  5862. const int nTerm = strlen(pTerm);
  5863. fulltext_vtab *v;
  5864. int rc;
  5865. DataBuffer doclist;
  5866. memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor));
  5867. v = cursor_vtab(pCursor);
  5868. dataBufferInit(&doclist, 0);
  5869. /* termSelect() yields the same logical doclist that queries are
  5870. ** run against.
  5871. */
  5872. if( argc==2 ){
  5873. rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist);
  5874. }else{
  5875. sqlite3_stmt *s = NULL;
  5876. /* Get our specific segment's information. */
  5877. rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s);
  5878. if( rc==SQLITE_OK ){
  5879. rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2]));
  5880. if( rc==SQLITE_OK ){
  5881. rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3]));
  5882. }
  5883. }
  5884. if( rc==SQLITE_OK ){
  5885. rc = sqlite3_step(s);
  5886. if( rc==SQLITE_DONE ){
  5887. dataBufferDestroy(&doclist);
  5888. generateError(pContext, "dump_doclist", "segment not found");
  5889. return;
  5890. }
  5891. /* Found a segment, load it into doclist. */
  5892. if( rc==SQLITE_ROW ){
  5893. const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1);
  5894. const char *pData = sqlite3_column_blob(s, 2);
  5895. const int nData = sqlite3_column_bytes(s, 2);
  5896. /* loadSegment() is used by termSelect() to load each
  5897. ** segment's data.
  5898. */
  5899. rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0,
  5900. &doclist);
  5901. if( rc==SQLITE_OK ){
  5902. rc = sqlite3_step(s);
  5903. /* Should not have more than one matching segment. */
  5904. if( rc!=SQLITE_DONE ){
  5905. sqlite3_reset(s);
  5906. dataBufferDestroy(&doclist);
  5907. generateError(pContext, "dump_doclist", "invalid segdir");
  5908. return;
  5909. }
  5910. rc = SQLITE_OK;
  5911. }
  5912. }
  5913. }
  5914. sqlite3_reset(s);
  5915. }
  5916. if( rc==SQLITE_OK ){
  5917. if( doclist.nData>0 ){
  5918. createDoclistResult(pContext, doclist.pData, doclist.nData);
  5919. }else{
  5920. /* TODO(shess): This can happen if the term is not present, or
  5921. ** if all instances of the term have been deleted and this is
  5922. ** an all-index dump. It may be interesting to distinguish
  5923. ** these cases.
  5924. */
  5925. sqlite3_result_text(pContext, "", 0, SQLITE_STATIC);
  5926. }
  5927. }else if( rc==SQLITE_NOMEM ){
  5928. /* Handle out-of-memory cases specially because if they are
  5929. ** generated in fts2 code they may not be reflected in the db
  5930. ** handle.
  5931. */
  5932. /* TODO(shess): Handle this more comprehensively.
  5933. ** sqlite3ErrStr() has what I need, but is internal.
  5934. */
  5935. generateError(pContext, "dump_doclist", "out of memory");
  5936. }else{
  5937. generateError(pContext, "dump_doclist", NULL);
  5938. }
  5939. dataBufferDestroy(&doclist);
  5940. }
  5941. }
  5942. #endif
  5943. /*
  5944. ** This routine implements the xFindFunction method for the FTS2
  5945. ** virtual table.
  5946. */
  5947. static int fulltextFindFunction(
  5948. sqlite3_vtab *pVtab,
  5949. int nArg,
  5950. const char *zName,
  5951. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5952. void **ppArg
  5953. ){
  5954. if( strcmp(zName,"snippet")==0 ){
  5955. *pxFunc = snippetFunc;
  5956. return 1;
  5957. }else if( strcmp(zName,"offsets")==0 ){
  5958. *pxFunc = snippetOffsetsFunc;
  5959. return 1;
  5960. }else if( strcmp(zName,"optimize")==0 ){
  5961. *pxFunc = optimizeFunc;
  5962. return 1;
  5963. #ifdef SQLITE_TEST
  5964. /* NOTE(shess): These functions are present only for testing
  5965. ** purposes. No particular effort is made to optimize their
  5966. ** execution or how they build their results.
  5967. */
  5968. }else if( strcmp(zName,"dump_terms")==0 ){
  5969. /* fprintf(stderr, "Found dump_terms\n"); */
  5970. *pxFunc = dumpTermsFunc;
  5971. return 1;
  5972. }else if( strcmp(zName,"dump_doclist")==0 ){
  5973. /* fprintf(stderr, "Found dump_doclist\n"); */
  5974. *pxFunc = dumpDoclistFunc;
  5975. return 1;
  5976. #endif
  5977. }
  5978. return 0;
  5979. }
  5980. /*
  5981. ** Rename an fts2 table.
  5982. */
  5983. static int fulltextRename(
  5984. sqlite3_vtab *pVtab,
  5985. const char *zName
  5986. ){
  5987. fulltext_vtab *p = (fulltext_vtab *)pVtab;
  5988. int rc = SQLITE_NOMEM;
  5989. char *zSql = sqlite3_mprintf(
  5990. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';"
  5991. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
  5992. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';"
  5993. , p->zDb, p->zName, zName
  5994. , p->zDb, p->zName, zName
  5995. , p->zDb, p->zName, zName
  5996. );
  5997. if( zSql ){
  5998. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  5999. sqlite3_free(zSql);
  6000. }
  6001. return rc;
  6002. }
  6003. static const sqlite3_module fts2Module = {
  6004. /* iVersion */ 0,
  6005. /* xCreate */ fulltextCreate,
  6006. /* xConnect */ fulltextConnect,
  6007. /* xBestIndex */ fulltextBestIndex,
  6008. /* xDisconnect */ fulltextDisconnect,
  6009. /* xDestroy */ fulltextDestroy,
  6010. /* xOpen */ fulltextOpen,
  6011. /* xClose */ fulltextClose,
  6012. /* xFilter */ fulltextFilter,
  6013. /* xNext */ fulltextNext,
  6014. /* xEof */ fulltextEof,
  6015. /* xColumn */ fulltextColumn,
  6016. /* xRowid */ fulltextRowid,
  6017. /* xUpdate */ fulltextUpdate,
  6018. /* xBegin */ fulltextBegin,
  6019. /* xSync */ fulltextSync,
  6020. /* xCommit */ fulltextCommit,
  6021. /* xRollback */ fulltextRollback,
  6022. /* xFindFunction */ fulltextFindFunction,
  6023. /* xRename */ fulltextRename,
  6024. };
  6025. static void hashDestroy(void *p){
  6026. fts2Hash *pHash = (fts2Hash *)p;
  6027. sqlite3Fts2HashClear(pHash);
  6028. sqlite3_free(pHash);
  6029. }
  6030. /*
  6031. ** The fts2 built-in tokenizers - "simple" and "porter" - are implemented
  6032. ** in files fts2_tokenizer1.c and fts2_porter.c respectively. The following
  6033. ** two forward declarations are for functions declared in these files
  6034. ** used to retrieve the respective implementations.
  6035. **
  6036. ** Calling sqlite3Fts2SimpleTokenizerModule() sets the value pointed
  6037. ** to by the argument to point a the "simple" tokenizer implementation.
  6038. ** Function ...PorterTokenizerModule() sets *pModule to point to the
  6039. ** porter tokenizer/stemmer implementation.
  6040. */
  6041. void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  6042. void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  6043. void sqlite3Fts2IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  6044. int sqlite3Fts2InitHashTable(sqlite3 *, fts2Hash *, const char *);
  6045. /*
  6046. ** Initialize the fts2 extension. If this extension is built as part
  6047. ** of the sqlite library, then this function is called directly by
  6048. ** SQLite. If fts2 is built as a dynamically loadable extension, this
  6049. ** function is called by the sqlite3_extension_init() entry point.
  6050. */
  6051. int sqlite3Fts2Init(sqlite3 *db){
  6052. int rc = SQLITE_OK;
  6053. fts2Hash *pHash = 0;
  6054. const sqlite3_tokenizer_module *pSimple = 0;
  6055. const sqlite3_tokenizer_module *pPorter = 0;
  6056. const sqlite3_tokenizer_module *pIcu = 0;
  6057. sqlite3Fts2SimpleTokenizerModule(&pSimple);
  6058. sqlite3Fts2PorterTokenizerModule(&pPorter);
  6059. #ifdef SQLITE_ENABLE_ICU
  6060. sqlite3Fts2IcuTokenizerModule(&pIcu);
  6061. #endif
  6062. /* Allocate and initialize the hash-table used to store tokenizers. */
  6063. pHash = sqlite3_malloc(sizeof(fts2Hash));
  6064. if( !pHash ){
  6065. rc = SQLITE_NOMEM;
  6066. }else{
  6067. sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
  6068. }
  6069. /* Load the built-in tokenizers into the hash table */
  6070. if( rc==SQLITE_OK ){
  6071. if( sqlite3Fts2HashInsert(pHash, "simple", 7, (void *)pSimple)
  6072. || sqlite3Fts2HashInsert(pHash, "porter", 7, (void *)pPorter)
  6073. || (pIcu && sqlite3Fts2HashInsert(pHash, "icu", 4, (void *)pIcu))
  6074. ){
  6075. rc = SQLITE_NOMEM;
  6076. }
  6077. }
  6078. /* Create the virtual table wrapper around the hash-table and overload
  6079. ** the two scalar functions. If this is successful, register the
  6080. ** module with sqlite.
  6081. */
  6082. if( SQLITE_OK==rc
  6083. && SQLITE_OK==(rc = sqlite3Fts2InitHashTable(db, pHash, "fts2_tokenizer"))
  6084. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  6085. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
  6086. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1))
  6087. #ifdef SQLITE_TEST
  6088. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1))
  6089. && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1))
  6090. #endif
  6091. ){
  6092. return sqlite3_create_module_v2(
  6093. db, "fts2", &fts2Module, (void *)pHash, hashDestroy
  6094. );
  6095. }
  6096. /* An error has occurred. Delete the hash table and return the error code. */
  6097. assert( rc!=SQLITE_OK );
  6098. if( pHash ){
  6099. sqlite3Fts2HashClear(pHash);
  6100. sqlite3_free(pHash);
  6101. }
  6102. return rc;
  6103. }
  6104. #if !SQLITE_CORE
  6105. #ifdef _WIN32
  6106. __declspec(dllexport)
  6107. #endif
  6108. int sqlite3_fts2_init(
  6109. sqlite3 *db,
  6110. char **pzErrMsg,
  6111. const sqlite3_api_routines *pApi
  6112. ){
  6113. SQLITE_EXTENSION_INIT2(pApi)
  6114. return sqlite3Fts2Init(db);
  6115. }
  6116. #endif
  6117. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */